diff --git a/.gitignore b/.gitignore index 7b4e676..7bc1db5 100644 --- a/.gitignore +++ b/.gitignore @@ -47,5 +47,6 @@ src/test/resources/font src/main/resources/WEB-INF/vm/outFile target/ *.back -src/main/youhong_ai_old_src/ -src/main/youhong_ai_jitu_src/ \ No newline at end of file +# 老项目代码 +#src/main/youhong_ai_old_src/ +#src/main/youhong_ai_jitu_src/ \ No newline at end of file diff --git a/src/main/java/com/api/youhong/ai/yashilandai/openbill/controller/OpenThenBillController.java b/src/main/java/com/api/youhong/ai/yashilandai/openbill/controller/OpenThenBillController.java new file mode 100644 index 0000000..746cc72 --- /dev/null +++ b/src/main/java/com/api/youhong/ai/yashilandai/openbill/controller/OpenThenBillController.java @@ -0,0 +1,38 @@ +package com.api.youhong.ai.yashilandai.openbill.controller; + +import aiyh.utils.ApiResult; +import aiyh.utils.Util; +import com.api.youhong.ai.yashilandai.openbill.service.OpenThenBillService; +import org.apache.log4j.Logger; + +import javax.ws.rs.Consumes; +import javax.ws.rs.Path; +import javax.ws.rs.Produces; +import javax.ws.rs.core.MediaType; + +/** + *

拆单api接口

+ * + *

create: 2023/4/25 10:09

+ * + * @author youHong.ai + */ + +@Path("/ayh/estee-Lauder/open-bill") +public class OpenThenBillController { + + private final OpenThenBillService service = new OpenThenBillService(); + private final Logger log = Util.getLogger(); + + @Path("/data/get") + @Produces(MediaType.APPLICATION_JSON) + @Consumes(MediaType.APPLICATION_JSON) + public String dataGet() { + try { + return ApiResult.success(service.getOpenBillListData()); + } catch (Exception e) { + log.error("get open the bill data error!" + Util.getErrString(e)); + return ApiResult.error("system error!"); + } + } +} diff --git a/src/main/java/com/api/youhong/ai/yashilandai/openbill/mapper/OpenThenBillMapper.java b/src/main/java/com/api/youhong/ai/yashilandai/openbill/mapper/OpenThenBillMapper.java new file mode 100644 index 0000000..600faf6 --- /dev/null +++ b/src/main/java/com/api/youhong/ai/yashilandai/openbill/mapper/OpenThenBillMapper.java @@ -0,0 +1,26 @@ +package com.api.youhong.ai.yashilandai.openbill.mapper; + +import aiyh.utils.annotation.recordset.Select; +import aiyh.utils.annotation.recordset.SqlMapper; + +import java.util.List; +import java.util.Map; + +/** + *

+ * + *

create: 2023/4/25 10:15

+ * + * @author youHong.ai + */ +@SqlMapper +public interface OpenThenBillMapper { + + /** + *

查询数据列表

+ * + * @return 数据列表 + */ + @Select("select * from v_online") + List> selectList(); +} diff --git a/src/main/java/com/api/youhong/ai/yashilandai/openbill/service/OpenThenBillService.java b/src/main/java/com/api/youhong/ai/yashilandai/openbill/service/OpenThenBillService.java new file mode 100644 index 0000000..0c3ae99 --- /dev/null +++ b/src/main/java/com/api/youhong/ai/yashilandai/openbill/service/OpenThenBillService.java @@ -0,0 +1,30 @@ +package com.api.youhong.ai.yashilandai.openbill.service; + +import aiyh.utils.Util; +import com.api.youhong.ai.yashilandai.openbill.mapper.OpenThenBillMapper; + +import java.util.List; +import java.util.Map; + +/** + *

+ * + *

create: 2023/4/25 10:12

+ * + * @author youHong.ai + */ +public class OpenThenBillService { + + + private final OpenThenBillMapper mapper = Util.getMapper(OpenThenBillMapper.class); + + public Object getOpenBillListData() { + return null; + } + + public List> getData() { + List> dataList = mapper.selectList(); + return null; + } + +} diff --git a/src/main/youhong_ai_jitu_src/com/api/company/CompanyInfo.java b/src/main/youhong_ai_jitu_src/com/api/company/CompanyInfo.java new file mode 100644 index 0000000..2578a17 --- /dev/null +++ b/src/main/youhong_ai_jitu_src/com/api/company/CompanyInfo.java @@ -0,0 +1,48 @@ +package com.api.company; + +import com.alibaba.fastjson.JSONObject; +import com.engine.common.util.ParamUtil; +import jntchina.service.oa.util.ModifyDetailInfo; +import weaver.general.Util; + +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; +import javax.ws.rs.GET; +import javax.ws.rs.POST; +import javax.ws.rs.Path; +import javax.ws.rs.Produces; +import javax.ws.rs.core.Context; +import java.util.HashMap; +import java.util.Map; +@Path("/jnt/company") +public class CompanyInfo { + @GET + @Path("/test") + @Produces({"text/plain"}) + public String test(@Context HttpServletRequest request, @Context HttpServletResponse response){ + Map apidatas = new HashMap(); + System.out.println("de"); + String mess=""; + String path=""; + boolean api_status=true; + try { + //String field,String fromtableName,String totableName,int modeid,int billid,String qyid 608 9175 + /** /api/jnt/company/test?field=djgd,cgbl,cgfs,gfzl&fromtableName=uf_jnqyxxbgb_dt1&totableName=uf_jnqyxxbgb_dt2&modeid=35001&billid=608&qyid=9175& **/ + Map param= ParamUtil.request2Map(request); + String field=(String)param.get("field"); + String fromtableName=(String)param.get("fromtableName"); + String totableName=(String)param.get("totableName"); + int modeid= Util.getIntValue((String)param.get("modeid"),0); + int billid=Util.getIntValue((String)param.get("billid"),0);; + String qyid=(String)param.get("qyid"); + ModifyDetailInfo modifyDetailInfo=new ModifyDetailInfo(field, fromtableName, totableName, modeid, billid, qyid); + modifyDetailInfo.setDtailJson(); + } catch (Exception e) { + mess="异常"+e.getMessage(); + e.printStackTrace(); + apidatas.put("status", false); + apidatas.put("msg", "catch exception : " + e.getMessage()); + } + return JSONObject.toJSONString(apidatas); + } +} diff --git a/src/main/youhong_ai_jitu_src/com/api/dys/wdzxys/controller/WdzxysWorkflowController.java b/src/main/youhong_ai_jitu_src/com/api/dys/wdzxys/controller/WdzxysWorkflowController.java new file mode 100644 index 0000000..936b333 --- /dev/null +++ b/src/main/youhong_ai_jitu_src/com/api/dys/wdzxys/controller/WdzxysWorkflowController.java @@ -0,0 +1,56 @@ +package com.api.dys.wdzxys.controller; + +import aiyh.utils.Util; +import com.alibaba.fastjson.JSON; +import com.api.dys.wdzxys.service.WdzxysWorkflowService; +import io.swagger.v3.oas.annotations.parameters.RequestBody; +import org.apache.log4j.Logger; + +import javax.ws.rs.POST; +import javax.ws.rs.Path; +import javax.ws.rs.Produces; +import javax.ws.rs.core.MediaType; +import java.util.HashMap; +import java.util.Map; + +/** + * @Author DYS + * @Date 2023/3/21 23:15 + * @description 网点装修验收流程的controller + * create at weaver + */ +@Path("/dys") +public class WdzxysWorkflowController { + private final Logger log = Util.getLogger(); + private final WdzxysWorkflowService wdzxysWorkflowService = new WdzxysWorkflowService(); + + /** + * 获取网点装修验收流程的所属代理商 + * + * @param map + * @return + */ + @Path("/getSsdlq") + @POST + @Produces(MediaType.APPLICATION_JSON) + public String getSsdlq(@RequestBody Map map) { + log.info("网点装修验收流程的controller:" + map.toString()); + String ssdlqId = (String) map.get("ssdlqId");//所属代理区id + String ssdlqName = (String) map.get("ssdlqName");//所属代理区name + log.info("所属代理区id:[" + ssdlqId + "], 所属代理区name:[" + ssdlqName + "]"); + //根据代理区name查询代理区的网点编码,然后根据网点编码查所属代理区的个数 + int ssdlqNum = wdzxysWorkflowService.getssdlqName(ssdlqName); + Map result = new HashMap<>(); + result.put("code", "200"); + result.put("msg", "查询成功"); + //查询验收数量 验收数量需要单独设置一个建模表,从建模表里面查询 如果是第一次的话就给一个默认值0 + int dlqyssl = wdzxysWorkflowService.getdlqysNum(ssdlqName); + Map dataMap = new HashMap<>(); + dataMap.put("ssdlqNum", ssdlqNum); + dataMap.put("dlqyssl", dlqyssl); + result.put("data", dataMap); + log.info("代理区个数以及代理区验收数量:[" + dataMap.toString() + "]"); + log.info("返回结果:[" + result.toString() + "]"); + return JSON.toJSONString(result); + } +} diff --git a/src/main/youhong_ai_jitu_src/com/api/dys/wdzxys/mapper/WdzxysWorkflowMapper.java b/src/main/youhong_ai_jitu_src/com/api/dys/wdzxys/mapper/WdzxysWorkflowMapper.java new file mode 100644 index 0000000..0db163e --- /dev/null +++ b/src/main/youhong_ai_jitu_src/com/api/dys/wdzxys/mapper/WdzxysWorkflowMapper.java @@ -0,0 +1,26 @@ +package com.api.dys.wdzxys.mapper; + +import aiyh.utils.annotation.recordset.ParamMapper; +import aiyh.utils.annotation.recordset.Select; +import aiyh.utils.annotation.recordset.SqlMapper; + +/** + * @Author DYS + * @Date 2023/3/21 23:21 + * @description 网点装修验收流程mapper + * create at weaver + */ +@SqlMapper +public interface WdzxysWorkflowMapper { + + @Select("select count(1) from uf_netsiteinfo " + + "group by belong_area having belong_area = " + + "(select net_code from uf_netsiteinfo u where u.net_name = #{ssdlqName})") + int getssdlqName(@ParamMapper("ssdlqName") String ssdlqName); + + @Select("select dlqyssl from uf_dlqyssl where dlqmc = #{ssdlqName}") + int getdlqysNum(@ParamMapper("ssdlqName") String ssdlqName); + + @Select("select count(1) from uf_dlqyssl where dlqmc = #{ssdlqName}") + int getIfHasdlqmc(@ParamMapper("ssdlqName") String ssdlqName); +} diff --git a/src/main/youhong_ai_jitu_src/com/api/dys/wdzxys/service/WdzxysWorkflowService.java b/src/main/youhong_ai_jitu_src/com/api/dys/wdzxys/service/WdzxysWorkflowService.java new file mode 100644 index 0000000..ab260fe --- /dev/null +++ b/src/main/youhong_ai_jitu_src/com/api/dys/wdzxys/service/WdzxysWorkflowService.java @@ -0,0 +1,39 @@ +package com.api.dys.wdzxys.service; + +import aiyh.utils.Util; +import com.api.dys.wdzxys.mapper.WdzxysWorkflowMapper; +import weaver.conn.RecordSet; + +/** + * @Author DYS + * @Date 2023/3/21 23:22 + * @description 网点装修验收流程业务实现类 + * create at weaver + */ +public class WdzxysWorkflowService { + private final WdzxysWorkflowMapper wdzxysWorkflowMapper = Util.getMapper(WdzxysWorkflowMapper.class); + + /** + * 根据所属代理区 + * + * @param ssdlqName + * @return + */ + public int getssdlqName(String ssdlqName) { + return wdzxysWorkflowMapper.getssdlqName(ssdlqName); + } + + /** + * 流程归档时 代理区验收数量 + * + * @param ssdlqName + * @return + */ + public int getdlqysNum(String ssdlqName) { + int ifHasdlq = wdzxysWorkflowMapper.getIfHasdlqmc(ssdlqName); + if (ifHasdlq == 0) { + return 0; + } + return wdzxysWorkflowMapper.getdlqysNum(ssdlqName); + } +} diff --git a/src/main/youhong_ai_jitu_src/com/api/lh/action/CreateSubprocessAction.java b/src/main/youhong_ai_jitu_src/com/api/lh/action/CreateSubprocessAction.java new file mode 100644 index 0000000..8705000 --- /dev/null +++ b/src/main/youhong_ai_jitu_src/com/api/lh/action/CreateSubprocessAction.java @@ -0,0 +1,323 @@ +package com.api.lh.action; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.JSONObject; +import com.api.lh.config.DemoConfig; +import com.api.lh.util.CreateProcessUtil; +import selfdev.util.base.BaseUtil; +import selfdev.util.log.LogTool; +import weaver.conn.RecordSet; +import weaver.file.Prop; +import weaver.general.Util; +import weaver.interfaces.workflow.action.Action; +import weaver.soa.workflow.request.*; +import weaver.workflow.workflow.WorkflowVersion; + +import java.util.Arrays; + +/** + * @ClassName CreateSubprocessAction + * @Description 创建 01-付款申请-J&T中国(不对接NCC)流程 + * @Author louh + * @Date 2022/4/6 13:53 + * @Version 1.0 + */ +public class CreateSubprocessAction implements Action, DemoConfig { + LogTool log = new LogTool("/log/lh/CreateSubprocessAction", false); + //当前环境 + String mode = Prop.getPropValue("DevToProcess_jntchina", "mode"); + //付款申请流程id + String fk_workflowid = Prop.getPropValue("DevToProcess_jntchina", mode + "_fk_workflowid"); + + + @Override + public String execute(RequestInfo ri) { + RecordSet rs = new RecordSet(); + RecordSet rs1 = new RecordSet(); + + String requestid = ri.getRequestid(); + String workflowid = ri.getWorkflowid(); + try { + WorkflowVersion workflowVersion = new WorkflowVersion(fk_workflowid); + String newFid = workflowVersion.getActiveVersionWFID(); + + //获取表名 + String tablename = BaseUtil.getBaseInfoByParm("tablename", "workflow_bill", "1", "1", " and id in (select formid from workflow_base where id=" + workflowid + ")"); + log.writeLog("requestid---> " + requestid + "对应表名tablename---> " + tablename); + //主表数据id + String id = BaseUtil.getBaseInfoByParm("id", tablename, "requestid", requestid, ""); + + //主表申请日期 + String sqrq = BaseUtil.getBaseInfoByParm("sqrq", tablename, "requestid", requestid, ""); + //获取明细表不同批次号数据 + String sql = "select distinct pch,sfsczlccg from " + tablename + "_dt1 where mainid = " + id; + log.writeLog("获取明细表数据sql----> " + sql); + rs.execute(sql); + while (rs.next()) { + //实际付款金额 + double sum = 0.00; + //批次号 + String pch = Util.null2String(rs.getString("pch")).trim(); + if ("".equals(pch)) { + ri.getRequestManager().setMessagecontent("批次号不允许为空!"); + return FAILURE_AND_CONTINUE; + } + //是否生成子流程成功 + String sfsczlccg = Util.null2String(rs.getString("sfsczlccg")); + //成功生成子流程则不再生成 + if ("0".equals(sfsczlccg)) { + continue; + } + //生成子流程 + RequestService requestService = new RequestService(); + RequestInfo requestInfo = new RequestInfo(); + + //流程workflowid + requestInfo.setWorkflowid(newFid); + //提醒 + requestInfo.setRemindtype("0"); + //紧急程度 + requestInfo.setRequestlevel("0"); + //是否自动流转 + requestInfo.setIsNextFlow("0"); + + /* 根据批次号查询该批次号有多少条数据 */ + String pchSql = "select * from " + tablename + "_dt1 where mainid = " + id + " and pch = " + pch; + log.writeLog("根据批次号查询该批次号有多少条数据---> " + pchSql); + + rs1.execute(pchSql); + + //流程创建人id + String peopleId = ""; + //流程标题 + String bt = ""; + //公司名称 + String gsmc = ""; + //申请人部门id + String departmentid = ""; + //申请人分部id + String subcompanyid1 = ""; + //是否有合同 + String sfyht = ""; + //预计付款日期 + String yjfkrq = ""; + //供应商名称 + String gysmc = ""; + //账户名称 + String khmc = ""; + //银行账号 + String yxzh = ""; + //开户行 + String khx = ""; + //发票号码 + String fphm = ""; + //发票类型 + String fplx = ""; + //发票日期 + String fprq = ""; + //付款说明 + String fksm = ""; + //付款类型 + String fklx = ""; + + //拼接明细表数据 + DetailTableInfo dti = new DetailTableInfo(); + DetailTable[] dt = new DetailTable[0]; + int i = 0; + while (rs1.next()) { + String sqrgh = Util.null2String(rs1.getString("sqrgh")); /* 申请人工号 */ + /* 根据人员工号获取人员id */ + peopleId = BaseUtil.getBaseInfoByParm("id", "hrmresource", "workcode", sqrgh, ""); + if ("".equals(peopleId)) { + ri.getRequestManager().setMessagecontent("当前明细表申请人工号【" + sqrgh + "】未找到对应人员,请确认工号是否正确!"); + return FAILURE_AND_CONTINUE; + } + //标题 + bt = Util.null2String(rs1.getString("bt")); + //公司名称 + gsmc = Util.null2String(rs1.getString("gsmc")); + //申请人部门id + departmentid = BaseUtil.getBaseInfoByParm("departmentid", "hrmresource", "workcode", sqrgh, ""); + //申请人分部id + subcompanyid1 = BaseUtil.getBaseInfoByParm("subcompanyid1", "hrmresource", "workcode", sqrgh, ""); + //是否有合同 + sfyht = Util.null2String(rs1.getString("sfyht")).trim(); + //预计付款日期 + yjfkrq = Util.null2String(rs1.getString("yjfkrq")); + //供应商名称 + gysmc = Util.null2String(rs1.getString("gysmc")); + //账户名称 + khmc = Util.null2String(rs1.getString("khmc")); + //银行账号 + yxzh = Util.null2String(rs1.getString("yxzh")); + //开户行 + khx = Util.null2String(rs1.getString("khx")); + //发票号码 + fphm = Util.null2String(rs1.getString("fphm")); + //发票类型 + fplx = Util.null2String(rs1.getString("fplx")); + //发票日期 + fprq = Util.null2String(rs1.getString("fprq")); + //付款说明 + fksm = Util.null2String(rs1.getString("fksm")); + //付款类型 + fklx = Util.null2String(rs1.getString("fklx")); + //行数据 + Row[] row = new Row[0]; + //添加单元格到行 + Cell[] c = new Cell[0]; + //添加子表数据 + row = Arrays.copyOf(row, (row.length + 1)); + row[row.length - 1] = new Row(); + row[row.length - 1].setId((i + 1) + ""); + //费用承担部门 + String fycdbmbm = Util.null2String(rs1.getString("fycdbmbm")); /* 费用承担部门编码 */ + String bmid = BaseUtil.getBaseInfoByParm("id", "hrmdepartment", "departmentcode", fycdbmbm, ""); + + c = CreateProcessUtil.setCell(c, "fycdbm", bmid); + //不含税金额 + String bhsje = Util.null2String(rs1.getString("bhsje")); + if (!"".equals(bhsje)) { + bhsje = bhsje.replaceAll(",", ""); + } else { + bhsje = "0.00"; + } + c = CreateProcessUtil.setCell(c, "bhsje", bhsje); + //税率 + c = CreateProcessUtil.setCell(c, "sl", Util.null2String(rs1.getString("sl"))); + //税额 + String se = Util.null2String(rs1.getString("se")); + if (!"".equals(se)) { + se = se.replaceAll(",", ""); + } else { + se = "0.00"; + } + c = CreateProcessUtil.setCell(c, "se", se); + //价税合计 + String jshj = Util.null2String(rs1.getString("jshj")); + if (!"".equals(jshj)) { + jshj = jshj.replaceAll(",", ""); + } else { + jshj = "0.00"; + } + sum += Double.parseDouble(jshj); + c = CreateProcessUtil.setCell(c, "jshj", jshj); + //添加一行 + row[row.length - 1].setCell(c); + + dt = Arrays.copyOf(dt, (dt.length + 1)); + dt[dt.length - 1] = new DetailTable(); + dt[dt.length - 1].setId("1");//明细表 dt1 后面的1 + dt[dt.length - 1].setRow(row); + + ++i; + } + dti.setDetailTable(dt); + log.writeLog("明细表数据: " + JSON.toJSONString(dti)); + requestInfo.setDetailTableInfo(dti); + + + /* 流程创建人id */ + requestInfo.setCreatorid(peopleId); + //流程标题 + requestInfo.setDescription(bt); + //设置主表字段 + Property[] p = new Property[0]; + //公司名称 + p = CreateProcessUtil.setProperty(p, "gsmc", gsmc); + //创建日期 + p = CreateProcessUtil.setProperty(p, "cjrq", sqrq); + //申请人部门id + p = CreateProcessUtil.setProperty(p, "fygsbm", departmentid); + p = CreateProcessUtil.setProperty(p, "zz", subcompanyid1); + //姓名 + p = CreateProcessUtil.setProperty(p, "xm", peopleId); + //是否有合同 + sfyht = getSelectValue(sfyht, requestInfo.getWorkflowid(), "sfyht", ""); + //sfyht = getSelectValue(sfyht_fieldid, sfyht); + p = CreateProcessUtil.setProperty(p, "sfyht", sfyht); + //预计付款日期 + p = CreateProcessUtil.setProperty(p, "yjfkrq", yjfkrq); + //供应商名称 + p = CreateProcessUtil.setProperty(p, "gysmc", gysmc); + //账户名称 + p = CreateProcessUtil.setProperty(p, "yzhm", khmc); + //银行账号 + p = CreateProcessUtil.setProperty(p, "yxhm", yxzh); + //开户行 + p = CreateProcessUtil.setProperty(p, "yxmz", khx); + //发票号码 + p = CreateProcessUtil.setProperty(p, "fphm", fphm); + //发票类型 + fplx = getSelectValue(fplx, requestInfo.getWorkflowid(), "fplx", ""); + //fplx = getSelectValue(fplx_fieldid, fplx); + p = CreateProcessUtil.setProperty(p, "fplx", fplx); + //发票日期 + p = CreateProcessUtil.setProperty(p, "fprq", fprq); + //付款说明 + p = CreateProcessUtil.setProperty(p, "fksm", fksm); + + //实际付款金额大写 + p = CreateProcessUtil.setProperty(p, "sjfkje2", sum + ""); + + //付款方式 默认 银行汇款 + p = CreateProcessUtil.setProperty(p, "fkfs", "0"); + //币种 默认RMB + p = CreateProcessUtil.setProperty(p, "bz", "1"); + //付款类型 默认航空费 + p = CreateProcessUtil.setProperty(p, "fklx1", fklx); + //区域 + String fbid = BaseUtil.getBaseInfoByParm("subcompanyid1", "hrmresource", "id", peopleId, ""); + p = CreateProcessUtil.setProperty(p, "qy", fbid); + /**********************************新加字段*****************************************/ + //是否杭百费用 0:是 1:否 为否则显示付款类型值 + p = CreateProcessUtil.setProperty(p, "sfhbfy", "1"); + + //添加主表数据 + MainTableInfo mti = new MainTableInfo(); + mti.setProperty(p); + log.writeLog("主表数据: " + JSON.toJSONString(mti)); + requestInfo.setMainTableInfo(mti); + //创建流程 + String request = requestService.createRequest(requestInfo); + JSONObject judge = CreateProcessUtil.judge(request); + if ("1".equals(judge.getString("status"))) { + ri.getRequestManager().setMessagecontent("流程创建失败!"); + //修改明细表数据 + String updSql = "update " + tablename + "_dt1 set sfsczlccg = '" + judge.getString("status") + "', cfzlcxx = '" + judge.getString("msg") + "', cfrequestid = '" + judge.getString("requestid") + "' where mainid = " + id + " and pch = '" + pch + "'"; + log.writeLog("修改明细表数据sql----> " + updSql); + rs.execute(updSql); + return FAILURE_AND_CONTINUE; + } + //修改明细表数据 + String updSql = "update " + tablename + "_dt1 set sfsczlccg = '" + judge.getString("status") + "', cfzlcxx = '" + judge.getString("msg") + "', cfrequestid = '" + judge.getString("requestid") + "' where mainid = " + id + " and pch = '" + pch + "'"; + log.writeLog("修改明细表数据sql----> " + updSql); + rs.execute(updSql); + } + } catch (Exception e) { + log.writeLog("出现异常---> " + e); + ri.getRequestManager().setMessagecontent("内部出错,联系管理员查看问题!"); + return FAILURE_AND_CONTINUE; + } + return SUCCESS; + } + + + /** + * 根据字段id和选中名称获取 + * + * @param fieldid + * @param selectname + * @return + */ + public String getSelectValue(String fieldid, String selectname) { + RecordSet rs = new RecordSet(); + String selectValue = ""; + String sql = "select selectvalue from workflow_selectitem where fieldid = " + fieldid + " and convtomultilang(selectname,7) = '" + selectname + "'"; + rs.execute(sql); + if (rs.next()) { + selectValue = Util.null2String(rs.getString("selectvalue")); + } + return selectValue; + } +} diff --git a/src/main/youhong_ai_jitu_src/com/api/lh/action/CurrencyModifyAccountAction.java b/src/main/youhong_ai_jitu_src/com/api/lh/action/CurrencyModifyAccountAction.java new file mode 100644 index 0000000..21b0a74 --- /dev/null +++ b/src/main/youhong_ai_jitu_src/com/api/lh/action/CurrencyModifyAccountAction.java @@ -0,0 +1,125 @@ +package com.api.lh.action; + +import com.api.lh.config.DemoConfig; + +import selfdev.util.log.LogTool; +import weaver.conn.RecordSet; +import weaver.conn.RecordSetTrans; +import weaver.general.Util; +import weaver.interfaces.workflow.action.Action; +import weaver.soa.workflow.request.RequestInfo; + +/** + * @ClassName CurrencyModifyAccountAction + * @Description 同步冲抵明细信息数据到 --- 供应商预付欠票台账中 + * @Author louh + * @Date 2022/4/27 16:04 + * @Version 1.0 + */ +public class CurrencyModifyAccountAction implements Action, DemoConfig { + @Override + public String execute(RequestInfo ri) { + String requestid = ri.getRequestid(); + String workflowid = ri.getWorkflowid(); + RecordSet rs = new RecordSet(); + RecordSet rs1 = new RecordSet(); + RecordSet rs2 = new RecordSet(); + RecordSet rs3 = new RecordSet(); + RecordSetTrans rst = new RecordSetTrans(); + rst.setAutoCommit(false); + try{ + String tableName = getTableName(workflowid); + log.writeLog("requestid---> " + requestid + "对应表名tablename---> " + tableName); + String id = getId(tableName, requestid); + String sql = "select yfkqptzmxid, count(yfkqptzmxid) as sum from " + tableName + "_dt1 where mainid = " + id + " group by yfkqptzmxid having count(yfkqptzmxid) > 1"; + log.writeLog("根据主表数据id查询当前明细表数据是否有多次选择同一个预付款欠票台账明细id【yfkqptzmxid】sql---->" + sql); + rs.execute(sql); + if(rs.next()){ + ri.getRequestManager().setMessagecontent("同一张单据不允许多次选择相同的【预付款欠票台账明细id】,请重新选择抵扣明细表不同的【预付款欠票台账明细id】数据。"); + return FAILURE_AND_CONTINUE; + } + sql = "select * from "+ tableName + "_dt1 where mainid = "+ id; + log.writeLog("查询当前单据抵扣明细详细信息sql------> " + sql); + rs.execute(sql); + while(rs.next()){ + String yfkqptzmxid = Util.null2String(rs.getString("yfkqptzmxid")); /* 预付款欠票台账明细id */ +// double yfje = Double.parseDouble(Util.null2String(rs.getString("yfje")) == "" ? "0.00" : Util.null2String(rs.getString("yfje"))); /* 预付金额 */ + double bcdjje = Double.parseDouble(Util.null2String(rs.getString("bcdjje")) == "" ? "0.00" : Util.null2String(rs.getString("bcdjje"))); /* 本次抵扣金额 */ + String bz = Util.null2String(rs.getString("bz"));/* 备注 */ + String nccdh = Util.null2String(rs.getString("nccdh")); /* ncc单号 */ + String xgyflc = Util.null2String(rs.getString("xgyflc")); //相关预付流程 + String sql1 = "select * from uf_fksqyfb_dt1 where id = " + yfkqptzmxid; + log.writeLog("查询台账本次抵扣流程信息sql----> " + sql1); + rs1.execute(sql1); + //已核销金额 + double yhxje = 0.00; + //剩余未核销金额 + double sywhxje = 0.00; + //预付款金额 + double fkje = 0.00; + //相关核销流程 + String xghxlc = ""; + if(rs1.next()){ + xghxlc = Util.null2String(rs1.getString("xghxlc")); + yhxje = Double.parseDouble(Util.null2String(rs1.getString("yhxje")) == "" ? "0.00" : Util.null2String(rs1.getString("yhxje"))); + sywhxje = Double.parseDouble(Util.null2String(rs1.getString("sywhxje")) == "" ? "0.00" : Util.null2String(rs1.getString("sywhxje"))); + fkje = Double.parseDouble(Util.null2String(rs1.getString("fkje")) == "" ? "0.00" : Util.null2String(rs1.getString("fkje"))); + } + if(bcdjje > sywhxje){ + ri.getRequestManager().setMessagecontent("当前抵扣明细本次抵扣金额【" + bcdjje + "】大于剩余未核销金额【" + sywhxje + "】,请确认金额是否正确。"); + return FAILURE_AND_CONTINUE; + } + yhxje = bcdjje + yhxje; + if(yhxje > fkje){ + ri.getRequestManager().setMessagecontent("当前抵扣明细本次抵扣金额与历史抵扣金额共【" + yhxje + "】大于借款总金额【" + fkje + "】,请确认金额是否正确。"); + return FAILURE_AND_CONTINUE; + } + sywhxje = fkje - yhxje; + if(sywhxje < 0.00){ + ri.getRequestManager().setMessagecontent("当前抵扣明细单据总金额【"+ fkje + "】,核销总金额【" + yhxje + "】相减,则剩余未核销金额小于0.00元,请确认金额是否正确。"); + return FAILURE_AND_CONTINUE; + } + + if("".equals(xghxlc)){ + xghxlc = requestid; + }else { + xghxlc += "," + requestid; + } + + + String updSql = "update uf_fksqyfb_dt1 set " + + "yhxje = '" + yhxje + "', " + + "sywhxje = '" + sywhxje + "'," + + " xghxlc ='" + xghxlc + "' where id = '" + yfkqptzmxid + "'"; + log.writeLog("修改台账信息sql-----> " + updSql); + rst.executeSql(updSql); + + sql1 = "select * from uf_fksqyfb where qqid = '" + xgyflc + "'" ; + log.writeLog("查询主表总预付金额及核销金额sql----> " + sql1); + rs2.execute(sql1); + double fkje1 = 0.00; + double yhxje1 = 0.00; + double sywhxje1 = 0.00; + if (rs2.next()){ + fkje1 = Double.parseDouble(Util.null2String(rs2.getString("fkje"))==""?"0.00":Util.null2String(rs2.getString("fkje")));//付款金额 + yhxje1 = Double.parseDouble(Util.null2String(rs2.getString("yhxje"))==""?"0.00":Util.null2String(rs2.getString("yhxje")));//已核销金额 + sywhxje1 = Double.parseDouble(Util.null2String(rs2.getString("sywhxje"))==""?"0.00":Util.null2String(rs2.getString("sywhxje")));//剩余金额 + } + double bchxje = bcdjje + yhxje1; + sywhxje1 = fkje1 - bchxje; + updSql = "update uf_fksqyfb set yhxje = '" + bchxje + "'," + + " sywhxje ='" + sywhxje1 + "' where ncclcdh = '" + nccdh + "' and qqid = '" + xgyflc + "'" ; + log.writeLog("修改本次台账主表信息sql-----> " + updSql); + //rst.executeSql(updSql); + rs3.execute(updSql); + } + rst.commit(); + }catch (Exception e){ + rst.rollback(); + log.writeLog("出现异常-----> " + e); + ri.getRequestManager().setMessagecontent("系统内部出错----> " + e); + return FAILURE_AND_CONTINUE; + } + return SUCCESS; + } +} diff --git a/src/main/youhong_ai_jitu_src/com/api/lh/action/CurrencyModifyAccountActionYY.java b/src/main/youhong_ai_jitu_src/com/api/lh/action/CurrencyModifyAccountActionYY.java new file mode 100644 index 0000000..f0c92c4 --- /dev/null +++ b/src/main/youhong_ai_jitu_src/com/api/lh/action/CurrencyModifyAccountActionYY.java @@ -0,0 +1,123 @@ +package com.api.lh.action; + +import com.api.lh.config.DemoConfig; +import weaver.conn.RecordSet; +import weaver.conn.RecordSetTrans; +import weaver.general.Util; +import weaver.interfaces.workflow.action.Action; +import weaver.soa.workflow.request.RequestInfo; + +/** + * @ClassName CurrencyModifyAccountAction + * @Description 同步冲抵明细信息数据到 --- 供应商预付欠票台账中 + * @Author ycf + * @Date 2022/4/27 16:04 + * @Version 1.0 + */ +public class CurrencyModifyAccountActionYY implements Action, DemoConfig { + @Override + public String execute(RequestInfo ri) { + String requestid = ri.getRequestid(); + String workflowid = ri.getWorkflowid(); + RecordSet rs = new RecordSet(); + RecordSet rs1 = new RecordSet(); + RecordSet rs2 = new RecordSet(); + RecordSet rs3 = new RecordSet(); + RecordSetTrans rst = new RecordSetTrans(); + rst.setAutoCommit(false); + try{ + String tableName = getTableName(workflowid); + log.writeLog("requestid---> " + requestid + "对应表名tablename---> " + tableName); + String id = getId(tableName, requestid); + String sql = "select yfkqptzmxid, count(yfkqptzmxid) as sum from " + tableName + "_dt1 where mainid = " + id + " group by yfkqptzmxid having count(yfkqptzmxid) > 1"; + log.writeLog("根据主表数据id查询当前明细表数据是否有多次选择同一个预付款欠票台账明细id【yfkqptzmxid】sql---->" + sql); + rs.execute(sql); + if(rs.next()){ + ri.getRequestManager().setMessagecontent("同一张单据不允许多次选择相同的【预付款欠票台账明细id】,请重新选择抵扣明细表不同的【预付款欠票台账明细id】数据。"); + return FAILURE_AND_CONTINUE; + } + sql = "select * from "+ tableName + "_dt1 where mainid = "+ id; + log.writeLog("查询当前单据抵扣明细详细信息sql------> " + sql); + rs.execute(sql); + while(rs.next()){ + String yfkqptzmxid = Util.null2String(rs.getString("yfkqptzmxid")); /* 预付款欠票台账明细id */ +// double yfje = Double.parseDouble(Util.null2String(rs.getString("yfje")) == "" ? "0.00" : Util.null2String(rs.getString("yfje"))); /* 预付金额 */ + double bcdjje = Double.parseDouble(Util.null2String(rs.getString("bcdjje")) == "" ? "0.00" : Util.null2String(rs.getString("bcdjje"))); /* 本次抵扣金额 */ + String bz = Util.null2String(rs.getString("bz"));/* 备注 */ + String nccdh = Util.null2String(rs.getString("nccdh")); /* ncc单号 */ + String xgyflc = Util.null2String(rs.getString("xgyflc")); //相关预付流程 + String sql1 = "select * from uf_gysqktzyy_dt1 where id = " + yfkqptzmxid; + log.writeLog("查询台账本次抵扣流程信息sql----> " + sql1); + rs1.execute(sql1); + //已核销金额 + double yhxje = 0.00; + //剩余未核销金额 + double sywhxje = 0.00; + //预付款金额 + double fkje = 0.00; + //相关核销流程 + String xghxlc = ""; + if(rs1.next()){ + xghxlc = Util.null2String(rs1.getString("xghxlc")); + yhxje = Double.parseDouble(Util.null2String(rs1.getString("yhxje")) == "" ? "0.00" : Util.null2String(rs1.getString("yhxje"))); + sywhxje = Double.parseDouble(Util.null2String(rs1.getString("sywhxje")) == "" ? "0.00" : Util.null2String(rs1.getString("sywhxje"))); + fkje = Double.parseDouble(Util.null2String(rs1.getString("fkje")) == "" ? "0.00" : Util.null2String(rs1.getString("fkje"))); + } + if(bcdjje > sywhxje){ + ri.getRequestManager().setMessagecontent("当前抵扣明细本次抵扣金额【" + bcdjje + "】大于剩余未核销金额【" + sywhxje + "】,请确认金额是否正确。"); + return FAILURE_AND_CONTINUE; + } + yhxje = bcdjje + yhxje; + if(yhxje > fkje){ + ri.getRequestManager().setMessagecontent("当前抵扣明细本次抵扣金额与历史抵扣金额共【" + yhxje + "】大于借款总金额【" + fkje + "】,请确认金额是否正确。"); + return FAILURE_AND_CONTINUE; + } + sywhxje = fkje - yhxje; + if(sywhxje < 0.00){ + ri.getRequestManager().setMessagecontent("当前抵扣明细单据总金额【"+ fkje + "】,核销总金额【" + yhxje + "】相减,则剩余未核销金额小于0.00元,请确认金额是否正确。"); + return FAILURE_AND_CONTINUE; + } + + if("".equals(xghxlc)){ + xghxlc = requestid; + }else { + xghxlc += "," + requestid; + } + + + String updSql = "update uf_gysqktzyy_dt1 set " + + "yhxje = '" + yhxje + "', " + + "sywhxje = '" + sywhxje + "'," + + " xghxlc ='" + xghxlc + "' where id = '" + yfkqptzmxid + "'"; + log.writeLog("修改台账信息sql-----> " + updSql); + rst.executeSql(updSql); + + sql1 = "select * from uf_gysqktzyy where qqid = '" + xgyflc + "'" ; + rs2.execute(sql1); + double fkje1 = 0.00; + double yhxje1 = 0.00; + double sywhxje1 = 0.00; + if (rs2.next()){ + fkje1 = Double.parseDouble(Util.null2String(rs2.getString("fkje"))==""?"0.00":Util.null2String(rs2.getString("fkje")));//付款金额 + yhxje1 = Double.parseDouble(Util.null2String(rs2.getString("yhxje"))==""?"0.00":Util.null2String(rs2.getString("yhxje")));//已核销金额 + sywhxje1 = Double.parseDouble(Util.null2String(rs2.getString("sywhxje"))==""?"0.00":Util.null2String(rs2.getString("sywhxje")));//剩余金额 + } + double bchxje = bcdjje + yhxje1; + sywhxje1 = fkje1 - bchxje; + updSql = "update uf_gysqktzyy set yhxje = '" + bchxje + "'," + + " sywhxje ='" + sywhxje1 + "' where ncclcdh = '" + nccdh + "' and qqid = '" + xgyflc + "'" ; + log.writeLog("修改本次台账主表信息sql-----> " + updSql); + //rst.executeSql(updSql); + rs3.execute(updSql); + + } + rst.commit(); + }catch (Exception e){ + rst.rollback(); + log.writeLog("出现异常-----> " + e); + ri.getRequestManager().setMessagecontent("系统内部出错----> " + e); + return FAILURE_AND_CONTINUE; + } + return SUCCESS; + } +} diff --git a/src/main/youhong_ai_jitu_src/com/api/lh/action/NCCAdvanceTossAction.java b/src/main/youhong_ai_jitu_src/com/api/lh/action/NCCAdvanceTossAction.java new file mode 100644 index 0000000..dbcd315 --- /dev/null +++ b/src/main/youhong_ai_jitu_src/com/api/lh/action/NCCAdvanceTossAction.java @@ -0,0 +1,191 @@ +package com.api.lh.action; + +import com.alibaba.fastjson.JSONArray; +import com.alibaba.fastjson.JSONObject; +import com.api.lh.port.AddJournal; +import com.api.lh.port.Items; +import com.api.lh.port.StuData; +import com.api.lh.util.DUtil; +import jntchina.util.HttpClientToDC; +import selfdev.util.base.BaseUtil; +import selfdev.util.log.LogTool; +import weaver.conn.RecordSet; +import weaver.file.Prop; +import weaver.general.Util; +import weaver.interfaces.workflow.action.Action; +import weaver.soa.workflow.request.RequestInfo; + +import java.text.SimpleDateFormat; +import java.util.ArrayList; +import java.util.Date; +import java.util.List; + +/** + * @ClassName NCCAdvanceTossAction + * @Description 抛转预付单数据给NCC + * @Author louh + * @Date 2022/3/9 11:06 + * @Version 1.0 + */ +public class NCCAdvanceTossAction implements Action { + + LogTool log = new LogTool("/log/lh/action/NCCAdvanceTossAction", false); + static final String mode = Prop.getPropValue("DevToDC_jntchina","mode"); + static final String baseUrl = Prop.getPropValue("DevToDC_jntchina", mode + "_baseUrl"); + + @Override + public String execute(RequestInfo ri) { + SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); + String date = dateFormat.format(new Date()); + String startDate = date.substring(0, 10); + String endDate = date.substring(11); + date = getNewDate(startDate, endDate); + JSONObject json = new JSONObject(); + RecordSet rs = new RecordSet(); + String xrnccsbcsfts = ""; + String s= ""; + //单据属性 + String djsx = ""; + String requestid = ri.getRequestid(); + String workflowid = ri.getWorkflowid(); + try{ + //获取表名 + String tablename = BaseUtil.getBaseInfoByParm("tablename", "workflow_bill", "1", "1", " and id in (select formid from workflow_base where id=" + workflowid + ")"); + log.writeLog("requestid---> " + requestid + "对应表名tablename---> " + tablename); + /* 主表数据id */ + String id = BaseUtil.getBaseInfoByParm("id", tablename, "requestid", requestid, ""); + /* 流程编号 */ + String lcbh = BaseUtil.getBaseInfoByParm("lcbh", tablename, "requestid", requestid, ""); + /* 供应商名称 */ + String gysmc = BaseUtil.getBaseInfoByParm("gysmc", tablename, "requestid", requestid, ""); + /* 付款金额 */ + String fkje = BaseUtil.getBaseInfoByParm("jshjje", tablename, "requestid", requestid, ""); + /* 公司名称(NCC财务组织编码) */ + String gsmc = BaseUtil.getBaseInfoByParm("gsmc", tablename, "requestid", requestid, ""); + /* 制单人 */ + String zdr = BaseUtil.getBaseInfoByParm("zdr", tablename, "requestid", requestid, ""); + /* 制单人编码 */ + String workcode = BaseUtil.getBaseInfoByParm("workcode", "hrmresource", "id", zdr, ""); + /* 部门 */ + String bm = BaseUtil.getBaseInfoByParm("fygsbm", tablename, "requestid", requestid, ""); + /* 部门编码 */ + String departmentcode = BaseUtil.getBaseInfoByParm("departmentcode", "hrmdepartment", "id", bm, ""); + /* 银行账号 */ + String yxhm = BaseUtil.getBaseInfoByParm("yxhm", tablename, "requestid", requestid, ""); + //是否提示报错信息 + xrnccsbcsfts = BaseUtil.getBaseInfoByParm("xrnccsbcsfts", tablename, "requestid", requestid, ""); + //银行付款备注 + String yxfkbz = BaseUtil.getBaseInfoByParm("yxfkbz", tablename, "requestid", requestid, ""); + + double je = Double.parseDouble(fkje.replaceAll(",", "")); + String sql = "select * from " + tablename + "_dt2 where mainid = " + id; + log.writeLog("查询应付单明细数据sql-----> " + sql); + rs.execute(sql); + List list = new ArrayList<>(); + while(rs.next()){ + /* 本次付款金额 */ + String je1 = Util.null2String(rs.getString("bcfkje")); + double v = Double.parseDouble(je1.replaceAll(",", "")); + /* 付款计划唯一id */ + String fkjhwyid = Util.null2String(rs.getString("fkjhwyid")); + /* 采购订单明细id */ + String cgddmxid = Util.null2String(rs.getString("cgddmxid")); + /* 采购订单号 */ + String cgddh = Util.null2String(rs.getString("cgddh")); + /* 摘要 */ + String zy = Util.null2String(rs.getString("zy")); + /* 成本中心 */ + String wd = Util.null2String(rs.getString("wd")); + + djsx = Util.null2String(rs.getString("fkdbm")); + s = djsx == "F3-Cxx-06" ? "" : djsx; + Items items = new Items("1", gysmc,departmentcode, "", "1","CNY",v + "", + "1",v + "","1",v + "","1", + v + "","1",v + "",cgddmxid,cgddh,fkjhwyid,"", + zy, s, "", departmentcode, yxhm, "", wd); + + list.add(items); + } + StuData stuData = new StuData(gsmc,s,date,"1","CNY",yxhm,je + "", + "1",je + "","1",je + "","1",je + "", + workcode,requestid,lcbh,gysmc,list,departmentcode, "", yxfkbz); + json = (JSONObject) JSONObject.toJSON(stuData); + log.writeLog("json-----> " + json); + /* 调用NCC付款单接口 */ + + //获取token + String token = HttpClientToDC.getToken(); + log.writeLog("获取中台的数据token----》 " + token); + if ("".equals(weaver.general.Util.null2String(token))) { + ri.getRequestManager().setMessagecontent("未获取到中台token,请联系管理员查看问题!"); + return FAILURE_AND_CONTINUE; + } + String result = HttpClientToDC.sendPostApi(baseUrl + "/dcoaapi/ncc/sendPreBill", token, json.toJSONString()); + + //String result = NCCUtils.sendApi(baseUrl + "/dcoaapi/ncc/sendPreBill", json.toJSONString()); + log.writeLog("result----> " + result); + + JSONObject parse = (JSONObject) JSONObject.parse(result); + String success = parse.getString("succ"); + String msg = parse.getString("msg"); + if(success.equals("true")) { + JSONObject data = parse.getJSONObject("data"); + String billno = data.getString("billno"); /* ncc单据号 */ + String pk_bill = data.getString("pk_bill");/* ncc单据主键 */ + String billmaker = data.getString("billmaker"); /* 制单人 */ + String pk_org = data.getString("pk_org"); /* 财务组织编码 */ + String updSql = "update " + tablename + " set nccdjzj = '" + pk_bill + "', ncczdr = '" + billmaker + "', nccfkdh ='" + billno + "',ncccwzzbm = '" + pk_org + "',nccfhxx = '" + msg + "',sfcgscnccfkd = 0 where requestid = " + requestid; + log.writeLog("修改当前单据NCC回传信息sql----> " + updSql); + rs.execute(updSql); + //获取回传的明细表付款单id + JSONArray items = data.getJSONArray("items"); + for (int i = 0; i < items.size(); i++) { + JSONObject resultData = items.getJSONObject(i); + String itemid = resultData.getString("itemid");/* 采购订单明细id */ + String pk_payitem = resultData.getString("pk_payitem"); /* 付款单id */ + String payplanid = resultData.getString("payplanid");/* 付款计划id */ + String upddelSql = "update " + tablename + "_dt2 set fkdid = '" + pk_payitem + "' where cgddmxid = '" + itemid + "' and fkjhwyid = '" + payplanid + "' and mainid = " + id ; + log.writeLog("修改明细表的明细数据sql---->" + upddelSql); + rs.execute(upddelSql); + } + }else{ + String updSql = "update " + tablename + " set sfcgscnccfkd = 1,nccfhxx = '" + msg + "' where requestid = " + requestid; + rs.execute(updSql); + AddJournal.addInfo("抛转预付单数据到NCC", json, result, "1", requestid); + if("yes".equals(xrnccsbcsfts)) { + ri.getRequestManager().setMessagecontent(msg); + return FAILURE_AND_CONTINUE; + }else{ + return SUCCESS; + } + } + AddJournal.addInfo("抛转预付单数据到NCC", json, result, "0", requestid); + }catch (Exception e){ + AddJournal.addInfo("抛转预付单数据到NCC", json, "出现异常---> " + e, "1", requestid); + if("yes".equals(xrnccsbcsfts)) { + ri.getRequestManager().setMessagecontent("数据传递出错-----> " + e.getMessage()); + return FAILURE_AND_CONTINUE; + }else{ + return SUCCESS; + } + } + + return SUCCESS; + } + + public static void main(String[] args) { + System.out.println(getNewDate("2022-06-30", "18:00:00")); + } + + public static String getNewDate(String startDate, String endDate){ + if(DUtil.getLastDayOfMonth(startDate).equals(startDate)){ + int i = endDate.compareTo("18:00:00"); + if (i >= 0){ + startDate = DUtil.getFirstDayOfNextMonth(startDate); + endDate = "00:30:00"; + } + } + + return startDate + " " + endDate; + } +} diff --git a/src/main/youhong_ai_jitu_src/com/api/lh/action/NCCAdvanceValidationAction.java b/src/main/youhong_ai_jitu_src/com/api/lh/action/NCCAdvanceValidationAction.java new file mode 100644 index 0000000..ff59efa --- /dev/null +++ b/src/main/youhong_ai_jitu_src/com/api/lh/action/NCCAdvanceValidationAction.java @@ -0,0 +1,114 @@ +package com.api.lh.action; + +import com.alibaba.fastjson.JSONArray; +import com.alibaba.fastjson.JSONObject; +import com.api.lh.port.AddJournal; +import com.wbi.util.Util; +import jntchina.util.HttpClientToDC; +import jntchina.util.NCCUtils; +import selfdev.util.base.BaseUtil; +import selfdev.util.log.LogTool; +import weaver.conn.RecordSet; +import weaver.file.Prop; +import weaver.interfaces.workflow.action.Action; +import weaver.soa.workflow.request.RequestInfo; + +/** + * @ClassName NCCPayableValidationAction + * @Description 提交预付单数据到NCC进行效验,判断数据是否一致 + * @Author louh + * @Date 2022/3/1 14:01 + * @Version 1.0 + */ +public class NCCAdvanceValidationAction implements Action { + static final String mode = Prop.getPropValue("DevToDC_jntchina","mode"); + static final String baseUrl = Prop.getPropValue("DevToDC_jntchina", mode + "_baseUrl"); + LogTool log = new LogTool("/log/lh/NCCAdvanceValidationAction", false); + @Override + public String execute(RequestInfo ri) { + JSONObject json = new JSONObject(); + JSONArray jsonArray = new JSONArray(); + RecordSet rs = new RecordSet(); + /* 流程requestid */ + String requestid = ri.getRequestid(); + /* 流程id */ + String workflowid = ri.getWorkflowid(); + try { + //获取表名 + String tablename = BaseUtil.getBaseInfoByParm("tablename", "workflow_bill", "1", "1", " and id in (select formid from workflow_base where id=" + workflowid + ")"); + + log.writeLog("requestid---> " + requestid + "对应表名tablename---> " + tablename); + + /* 主表数据id */ + String id = BaseUtil.getBaseInfoByParm("id", tablename, "requestid", requestid, ""); + + String sql = "select * from " + tablename + "_dt2 where mainid = " + id; + log.writeLog("查询明细表预付单数据sql-----> " + sql); + rs.execute(sql); + + while (rs.next()) { + JSONObject jsonObject = new JSONObject(); + /* 预付单付款计划唯一id */ + jsonObject.put("pk_item", Util.null2String(rs.getString("fkjhwyid"))); + /* 本次付款金额 */ + jsonObject.put("mny", Util.null2String(rs.getString("bcfkje"))); + jsonArray.add(jsonObject); + } + json.put("request", jsonArray); + log.writeLog("request: " + json); + + //获取token + String token = HttpClientToDC.getToken(); + log.writeLog("获取中台的数据token----》 " + token); + if ("".equals(weaver.general.Util.null2String(token))) { + ri.getRequestManager().setMessagecontent("未获取到中台token,请联系管理员查看问题!"); + return FAILURE_AND_CONTINUE; + } + String result = HttpClientToDC.sendPostApi(baseUrl + "/dcoaapi/ncc/payApplication", token, json.toJSONString()); + + + //result = NCCUtils.sendApi(baseUrl + "/nccloud/api/jitu/arap/busi/mnycheck", json.toJSONString()); + /* 解析返回的数据 */ + JSONObject result_json = (JSONObject) JSONObject.parse(result); + String allmsg = ""; + String success = result_json.getString("succ"); + String msg = result_json.getString("msg"); + + if("true".equals(success)) { + JSONArray data = result_json.getJSONArray("data"); + for (int i = 0; i < data.size(); i++) { + JSONObject item = data.getJSONObject(i); + String flag = item.getString("flag"); /* 是否正确 */ + if (!"Y".equals(flag)) { //数据不一致 + String pk_item = item.getString("pk_item"); + /* 根据预付单付款计划唯一id去查询表单对应数据 */ + String podb_sql = "select * from " + tablename + "_dt2 where fkjhwyid = '" + pk_item +"' and mainid = " + id; + log.writeLog("根据预付单明细行唯一id去查询表单对应数据sql-----> " + podb_sql); + rs.execute(podb_sql); + if(rs.next()){ + /* 采购订单号 */ + String cgddh = Util.null2String(rs.getString("cgddh")); + allmsg += cgddh + ","; + } + } + } + }else{ + ri.getRequestManager().setMessagecontent(msg); + AddJournal.addInfo("效验预付单据数据是否正确", json, result, "1", requestid); + return FAILURE_AND_CONTINUE; + } + if(!"".equals(allmsg)){ + allmsg += "数据效验不通过!请删除当前单据,重新获取NCC数据并选择!"; + ri.getRequestManager().setMessagecontent(allmsg); + AddJournal.addInfo("效验预付单据数据是否正确", json, result, "1", requestid); + return FAILURE_AND_CONTINUE; + } + AddJournal.addInfo("效验预付单据数据是否正确", json, result, "0", requestid); + }catch (Exception e) { + AddJournal.addInfo("效验预付单据数据是否正确", json, "出现异常" + e, "1", requestid); + ri.getRequestManager().setMessagecontent("数据传递出错----> " + e.getMessage()); + return FAILURE_AND_CONTINUE; + } + return SUCCESS; + } +} diff --git a/src/main/youhong_ai_jitu_src/com/api/lh/action/NCCAdvanceWriteOffAction.java b/src/main/youhong_ai_jitu_src/com/api/lh/action/NCCAdvanceWriteOffAction.java new file mode 100644 index 0000000..31d0db0 --- /dev/null +++ b/src/main/youhong_ai_jitu_src/com/api/lh/action/NCCAdvanceWriteOffAction.java @@ -0,0 +1,166 @@ +package com.api.lh.action; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.JSONObject; +import com.alibaba.fastjson.serializer.SerializerFeature; +import com.api.lh.config.DemoConfig; +import com.api.lh.port.AddJournal; +import com.api.lh.port.Billdata; +import com.api.lh.port.ErBxcontrast; +import jntchina.util.HttpClientToDC; +import selfdev.util.base.BaseUtil; +import selfdev.util.log.LogTool; +import weaver.conn.RecordSet; +import weaver.general.Util; +import weaver.interfaces.workflow.action.Action; +import weaver.soa.workflow.request.RequestInfo; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +/** + * @ClassName NCCAdvanceWriteOffAction + * @Description 供应商预付核销流程核销数据写入NCC + * @Author louh + * @Date 2022/4/13 14:06 + * @Version 1.0 + */ +public class NCCAdvanceWriteOffAction implements Action, DemoConfig { + LogTool log = new LogTool("/log/lh/NCCAdvanceWriteOffAction", false); + + @Override + public String execute(RequestInfo ri) { + String requestid = ri.getRequestid(); //requestid + String workflowid = ri.getWorkflowid(); //workflowid + RecordSet rs = new RecordSet(); + Billdata billdata = null; //存储主表数据 + List bxcontrasts = new ArrayList<>(); //存储明细数据 + + JSONObject json = null; //传递数据 + + try { + //获取表名 + String tablename = BaseUtil.getBaseInfoByParm("tablename", "workflow_bill", "1", "1", " and id in (select formid from workflow_base where id=" + workflowid + ")"); + log.writeLog("requestid---> " + requestid + "对应表名tablename---> " + tablename); + //主表数据id + String id = BaseUtil.getBaseInfoByParm("id", tablename, "requestid", requestid, ""); + String sql = "select xgyflc, count(xgyflc) as sum from " + tablename + "_dt1 where mainid = " + id + " group by xgyflc having count(xgyflc) > 1"; + log.writeLog("根据主表数据id查询当前明细表数据是否有多次选择同一个相关预付流程【requestid】sql---->" + sql); + rs.execute(sql); + if(rs.next()){ + ri.getRequestManager().setMessagecontent("同一张单据不允许多次选择相同的【相关预付流程】,请重新选择明细表不同的【相关预付流程】数据。"); + return FAILURE_AND_CONTINUE; + } + sql = "select * from " + tablename + "_dt1 where mainid = " + id; + log.writeLog("根据主表数据id查询当前明细数据sql----> " + sql); + rs.execute(sql); + while(rs.next()){ + //已核销金额 + double yhxje = Double.parseDouble(Util.null2String(rs.getString("yhxje")) == "" ? "0.00": Util.null2String(rs.getString("yhxje"))); + //剩余未核销金额 + double sywhxje = Double.parseDouble(Util.null2String(rs.getString("sywhxje"))); + //预付金额 + double yfje = Double.parseDouble(Util.null2String(rs.getString("yfje"))); + //本次核销金额 + double bchxje = Double.parseDouble(Util.null2String(rs.getString("bchxje")) == "" ? "0.00" : Util.null2String(rs.getString("bchxje"))); + //相关预付流程 + String xgyflc = Util.null2String(rs.getString("xgyflc")); + //本次核销金额大于剩余未核销金额 + if(bchxje > sywhxje){ + ri.getRequestManager().setMessagecontent("【相关预付流程 " + xgyflc + "】 剩余未核销金额【" + sywhxje + "】元、本次核销金额【" + bchxje + "】、大于【剩余未核销金额】,请重新填写【本次核销金额】"); + return FAILURE_AND_CONTINUE; + } + //当前条数共计合计金额 + double money = yhxje + bchxje; + if(money > yfje){ + ri.getRequestManager().setMessagecontent("【相关预付流程 " + xgyflc + "】 已核销金额【" + yhxje + "】元、本次核销金额【" + bchxje + "】、合计【" + money + "】元!大于预付金额,请重新填写【本次核销金额】"); + return FAILURE_AND_CONTINUE; + } + + //ncc借款单号 + String nccdh = Util.null2String(rs.getString("nccdh")); + ErBxcontrast bxcontrast = new ErBxcontrast(nccdh,"",bchxje + ""); + bxcontrasts.add(bxcontrast); + + } + sql = "select * from " + tablename + " where requestid = " + requestid; + log.writeLog("查询当前主表数据sql------> " + sql); + rs.execute(sql); + if(rs.next()){ + String sqr = Util.null2String(rs.getString("sqr"));//申请人 + //申请人工号 + String workcode = BaseUtil.getBaseInfoByParm("workcode", "hrmresource", "id", sqr, ""); + String sqbm = Util.null2String(rs.getString("sqbm")); //申请部门 + //申请部门编码 + String departmentcode = BaseUtil.getBaseInfoByParm("departmentcode", "hrmdepartment", "id", sqbm, ""); + String gsmc = Util.null2String(rs.getString("gsmc")); + billdata = new Billdata(gsmc, //公司名称 + "", + "", + "", + Util.null2String(rs.getString("sqrq")), //申请日期 + Util.null2String(rs.getString("hxje")), //核销金额 + gsmc, + "", + workcode, + "", + "", + requestid, + Util.null2String(rs.getString("lcbh")), //流程编号 + "", + departmentcode, //申请部门 + Util.null2String(rs.getString("sm")), //说明 + bxcontrasts + ); + } + + String result = JSON.toJSONString(billdata, SerializerFeature.DisableCircularReferenceDetect); + json = (JSONObject) JSONObject.toJSON(billdata); + //获取token + String token = HttpClientToDC.getToken(); + log.writeLog("获取中台的数据token----》 " + token); + if ("".equals(Util.null2String(token))) { + ri.getRequestManager().setMessagecontent("为获取到中台token,请联系管理员查看问题!"); + AddJournal.addInfo("还款单接口", json, "未获取到中台token,请联系管理员查看问题!", "1", requestid); + return FAILURE_AND_CONTINUE; + } + + //调用中台还款单接口 + log.writeLog("开始调用中台还款单接口--------"); + result = HttpClientToDC.sendPostApi( baseUrl + "/dcoaapi/ncc/repaymentBill", token, result); + JSONObject parse = (JSONObject) JSONObject.parse(result); + log.writeLog("返回数据----- " + parse.toJSONString()); + String success = parse.getString("succ"); + String msg = parse.getString("msg"); + if(success.equals("true")) { + JSONObject data = parse.getJSONObject("data"); + String pk_bill = data.getString("pk_bill");/* ncc单据id */ + String billno = data.getString("billno"); /* ncc单据号 */ + String updSql = "update " + tablename + " set nccdjzj = '" + pk_bill + "', nccfkdh ='" + billno + "', nccfhxx = '" + msg + "',sfcgscnccfkd = 0 where requestid = " + requestid; + log.writeLog("修改当前单据NCC回传信息sql----> " + updSql); + rs.execute(updSql); + + }else{ + String updSql = "update " + tablename + " set sfcgscnccfkd = 1,nccfhxx = '" + msg + "' where requestid = " + requestid; + rs.execute(updSql); + AddJournal.addInfo("还款单接口", json, result, "1", requestid); + ri.getRequestManager().setMessagecontent(msg); + return FAILURE_AND_CONTINUE; + } + AddJournal.addInfo("还款单接口", json, result, "0", requestid); + }catch (Exception e){ + ri.getRequestManager().setMessagecontent("数据传递NCC出错----->" + e); + AddJournal.addInfo("还款单接口",json, "出现异常+++" + e, "1", requestid); + return FAILURE_AND_CONTINUE; + } + return SUCCESS; + } + + public static void main(String[] args) { + double yhxje = Double.parseDouble("" == "" ? "0.00": ""); + System.out.println(yhxje); + + } +} diff --git a/src/main/youhong_ai_jitu_src/com/api/lh/action/NCCPayableDataAction.java b/src/main/youhong_ai_jitu_src/com/api/lh/action/NCCPayableDataAction.java new file mode 100644 index 0000000..555a680 --- /dev/null +++ b/src/main/youhong_ai_jitu_src/com/api/lh/action/NCCPayableDataAction.java @@ -0,0 +1,180 @@ +package com.api.lh.action; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.JSONArray; +import com.alibaba.fastjson.JSONObject; +import com.alibaba.fastjson.serializer.SerializerFeature; +import com.api.lh.port.AddJournal; +import jntchina.util.HttpClientToDC; +import jntchina.util.NCCUtils; +import selfdev.util.log.LogTool; +import weaver.file.Prop; +import weaver.general.Util; +import weaver.interfaces.workflow.action.Action; + +import javax.ws.rs.POST; +import javax.ws.rs.Path; +import javax.ws.rs.Produces; +import java.util.HashMap; +import java.util.Map; + +/** + * @ClassName NCCPayableDataAction + * @Description 获取ncc应付单数据 + * @Author louh + * @Date 2022/2/24 10:17 + * @Version 1.0 + */ +@Path("/Data") +public class NCCPayableDataAction { + LogTool log = new LogTool("/log/lh/action/NCCPayableDataAction", false); + static final String mode = Prop.getPropValue("DevToDC_jntchina","mode"); + static final String baseUrl = Prop.getPropValue("DevToDC_jntchina", mode + "_baseUrl"); + + /* 应付单查询接口 */ + @POST + @Path("/getNCCPayableData") + @Produces({"application/json"}) + public String getNCCPayableData(String data){ + JSONObject json = null; + log.writeLog("应付单data: " + data); + String result = ""; + Map return_map = new HashMap<>(); + try { + json = (JSONObject) JSONObject.parse(data); + + //获取token + String token = HttpClientToDC.getToken(); + log.writeLog("获取中台的数据应付接口token----》 " + token); + if ("".equals(Util.null2String(token))) { + return_map.put("code", 500); + return_map.put("msg", "未获取到中台token,请联系管理员查看问题!"); + return return_map.toString(); + } + result = HttpClientToDC.sendPostApi(baseUrl + "/dcoaapi/ncc/payableBillSearch", token, data); + JSONObject parse = (JSONObject) JSONObject.parse(result); + String succ = parse.getString("succ"); + JSONArray jsonArray = new JSONArray(); + if ("true".equals(succ)){ + JSONArray datas = parse.getJSONArray("data"); + for (int i = 0; i < datas.size(); i++) { + JSONObject item = datas.getJSONObject(i); + String money = item.getString("money"); //剩余未付金额 + double v = Double.parseDouble(money); + if(v > 0){ + //获取原对象到账日期 + String denddate = item.getString("denddate"); + if(!"".equals(denddate)) { + item.remove("denddate"); + //生成新的到账日期 + denddate = denddate.substring(0, 10); + item.put("denddate", denddate); + } + jsonArray.add(item); + } + } + //删除原有数据 + parse.remove("data"); + parse.put("data", jsonArray); + }else{ + return_map.put("code", 500); + return_map.put("msg", "获取信息失败"); + AddJournal.addInfo("应付单查询接口", json, result, "1", ""); + return JSON.toJSONString(return_map, SerializerFeature.DisableCircularReferenceDetect); + } + result = parse.toJSONString(); + //result = NCCUtils.sendApi(baseUrl + "/nccloud/api/jitu/arap/busi/payablebillquery", data); + log.writeLog("result: " + result); + AddJournal.addInfo("应付单查询接口", json, result, "0", ""); + }catch (Exception e){ + log.writeLog("出现异常: " + e); + return_map.put("code", 500); + return_map.put("msg", "出现异常 " + e); + AddJournal.addInfo("应付单查询接口", json, "出现异常---> " + e, "1", ""); + return JSON.toJSONString(return_map, SerializerFeature.DisableCircularReferenceDetect); + } + return result; + } + + + /* 预付单付款计划查询接口 */ + @POST + @Path("/getNCCAdvanceData") + @Produces({"application/json"}) + public String getNCCAdvanceData(String data){ + + JSONObject json = null; + log.writeLog("预付单data: " + data); + String result = ""; + Map return_map = new HashMap<>(); + try { + json = (JSONObject) JSONObject.parse(data); + //获取token + String token = HttpClientToDC.getToken(); + log.writeLog("获取中台预付单的数据token----》 " + token); + if ("".equals(Util.null2String(token))) { + return_map.put("code", 500); + return_map.put("msg", "未获取到中台token,请联系管理员查看问题!"); + return return_map.toString(); + } + + result = HttpClientToDC.sendPostApi(baseUrl + "/dcoaapi/ncc/purchasePaymentBillSearch", token, data); + + //result = NCCUtils.sendApi(baseUrl + "/nccloud/api/jitu/arap/busi/orderquery", data); + JSONObject parse = (JSONObject) JSONObject.parse(result); + String succ = parse.getString("succ"); + JSONArray jsonArray = new JSONArray(); + if ("true".equals(succ)){ + JSONArray datas = parse.getJSONArray("data"); + for (int i = 0; i < datas.size(); i++) { + JSONObject item = datas.getJSONObject(i); + String money = item.getString("money"); //剩余未付金额 + double v = Double.parseDouble(money); + if(v > 0){ + //获取原对象到账日期 + String denddate = item.getString("denddate"); + if(!"".equals(denddate)) { + item.remove("denddate"); + //生成新的到账日期 + denddate = denddate.substring(0, 10); + item.put("denddate", denddate); + } + jsonArray.add(item); + } + } + //删除原有数据 + parse.remove("data"); + parse.put("data", jsonArray); + }else{ + return_map.put("code", 500); + return_map.put("msg", "获取信息失败"); + AddJournal.addInfo("预付单计划查询接口", json, result, "1", ""); + return JSON.toJSONString(return_map, SerializerFeature.DisableCircularReferenceDetect); + } + result = parse.toJSONString(); + log.writeLog("result: " + result); + AddJournal.addInfo("预付单计划查询接口", json, result, "0", ""); + }catch (Exception e){ + log.writeLog("出现异常: " + e); + return_map.put("code", 500); + return_map.put("msg", "出现异常 " + e); + AddJournal.addInfo("预付单计划查询接口", json, "出现异常---> " + e, "1", ""); + return JSON.toJSONString(return_map, SerializerFeature.DisableCircularReferenceDetect); + } + + return result; + } + + public static void main(String[] args) { + //NCCPayableDataAction nccPayableDataAction = new NCCPayableDataAction(); + //String nccPayableData = nccPayableDataAction.getNCCPayableData("{\"pk_org\":\"JTSDCN0001\",\"begindate\":\"2020-03-17\",\"enddate\":\"2022-03-17\",\"pk_supplier\":\"JTSDCN0030\"}"); + //System.out.println(nccPayableData); + //String token = HttpClientToDC.getToken(); + //System.out.println(token); + // 密码 + //final String password = Prop.getPropValue("DevToDC_jntchina", mode+"_password"); + //System.out.println("密码:" + password); + String time = "2021-01-01 00:00:00"; + System.out.println(time.substring(0,10)); + } +} diff --git a/src/main/youhong_ai_jitu_src/com/api/lh/action/NCCPayableTossAction.java b/src/main/youhong_ai_jitu_src/com/api/lh/action/NCCPayableTossAction.java new file mode 100644 index 0000000..2072d8e --- /dev/null +++ b/src/main/youhong_ai_jitu_src/com/api/lh/action/NCCPayableTossAction.java @@ -0,0 +1,182 @@ +package com.api.lh.action; + +import com.alibaba.fastjson.JSONArray; +import com.alibaba.fastjson.JSONObject; +import com.api.lh.port.AddJournal; +import com.api.lh.port.Items; +import com.api.lh.port.StuData; +import jntchina.util.HttpClientToDC; +import selfdev.util.base.BaseUtil; +import selfdev.util.log.LogTool; +import weaver.conn.RecordSet; +import weaver.file.Prop; +import weaver.general.Util; +import weaver.interfaces.workflow.action.Action; +import weaver.soa.workflow.request.RequestInfo; + +import java.text.SimpleDateFormat; +import java.util.ArrayList; +import java.util.Date; +import java.util.List; + +/** + * @ClassName NCCPayableTossAction + * @Description 抛转应付单数据到NCC + * @Author louh + * @Date 2022/3/1 14:35 + * @Version 1.0 + */ +public class NCCPayableTossAction implements Action { + LogTool log = new LogTool("/log/lh/action/NCCPayableTossAction", false); + static final String mode = Prop.getPropValue("DevToDC_jntchina","mode"); + static final String baseUrl = Prop.getPropValue("DevToDC_jntchina", mode + "_baseUrl"); + + @Override + public String execute(RequestInfo ri) { + SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); + String date = dateFormat.format(new Date()); + + String startDate = date.substring(0, 10); + String endDate = date.substring(11); + date = NCCAdvanceTossAction.getNewDate(startDate, endDate); + JSONObject json = new JSONObject(); + RecordSet rs = new RecordSet(); + String xrnccsbcsfts = ""; + String requestid = ri.getRequestid(); + String workflowid = ri.getWorkflowid(); + /* 单据属性 */ + String djsx = ""; + try{ + //获取表名 + String tablename = BaseUtil.getBaseInfoByParm("tablename", "workflow_bill", "1", "1", " and id in (select formid from workflow_base where id=" + workflowid + ")"); + log.writeLog("requestid---> " + requestid + "对应表名tablename---> " + tablename); + /* 主表数据id */ + String id = BaseUtil.getBaseInfoByParm("id", tablename, "requestid", requestid, ""); + /* 流程编号 */ + String lcbh = BaseUtil.getBaseInfoByParm("lcbh", tablename, "requestid", requestid, ""); + /* 供应商名称 */ + String gysmc = BaseUtil.getBaseInfoByParm("gysmc", tablename, "requestid", requestid, ""); + /* 付款金额 */ + String fkje = BaseUtil.getBaseInfoByParm("jshjje", tablename, "requestid", requestid, ""); + /* 公司名称(NCC财务组织编码) */ + String gsmc = BaseUtil.getBaseInfoByParm("gsmc", tablename, "requestid", requestid, ""); + /* 制单人 */ + String zdr = BaseUtil.getBaseInfoByParm("zdr", tablename, "requestid", requestid, ""); + /* 制单人编码 */ + String workcode = BaseUtil.getBaseInfoByParm("workcode", "hrmresource", "id", zdr, ""); + /* 部门 */ + String bm = BaseUtil.getBaseInfoByParm("fygsbm", tablename, "requestid", requestid, ""); + /* 部门编码 */ + String departmentcode = BaseUtil.getBaseInfoByParm("departmentcode", "hrmdepartment", "id", bm, ""); + /* 银行账号 */ + String yxhm = BaseUtil.getBaseInfoByParm("yxhm", tablename, "requestid", requestid, ""); + //是否提示报错信息 + xrnccsbcsfts = BaseUtil.getBaseInfoByParm("xrnccsbcsfts", tablename, "requestid", requestid, ""); + //银行付款备注 + String yxfkbz = BaseUtil.getBaseInfoByParm("yxfkbz", tablename, "requestid", requestid, ""); + double je = Double.parseDouble(fkje.replaceAll(",", "")); + String sql = "select * from " + tablename + "_dt2 where mainid = " + id; + log.writeLog("查询应付单明细数据sql-----> " + sql); + rs.execute(sql); + List list = new ArrayList<>(); + while(rs.next()){ + /* 本次付款金额 */ + String je1 = Util.null2String(rs.getString("je")); + double v = Double.parseDouble(je1.replaceAll(",", "")); + /* 应付单明细行唯一id */ + String yfdmxxwyid = Util.null2String(rs.getString("yfdmxxwyid")); + /* 应付单据号 */ + String yfdh = Util.null2String(rs.getString("yfdh")); + /* 摘要 */ + String zy = Util.null2String(rs.getString("zy")); + /* 单据属性 */ + djsx = Util.null2String(rs.getString("djsx")); + /* 物料 */ + String wl = Util.null2String(rs.getString("wl")); + + /* 成本中心 */ + String wd = Util.null2String(rs.getString("wd")); + //部门编码 + String bmbm = Util.null2String(rs.getString("bmbm")); + Items items = new Items("1", gysmc,departmentcode, "", "0", + "CNY",v + "","1",v + "", + "1",v + "","1",v + "","1", + v + "",yfdmxxwyid,"","",yfdh, zy, djsx, + wl, bmbm, yxhm, "", wd); + list.add(items); + } + StuData stuData = new StuData(gsmc,djsx,date,"1","CNY", + yxhm,je + "","1",je + "","1", + je + "","1",je + "",workcode,requestid,lcbh, + gysmc,list,departmentcode, "", yxfkbz); + json = (JSONObject) JSONObject.toJSON(stuData); + log.writeLog("json-----> " + json); + + //获取token + String token = HttpClientToDC.getToken(); + log.writeLog("获取中台的数据token----》 " + token); + if ("".equals(weaver.general.Util.null2String(token))) { + ri.getRequestManager().setMessagecontent("未获取到中台token,请联系管理员查看问题!"); + return FAILURE_AND_CONTINUE; + } + String result = HttpClientToDC.sendPostApi(baseUrl + "/dcoaapi/ncc/sendPaymentBill", token, json.toJSONString()); + + /* 调用NCC付款单接口 */ + //String result = NCCUtils.sendApi(baseUrl + "/nccloud/api/jitu/arap/fkbill/insert", json.toJSONString()); + log.writeLog("result----> " + result); + + JSONObject parse = (JSONObject) JSONObject.parse(result); + String success = parse.getString("succ"); + String msg = parse.getString("msg"); + if(success.equals("true")) { + JSONObject data = parse.getJSONObject("data"); + String billno = data.getString("billno"); /* ncc单据号 */ + String pk_bill = data.getString("pk_bill");/* ncc单据主键 */ + String billmaker = data.getString("billmaker"); /* 制单人 */ + String pk_org = data.getString("pk_org"); /* 财务组织编码 */ + String updSql = "update " + tablename + " set nccdjzj = '" + pk_bill + "', ncczdr = '" + billmaker + "', nccfkdh ='" + billno + "',ncccwzzbm = '" + pk_org + "', nccfhxx = '" + msg + "',sfcgscnccfkd = 0 where requestid = " + requestid; + log.writeLog("修改当前单据NCC回传信息sql----> " + updSql); + rs.execute(updSql); + //获取回传的明细表付款单id + JSONArray items = data.getJSONArray("items"); + for (int i = 0; i < items.size(); i++) { + JSONObject resultData = items.getJSONObject(i); + String itemid = resultData.getString("itemid");/* 应付单明细id */ + String pk_payitem = resultData.getString("pk_payitem"); /* 付款单id */ + String upddelSql = "update " + tablename + "_dt2 set fkdid = '" + pk_payitem + "' where yfdmxxwyid = '" + itemid + "' and mainid = " + id ; + log.writeLog("修改明细表的明细数据sql---->" + upddelSql); + rs.execute(upddelSql); + } + }else{ + String updSql = "update " + tablename + " set sfcgscnccfkd = 1,nccfhxx = '" + msg + "' where requestid = " + requestid; + rs.execute(updSql); + AddJournal.addInfo("抛转应付单数据到NCC", json, result, "1", requestid); + if("yes".equals(xrnccsbcsfts)) { + ri.getRequestManager().setMessagecontent(msg); + return FAILURE_AND_CONTINUE; + }else{ + return SUCCESS; + } + } + AddJournal.addInfo("抛转应付单数据到NCC", json, result, "0", requestid); + + }catch (Exception e){ + + AddJournal.addInfo("抛转应付单数据到NCC", json, "出现异常---> " + e, "1", requestid); + if("yes".equals(xrnccsbcsfts)) { + ri.getRequestManager().setMessagecontent("数据传递出错-----> " + e.getMessage()); + return FAILURE_AND_CONTINUE; + }else{ + return SUCCESS; + } + } + + return SUCCESS; + } + + + public static void main(String[] args) { + + System.out.println(NCCAdvanceTossAction.getNewDate("2022-06-29", "18:00:00")); + } +} diff --git a/src/main/youhong_ai_jitu_src/com/api/lh/action/NCCPayableValidationAction.java b/src/main/youhong_ai_jitu_src/com/api/lh/action/NCCPayableValidationAction.java new file mode 100644 index 0000000..838561f --- /dev/null +++ b/src/main/youhong_ai_jitu_src/com/api/lh/action/NCCPayableValidationAction.java @@ -0,0 +1,113 @@ +package com.api.lh.action; + +import com.alibaba.fastjson.JSONArray; +import com.alibaba.fastjson.JSONObject; +import com.api.lh.port.AddJournal; +import com.wbi.util.Util; +import jntchina.util.HttpClientToDC; +import jntchina.util.NCCUtils; +import selfdev.util.base.BaseUtil; +import selfdev.util.log.LogTool; +import weaver.conn.RecordSet; +import weaver.file.Prop; +import weaver.interfaces.workflow.action.Action; +import weaver.soa.workflow.request.RequestInfo; + +/** + * @ClassName NCCPayableValidationAction + * @Description 提交应付单数据到NCC进行效验,判断数据是否一致 + * @Author louh + * @Date 2022/3/1 14:01 + * @Version 1.0 + */ +public class NCCPayableValidationAction implements Action { + static final String mode = Prop.getPropValue("DevToDC_jntchina","mode"); + static final String baseUrl = Prop.getPropValue("DevToDC_jntchina", mode + "_baseUrl"); + + LogTool log = new LogTool("/log/lh/NCCPayableValidationAction", false); + @Override + public String execute(RequestInfo ri) { + JSONObject json = new JSONObject(); + JSONArray jsonArray = new JSONArray(); + RecordSet rs = new RecordSet(); + /* 流程requestid */ + String requestid = ri.getRequestid(); + /* 流程id */ + String workflowid = ri.getWorkflowid(); + try { + //获取表名 + String tablename = BaseUtil.getBaseInfoByParm("tablename", "workflow_bill", "1", "1", " and id in (select formid from workflow_base where id=" + workflowid + ")"); + + log.writeLog("requestid---> " + requestid + "对应表名tablename---> " + tablename); + + /* 主表数据id */ + String id = BaseUtil.getBaseInfoByParm("id", tablename, "requestid", requestid, ""); + + String sql = "select * from " + tablename + "_dt2 where mainid = " + id; + log.writeLog("查询明细表应付单数据sql-----> " + sql); + rs.execute(sql); + + while (rs.next()) { + JSONObject jsonObject = new JSONObject(); + /* 应付单明细行唯一id */ + jsonObject.put("pk_item", Util.null2String(rs.getString("yfdmxxwyid"))); + /* 本次付款金额 */ + jsonObject.put("mny", Util.null2String(rs.getString("je"))); + jsonArray.add(jsonObject); + } + json.put("request", jsonArray); + log.writeLog("request: " + json); + + //获取token + String token = HttpClientToDC.getToken(); + log.writeLog("获取中台的数据token----》 " + token); + if ("".equals(weaver.general.Util.null2String(token))) { + ri.getRequestManager().setMessagecontent("未获取到中台token,请联系管理员查看问题!"); + return FAILURE_AND_CONTINUE; + } + String result = HttpClientToDC.sendPostApi(baseUrl + "/dcoaapi/ncc/payApplication", token, json.toJSONString()); + + //result = NCCUtils.sendApi(baseUrl + "nccloud/api/jitu/arap/busi/mnycheck", json.toJSONString()); + /* 解析返回的数据 */ + JSONObject result_json = (JSONObject) JSONObject.parse(result); + String allmsg = ""; + String success = result_json.getString("succ"); + String msg = result_json.getString("msg"); + if("true".equals(success)){ + JSONArray data = result_json.getJSONArray("data"); + for (int i = 0; i < data.size(); i++) { + JSONObject item = data.getJSONObject(i); + String flag = item.getString("flag"); /* 是否正确 */ + if(!"Y".equals(flag)) { //数据不一致 + String pk_item = item.getString("pk_item"); /* 应付款单号 */ + /* 根据应付单明细行唯一id去查询表单对应数据 */ + String podb_sql = "select * from " + tablename + "_dt2 where yfdmxxwyid = '" + pk_item +"' and mainid = " + id; + log.writeLog("根据应付单明细行唯一id去查询表单对应数据sql-----> " + podb_sql); + rs.execute(podb_sql); + if(rs.next()){ + /* 采购订单号 */ + String cgddh = Util.null2String(rs.getString("cgddh")); + allmsg += cgddh + ","; + } + } + } + }else{ + ri.getRequestManager().setMessagecontent(msg); + AddJournal.addInfo("效验应付单据数据是否正确", json, result, "1", requestid); + return FAILURE_AND_CONTINUE; + } + if(!"".equals(allmsg)){ + allmsg += "数据效验不通过!请删除当前单据,重新获取NCC数据并选择!"; + ri.getRequestManager().setMessagecontent(allmsg); + AddJournal.addInfo("效验应付单据数据是否正确", json, result, "1", requestid); + return FAILURE_AND_CONTINUE; + } + AddJournal.addInfo("效验应付单据数据是否正确", json, result, "0", requestid); + }catch (Exception e) { + AddJournal.addInfo("效验应付单据数据是否正确", json, "出现异常" + e, "1", requestid); + ri.getRequestManager().setMessagecontent("数据传递出错----> " + e.getMessage()); + return FAILURE_AND_CONTINUE; + } + return SUCCESS; + } +} diff --git a/src/main/youhong_ai_jitu_src/com/api/lh/action/UpdPaymentAccountAction.java b/src/main/youhong_ai_jitu_src/com/api/lh/action/UpdPaymentAccountAction.java new file mode 100644 index 0000000..ebb05d0 --- /dev/null +++ b/src/main/youhong_ai_jitu_src/com/api/lh/action/UpdPaymentAccountAction.java @@ -0,0 +1,111 @@ +package com.api.lh.action; + +import com.api.lh.config.DemoConfig; +import selfdev.util.log.LogTool; +import weaver.conn.RecordSet; +import weaver.conn.RecordSetTrans; +import weaver.general.Util; +import weaver.interfaces.workflow.action.Action; +import weaver.soa.workflow.request.RequestInfo; + +/** + * @ClassName UpdPaymentAccountData + * @Description 修改 付款申请(NCC集成)预付台账 数据 + * @Author louh + * @Date 2022/4/21 17:38 + * @Version 1.0 + */ +public class UpdPaymentAccountAction implements Action, DemoConfig { + @Override + public String execute(RequestInfo ri) { + RecordSet rs = new RecordSet(); + RecordSet rs1 = new RecordSet(); + RecordSet rs2 = new RecordSet(); + RecordSetTrans rst = new RecordSetTrans(); + rst.setAutoCommit(false); + String requestid = ri.getRequestid(); + String workflowid = ri.getWorkflowid(); + try { + //获取表名 + String tablename = getTableName(workflowid); + log.writeLog("requestid---> " + requestid + "对应表名tablename---> " + tablename); + //获取当前表单数据id + String id = getId(tablename, requestid); + String sql = "select yfkqptzmxid, " + + "sum(bchxje) as hxje," + + " avg(yfje) as zje," + + " avg(sywhxje) as whxje," + + " avg(xgyflc) as req, avg(yhxje) as yhxje1 " + + "from " + tablename + "_dt1 " + + "where mainid = '" + id + "'" + + "group by yfkqptzmxid having count(yfkqptzmxid) > 0"; + log.writeLog("查询明细表1sql-----> " + sql); + rs.execute(sql); + while(rs.next()){ + String yfkqptzmxid = Util.null2String(rs.getString("yfkqptzmxid")); //预付款欠票台账明细id + double bchxje = Double.parseDouble(Util.null2String(rs.getString("hxje")) == "" ? "0.00" : Util.null2String(rs.getString("hxje"))); //核销金额 + double yfje = Double.parseDouble(Util.null2String(rs.getString("zje"))==""?"0.00":Util.null2String(rs.getString("zje")));//预付金额 + double sywhxje = Double.parseDouble(Util.null2String(rs.getString("whxje")) == "" ? "0.00":Util.null2String(rs.getString("whxje"))); //未核销金额 + String req = Util.null2String(rs.getString("req")); //相关预付流程requestid + double yhxje = Double.parseDouble(Util.null2String(rs.getString("yhxje1")) == "" ? "0.00" : Util.null2String(rs.getString("yhxje1"))); //核销金额 + + if (bchxje > yfje){ + ri.getRequestManager().setMessagecontent("预付欠票台账明细id【" + yfkqptzmxid + "】本次核销金额【" + bchxje + "】大于预付总金额【" + yfje + "】"); + return FAILURE_AND_CONTINUE; + } + + //根据供应商预付欠票台账明细id查询该数据为还款金额 + String sql1 = "select * from uf_fksqyfb_dt1 where id = '" + yfkqptzmxid + "'"; + log.writeLog("获取剩余未核销金额明细sql-----> " + sql1); + rs1.execute(sql1); + String xghxlc = ""; + double sywhxje2 = 0.00; + if(rs1.next()){ + xghxlc = Util.null2String(rs1.getString("xghxlc")); //相关核销流程 + sywhxje2 = Double.parseDouble(Util.null2String(rs1.getString("sywhxje")) == "" ? "0.00":Util.null2String(rs1.getString("sywhxje"))); //剩余未核销金额 + } + if ("".equals(xghxlc)){ + xghxlc = requestid; + }else{ + xghxlc += "," + requestid; + } + yhxje = yhxje + bchxje; + if(sywhxje2 < bchxje){ + ri.getRequestManager().setMessagecontent("预付欠票台账明细id【" + yfkqptzmxid + "】本次核销金额【" + bchxje + "】大于剩余未核销金额【" + sywhxje2 + "】,请重新选取抵扣明细数据,获取最新的台账数据!"); + return FAILURE_AND_CONTINUE; + } + sywhxje2 = sywhxje2 - bchxje; + + String updSql = "update uf_fksqyfb_dt1 set yhxje = '" + yhxje + "', sywhxje = '" + sywhxje2 + "', xghxlc = '" + xghxlc + "' where id = " + yfkqptzmxid; + log.writeLog("修改供应商预付欠票台账明细sql-----> " + updSql); + rst.executeSql(updSql); + //查询主表总预付金额及核销金额 + sql1 = "select * from uf_fksqyfb where qqid = '" + req + "'"; + log.writeLog("查询主表总预付金额及核销金额sql----> " + sql1); + rs1.execute(sql1); + if(rs1.next()){ + double fkje = Double.parseDouble(Util.null2String(rs1.getString("fkje"))==""?"0.00":Util.null2String(rs1.getString("fkje")));//付款金额 + double yhxje1 = Double.parseDouble(Util.null2String(rs1.getString("yhxje"))==""?"0.00":Util.null2String(rs1.getString("yhxje")));//已核销金额 + double sywhxje1 = Double.parseDouble(Util.null2String(rs1.getString("sywhxje"))==""?"0.00":Util.null2String(rs1.getString("sywhxje")));//剩余金额 + + if(bchxje > sywhxje1){ + ri.getRequestManager().setMessagecontent("本次核销金额【" + bchxje + "】大于剩余为核销金额【" + sywhxje1 + "】"); + return FAILURE_AND_CONTINUE; + } + bchxje = bchxje + yhxje1; + sywhxje1 = fkje - bchxje; + updSql = "update uf_fksqyfb set sywhxje = '" + sywhxje1 + "', yhxje = '" + bchxje + "' where qqid = '" + req + "'"; + log.writeLog("修改供应商预付欠票台账主数据sql-----> " + updSql); + //rst.executeSql(updSql); + rs2.execute(updSql); + } + } + rst.commit(); + } catch (Exception e) { + rst.rollback(); + ri.getRequestManager().setMessagecontent("修改台账出现异常-----" + e); + return FAILURE_AND_CONTINUE; + } + return SUCCESS; + } +} diff --git a/src/main/youhong_ai_jitu_src/com/api/lh/action/UpdPaymentAccountActionYY.java b/src/main/youhong_ai_jitu_src/com/api/lh/action/UpdPaymentAccountActionYY.java new file mode 100644 index 0000000..423b58f --- /dev/null +++ b/src/main/youhong_ai_jitu_src/com/api/lh/action/UpdPaymentAccountActionYY.java @@ -0,0 +1,109 @@ +package com.api.lh.action; + +import com.api.lh.config.DemoConfig; +import weaver.conn.RecordSet; +import weaver.conn.RecordSetTrans; +import weaver.general.Util; +import weaver.interfaces.workflow.action.Action; +import weaver.soa.workflow.request.RequestInfo; + +/** + * @ClassName UpdPaymentAccountData + * @Description 修改 付款申请(NCC集成)预付台账 数据 + * @Author ycf + * @Date 2022/4/21 17:38 + * @Version 1.0 + */ +public class UpdPaymentAccountActionYY implements Action, DemoConfig { + @Override + public String execute(RequestInfo ri) { + RecordSet rs = new RecordSet(); + RecordSet rs1 = new RecordSet(); + RecordSet rs2 = new RecordSet(); + RecordSetTrans rst = new RecordSetTrans(); + rst.setAutoCommit(false); + String requestid = ri.getRequestid(); + String workflowid = ri.getWorkflowid(); + try { + //获取表名 + String tablename = getTableName(workflowid); + log.writeLog("requestid---> " + requestid + "对应表名tablename---> " + tablename); + //获取当前表单数据id + String id = getId(tablename, requestid); + String sql = "select yfkqptzmxid, " + + "sum(bchxje) as hxje," + + " avg(yfje) as zje," + + " avg(sywhxje) as whxje," + + " avg(xgyflc) as req, avg(yhxje) as yhxje1 " + + "from " + tablename + "_dt1 " + + "where mainid = '" + id + "'" + + "group by yfkqptzmxid having count(yfkqptzmxid) > 0"; + log.writeLog("查询明细表1sql-----> " + sql); + rs.execute(sql); + while(rs.next()){ + String yfkqptzmxid = Util.null2String(rs.getString("yfkqptzmxid")); //预付款欠票台账明细id + double bchxje = Double.parseDouble(Util.null2String(rs.getString("hxje")) == "" ? "0.00" : Util.null2String(rs.getString("hxje"))); //核销金额 + double yfje = Double.parseDouble(Util.null2String(rs.getString("zje"))==""?"0.00":Util.null2String(rs.getString("zje")));//预付金额 + double sywhxje = Double.parseDouble(Util.null2String(rs.getString("whxje")) == "" ? "0.00":Util.null2String(rs.getString("whxje"))); //未核销金额 + String req = Util.null2String(rs.getString("req")); //相关预付流程requestid + double yhxje = Double.parseDouble(Util.null2String(rs.getString("yhxje1")) == "" ? "0.00" : Util.null2String(rs.getString("yhxje1"))); //核销金额 + + if (bchxje > yfje){ + ri.getRequestManager().setMessagecontent("预付欠票台账明细id【" + yfkqptzmxid + "】本次核销金额【" + bchxje + "】大于预付总金额【" + yfje + "】"); + return FAILURE_AND_CONTINUE; + } + + //根据供应商预付欠票台账明细id查询该数据为还款金额 + String sql1 = "select * from uf_gysqktzyy_dt1 where id = '" + yfkqptzmxid + "'"; + + rs1.execute(sql1); + String xghxlc = ""; + double sywhxje2 = 0.00; + if(rs1.next()){ + xghxlc = Util.null2String(rs1.getString("xghxlc")); //相关核销流程 + sywhxje2 = Double.parseDouble(Util.null2String(rs1.getString("sywhxje")) == "" ? "0.00":Util.null2String(rs1.getString("sywhxje"))); //剩余未核销金额 + } + if ("".equals(xghxlc)){ + xghxlc = requestid; + }else{ + xghxlc += "," + requestid; + } + yhxje = yhxje + bchxje; + if(sywhxje2 < bchxje){ + ri.getRequestManager().setMessagecontent("预付欠票台账明细id【" + yfkqptzmxid + "】本次核销金额【" + bchxje + "】大于剩余未核销金额【" + sywhxje2 + "】,请重新选取抵扣明细数据,获取最新的台账数据!"); + return FAILURE_AND_CONTINUE; + } + sywhxje2 = sywhxje2 - bchxje; + String updSql = "update uf_gysqktzyy_dt1 set yhxje = '" + yhxje + "', sywhxje = '" + sywhxje2 + "', xghxlc = '" + xghxlc + "' where id = " + yfkqptzmxid; + log.writeLog("修改供应商预付欠票台账明细sql-----> " + updSql); + rst.executeSql(updSql); + //查询主表总预付金额及核销金额 + sql1 = "select * from uf_gysqktzyy where qqid = '" + req + "'"; + log.writeLog("查询主表总预付金额及核销金额sql----> " + sql1); + rs1.execute(sql1); + if(rs1.next()){ + double fkje = Double.parseDouble(Util.null2String(rs1.getString("fkje"))==""?"0.00":Util.null2String(rs1.getString("fkje")));//付款金额 + double yhxje1 = Double.parseDouble(Util.null2String(rs1.getString("yhxje"))==""?"0.00":Util.null2String(rs1.getString("yhxje")));//已核销金额 + double sywhxje1 = Double.parseDouble(Util.null2String(rs1.getString("sywhxje"))==""?"0.00":Util.null2String(rs1.getString("sywhxje")));//剩余金额 + + if(bchxje > sywhxje1){ + ri.getRequestManager().setMessagecontent("本次核销金额【" + bchxje + "】大于剩余未核销金额【" + sywhxje1 + "】"); + return FAILURE_AND_CONTINUE; + } + bchxje = bchxje + yhxje1; + sywhxje1 = fkje - bchxje; + updSql = "update uf_gysqktzyy set sywhxje = '" + sywhxje1 + "', yhxje = '" + bchxje + "' where qqid = '" + req + "'"; + log.writeLog("修改供应商预付欠票台账主数据sql-----> " + updSql); + //rst.executeSql(updSql); + rs2.execute(updSql); + } + } + rst.commit(); + } catch (Exception e) { + rst.rollback(); + ri.getRequestManager().setMessagecontent("修改台账出现异常-----" + e); + return FAILURE_AND_CONTINUE; + } + return SUCCESS; + } +} diff --git a/src/main/youhong_ai_jitu_src/com/api/lh/action/VaildateDocumentTypeAction.java b/src/main/youhong_ai_jitu_src/com/api/lh/action/VaildateDocumentTypeAction.java new file mode 100644 index 0000000..4bc2526 --- /dev/null +++ b/src/main/youhong_ai_jitu_src/com/api/lh/action/VaildateDocumentTypeAction.java @@ -0,0 +1,45 @@ +package com.api.lh.action; + +import selfdev.util.base.BaseUtil; +import selfdev.util.log.LogTool; +import weaver.conn.RecordSet; +import weaver.interfaces.workflow.action.Action; +import weaver.soa.workflow.request.RequestInfo; + +/** + * @ClassName VaildatePayableDocumentTypeAction + * @Description 效验明细选取单据类型是否一致 + * @Author louh + * @Date 2022/3/29 11:40 + * @Version 1.0 + */ +public class VaildateDocumentTypeAction implements Action { + @Override + public String execute(RequestInfo ri) { + LogTool log = new LogTool("/log/lh/VaildateDocumentTypeAction",false); + String requestid = ri.getRequestid(); + RecordSet rs = new RecordSet(); + String workflowid = ri.getWorkflowid(); + try{ + //获取表名 + String tablename = BaseUtil.getBaseInfoByParm("tablename", "workflow_bill", "1", "1", " and id in (select formid from workflow_base where id=" + workflowid + ")"); + log.writeLog("requestid---> " + requestid + "对应表名tablename---> " + tablename); + //主表id + String id = BaseUtil.getBaseInfoByParm("id", tablename, "requestid", requestid, ""); + //根据主表数据id获取明细数据sql + String sql = "select distinct cgddlx from " + tablename + "_dt2 where mainid = " + id; + log.writeLog("根据主表数据id获取明细数据sql---> " + sql); + rs.execute(sql); + int counts = rs.getCounts(); + log.writeLog("总行数: " + counts); + if(counts > 1){ + ri.getRequestManager().setMessagecontent("同一张付款单,采购类型必须相同,请重新选择要付款的单据!"); + return FAILURE_AND_CONTINUE; + } + }catch (Exception e){ + ri.getRequestManager().setMessagecontent("内部错误---- > " + e); + return FAILURE_AND_CONTINUE; + } + return SUCCESS; + } +} diff --git a/src/main/youhong_ai_jitu_src/com/api/lh/action/ValidateAdvanceMultiplePodhAction.java b/src/main/youhong_ai_jitu_src/com/api/lh/action/ValidateAdvanceMultiplePodhAction.java new file mode 100644 index 0000000..6d416a5 --- /dev/null +++ b/src/main/youhong_ai_jitu_src/com/api/lh/action/ValidateAdvanceMultiplePodhAction.java @@ -0,0 +1,43 @@ +package com.api.lh.action; + +import selfdev.util.base.BaseUtil; +import selfdev.util.log.LogTool; +import weaver.conn.RecordSet; +import weaver.interfaces.workflow.action.Action; +import weaver.soa.workflow.request.RequestInfo; + +/** + * @ClassName ValidateAdvanceMultiplePodhAction + * @Description 预付单禁止一张单据选取不同的采购订单号 + * @Author louh + * @Date 2022/3/30 17:29 + * @Version 1.0 + */ +public class ValidateAdvanceMultiplePodhAction implements Action { + LogTool log = new LogTool("/log/lh/ValidateAdvanceMultiplePodhAction", false); + @Override + public String execute(RequestInfo ri) { + RecordSet rs = new RecordSet(); + String requestid = ri.getRequestid(); + String workflowid = ri.getWorkflowid(); + try { + //获取表名 + String tablename = BaseUtil.getBaseInfoByParm("tablename", "workflow_bill", "1", "1", " and id in (select formid from workflow_base where id=" + workflowid + ")"); + log.writeLog("requestid---> " + requestid + "对应表名tablename---> " + tablename); + String id = BaseUtil.getBaseInfoByParm("id", tablename, "requestid", requestid, ""); + String sql = "select distinct cgddh from " + tablename + "_dt2 where mainid = " + id; + log.writeLog("查询当前单据明细sql---->" + sql); + rs.execute(sql); + int counts = rs.getCounts(); + if(counts > 1){ + ri.getRequestManager().setMessagecontent("一张预付单据不允许选择不同的采购订单号!请重新获取ncc数据,并进行选择!"); + return FAILURE_AND_CONTINUE; + } + }catch (Exception e){ + ri.getRequestManager().setMessagecontent("内部错误--->" + e); + log.writeLog("出现异常: " + e); + return FAILURE_AND_CONTINUE; + } + return SUCCESS; + } +} diff --git a/src/main/youhong_ai_jitu_src/com/api/lh/action/ValidateAdvancePodhAction.java b/src/main/youhong_ai_jitu_src/com/api/lh/action/ValidateAdvancePodhAction.java new file mode 100644 index 0000000..b71d436 --- /dev/null +++ b/src/main/youhong_ai_jitu_src/com/api/lh/action/ValidateAdvancePodhAction.java @@ -0,0 +1,74 @@ +package com.api.lh.action; + +import selfdev.util.base.BaseUtil; +import selfdev.util.log.LogTool; +import weaver.conn.RecordSet; +import weaver.general.Util; +import weaver.interfaces.workflow.action.Action; +import weaver.soa.workflow.request.RequestInfo; + +/** + * @ClassName ValidateAdvancePodhAction + * @Description 效验NCC单号预付单是否有历史流程在审批中 + * @Author louh + * @Date 2022/3/7 15:26 + * @Version 1.0 + */ +public class ValidateAdvancePodhAction implements Action { + + LogTool log = new LogTool("/log/lh/action/ValidateAdvancePodhAction", false); + @Override + public String execute(RequestInfo ri) { + RecordSet rs = new RecordSet(); + RecordSet rs1 = new RecordSet(); + String requestid = ri.getRequestid(); + + String workflowid = ri.getWorkflowid(); + try{ + //获取表名 + String tablename = BaseUtil.getBaseInfoByParm("tablename", "workflow_bill", "1", "1", " and id in (select formid from workflow_base where id=" + workflowid + ")"); + log.writeLog("requestid---> " + requestid + "对应表名tablename---> " + tablename); + /* 公司名称 */ + String gsmc = BaseUtil.getBaseInfoByParm("gsmc", tablename, "requestid", requestid, ""); + /* 供应商名称 */ + String gysmc = BaseUtil.getBaseInfoByParm("gysmc", tablename, "requestid", requestid, ""); + /* 当前主表数据id */ + String id = BaseUtil.getBaseInfoByParm("id", tablename, "requestid", requestid, ""); + + + String sql = "select * from " + tablename + "_dt2 where mainid = " + id; + log.writeLog("查讯当前流程明细表数据sql-----> " + sql); + rs.execute(sql); + while(rs.next()){ + /* 采购订单号 */ + String cgddh = Util.null2String(rs.getString("cgddh")); + String sql1 = "select * from cgddcx20220429 where gsmc = '" + gsmc + "' and gysmc ='" + gysmc +"' and cgddh = '" + cgddh + "' and podhName = 0 and stutas not in (0,3)"; + log.writeLog("获取当前采购订单号是否有在审批中的流程sql----> " + sql1); + rs1.execute(sql1); + if(rs1.next()){ //如果有值说明有在审批中的流程 + /* 流程编号 */ + String lcbh = Util.null2String(rs1.getString("lcbh")); + String requestid1 = Util.null2String(rs1.getString("requestid")); + ri.getRequestManager().setMessagecontent("当前采购订单号【" + cgddh + "】有在审批中的流程,对应的流程编号【" + lcbh +"】和requestid为【" + requestid1 + "】,请先审批完此流程再次提交该流程!"); + return FAILURE_AND_CONTINUE; + } + //没有在审批中的流程则判断本次付款金额是否大于剩余未付金额 + /* 本次付款金额 */ + String je = Util.null2String(rs.getString("bcfkje")); + /* 剩余未付金额 */ + String sywfje = Util.null2String(rs.getString("sywfje")); + double v = Double.parseDouble(je.replaceAll(",", "")); + double v1 = Double.parseDouble(sywfje.replaceAll(",", "")); + if(v > v1){ + ri.getRequestManager().setMessagecontent("当前采购订单号【" + cgddh + "】本次付款金额【" +v + "】元,大于剩余未付金额【" + v1 + "】元!"); + return FAILURE_AND_CONTINUE; + } + } + }catch (Exception e){ + ri.getRequestManager().setMessagecontent("提交失败,请联系管理员查看问题----> " + e); + log.writeLog("requestid----> " + requestid + " 出现异常: " + e); + return FAILURE_AND_CONTINUE; + } + return SUCCESS; + } +} diff --git a/src/main/youhong_ai_jitu_src/com/api/lh/action/ValidatePayablePodhAction.java b/src/main/youhong_ai_jitu_src/com/api/lh/action/ValidatePayablePodhAction.java new file mode 100644 index 0000000..b5a7413 --- /dev/null +++ b/src/main/youhong_ai_jitu_src/com/api/lh/action/ValidatePayablePodhAction.java @@ -0,0 +1,73 @@ +package com.api.lh.action; + +import selfdev.util.base.BaseUtil; +import selfdev.util.log.LogTool; +import weaver.conn.RecordSet; +import weaver.general.Util; +import weaver.interfaces.workflow.action.Action; +import weaver.soa.workflow.request.RequestInfo; + +/** + * @ClassName NCCValidatePayablePodh + * @Description 效验NCC单号应付单是否有历史流程在审批中 + * @Author louh + * @Date 2022/3/7 14:32 + * @Version 1.0 + */ +public class ValidatePayablePodhAction implements Action { + LogTool log = new LogTool("/log/lh/action/ValidatePayablePodhAction", false); + @Override + public String execute(RequestInfo ri) { + RecordSet rs = new RecordSet(); + RecordSet rs1 = new RecordSet(); + String requestid = ri.getRequestid(); + + String workflowid = ri.getWorkflowid(); + try{ + //获取表名 + String tablename = BaseUtil.getBaseInfoByParm("tablename", "workflow_bill", "1", "1", " and id in (select formid from workflow_base where id=" + workflowid + ")"); + log.writeLog("requestid---> " + requestid + "对应表名tablename---> " + tablename); + /* 公司名称 */ + String gsmc = BaseUtil.getBaseInfoByParm("gsmc", tablename, "requestid", requestid, ""); + /* 供应商名称 */ + String gysmc = BaseUtil.getBaseInfoByParm("gysmc", tablename, "requestid", requestid, ""); + /* 当前主表数据id */ + String id = BaseUtil.getBaseInfoByParm("id", tablename, "requestid", requestid, ""); + + + String sql = "select * from " + tablename + "_dt2 where mainid = " + id; + log.writeLog("查讯当前流程明细表数据sql-----> " + sql); + rs.execute(sql); + while(rs.next()){ + /* 采购订单号 */ + String cgddh = Util.null2String(rs.getString("cgddh")); + String sql1 = "select * from cgddcx20220429 where gsmc = '" + gsmc + "' and gysmc ='" + gysmc +"' and cgddh = '" + cgddh + "' and stutas not in (0,3)"; + log.writeLog("获取当前采购订单号是否有在审批中的流程sql----> " + sql1); + rs1.execute(sql1); + if(rs1.next()){ //如果有值说明有在审批中的流程 + /* 流程编号 */ + String lcbh = Util.null2String(rs1.getString("lcbh")); + String requestid1 = Util.null2String(rs1.getString("requestid")); + ri.getRequestManager().setMessagecontent("当前采购订单号【" + cgddh + "】有在审批中的流程,对应的流程编号【" + lcbh +"】和requestid为【" + requestid1 + "】,请先审批完此流程再次提交该流程!"); + return FAILURE_AND_CONTINUE; + } + //没有在审批中的流程则判断本次付款金额是否大于剩余未付金额 + /* 本次付款金额 */ + String je = Util.null2String(rs.getString("je")); + /* 剩余未付金额 */ + String sywfje = Util.null2String(rs.getString("sywfje")); + double v = Double.parseDouble(je.replaceAll(",", "")); + double v1 = Double.parseDouble(sywfje.replaceAll(",", "")); + if(v > v1){ + ri.getRequestManager().setMessagecontent("当前采购订单号【" + cgddh + "】本次付款金额【" +v + "】元,大于剩余未付金额【" + v1 + "】元!"); + return FAILURE_AND_CONTINUE; + } + } + }catch (Exception e){ + ri.getRequestManager().setMessagecontent("提交失败,请联系管理员查看问题----> " + e); + log.writeLog("requestid----> " + requestid + " 出现异常: " + e); + return FAILURE_AND_CONTINUE; + } + return SUCCESS; + } +} diff --git a/src/main/youhong_ai_jitu_src/com/api/lh/action/two/NCCPaymentValidityAction.java b/src/main/youhong_ai_jitu_src/com/api/lh/action/two/NCCPaymentValidityAction.java new file mode 100644 index 0000000..9884938 --- /dev/null +++ b/src/main/youhong_ai_jitu_src/com/api/lh/action/two/NCCPaymentValidityAction.java @@ -0,0 +1,102 @@ +package com.api.lh.action.two; + +import com.api.lh.config.DemoConfig; +import selfdev.util.base.BaseUtil; +import selfdev.util.log.LogTool; +import weaver.conn.RecordSet; +import weaver.general.Util; +import weaver.interfaces.workflow.action.Action; +import weaver.soa.workflow.request.RequestInfo; + +/** + * @ClassName NCCPaymentValidityAction + * @Description 付款申请(NCC集成) 提交效验 + * @Author louh + * @Date 2022/5/9 14:42 + * @Version 1.0 + */ +public class NCCPaymentValidityAction implements Action, DemoConfig { + + @Override + public String execute(RequestInfo ri) { + RecordSet rs = new RecordSet(); + String requestid = ri.getRequestid(); + String workflowid = ri.getWorkflowid(); + String tableName = getTableName(workflowid); + log.writeLog("当前requestid========> " + requestid + " 对应表名为=======> " + tableName); + String id = getId(tableName, requestid); + + //1.效验同一张单据是否选择了两条相同的抵扣明细 + String sql = "select yfkqptzmxid, count(yfkqptzmxid) as sum from " + tableName + "_dt1 where mainid = " + id + " group by yfkqptzmxid having count(yfkqptzmxid) > 1"; + log.writeLog("根据主表数据id查询当前明细表数据是否有多次选择同一个预付款欠票台账明细id【yfkqptzmxid】sql---->" + sql); + rs.execute(sql); + if(rs.next()){ + ri.getRequestManager().setMessagecontent("同一张单据不允许多次选择相同的【预付款欠票台账明细id】,请重新选择抵扣明细表不同的【预付款欠票台账明细id】数据。"); + return FAILURE_AND_CONTINUE; + } + + //供应商名称 + String gysmc = BaseUtil.getBaseInfoByParm("gysmc", tableName, "requestid", requestid, ""); + //公司名称 + String gsmc = BaseUtil.getBaseInfoByParm("gsmc", tableName, "requestid", requestid, ""); + + + //2.效验明细表本次扣减金额是否大于剩余未付金额 + sql = "select * from " + tableName + "_dt1 where mainid = " + id; + rs.execute(sql); + while(rs.next()){ + //剩余未付金额 + double sywfje = Double.parseDouble(Util.null2String(rs.getString("sywfje")) == "" ? "0.00" : Util.null2String(rs.getString("sywfje"))); + //本次抵减金额 + double bcdjje = Double.parseDouble(Util.null2String(rs.getString("bcdjje")) == "" ? "0.00" : Util.null2String(rs.getString("bcdjje"))); + //预付流程编号 + String yflcbh = Util.null2String(rs.getString("yflcbh")); + + //效验是否有历史单据再审批中 + sql = "select b.requestid," + + " b.lcbh," + + " b.gsmc," + + "b.gysmc," + + "a.id," + + "(select lcbh from uf_fksqyfb where qqid = a.xgyflc) as bh," + + "(select currentnodetype from workflow_requestbase where requestid = b.requestid) as stutas" + + " from " + tableName + "_dt1 a left join " + tableName + " b on a.mainid = b.id " + + " where b.gysmc = '" + gysmc + "' and b.gsmc = '" + gsmc + "' and a.yflcbh = '" + yflcbh + "'"; + log.writeLog("效验是否有历史单据再审批中sql-----> " + sql); + rs.execute(sql); + while(rs.next()){ + String stutas = Util.null2String(rs.getString("stutas")); /* 流程状态 */ + if(!"0".equals(stutas) && !"3".equals(stutas)){ + String bh = Util.null2String(rs.getString("bh")); /* 预付流程编号 */ + String lcbh = Util.null2String(rs.getString("lcbh")); /* 审批中流程编号 */ + ri.getRequestManager().setMessagecontent("当前抵扣明细中【" + bh + "】正在审批中,审批的流程编号为【" + lcbh + "】,请先走完审批中的流程后继续提交该流程!"); + return FAILURE_AND_CONTINUE; + } + } + + if(bcdjje > sywfje){ + ri.getRequestManager().setMessagecontent("抵扣明细预付流程编号【" + yflcbh + "】中本次抵减金额【" + bcdjje + "】不允许大于剩余未付金额【" + sywfje + "】"); + return FAILURE_AND_CONTINUE; + } + } + + + + + //4.效验主表抵扣金额是否大于申请金额 + sql = "select * from " + tableName + " where requestid = " + requestid; + log.writeLog("效验主表抵扣金额是否大于申请金额sql-----> " + sql); + rs.execute(sql); + if(rs.next()){ + //抵扣金额 + double dkje = Double.parseDouble(Util.null2String(rs.getString("dkje")) == "" ? "0.00" : Util.null2String(rs.getString("dkje"))); + //申请金额 + double jshjje = Double.parseDouble(Util.null2String(rs.getString("jshjje")) == "" ? "0.00" : Util.null2String(rs.getString("jshjje"))); + if(dkje > jshjje){ + ri.getRequestManager().setMessagecontent("抵扣总金额【" + dkje + "】不能大于申请总金额【" + jshjje + "】"); + return FAILURE_AND_CONTINUE; + } + } + return SUCCESS; + } +} diff --git a/src/main/youhong_ai_jitu_src/com/api/lh/action/two/NCCPaymentValidityActionYY.java b/src/main/youhong_ai_jitu_src/com/api/lh/action/two/NCCPaymentValidityActionYY.java new file mode 100644 index 0000000..8e65234 --- /dev/null +++ b/src/main/youhong_ai_jitu_src/com/api/lh/action/two/NCCPaymentValidityActionYY.java @@ -0,0 +1,100 @@ +package com.api.lh.action.two; + +import com.api.lh.config.DemoConfig; +import selfdev.util.base.BaseUtil; +import weaver.conn.RecordSet; +import weaver.general.Util; +import weaver.interfaces.workflow.action.Action; +import weaver.soa.workflow.request.RequestInfo; + +/** + * @ClassName NCCPaymentValidityAction + * @Description 付款申请(NCC集成) 提交效验 + * @Author ycf + * @Date 2022/5/9 14:42 + * @Version 1.0 + */ +public class NCCPaymentValidityActionYY implements Action, DemoConfig { + @Override + public String execute(RequestInfo ri) { + RecordSet rs = new RecordSet(); + String requestid = ri.getRequestid(); + String workflowid = ri.getWorkflowid(); + String tableName = getTableName(workflowid); + log.writeLog("当前requestid========> " + requestid + " 对应表名为=======> " + tableName); + String id = getId(tableName, requestid); + + //1.效验同一张单据是否选择了两条相同的抵扣明细 + String sql = "select yfkqptzmxid, count(yfkqptzmxid) as sum from " + tableName + "_dt1 where mainid = " + id + " group by yfkqptzmxid having count(yfkqptzmxid) > 1"; + log.writeLog("根据主表数据id查询当前明细表数据是否有多次选择同一个预付款欠票台账明细id【yfkqptzmxid】sql---->" + sql); + rs.execute(sql); + if(rs.next()){ + ri.getRequestManager().setMessagecontent("同一张单据不允许多次选择相同的【预付款欠票台账明细id】,请重新选择抵扣明细表不同的【预付款欠票台账明细id】数据。"); + return FAILURE_AND_CONTINUE; + } + + //供应商名称 + String gysmc = BaseUtil.getBaseInfoByParm("gysmc", tableName, "requestid", requestid, ""); + //公司名称 + String gsmc = BaseUtil.getBaseInfoByParm("gsmc", tableName, "requestid", requestid, ""); + + + //2.效验明细表本次扣减金额是否大于剩余未付金额 + sql = "select * from " + tableName + "_dt1 where mainid = " + id; + rs.execute(sql); + while(rs.next()){ + //剩余未付金额 + double sywfje = Double.parseDouble(Util.null2String(rs.getString("sywfje")) == "" ? "0.00" : Util.null2String(rs.getString("sywfje"))); + //本次抵减金额 + double bcdjje = Double.parseDouble(Util.null2String(rs.getString("bcdjje")) == "" ? "0.00" : Util.null2String(rs.getString("bcdjje"))); + //预付流程编号 + String yflcbh = Util.null2String(rs.getString("yflcbh")); + + //效验是否有历史单据再审批中 + sql = "select b.requestid," + + " b.lcbh," + + " b.gsmc," + + "b.gysmc," + + "a.id," + + "(select lcbh from uf_gysqktzyy where qqid = a.xgyflc) as bh," + + "(select currentnodetype from workflow_requestbase where requestid = b.requestid) as stutas" + + " from " + tableName + "_dt1 a left join " + tableName + " b on a.mainid = b.id " + + " where b.gysmc = '" + gysmc + "' and b.gsmc = '" + gsmc + "' and a.yflcbh = '" + yflcbh + "'"; + log.writeLog("效验是否有历史单据再审批中sql-----> " + sql); + rs.execute(sql); + while(rs.next()){ + String stutas = Util.null2String(rs.getString("stutas")); /* 流程状态 */ + if(!"0".equals(stutas) && !"3".equals(stutas)){ + String bh = Util.null2String(rs.getString("bh")); /* 预付流程编号 */ + String lcbh = Util.null2String(rs.getString("lcbh")); /* 审批中流程编号 */ + ri.getRequestManager().setMessagecontent("当前抵扣明细中【" + bh + "】正在审批中,审批的流程编号为【" + lcbh + "】,请先走完审批中的流程后继续提交该流程!"); + return FAILURE_AND_CONTINUE; + } + } + + if(bcdjje > sywfje){ + ri.getRequestManager().setMessagecontent("抵扣明细预付流程编号【" + yflcbh + "】中本次抵减金额【" + bcdjje + "】不允许大于剩余未付金额【" + sywfje + "】"); + return FAILURE_AND_CONTINUE; + } + } + + + + + //4.效验主表抵扣金额是否大于申请金额 + sql = "select * from " + tableName + " where requestid = " + requestid; + log.writeLog("效验主表抵扣金额是否大于申请金额sql-----> " + sql); + rs.execute(sql); + if(rs.next()){ + //抵扣金额 + double dkje = Double.parseDouble(Util.null2String(rs.getString("dkje")) == "" ? "0.00" : Util.null2String(rs.getString("dkje"))); + //申请金额 + double jshjje = Double.parseDouble(Util.null2String(rs.getString("jshjje")) == "" ? "0.00" : Util.null2String(rs.getString("jshjje"))); + if(dkje > jshjje){ + ri.getRequestManager().setMessagecontent("抵扣总金额【" + dkje + "】不能大于申请总金额【" + jshjje + "】"); + return FAILURE_AND_CONTINUE; + } + } + return SUCCESS; + } +} diff --git a/src/main/youhong_ai_jitu_src/com/api/lh/action/two/NCCSupplierCWOAction.java b/src/main/youhong_ai_jitu_src/com/api/lh/action/two/NCCSupplierCWOAction.java new file mode 100644 index 0000000..25eb204 --- /dev/null +++ b/src/main/youhong_ai_jitu_src/com/api/lh/action/two/NCCSupplierCWOAction.java @@ -0,0 +1,357 @@ +package com.api.lh.action.two; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.JSONObject; +import com.alibaba.fastjson.serializer.SerializerFeature; +import com.api.lh.config.DemoConfig; +import com.api.lh.port.AddJournal; +import jntchina.entity.ErBxcontrast; +import jntchina.entity.ReimbursementOrder; +import jntchina.entity.ReimbursementOrderBody; +import jntchina.util.HttpClientToDC; +import selfdev.util.base.BaseUtil; +import weaver.conn.RecordSet; +import weaver.general.Util; +import weaver.hrm.resource.ResourceComInfo; +import weaver.interfaces.workflow.action.Action; +import weaver.soa.workflow.request.RequestInfo; + +import java.util.ArrayList; +import java.util.List; +import java.util.Map; +import java.util.UUID; + +/** + * @ClassName NCCSupplierCWOAction + * @Description 供应商预付核销流程生成NCC对公报销单 + * @Author louh + * @Date 2022/5/16 17:10 + * @Version 1.0 + */ +public class NCCSupplierCWOAction implements Action, DemoConfig { + + @Override + public String execute(RequestInfo ri) { + String requestid = ri.getRequestid(); + String workflowid = ri.getWorkflowid(); + + //获取当前用户的登录账号(即工号) + String loginid=ri.getRequestManager().getUser().getLoginid(); + + ReimbursementOrder reimbursementOrder = new ReimbursementOrder(); + String tableName = getTableName(workflowid); + log.writeLog("当前requestid========> " + requestid + " 对应表名为=======> " + tableName); + String id = getId(tableName, requestid); + JSONObject json = null; + String mainId = ""; + String isShowErrorMsg = "";//写入NCC失败时是否显示报错信息 + String pk_org = ""; // 报销单位 JTSDCN0001 + String fygsbm = ""; // 申请部门 + String total = ""; // 报销金额 金额由表体相应字段汇总得出 + String deptid = ""; // 部门 传输编码 + String djlxbm = "264X-Cxx-YFKHXD"; // 单据类型编码 对私报销单:264X-Cxx-DSBXD 对公报销单:264X-Cxx-DGBXD + String djlxmc = "预付核销"; // 单据类型名称 默认 对公报销单 + String djrq = ""; // 单据日期 yyyy-mm-dd hh:mm:ss + String payflag = ""; // 支付状态 + String paytarget = "1"; // 收款对象 0=员工,1=供应商,2=客户,默认为供应商 + String receiver = ""; // 收款人 + String skyhzh = ""; // 收款人银行账号 + String hbbm = ""; // yonyou88", //收款人(供应商) + String custaccount= ""; //收款银行账户(供应商) + String jkbxr = ""; // 借款报销人 传输编码 + String operator = ""; // 录入人 + String xm= ""; // 申请人 + String jsfs = "3"; // 结算方式 3 网银 + String fkyhzh = ""; // 单位银行账户 传输编码 + String jobid = ""; // 项目 + String zy = ""; // 报销事由 + String kjqj = ""; // 会计期间 + String kjnd = ""; // 会计年度 + String fjzs = ""; // 附件张数 需业务人员在OA上传附件同时填写附件张数后传数据到NCC + String zyx1 = ""; // OA单据号 OA传过来,用于联查单据 + String zyx2 = ""; // 提交人 提交人姓名 + String zyx3 = ""; // OA核销单号 + String zyx5 = ""; // OARequestID + String zyx8="";//银行付款备注 + String zyx9=ri.getRequestManager().getRequestname();//标题 + String tablecode = "arap_bxbusitem"; + RecordSet rs = new RecordSet(); + + try{ + String sql = " select * from " + tableName + " where requestid='" + requestid + "'"; + rs.execute(sql); + if(rs.next()) { + mainId = id; + isShowErrorMsg = Util.null2String(rs.getString("xrnccsbcsfts")); + xm = Util.null2String(rs.getString("sqr")); // 借款报销人(取流程申请人) + pk_org = Util.null2String(rs.getString("gsmc")); // 公司名称 + total = Util.null2String(rs.getString("hxje")); // 报销金额 金额由表体相应字段汇总得出 + fygsbm = Util.null2String(rs.getString("sqbm")); // 申请部门 + hbbm = Util.null2String(rs.getString("gysmc")); // 收款人,供应商编码 + custaccount = Util.null2String(rs.getString("yxzh")); // 收款人银行账号 + zyx8 = Util.null2String(rs.getString("yxfkbz")); //银行付款备注 + zy = Util.null2String(rs.getString("sm")); // 付款说明 + zyx1 = Util.null2String(rs.getString("lcbh")); // OA单据号 OA传过来,用于联查单据 + zyx2 = Util.null2String(rs.getString("sqr")); // 提交人 提交人姓名 + djrq = Util.null2String(rs.getString("sqrq")); //申请日期 + zyx5 = requestid; // OARequestID + } + kjqj = djrq.substring(5,7); // 会计期间 + kjnd = djrq.substring(0,4); // 会计年度 + + //根据部门ID查询部门编码 + deptid= BaseUtil.getBaseInfoByParm("departmentcode", "hrmdepartment", "id", fygsbm, ""); + //获取员工默认的组织对应的类型 + String userDefaultCompanyType=BaseUtil.getBaseInfoByParm("company_type", "v_oa_user_org_nsrsbh", "userid", xm, ""); + //获取付款单选择的组织对应的类型 + String selectCompanyType=BaseUtil.getBaseInfoByParm("company_type", "uf_businessunit", "code", pk_org, ""); + log.writeLog("userDefaultCompanyType------>" + userDefaultCompanyType); + log.writeLog("selectCompanyType------>" + selectCompanyType); + + //跨组织,则说明代理区向总部申请付款 + if(!userDefaultCompanyType.equals(selectCompanyType)){ + //查询建模维护的对应关系 + String defaultDeptNo=BaseUtil.getBaseInfoByParm("mroabmbm", "uf_kzzfkdybmsz", "sqgslx", userDefaultCompanyType, " and fkgslx='"+selectCompanyType+"'"); + log.writeLog("defaultDeptNo------>" + defaultDeptNo); + if(!"".equals(defaultDeptNo)){ + deptid=defaultDeptNo; + } + } + + //截取前120位 + if(zy.length()>120){ + zy=zy.substring(0,120); + } + //标题截取前150位 + if (zyx9.length() > 150){ + zyx9 = zyx9.substring(0, 150); + } + + jkbxr = new ResourceComInfo().getWorkcode(xm); //借款报销人工号(即申请人工号) + operator = loginid;// + + //获取UUID + String uuid= UUID.randomUUID().toString().replace("-", "").toUpperCase(); + log.writeLog("receiver------>"+receiver); + + //查询抵扣明细 + sql = " select * from " + tableName + "_dt1 where mainid='" + mainId + "'"; + rs.execute(sql); +// while (rs.next()) { +// zyx3+=Util.null2String(rs.getString("yflcbh"))+","; +// } +// +// //将预付流程编号赋值到zyx3字段中 +// if(!"".equals(zyx3)){ +// zyx3=zyx3.substring(0,zyx3.length()-1); +// } + + reimbursementOrder.setUuid(uuid); + reimbursementOrder.setPk_org(pk_org); + reimbursementOrder.setTotal(total); + reimbursementOrder.setDeptid(deptid); + reimbursementOrder.setDjlxbm(djlxbm); + reimbursementOrder.setDjrq(djrq); + reimbursementOrder.setPayflag(payflag); + reimbursementOrder.setPaytarget(paytarget); + reimbursementOrder.setReceiver(receiver); + reimbursementOrder.setHbbm(hbbm); + reimbursementOrder.setSkyhzh(skyhzh); + reimbursementOrder.setCustaccount(custaccount); + reimbursementOrder.setJkbxr(jkbxr); + reimbursementOrder.setOperator(operator); + reimbursementOrder.setJsfs(jsfs); + reimbursementOrder.setFkyhzh(fkyhzh); + reimbursementOrder.setJobid(jobid); + reimbursementOrder.setZy(zy); + reimbursementOrder.setKjqj(kjqj); + reimbursementOrder.setKjnd(kjnd); + reimbursementOrder.setFjzs(fjzs); + reimbursementOrder.setZyx1(zyx1); + reimbursementOrder.setZyx2(zyx2); + reimbursementOrder.setZyx3(zyx3); + reimbursementOrder.setZyx5(zyx5); + reimbursementOrder.setZyx8(zyx8); + reimbursementOrder.setZyx9(zyx9); + + log.writeLog("【header数据准备完毕...】"); + + //获取OA-NCC发票映射关系表 + Map map_oafplx_nccfplcx=BaseUtil.getMapKeyValueInfoByParm("uf_oafplx_nccfplx", "", "oafplxid", "nccfplxbm"); + //对公报销 + List reimbursementOrderBodyList = new ArrayList(); + List erBxcontrasts = new ArrayList<>(); + + int rowno = 0; + String sql1 = " select c.INVOICECODE,c.INVOICENUMBER,c.invoicetype,a.* from " + tableName + "_dt1 a " + + " left join fnainvoiceledger c on a.fphm=c.id " + + " where a.mainid = " + mainId; + log.writeLog("SQL1-----> " + sql1); + rs.execute(sql1); + while (rs.next()){ + String jobid1 = ""; // 项目 + + String fycdbm = BaseUtil.getBaseInfoByParm("fycdbm", "uf_fksqyfb_dt1", "id", Util.null2String(rs.getString("yfkqptzmxid")), ""); //费用承担部门 + String amount = Util.null2String(rs.getString("bchxje")); // 付款 + String defitem36 = Util.null2o(rs.getString("fpje")); // 发票金额 + String tax_rate = Util.null2String(rs.getString("sl")); // 税率 3% + String tax_amount = Util.null2String(rs.getString("se")); // 税额 + String tni_amount = Util.null2String(rs.getString("bhsje")); // 无税金额 + String szxmid = BaseUtil.getBaseInfoByParm("fylx", "uf_fksqyfb_dt1", "id", Util.null2String(rs.getString("yfkqptzmxid")), ""); // 收支项目 0101 汽车费用 + String fpdm = Util.null2String(rs.getString("INVOICECODE")); // 发票代码 + String fphm = Util.null2String(rs.getString("INVOICENUMBER")); // 发票号码 + String invoicetype = Util.null2String(rs.getString("invoicetype")); // OA发票类型 + //NCC发票类型 + String fplxpk=Util.null2String(map_oafplx_nccfplcx.get(invoicetype)); + +// String fphmId = Util.null2String(rs.getString("fphm")); // 发票号码 +// if(!"".equals(fphmId)){ +// // 得到浏览按钮中发票号码的id,再去数据库中把发票号码和发票代码查出来 +// rsFna.execute(" select * from fnainvoiceledger where id = " + fphmId); +// while (rsFna.next()) { +// fpdm = Util.null2String(rsFna.getString("INVOICECODE")); // 发票代码 +// fphm = Util.null2String(rsFna.getString("INVOICENUMBER")); // 发票号码 +// fplxpk = Util.null2String(map_oafplx_nccfplcx.get(Util.null2String(rsFna.getString("invoicetype")))); // OA发票类型 +// } +// } + //发票金额为空时,默认等于付款金额 + if(Double.parseDouble(defitem36)==0){ + defitem36=amount; + } + + String defitem46 = BaseUtil.getBaseInfoByParm("cbzx", "uf_fksqyfb_dt1", "id", Util.null2String(rs.getString("yfkqptzmxid")), ""); // 网点(成本中心) + String defitem45 = BaseUtil.getBaseInfoByParm("gj", "uf_fksqyfb_dt1", "id", Util.null2String(rs.getString("yfkqptzmxid")), ""); // 国家 + String defitem44 = BaseUtil.getBaseInfoByParm("ck", "uf_fksqyfb_dt1", "id", Util.null2String(rs.getString("yfkqptzmxid")), ""); // 仓库 + String defitem43 = BaseUtil.getBaseInfoByParm("cph", "uf_fksqyfb_dt1", "id", Util.null2String(rs.getString("yfkqptzmxid")), ""); //车牌号 + String defitem42 = BaseUtil.getBaseInfoByParm("oamxxid", "uf_fksqyfb_dt1", "id", Util.null2String(rs.getString("yfkqptzmxid")), ""); // OA明细行ID + //根据部门ID查询部门编码(传NCC) + String fycdbm_NCC=BaseUtil.getBaseInfoByParm("departmentcode", "hrmdepartment", "id", fycdbm, ""); + + rowno++; + + log.writeLog("----fycdbm_NCC:" + fycdbm_NCC); + log.writeLog("----amount:" + amount); + log.writeLog("----tax_rate:" + tax_rate); + log.writeLog("----tax_amount:" + tax_amount); + log.writeLog("----tni_amount:" + tni_amount); + + + ReimbursementOrderBody body = new ReimbursementOrderBody(); + body.setJobid(jobid1); + body.setDeptid(fycdbm_NCC); + body.setAmount(amount); + body.setTax_rate(tax_rate); + body.setTax_amount(tax_amount); + body.setTni_amount(tni_amount); + body.setTablecode(tablecode); + body.setRowno(rowno+""); + body.setSzxmid(BaseUtil.getBaseInfoByParm("bm", "uf_fylx", "id", szxmid, "")); + body.setFpdm(fpdm); + body.setFphm(fphm); + body.setFplxpk(fplxpk); + body.setDefitem36(defitem36); + body.setDefitem46(defitem46); + body.setDefitem45(defitem45); + body.setDefitem44(defitem44); + body.setDefitem43(defitem43); + body.setDefitem42(defitem42); + //body.setDefitem48(fycdbm_NCC); + reimbursementOrderBodyList.add(body); + } + reimbursementOrder.setEr_busitem(reimbursementOrderBodyList); + sql = "select yfkqptzmxid, sum(bchxje) as hxje, avg(yfje) as zje, avg(xgyflc) as req from " + tableName + "_dt1" + + " where mainid = '" + id + "' group by yfkqptzmxid having count(yfkqptzmxid) > 0"; + log.writeLog("获取预付核销数据明细sql-----> " +sql); + rs.execute(sql); + while(rs.next()){ + String szxmid = BaseUtil.getBaseInfoByParm("fylx", "uf_fksqyfb_dt1", "id", Util.null2String(rs.getString("yfkqptzmxid")), ""); + ErBxcontrast erBxcontrast = new ErBxcontrast( + BaseUtil.getBaseInfoByParm("ncclcdh", "uf_fksqyfb","qqid", Util.null2String(rs.getString("req")), ""), + BaseUtil.getBaseInfoByParm("bm", "uf_fylx", "id", szxmid, ""), + Util.null2String(rs.getString("hxje")), + BaseUtil.getBaseInfoByParm("oamxxid", "uf_fksqyfb_dt1", "id", Util.null2String(rs.getString("yfkqptzmxid")), ""), + Util.null2String(rs.getString("yfkqptzmxid"))); + erBxcontrasts.add(erBxcontrast); + } + reimbursementOrder.setEr_bxcontrast(erBxcontrasts); + String parm=JSONObject.toJSONString(reimbursementOrder, SerializerFeature.DisableCircularReferenceDetect); + log.writeLog(djlxmc+"准备传入中台的数据为------>" + parm); + //获取TOKEN + String token = HttpClientToDC.getToken(); + log.writeLog("获取数据中台的token------>" + token); + if ("".equals(Util.null2String(token))) { + String tokenMsg="流程提交失败,未获取到数据中台接口TOKEN,请联系管理员处理!"; + //将NCC返回结果回写至OA流程表单 + rs.execute(" update " + tableName + " set sfcgscnccfkd = 1 ,nccfhxx='" + tokenMsg.replace("'", "''") + "' where requestid = " + requestid); + AddJournal.addInfo("费用报销接口", JSON.parseObject(parm), tokenMsg, "1", requestid); + //是否需要显示报错信息 + if("yes".equals(isShowErrorMsg)){ + ri.getRequestManager().setMessagecontent(tokenMsg); + return Action.FAILURE_AND_CONTINUE; + }else{ + return SUCCESS; + } + } + + //调用NCC接口,将数据传给NCC + String returndata = HttpClientToDC.sendPostApi(baseUrl+"/dcnccapi/claimForm/receiveData",token, parm); + log.writeLog("【调用数据中台报销接口返回结果result:】" + returndata); + if (!"".equals(returndata) && returndata != null) { + JSONObject jsonObject = JSONObject.parseObject(returndata); + String success = Util.null2String(jsonObject.get("succ")); + log.writeLog("--------发送请求返回的success值为:" + success); + if ("true".equals(success)) { + JSONObject data = jsonObject.getJSONObject("data"); + String billno = Util.null2String(data.get("billno"));//NCC单号 + log.writeLog("--------发送请求返回的billno值为:" + billno); + //将NCC返回结果回写至OA流程表单 + rs.execute(" update " + tableName + " set sfcgscnccfkd = 0 , nccfkdh = '" + billno + "',nccfhxx='' where requestid = " + requestid); + AddJournal.addInfo("费用报销接口", JSON.parseObject(parm), returndata, "0", requestid); + } else { + String message = Util.null2String(jsonObject.get("msg")); + String message2=message.replace("'", "''"); + //超出1333个字符,则只截取前面这部分 + if(message2.length()>1334){ + message2=message2.substring(0,1333); + } + //将NCC返回结果回写至OA流程表单 + rs.execute(" update " + tableName + " set sfcgscnccfkd = 1 ,nccfhxx='" + message2 + "' where requestid = " + requestid); + AddJournal.addInfo("费用报销接口", JSON.parseObject(parm), returndata, "1", requestid); + //是否需要显示报错信息 + if("yes".equals(isShowErrorMsg)){ + ri.getRequestManager().setMessagecontent("流程数据写入NCC生成"+djlxmc+"失败,失败信息:
"+message); + return Action.FAILURE_AND_CONTINUE; + }else{ + return SUCCESS; + } + } + } else { + String ermsg="流程数据写入NCC生成"+djlxmc+"失败,未获取到接口返回结果,请联系系统管理员处理!"; + AddJournal.addInfo("费用报销接口", JSON.parseObject(parm), ermsg, "1", requestid); + //将NCC返回结果回写至OA流程表单 + rs.execute(" update " + tableName + " set sfcgscnccfkd = 1 ,nccfhxx='" + ermsg.replace("'", "''") + "' where requestid = " + requestid); + //是否需要显示报错信息 + if("yes".equals(isShowErrorMsg)){ + ri.getRequestManager().setMessagecontent(ermsg); + return Action.FAILURE_AND_CONTINUE; + }else{ + return SUCCESS; + } + } + + }catch (Exception e){ + String ermsg="流程数据生成预付核销单失败!" + e.toString(); + //将NCC返回结果回写至OA流程表单 + AddJournal.addInfo("费用报销接口", json, ermsg, "1", requestid); + rs.execute(" update " + tableName + " set sfcgscnccfkd = 1 ,nccfhxx='" + ermsg.replace("'", "''") + "' where requestid = " + requestid); + //是否需要显示报错信息 + if("yes".equals(isShowErrorMsg)){ + ri.getRequestManager().setMessagecontent(ermsg); + return Action.FAILURE_AND_CONTINUE; + }else{ + return SUCCESS; + } + } + return SUCCESS; + } +} diff --git a/src/main/youhong_ai_jitu_src/com/api/lh/action/two/NCCSupplierCWOActionYY.java b/src/main/youhong_ai_jitu_src/com/api/lh/action/two/NCCSupplierCWOActionYY.java new file mode 100644 index 0000000..383a2cb --- /dev/null +++ b/src/main/youhong_ai_jitu_src/com/api/lh/action/two/NCCSupplierCWOActionYY.java @@ -0,0 +1,360 @@ +package com.api.lh.action.two; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.JSONObject; +import com.alibaba.fastjson.serializer.SerializerFeature; +import com.api.lh.config.DemoConfig; +import com.api.lh.port.AddJournal; +import jntchina.entity.*; +import jntchina.util.DataBaseUtils; +import jntchina.util.HttpClientToDC; +import selfdev.util.base.BaseUtil; +import weaver.conn.RecordSet; +import weaver.general.Util; +import weaver.hrm.resource.ResourceComInfo; +import weaver.interfaces.workflow.action.Action; +import weaver.soa.workflow.request.RequestInfo; + +import java.util.ArrayList; +import java.util.List; +import java.util.Map; +import java.util.UUID; + +/** + * @ClassName NCCSupplierCWOAction + * @Description 供应商预付核销流程生成NCC对公报销单 + * @Author ycf + * @Date 2022/5/16 17:10 + * @Version 1.0 + */ + public class NCCSupplierCWOActionYY implements Action, DemoConfig { + + @Override + public String execute(RequestInfo ri) { + // + String requestid = ri.getRequestid(); + String workflowid = ri.getWorkflowid(); + + //获取当前用户的登录账号(即工号) + String loginid=ri.getRequestManager().getUser().getLoginid(); + + ReimbursementOrderYY reimbursementOrder = new ReimbursementOrderYY(); + String tableName = getTableName(workflowid); + log.writeLog("当前requestid========> " + requestid + " 对应表名为=======> " + tableName); + String id = getId(tableName, requestid); + JSONObject json = null; + String mainId = ""; + String isShowErrorMsg = "";//写入NCC失败时是否显示报错信息 + String pk_org = ""; // 报销单位 JTSDCN0001 + String fygsbm = ""; // 申请部门 + String total = ""; // 报销金额 金额由表体相应字段汇总得出 + String deptid = ""; // 部门 传输编码 + String djlxbm = "264X-Cxx-YFKHXD"; // 单据类型编码 对私报销单:264X-Cxx-DSBXD 对公报销单:264X-Cxx-DGBXD + String djlxmc = "预付核销"; // 单据类型名称 默认 对公报销单 + String djrq = ""; // 单据日期 yyyy-mm-dd hh:mm:ss + String payflag = ""; // 支付状态 + String paytarget = "1"; // 收款对象 0=员工,1=供应商,2=客户,默认为供应商 + String receiver = ""; // 收款人 + String skyhzh = ""; // 收款人银行账号 + String hbbm = ""; // yonyou88", //收款人(供应商) + String custaccount= ""; //收款银行账户(供应商) + String jkbxr = ""; // 借款报销人 传输编码 + String operator = ""; // 录入人 + String xm= ""; // 申请人 + String jsfs = "3"; // 结算方式 3 网银 + String fkyhzh = ""; // 单位银行账户 传输编码 + String jobid = ""; // 项目 + String zy = ""; // 报销事由 + String kjqj = ""; // 会计期间 + String kjnd = ""; // 会计年度 + String fjzs = ""; // 附件张数 需业务人员在OA上传附件同时填写附件张数后传数据到NCC + String zyx1 = ""; // OA单据号 OA传过来,用于联查单据 + String zyx2 = ""; // 提交人 提交人姓名 + String zyx3 = ""; // OA核销单号 + String zyx5 = ""; // OARequestID + String zyx8="";//银行付款备注 + String zyx9=ri.getRequestManager().getRequestname().length()>140?ri.getRequestManager().getRequestname().substring(0,140):ri.getRequestManager().getRequestname();//标题 + String tablecode = "arap_bxbusitem"; + RecordSet rs = new RecordSet(); + + try{ + String sql = " select * from " + tableName + " where requestid='" + requestid + "'"; + rs.execute(sql); + if(rs.next()) { + mainId = id; + isShowErrorMsg = Util.null2String(rs.getString("xrnccsbcsfts")); + xm = Util.null2String(rs.getString("sqr")); // 借款报销人(取流程申请人) + pk_org = Util.null2String(rs.getString("gsmc")); // 公司名称 + total = Util.null2String(rs.getString("hxje")); // 报销金额 金额由表体相应字段汇总得出 + fygsbm = Util.null2String(rs.getString("sqbm")); // 申请部门 + hbbm = Util.null2String(rs.getString("gysmc")); // 收款人,供应商编码 + custaccount = Util.null2String(rs.getString("yxzh")); // 收款人银行账号 + zyx8 = Util.null2String(rs.getString("yxfkbz")); //银行付款备注 + zy = Util.null2String(rs.getString("sm")); // 付款说明 + zyx1 = Util.null2String(rs.getString("lcbh")); // OA单据号 OA传过来,用于联查单据 + zyx2 = Util.null2String(rs.getString("sqr")); // 提交人 提交人姓名 + djrq = Util.null2String(rs.getString("sqrq")); //申请日期 + zyx5 = requestid; // OARequestID + } + kjqj = djrq.substring(5,7); // 会计期间 + kjnd = djrq.substring(0,4); // 会计年度 + + //根据部门ID查询部门编码 + deptid= BaseUtil.getBaseInfoByParm("departmentcode", "hrmdepartment", "id", fygsbm, ""); + //获取员工默认的组织对应的类型 + String userDefaultCompanyType=BaseUtil.getBaseInfoByParm("company_type", "v_oa_user_org_nsrsbh", "userid", xm, ""); + //获取付款单选择的组织对应的类型 + String selectCompanyType=BaseUtil.getBaseInfoByParm("company_type", "uf_businessunit", "code", pk_org, ""); + log.writeLog("userDefaultCompanyType------>" + userDefaultCompanyType); + log.writeLog("selectCompanyType------>" + selectCompanyType); + + //跨组织,则说明代理区向总部申请付款 + if(!userDefaultCompanyType.equals(selectCompanyType)){ + //查询建模维护的对应关系 + String defaultDeptNo=BaseUtil.getBaseInfoByParm("mroabmbm", "uf_kzzfkdybmsz", "sqgslx", userDefaultCompanyType, " and fkgslx='"+selectCompanyType+"'"); + log.writeLog("defaultDeptNo------>" + defaultDeptNo); + if(!"".equals(defaultDeptNo)){ + deptid=defaultDeptNo; + } + } + + //截取前120位 + if(zy.length()>120){ + zy=zy.substring(0,120); + } + + jkbxr = new ResourceComInfo().getWorkcode(xm); //借款报销人工号(即申请人工号) + operator = loginid;// + + //获取UUID + String uuid= UUID.randomUUID().toString().replace("-", "").toUpperCase(); + log.writeLog("receiver------>"+receiver); + + //查询抵扣明细 + sql = " select * from " + tableName + "_dt1 where mainid='" + mainId + "'"; + rs.execute(sql); +// while (rs.next()) { +// zyx3+=Util.null2String(rs.getString("yflcbh"))+","; +// } +// +// //将预付流程编号赋值到zyx3字段中 +// if(!"".equals(zyx3)){ +// zyx3=zyx3.substring(0,zyx3.length()-1); +// } + + reimbursementOrder.setUuid(uuid); + reimbursementOrder.setPk_org(pk_org); + reimbursementOrder.setTotal(total); + reimbursementOrder.setDeptid(deptid); + reimbursementOrder.setDjlxbm(djlxbm); + reimbursementOrder.setDjrq(djrq); + reimbursementOrder.setPayflag(payflag); + reimbursementOrder.setPaytarget(paytarget); + reimbursementOrder.setReceiver(receiver); + reimbursementOrder.setHbbm(hbbm); + reimbursementOrder.setSkyhzh(skyhzh); + reimbursementOrder.setCustaccount(custaccount); + reimbursementOrder.setJkbxr(jkbxr); + reimbursementOrder.setOperator(operator); + reimbursementOrder.setJsfs(jsfs); + reimbursementOrder.setFkyhzh(fkyhzh); + reimbursementOrder.setJobid(jobid); + reimbursementOrder.setZy(zy); + reimbursementOrder.setKjqj(kjqj); + reimbursementOrder.setKjnd(kjnd); + reimbursementOrder.setFjzs(fjzs); + reimbursementOrder.setZyx1(zyx1); + reimbursementOrder.setZyx2(zyx2); + reimbursementOrder.setZyx3(zyx3); + reimbursementOrder.setZyx5(zyx5); + reimbursementOrder.setZyx8(zyx8); + reimbursementOrder.setZyx9(zyx9); + + log.writeLog("【header数据准备完毕...】"); + + //获取OA-NCC发票映射关系表 + Map map_oafplx_nccfplcx=BaseUtil.getMapKeyValueInfoByParm("uf_oafplx_nccfplx", "", "oafplxid", "nccfplxbm"); + //对公报销 + List reimbursementOrderBodyList = new ArrayList(); + List erBxcontrasts = new ArrayList<>(); + + int rowno = 0; + String sql1 = " select c.INVOICECODE,c.INVOICENUMBER,c.invoicetype,a.* from " + tableName + "_dt1 a " + + " left join fnainvoiceledger c on a.fphm=c.id " + + " where a.mainid = " + mainId; + log.writeLog("SQL1-----> " + sql1); + rs.execute(sql1); + while (rs.next()){ + String jobid1 = ""; // 项目 + + String fycdbm = BaseUtil.getBaseInfoByParm("fycdbm", "uf_gysqktzyy_dt1", "id", Util.null2String(rs.getString("yfkqptzmxid")), ""); //费用承担部门 + String amount = Util.null2String(rs.getString("bchxje")); // 付款 + String defitem36 = Util.null2o(rs.getString("fpje")); // 发票金额 + String tax_rate = Util.null2String(rs.getString("sl")); // 税率 3% + String tax_amount = Util.null2String(rs.getString("se")); // 税额 + String tni_amount = Util.null2String(rs.getString("bhsje")); // 无税金额 + String szxmid = BaseUtil.getBaseInfoByParm("fylx", "uf_gysqktzyy_dt1", "id", Util.null2String(rs.getString("yfkqptzmxid")), ""); // 收支项目 0101 汽车费用 + String fpdm = Util.null2String(rs.getString("INVOICECODE")); // 发票代码 + String fphm = Util.null2String(rs.getString("INVOICENUMBER")); // 发票号码 + String invoicetype = Util.null2String(rs.getString("invoicetype")); // OA发票类型 + //NCC发票类型 + String fplxpk=Util.null2String(map_oafplx_nccfplcx.get(invoicetype)); + +// String fphmId = Util.null2String(rs.getString("fphm")); // 发票号码 +// if(!"".equals(fphmId)){ +// // 得到浏览按钮中发票号码的id,再去数据库中把发票号码和发票代码查出来 +// rsFna.execute(" select * from fnainvoiceledger where id = " + fphmId); +// while (rsFna.next()) { +// fpdm = Util.null2String(rsFna.getString("INVOICECODE")); // 发票代码 +// fphm = Util.null2String(rsFna.getString("INVOICENUMBER")); // 发票号码 +// fplxpk = Util.null2String(map_oafplx_nccfplcx.get(Util.null2String(rsFna.getString("invoicetype")))); // OA发票类型 +// } +// } + //发票金额为空时,默认等于付款金额 + if(Double.parseDouble(defitem36)==0){ + defitem36=amount; + } + + sql = "select * from uf_gysqktzyy_dt1 where id = " + Util.null2String(rs.getString("yfkqptzmxid")); + log.writeLog("获取明细数据:"+sql); + + + Map dataMap = DataBaseUtils.getDataMap(sql); + String defitem46 = dataMap.get("CBZX"); // 网点(成本中心) + String defitem45 = dataMap.get("GJ"); // 国家 + String defitem44 = dataMap.get("CK"); // 仓库 + String defitem43 = dataMap.get("CPH"); //车牌号 + String defitem42 = dataMap.get("OAMXXID"); // OA明细行ID + //根据部门ID查询部门编码(传NCC) +// String fycdbm_NCC=BaseUtil.getBaseInfoByParm("departmentcode", "hrmdepartment", "id", fycdbm, ""); +// fycdbm_NCC = fycdbm;//直接取NCC的费用承担部门 + + rowno++; + + log.writeLog("----fycdbm_NCC:" + fycdbm); + log.writeLog("----amount:" + amount); + log.writeLog("----tax_rate:" + tax_rate); + log.writeLog("----tax_amount:" + tax_amount); + log.writeLog("----tni_amount:" + tni_amount); + + + ReimbursementOrderBodyYY body = new ReimbursementOrderBodyYY(); + body.setJobid(jobid1); + body.setDeptid(fycdbm); + body.setAmount(amount); + body.setTax_rate(tax_rate); + body.setTax_amount(tax_amount); + body.setTni_amount(tni_amount); + body.setTablecode(tablecode); + body.setRowno(rowno+""); + body.setSzxmid(BaseUtil.getBaseInfoByParm("bm", "uf_fylx", "id", szxmid, "")); + body.setFpdm(fpdm); + body.setFphm(fphm); + body.setFplxpk(fplxpk); + body.setDefitem36(defitem36); + body.setDefitem46(defitem46); + body.setDefitem45(defitem45); + body.setDefitem44(defitem44); + body.setDefitem43(defitem43); + body.setDefitem42(defitem42); + body.setDeptidIsNeedConvert("no"); + //body.setDefitem48(fycdbm_NCC); + reimbursementOrderBodyList.add(body); + } + reimbursementOrder.setEr_busitem(reimbursementOrderBodyList); + sql = "select yfkqptzmxid, sum(bchxje) as hxje, avg(yfje) as zje, avg(xgyflc) as req from " + tableName + "_dt1" + + " where mainid = '" + id + "' group by yfkqptzmxid having count(yfkqptzmxid) > 0"; + log.writeLog("获取预付核销数据明细sql-----> " +sql); + rs.execute(sql); + while(rs.next()){ + String szxmid = BaseUtil.getBaseInfoByParm("fylx", "uf_gysqktzyy_dt1", "id", Util.null2String(rs.getString("yfkqptzmxid")), ""); + ErBxcontrast erBxcontrast = new ErBxcontrast( + BaseUtil.getBaseInfoByParm("ncclcdh", "uf_gysqktzyy","qqid", Util.null2String(rs.getString("req")), ""), + BaseUtil.getBaseInfoByParm("bm", "uf_fylx", "id", szxmid, ""), + Util.null2String(rs.getString("hxje")), + BaseUtil.getBaseInfoByParm("oamxxid", "uf_gysqktzyy_dt1", "id", Util.null2String(rs.getString("yfkqptzmxid")), ""), + Util.null2String(rs.getString("yfkqptzmxid"))); + erBxcontrasts.add(erBxcontrast); + } + reimbursementOrder.setEr_bxcontrast(erBxcontrasts); + String parm=JSONObject.toJSONString(reimbursementOrder, SerializerFeature.DisableCircularReferenceDetect); + log.writeLog(djlxmc+"准备传入中台的数据为------>" + parm); + //获取TOKEN + String token = HttpClientToDC.getToken(); + log.writeLog("获取数据中台的token------>" + token); + if ("".equals(Util.null2String(token))) { + String tokenMsg="流程提交失败,未获取到数据中台接口TOKEN,请联系管理员处理!"; + //将NCC返回结果回写至OA流程表单 + rs.execute(" update " + tableName + " set sfcgscnccfkd = 1 ,nccfhxx='" + tokenMsg.replace("'", "''") + "' where requestid = " + requestid); + AddJournal.addInfo("费用报销接口", JSON.parseObject(parm), tokenMsg, "1", requestid); + //是否需要显示报错信息 + if("yes".equals(isShowErrorMsg)){ + ri.getRequestManager().setMessagecontent(tokenMsg); + return Action.FAILURE_AND_CONTINUE; + }else{ + return SUCCESS; + } + } + + //调用NCC接口,将数据传给NCC + String returndata = HttpClientToDC.sendPostApi(baseUrl+"/dcnccapi/claimForm/receiveData",token, parm); + log.writeLog("【调用数据中台报销接口返回结果result:】" + returndata); + if (!"".equals(returndata) && returndata != null) { + JSONObject jsonObject = JSONObject.parseObject(returndata); + String success = Util.null2String(jsonObject.get("succ")); + log.writeLog("--------发送请求返回的success值为:" + success); + if ("true".equals(success)) { + JSONObject data = jsonObject.getJSONObject("data"); + String billno = Util.null2String(data.get("billno"));//NCC单号 + log.writeLog("--------发送请求返回的billno值为:" + billno); + //将NCC返回结果回写至OA流程表单 + rs.execute(" update " + tableName + " set sfcgscnccfkd = 0 , nccfkdh = '" + billno + "',nccfhxx='' where requestid = " + requestid); + AddJournal.addInfo("费用报销接口", JSON.parseObject(parm), returndata, "0", requestid); + } else { + String message = Util.null2String(jsonObject.get("msg")); + String message2=message.replace("'", "''"); + //超出1333个字符,则只截取前面这部分 + if(message2.length()>1334){ + message2=message2.substring(0,1333); + } + //将NCC返回结果回写至OA流程表单 + rs.execute(" update " + tableName + " set sfcgscnccfkd = 1 ,nccfhxx='" + message2 + "' where requestid = " + requestid); + AddJournal.addInfo("费用报销接口", JSON.parseObject(parm), returndata, "1", requestid); + //是否需要显示报错信息 + if("yes".equals(isShowErrorMsg)){ + ri.getRequestManager().setMessagecontent("流程数据写入NCC生成"+djlxmc+"失败,失败信息:
"+message); + return Action.FAILURE_AND_CONTINUE; + }else{ + return SUCCESS; + } + } + } else { + String ermsg="流程数据写入NCC生成"+djlxmc+"失败,未获取到接口返回结果,请联系系统管理员处理!"; + AddJournal.addInfo("费用报销接口", JSON.parseObject(parm), ermsg, "1", requestid); + //将NCC返回结果回写至OA流程表单 + rs.execute(" update " + tableName + " set sfcgscnccfkd = 1 ,nccfhxx='" + ermsg.replace("'", "''") + "' where requestid = " + requestid); + //是否需要显示报错信息 + if("yes".equals(isShowErrorMsg)){ + ri.getRequestManager().setMessagecontent(ermsg); + return Action.FAILURE_AND_CONTINUE; + }else{ + return SUCCESS; + } + } + + }catch (Exception e){ + String ermsg="流程数据生成预付核销单失败!" + e.toString(); + //将NCC返回结果回写至OA流程表单 + AddJournal.addInfo("费用报销接口", json, ermsg, "1", requestid); + rs.execute(" update " + tableName + " set sfcgscnccfkd = 1 ,nccfhxx='" + ermsg.replace("'", "''") + "' where requestid = " + requestid); + //是否需要显示报错信息 + if("yes".equals(isShowErrorMsg)){ + ri.getRequestManager().setMessagecontent(ermsg); + return Action.FAILURE_AND_CONTINUE; + }else{ + return SUCCESS; + } + } + return SUCCESS; + } +} diff --git a/src/main/youhong_ai_jitu_src/com/api/lh/action/two/SupplierVerificationAction.java b/src/main/youhong_ai_jitu_src/com/api/lh/action/two/SupplierVerificationAction.java new file mode 100644 index 0000000..414f1d4 --- /dev/null +++ b/src/main/youhong_ai_jitu_src/com/api/lh/action/two/SupplierVerificationAction.java @@ -0,0 +1,95 @@ +package com.api.lh.action.two; + +import com.api.lh.config.DemoConfig; + +import selfdev.util.base.BaseUtil; +import selfdev.util.log.LogTool; +import weaver.conn.RecordSet; +import weaver.general.Util; +import weaver.interfaces.workflow.action.Action; +import weaver.soa.workflow.request.RequestInfo; + +/** + * @ClassName SupplierVerificationAction + * @Description 供应商预付核销提交效验action + * @Author louh + * @Date 2022/5/16 16:04 + * @Version 1.0 + */ +public class SupplierVerificationAction implements Action, DemoConfig { + LogTool log = new LogTool("/log/lh/SupplierVerificationAction", false); + @Override + public String execute(RequestInfo ri) { + RecordSet rs = new RecordSet(); + RecordSet rs1 = new RecordSet(); + String requestid = ri.getRequestid(); + String workflowid = ri.getWorkflowid(); + String tableName = getTableName(workflowid); + log.writeLog("当前requestid========> " + requestid + " 对应表名为=======> " + tableName); + String id = getId(tableName, requestid); + //供应商名称 + String gysmc = BaseUtil.getBaseInfoByParm("gysmc", tableName, "requestid", requestid, ""); + //公司名称 + String gsmc = BaseUtil.getBaseInfoByParm("gsmc", tableName, "requestid", requestid, ""); + + + //1.效验每张单据的抵扣金额是否超过预付金额 + String sql = "select yfkqptzmxid, sum(bchxje) as hxje, avg(yfje) as zje from " + tableName + "_dt1 " + + " where mainid = '" + id + "'" + + "group by yfkqptzmxid having count(yfkqptzmxid) > 0"; + log.writeLog("效验每张单据的抵扣金额是否超过预付金额sql-----> " + sql); + rs.execute(sql); + while(rs.next()){ + String yfkqptzmxid = Util.null2String(rs.getString("yfkqptzmxid")); //预付款欠票台账明细id + double hxje = Double.parseDouble(Util.null2String(rs.getString("hxje"))==""?"0.00":Util.null2String(rs.getString("hxje"))); //本次核销金额 + double zje = Double.parseDouble(Util.null2String(rs.getString("zje"))==""?"0.00":Util.null2String(rs.getString("zje"))); //预付金额 + if(hxje > zje){ + ri.getRequestManager().setMessagecontent("当前单据预付核销明细中预付款欠票台账明细id【" + yfkqptzmxid + "】抵扣总金额【" + hxje + "】合计大于预付金额【" + zje + "】,请重新选取要核销的数据!"); + return FAILURE_AND_CONTINUE; + } + + + + //预付流程编号 + String yflcbh = weaver.general.Util.null2String(rs.getString("yflcbh")); + + //效验是否有历史单据再审批中 + sql = "select b.requestid," + + " b.lcbh," + + " b.gsmc," + + "b.gysmc," + + "a.id," + + "(select lcbh from uf_fksqyfb where qqid = a.xgyflc) as bh," + + "(select currentnodetype from workflow_requestbase where requestid = b.requestid) as stutas" + + " from " + tableName + "_dt1 a left join " + tableName + " b on a.mainid = b.id " + + " where b.gysmc = '" + gysmc + "' and b.gsmc = '" + gsmc + "' and a.yflcbh = '" + yflcbh + "'"; + log.writeLog("效验是否有历史单据再审批中sql-----> " + sql); + rs1.execute(sql); + while(rs1.next()){ + String stutas = Util.null2String(rs1.getString("stutas")); /* 流程状态 */ + if(!"0".equals(stutas) && !"3".equals(stutas)){ + String bh = Util.null2String(rs1.getString("bh")); /* 预付流程编号 */ + String lcbh = Util.null2String(rs1.getString("lcbh")); /* 审批中流程编号 */ + ri.getRequestManager().setMessagecontent("当前抵扣明细中【" + bh + "】正在审批中,审批的流程编号为【" + lcbh + "】,请先走完审批中的流程后继续提交该流程!"); + return FAILURE_AND_CONTINUE; + } + } + } + + //2.效验明细表每行抵扣金额不得大于发票金额 + sql = "select yfkqptzmxid, bchxje, fpje from " + tableName + "_dt1 where mainid = " + id; + rs.execute(sql); + while(rs.next()){ + double bchxje = Double.parseDouble(Util.null2o(rs.getString("bchxje"))); + double fpje = Double.parseDouble(Util.null2o(rs.getString("fpje"))); + if (bchxje > fpje){ + String yfkqptzmxid = Util.null2String(rs.getString("yfkqptzmxid")); + ri.getRequestManager().setMessagecontent("当前单据预付核销明细中预付款欠票台账明细id【" + yfkqptzmxid + "】抵扣金额【" + bchxje + "】发票金额【" + fpje + "】,请重新选取要核销的数据!"); + return FAILURE_AND_CONTINUE; + } + } + + + return SUCCESS; + } +} diff --git a/src/main/youhong_ai_jitu_src/com/api/lh/action/two/SupplierVerificationActionYY.java b/src/main/youhong_ai_jitu_src/com/api/lh/action/two/SupplierVerificationActionYY.java new file mode 100644 index 0000000..ab3e7f5 --- /dev/null +++ b/src/main/youhong_ai_jitu_src/com/api/lh/action/two/SupplierVerificationActionYY.java @@ -0,0 +1,79 @@ +package com.api.lh.action.two; + +import com.api.lh.config.DemoConfig; +import com.wbi.util.Util; +import selfdev.util.base.BaseUtil; +import selfdev.util.log.LogTool; +import weaver.conn.RecordSet; +import weaver.interfaces.workflow.action.Action; +import weaver.soa.workflow.request.RequestInfo; + +/** + * @ClassName SupplierVerificationAction + * @Description 供应商预付核销提交效验action + * @Author ycf + * @Date 2022/5/16 16:04 + * @Version 1.0 + */ +public class SupplierVerificationActionYY implements Action, DemoConfig { + LogTool log = new LogTool("/log/lh/SupplierVerificationAction", false); + @Override + public String execute(RequestInfo ri) { + RecordSet rs = new RecordSet(); + String requestid = ri.getRequestid(); + String workflowid = ri.getWorkflowid(); + String tableName = getTableName(workflowid); + log.writeLog("当前requestid========> " + requestid + " 对应表名为=======> " + tableName); + String id = getId(tableName, requestid); + //供应商名称 + String gysmc = BaseUtil.getBaseInfoByParm("gysmc", tableName, "requestid", requestid, ""); + //公司名称 + String gsmc = BaseUtil.getBaseInfoByParm("gsmc", tableName, "requestid", requestid, ""); + + + //1.效验每张单据的抵扣金额是否超过预付金额 + String sql = "select yfkqptzmxid, sum(bchxje) as hxje, avg(yfje) as zje from " + tableName + "_dt1 " + + " where mainid = '" + id + "'" + + "group by yfkqptzmxid having count(yfkqptzmxid) > 0"; + log.writeLog("效验每张单据的抵扣金额是否超过预付金额sql-----> " + sql); + rs.execute(sql); + while(rs.next()){ + String yfkqptzmxid = Util.null2String(rs.getString("yfkqptzmxid")); //预付款欠票台账明细id + double hxje = Double.parseDouble(Util.null2String(rs.getString("hxje"))==""?"0.00":Util.null2String(rs.getString("hxje"))); //本次核销金额 + double zje = Double.parseDouble(Util.null2String(rs.getString("zje"))==""?"0.00":Util.null2String(rs.getString("zje"))); //预付金额 + if(hxje > zje){ + ri.getRequestManager().setMessagecontent("当前单据预付核销明细中预付款欠票台账明细id【" + yfkqptzmxid + "】抵扣总金额【" + hxje + "】合计大于预付金额【" + zje + "】,请重新选取要核销的数据!"); + return FAILURE_AND_CONTINUE; + } + + //预付流程编号 + String yflcbh = weaver.general.Util.null2String(rs.getString("yflcbh")); + + //效验是否有历史单据再审批中 + sql = "select b.requestid," + + " b.lcbh," + + " b.gsmc," + + "b.gysmc," + + "a.id," + + "(select lcbh from uf_gysqktzyy where qqid = a.xgyflc) as bh," + + "(select currentnodetype from workflow_requestbase where requestid = b.requestid) as stutas" + + " from " + tableName + "_dt1 a left join " + tableName + " b on a.mainid = b.id " + + " where b.gysmc = '" + gysmc + "' and b.gsmc = '" + gsmc + "' and a.yflcbh = '" + yflcbh + "'"; + log.writeLog("效验是否有历史单据再审批中sql-----> " + sql); + rs.execute(sql); + while(rs.next()){ + String stutas = weaver.general.Util.null2String(rs.getString("stutas")); /* 流程状态 */ + if(!"0".equals(stutas) && !"3".equals(stutas)){ + String bh = weaver.general.Util.null2String(rs.getString("bh")); /* 预付流程编号 */ + String lcbh = weaver.general.Util.null2String(rs.getString("lcbh")); /* 审批中流程编号 */ + ri.getRequestManager().setMessagecontent("当前抵扣明细中【" + bh + "】正在审批中,审批的流程编号为【" + lcbh + "】,请先走完审批中的流程后继续提交该流程!"); + return FAILURE_AND_CONTINUE; + } + } + } + + + + return SUCCESS; + } +} diff --git a/src/main/youhong_ai_jitu_src/com/api/lh/config/DemoConfig.java b/src/main/youhong_ai_jitu_src/com/api/lh/config/DemoConfig.java new file mode 100644 index 0000000..58bbca0 --- /dev/null +++ b/src/main/youhong_ai_jitu_src/com/api/lh/config/DemoConfig.java @@ -0,0 +1,57 @@ +package com.api.lh.config; + +import selfdev.util.base.BaseUtil; +import selfdev.util.log.LogTool; +import weaver.file.Prop; + +/** + * @Description TODO + * @Author louh + * @Date 2022/4/15 10:46 + * @Version 1.0 + */ +public interface DemoConfig { + + LogTool log = new LogTool("/log/lh/action", false); + //当前环境 + String mode = Prop.getPropValue("DevToDC_jntchina","mode"); + //当前路径地址 + String baseUrl = Prop.getPropValue("DevToDC_jntchina", mode + "_baseUrl"); + + //根据流程id或取主表表名 + default String getTableName(String workflowid){ + String tableName = BaseUtil.getBaseInfoByParm("tablename", "workflow_bill", "1", "1", " and id in (select formid from workflow_base where id=" + workflowid + ")"); + return tableName; + } + + //根据主表表名和requestid获取当前数据id + default String getId(String tablename, String requestid){ + String id = BaseUtil.getBaseInfoByParm("id", tablename, "requestid", requestid, "");; + return id; + } + + //根据表名查询建模模块ID + default String getModeid(String tablename){ + String modeid_select=BaseUtil.getBaseInfoByParm("id","modeinfo","1","1"," and formid in (select id from workflow_bill where tablename='uf_triggerwf_log') "); + return modeid_select; + } + + /** + * 根据下拉框的描述获取对应的值 + * @param selectname 下拉框描述 + * @param workflowid 流程id + * @param fieldname 字段名称 + * @param viewtype 默认0 表示主表字段 + * @return + */ + default String getSelectValue(String selectname, String workflowid, String fieldname, String viewtype){ + viewtype = viewtype == "" ? "0":viewtype; + selectname = selectname.trim(); + fieldname = fieldname.trim(); + String selectValue=BaseUtil.getBaseInfoByParm("selectvalue", "workflow_selectitem", "convtomultilang(selectname,7)", selectname, + " and fieldid in (select id from workflow_billfield where billid in (select formid from workflow_base where id="+ workflowid+") and fieldname='" + fieldname + "' and viewtype= " + viewtype + ")"); + return selectValue; + } + + +} diff --git a/src/main/youhong_ai_jitu_src/com/api/lh/port/AddJournal.java b/src/main/youhong_ai_jitu_src/com/api/lh/port/AddJournal.java new file mode 100644 index 0000000..20e1c45 --- /dev/null +++ b/src/main/youhong_ai_jitu_src/com/api/lh/port/AddJournal.java @@ -0,0 +1,81 @@ +package com.api.lh.port; + +import com.alibaba.fastjson.JSONObject; + +import com.api.lh.config.DemoConfig; +import selfdev.util.base.BaseUtil; +import weaver.conn.RecordSet; +import weaver.file.Prop; + +import java.text.SimpleDateFormat; +import java.util.Date; + +/** + * @ClassName AddJournal + * @Description 调用NCC接口日志 + * @Author louh + * @Date 2022/3/1 14:19 + * @Version 1.0 + */ +public class AddJournal { + + /** + * 添加调用日志 + * @param dyjk 调用接口 + * @param cdcs 传递参数 + * @param fhcs 返回参数 + * @param sfcg 是否成功 + * @param lcid 流程id + */ + public static void addInfo(String dyjk, JSONObject cdcs, String fhcs, String sfcg, String lcid){ + SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); + String format = dateFormat.format(new Date()); + RecordSet rs = new RecordSet(); + String select_modeid = getModeId("uf_dynccjkrzb"); + String sql = "insert into uf_dynccjkrzb (formmodeid,modedatacreater,modedatacreatertype,modedatacreatedate,modedatacreatetime, dyjk, cdcs, fhcs, sfcg, lcid)" + + " values (" + "'" + select_modeid + "'," + + "'" + 1 + "'," + + "'" + 0 + "'," + + "'" + format.substring(0, 10) + "'," + + "'" + format.substring(11) + "'," + + "'" + dyjk + "'," + + "'" + cdcs + "'," + + "'" + fhcs + "'," + + "'" + sfcg + "'," + + "'" + lcid + "')"; + rs.execute(sql); + } + + /** + * ncc调用我方接口日志 + * @param dyjk 调用接口 + * @param cdcs 传递参数 + * @param fhcs 返回参数 + * @param sfcg 是否成功 + * @param url 接口路径 + */ + public static void addInfo(String dyjk, Object cdcs, Object fhcs, String sfcg, String url, Object obj){ + SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); + String format = dateFormat.format(new Date()); + RecordSet rs = new RecordSet(); + String select_modeid = getModeId("uf_nccdywfjkrzb"); + String sql = "insert into uf_nccdywfjkrzb (formmodeid,modedatacreater,modedatacreatertype,modedatacreatedate,modedatacreatetime, dyjk,cdcs,fhcs,sfcg,jklj) " + + " values (" + "'" + select_modeid + "'," + + "'" + 1 + "'," + + "'" + 0 + "'," + + "'" + format.substring(0, 10) + "'," + + "'" + format.substring(11) + "'," + + "'" + dyjk + "'," + + "'" + cdcs + "'," + + "'" + fhcs + "'," + + "'" + sfcg + "'," + + "'" + url + "')"; + rs.execute(sql); + } + + //根据表名查询建模模块ID + public static String getModeId(String tablename){ + String modeid_select= BaseUtil.getBaseInfoByParm("id","modeinfo","1","1"," and formid in (select id from workflow_bill where tablename='" + tablename + "') "); + return modeid_select; + } +} diff --git a/src/main/youhong_ai_jitu_src/com/api/lh/port/Billdata.java b/src/main/youhong_ai_jitu_src/com/api/lh/port/Billdata.java new file mode 100644 index 0000000..dc0e897 --- /dev/null +++ b/src/main/youhong_ai_jitu_src/com/api/lh/port/Billdata.java @@ -0,0 +1,216 @@ +package com.api.lh.port; + +import java.util.List; + +/** + * @ClassName Billdata + * @Description 还款单请求----表头参数 + * @Author louh + * @Date 2022/4/14 13:48 + * @Version 1.0 + */ +public class Billdata { + + private String pk_org; /* 财务组织 */ + private String billtypecode; /* 单据类型 */ + private String bzbm; /* 默认 CNY */ + private String paytarget; /* 默认 0 */ + private String dbilldate; /* 单据日期 */ + private String totalmny; /* 还款金额 */ + private String payorg; /* 收款单位 */ + private String payment; /* 结算方式 默认银行转账 17 */ + private String pk_psndoc; /* 还款人 */ + private String psnaccnum; /* 还款人银行账户 */ + private String orgaccnum; /* 收款单位银行账户 */ + private String oarequestid; /* OA requestid */ + private String oavbillcode; /* 来源单据号 */ + private String fydwbm; /* 费用承担单位编码 */ + private String fydeptid; /* 费用承担部门编码 */ + private String zy; /* 备注 */ + private List er_bxcontrast; /* 冲借款信息 */ + + public Billdata(String pk_org, String billtypecode, String bzbm, String paytarget, String dbilldate, String totalmny, String payorg, String payment, String pk_psndoc, String psnaccnum, String orgaccnum, String oarequestid, String oavbillcode, String fydwbm, String fydeptid, String zy, List er_bxcontrast) { + this.pk_org = pk_org; + this.billtypecode = billtypecode == "" ? "2647" : billtypecode; + this.bzbm = bzbm =="" ? "CNY":bzbm; + this.paytarget = paytarget == ""? "0":paytarget; + this.dbilldate = dbilldate; + this.totalmny = totalmny == "" ? "0.00" : totalmny; + this.payorg = payorg; + this.payment = payment == "" ? "17": payment; + this.pk_psndoc = pk_psndoc; + this.psnaccnum = psnaccnum; + this.orgaccnum = orgaccnum; + this.oarequestid = oarequestid; + this.oavbillcode = oavbillcode; + this.fydwbm = fydwbm; + this.fydeptid = fydeptid; + this.zy = zy; + this.er_bxcontrast = er_bxcontrast; + } + + public String getPk_org() { + return pk_org; + } + + public void setPk_org(String pk_org) { + this.pk_org = pk_org; + } + + public String getBilltypecode() { + return billtypecode; + } + + public void setBilltypecode(String billtypecode) { + this.billtypecode = billtypecode == "" ? "263X-Cxx-01" : billtypecode; + } + + public String getBzbm() { + return bzbm; + } + + public void setBzbm(String bzbm) { + this.bzbm = bzbm == "" ? "CNY":bzbm; + } + + public String getPaytarget() { + return paytarget; + } + + public void setPaytarget(String paytarget) { + this.paytarget = paytarget == ""? "0":paytarget; + } + + public String getDbilldate() { + return dbilldate; + } + + public void setDbilldate(String dbilldate) { + this.dbilldate = dbilldate; + } + + public String getTotalmny() { + return totalmny; + } + + public void setTotalmny(String totalmny) { + this.totalmny = totalmny == "" ? "0.00" : totalmny; + } + + public String getPayorg() { + return payorg; + } + + public void setPayorg(String payorg) { + this.payorg = payorg; + } + + public String getPayment() { + return payment; + } + + public void setPayment(String payment) { + this.payment = payment == "" ? "17": payment; + } + + public String getPk_psndoc() { + return pk_psndoc; + } + + public void setPk_psndoc(String pk_psndoc) { + this.pk_psndoc = pk_psndoc; + } + + public String getPsnaccnum() { + return psnaccnum; + } + + public void setPsnaccnum(String psnaccnum) { + this.psnaccnum = psnaccnum; + } + + public String getOrgaccnum() { + return orgaccnum; + } + + public void setOrgaccnum(String orgaccnum) { + this.orgaccnum = orgaccnum; + } + + public String getOarequestid() { + return oarequestid; + } + + public void setOarequestid(String oarequestid) { + this.oarequestid = oarequestid; + } + + public String getOavbillcode() { + return oavbillcode; + } + + public void setOavbillcode(String oavbillcode) { + this.oavbillcode = oavbillcode; + } + + public String getFydwbm() { + return fydwbm; + } + + public void setFydwbm(String fydwbm) { + this.fydwbm = fydwbm; + } + + public String getFydeptid() { + return fydeptid; + } + + public void setFydeptid(String fydeptid) { + this.fydeptid = fydeptid; + } + + public String getZy() { + return zy; + } + + public void setZy(String zy) { + this.zy = zy; + } + + public List getEr_bxcontrast() { + return er_bxcontrast; + } + + public void setEr_bxcontrast(List er_bxcontrast) { + this.er_bxcontrast = er_bxcontrast; + } + + @Override + public String toString() { + return "Billdata{" + + "pk_org='" + pk_org + '\'' + + ", billtypecode='" + billtypecode + '\'' + + ", bzbm='" + bzbm + '\'' + + ", paytarget='" + paytarget + '\'' + + ", dbilldate='" + dbilldate + '\'' + + ", totalmny='" + totalmny + '\'' + + ", payorg='" + payorg + '\'' + + ", payment='" + payment + '\'' + + ", pk_psndoc='" + pk_psndoc + '\'' + + ", psnaccnum='" + psnaccnum + '\'' + + ", orgaccnum='" + orgaccnum + '\'' + + ", oarequestid='" + oarequestid + '\'' + + ", oavbillcode='" + oavbillcode + '\'' + + ", fydwbm='" + fydwbm + '\'' + + ", fydeptid='" + fydeptid + '\'' + + ", zy='" + zy + '\'' + + ", er_bxcontrast=" + er_bxcontrast + + '}'; + } + + public static void main(String[] args) { + Billdata billdata = new Billdata("","","","","","","","","","","","","","","","",null); + System.out.println(billdata); + } + +} diff --git a/src/main/youhong_ai_jitu_src/com/api/lh/port/ErBxcontrast.java b/src/main/youhong_ai_jitu_src/com/api/lh/port/ErBxcontrast.java new file mode 100644 index 0000000..438b7a2 --- /dev/null +++ b/src/main/youhong_ai_jitu_src/com/api/lh/port/ErBxcontrast.java @@ -0,0 +1,45 @@ +package com.api.lh.port; + +/** + * @ClassName ErBxcontrast + * @Description 还款单请求----表体数据 + * @Author louh + * @Date 2022/4/14 13:55 + * @Version 1.0 + */ +public class ErBxcontrast { + + private String jkbillcode; /* ncc借款单号 */ + private String inoutbusiclass; /* 收支项目 */ + private String hkmny; /* 还款金额 */ + + public ErBxcontrast(String jkbillcode, String inoutbusiclass, String hkmny) { + this.jkbillcode = jkbillcode; + this.inoutbusiclass = inoutbusiclass == "" ? "901038" : inoutbusiclass; + this.hkmny = hkmny == "" ? "0.00" : hkmny; + } + + public String getJkbillcode() { + return jkbillcode; + } + + public void setJkbillcode(String jkbillcode) { + this.jkbillcode = jkbillcode; + } + + public String getInoutbusiclass() { + return inoutbusiclass; + } + + public void setInoutbusiclass(String inoutbusiclass) { + this.inoutbusiclass = inoutbusiclass == "" ? "901038" : ""; + } + + public String getHkmny() { + return hkmny; + } + + public void setHkmny(String hkmny) { + this.hkmny = hkmny == "" ? "0.00" : hkmny; + } +} diff --git a/src/main/youhong_ai_jitu_src/com/api/lh/port/Items.java b/src/main/youhong_ai_jitu_src/com/api/lh/port/Items.java new file mode 100644 index 0000000..1fd49a8 --- /dev/null +++ b/src/main/youhong_ai_jitu_src/com/api/lh/port/Items.java @@ -0,0 +1,279 @@ +package com.api.lh.port; + +/** + * @ClassName Items + * @Description 需要抛转的,付款应付单.预付付款单-----明细表字段 + * @Author louh + * @Date 2022/3/1 14:49 + * @Version 1.0 + */ +public class Items { + private String objtype; /* 往来对象 1:供应商 2:部门 3:业务员*/ + private String supplier; /* 供应商编码,往来对象为供应商时必填 */ + private String pu_deptid; /* 业务部门编码 */ + private String pk_psndoc; /* 业务员编码, 往来对象为业务员时必填 */ + private String prepay; /* 付款性质 3:应付款 4:预付款 */ + private String pk_currtype; /* 币种编码 默认CNY */ + private String money_de; /* 贷方原币金额 */ + private String rate; /* 组织本币汇率, 默认1 */ + private String local_money_de; /* 组织本币金额 */ + private String grouprate; /* 组织本币汇率. 默认1 */ + private String groupdebit; /* 集团本币金额 */ + private String globalrate; /* 全局本币汇率, 默认1 */ + private String globaldebit; /* 全局本币金额 */ + private String quantity_de; /* 贷方数量 */ + private String price; /* 单价 */ + private String itemid; /* 采购订单/应付订单明细id*/ + private String ordervbillcode; /* 采购单据号 */ + private String payplanid; /* 付款计划id */ + private String paybillcode; /* 应付单据号 */ + private String scomment; /* 摘要 */ + private String pk_tradetype; /* 单据类型 */ + private String material; /* 物料 */ + private String pk_dept; /* 部门编码 */ + private String ap_recaccount; /* 收款银行账户编码 */ + private String ap_payaccount; /* 付款银行账号编码 默认为空*/ + private String def2; /* 网点编码 */ + public Items(String objtype, String supplier, String pu_deptid, String pk_psndoc, + String prepay, String pk_currtype, String money_de, String rate, + String local_money_de, String grouprate, String groupdebit, + String globalrate, String globaldebit, String quantity_de, + String price, String itemid, String ordervbillcode, String payplanid, + String paybillcode, String scomment, String pk_tradetype, String material, + String pk_dept, String ap_recaccount, String ap_payaccount, String def2) { + this.objtype = objtype; + this.supplier = supplier; + this.pu_deptid = pu_deptid; + this.pk_psndoc = pk_psndoc; + this.prepay = prepay; + this.pk_currtype = pk_currtype; + this.money_de = money_de; + this.rate = rate; + this.local_money_de = local_money_de; + this.grouprate = grouprate; + this.groupdebit = groupdebit; + this.globalrate = globalrate; + this.globaldebit = globaldebit; + this.quantity_de = quantity_de; + this.price = price; + this.itemid = itemid; + this.ordervbillcode = ordervbillcode; + this.payplanid = payplanid; + this.paybillcode = paybillcode; + this.scomment = scomment; + this.pk_tradetype = pk_tradetype; + this.material = material; + this.pk_dept = pk_dept; + this.ap_recaccount = ap_recaccount; + this.ap_payaccount = ap_payaccount; + this.def2 = def2; + } + + public String getObjtype() { + return objtype; + } + + public void setObjtype(String objtype) { + this.objtype = objtype; + } + + public String getSupplier() { + return supplier; + } + + public void setSupplier(String supplier) { + this.supplier = supplier; + } + + public String getPu_deptid() { + return pu_deptid; + } + + public void setPu_deptid(String pu_deptid) { + this.pu_deptid = pu_deptid; + } + + public String getPk_psndoc() { + return pk_psndoc; + } + + public void setPk_psndoc(String pk_psndoc) { + this.pk_psndoc = pk_psndoc; + } + + public String getPrepay() { + return prepay; + } + + public void setPrepay(String prepay) { + this.prepay = prepay; + } + + public String getPk_currtype() { + return pk_currtype; + } + + public void setPk_currtype(String pk_currtype) { + this.pk_currtype = pk_currtype; + } + + public String getMoney_de() { + return money_de; + } + + public void setMoney_de(String money_de) { + this.money_de = money_de; + } + + public String getRate() { + return rate; + } + + public void setRate(String rate) { + this.rate = rate; + } + + public String getLocal_money_de() { + return local_money_de; + } + + public void setLocal_money_de(String local_money_de) { + this.local_money_de = local_money_de; + } + + public String getGrouprate() { + return grouprate; + } + + public void setGrouprate(String grouprate) { + this.grouprate = grouprate; + } + + public String getGroupdebit() { + return groupdebit; + } + + public void setGroupdebit(String groupdebit) { + this.groupdebit = groupdebit; + } + + public String getGlobalrate() { + return globalrate; + } + + public void setGlobalrate(String globalrate) { + this.globalrate = globalrate; + } + + public String getGlobaldebit() { + return globaldebit; + } + + public void setGlobaldebit(String globaldebit) { + this.globaldebit = globaldebit; + } + + public String getQuantity_de() { + return quantity_de; + } + + public void setQuantity_de(String quantity_de) { + this.quantity_de = quantity_de; + } + + public String getPrice() { + return price; + } + + public void setPrice(String price) { + this.price = price; + } + + public String getItemid() { + return itemid; + } + + public void setItemid(String itemid) { + this.itemid = itemid; + } + + public String getOrdervbillcode() { + return ordervbillcode; + } + + public void setOrdervbillcode(String ordervbillcode) { + this.ordervbillcode = ordervbillcode; + } + + public String getPayplanid() { + return payplanid; + } + + public void setPayplanid(String payplanid) { + this.payplanid = payplanid; + } + + public String getPaybillcode() { + return paybillcode; + } + + public void setPaybillcode(String paybillcode) { + this.paybillcode = paybillcode; + } + + public String getScomment() { + return scomment; + } + + public void setScomment(String scomment) { + this.scomment = scomment; + } + + public String getPk_tradetype() { + return pk_tradetype; + } + + public void setPk_tradetype(String pk_tradetype) { + this.pk_tradetype = pk_tradetype; + } + + public String getMaterial() { + return material; + } + + public void setMaterial(String material) { + this.material = material; + } + + public String getPk_dept() { + return pk_dept; + } + + public void setPk_dept(String pk_dept) { + this.pk_dept = pk_dept; + } + + public String getAp_recaccount() { + return ap_recaccount; + } + + public void setAp_recaccount(String ap_recaccount) { + this.ap_recaccount = ap_recaccount; + } + + public String getAp_payaccount() { + return ap_payaccount; + } + + public void setAp_payaccount(String ap_payaccount) { + this.ap_payaccount = ap_payaccount; + } + + public String getDef2() { + return def2; + } + + public void setDef2(String def2) { + this.def2 = def2; + } +} diff --git a/src/main/youhong_ai_jitu_src/com/api/lh/port/StuData.java b/src/main/youhong_ai_jitu_src/com/api/lh/port/StuData.java new file mode 100644 index 0000000..c152dd5 --- /dev/null +++ b/src/main/youhong_ai_jitu_src/com/api/lh/port/StuData.java @@ -0,0 +1,234 @@ +package com.api.lh.port; + +import weaver.soa.workflow.request.RequestService; + +import java.util.List; + +/** + * @ClassName StuData + * @Description 需要抛转的,付款应付单.预付付款单-----主表字段 + * @Author louh + * @Date 2022/3/1 14:48 + * @Version 1.0 + */ +public class StuData { + private String local_money; /* 组织本币金额 */ + private String globallocal; /* 全局本币金额 */ + private String pk_tradetype; /* 交易类型编码: D3*/ + private String pk_currtype; /* 币种编码 默认CNY */ + private String grouplocal; /* 集团本币对象*/ + private String objtype; /* 往来对象 1:供应商编码,2:部门编码 3:业务员编码 */ + private String pk_org; /* 财务组织编码 */ + private String pu_deptid; /* 业务部门编码 */ + private String money; /* 原币金额 */ + private String rate; /* 组织本币汇率 默认1*/ + private String billmaker; /* 制单人编码 */ + private String supplier; /* 供应商编码 */ + private String grouprate; /* 集团本币汇率 默认1 */ + private String billdate; /* 制单日期 yyyy-MM-dd */ + private String ap_payaccount; /* 付款银行账户 */ + private String globalrate; /* 全局本币汇率 默认1*/ + private String oarequestid; /* Oarequestid*/ + private String oabillcode; /* oa单据编号 */ + private String ap_recaccount; /* 付款银行账户 */ + private String def80; /* 付款银行备注 */ + private List items; + + public StuData(String pk_org, String pk_tradetype, String billdate, + String objtype, String pk_currtype, String ap_recaccount, + String money, String rate, String local_money, String grouprate, + String grouplocal, String globalrate, String globallocal, + String billmaker, String oarequestid, String oabillcode, String supplier, + List items,String pu_deptid, String ap_payaccount, String def80) { + this.pk_org = pk_org; + this.pk_tradetype = pk_tradetype; + this.billdate = billdate; + this.objtype = objtype; + this.pk_currtype = pk_currtype; + this.ap_recaccount = ap_recaccount; + this.money = money; + this.rate = rate; + this.local_money = local_money; + this.grouprate = grouprate; + this.grouplocal = grouplocal; + this.globalrate = globalrate; + this.globallocal = globallocal; + this.billmaker = billmaker; + this.oarequestid = oarequestid; + this.oabillcode = oabillcode; + this.supplier = supplier; + this.items = items; + this.pu_deptid = pu_deptid; + this.ap_payaccount = ap_payaccount; + this.def80 = def80; + } + + public String getPk_org() { + return pk_org; + } + + public void setPk_org(String pk_org) { + this.pk_org = pk_org; + } + + public String getPk_tradetype() { + return pk_tradetype; + } + + public void setPk_tradetype(String pk_tradetype) { + this.pk_tradetype = pk_tradetype; + } + + public String getBilldate() { + return billdate; + } + + public void setBilldate(String billdate) { + this.billdate = billdate; + } + + public String getObjtype() { + return objtype; + } + + public void setObjtype(String objtype) { + this.objtype = objtype; + } + + public String getPk_currtype() { + return pk_currtype; + } + + public void setPk_currtype(String pk_currtype) { + this.pk_currtype = pk_currtype; + } + + public String getAp_recaccount() { + return ap_recaccount; + } + + public void setAp_recaccount(String ap_recaccount) { + this.ap_recaccount = ap_recaccount; + } + + public String getMoney() { + return money; + } + + public void setMoney(String money) { + this.money = money; + } + + public String getRate() { + return rate; + } + + public void setRate(String rate) { + this.rate = rate; + } + + public String getLocal_money() { + return local_money; + } + + public void setLocal_money(String local_money) { + this.local_money = local_money; + } + + public String getGrouprate() { + return grouprate; + } + + public void setGrouprate(String grouprate) { + this.grouprate = grouprate; + } + + public String getGrouplocal() { + return grouplocal; + } + + public void setGrouplocal(String grouplocal) { + this.grouplocal = grouplocal; + } + + public String getGlobalrate() { + return globalrate; + } + + public void setGlobalrate(String globalrate) { + this.globalrate = globalrate; + } + + public String getGloballocal() { + return globallocal; + } + + public void setGloballocal(String globallocal) { + this.globallocal = globallocal; + } + + public String getBillmaker() { + return billmaker; + } + + public void setBillmaker(String billmaker) { + this.billmaker = billmaker; + } + + public String getOarequestid() { + return oarequestid; + } + + public void setOarequestid(String oarequestid) { + this.oarequestid = oarequestid; + } + + public String getOabillcode() { + return oabillcode; + } + + public void setOabillcode(String oabillcode) { + this.oabillcode = oabillcode; + } + + public String getSupplier() { + return supplier; + } + + public void setSupplier(String supplier) { + this.supplier = supplier; + } + + public List getItems() { + return items; + } + + public void setItems(List items) { + this.items = items; + } + + public String getPu_deptid() { + return pu_deptid; + } + + public void setPu_deptid(String pu_deptid) { + this.pu_deptid = pu_deptid; + } + + public String getAp_payaccount() { + return ap_payaccount; + } + + public void setAp_payaccount(String ap_payaccount) { + this.ap_payaccount = ap_payaccount; + } + + public String getDef80() { + return def80; + } + + public void setDef80(String def80) { + this.def80 = def80; + } + +} diff --git a/src/main/youhong_ai_jitu_src/com/api/lh/util/CreateProcessUtil.java b/src/main/youhong_ai_jitu_src/com/api/lh/util/CreateProcessUtil.java new file mode 100644 index 0000000..baa5cc6 --- /dev/null +++ b/src/main/youhong_ai_jitu_src/com/api/lh/util/CreateProcessUtil.java @@ -0,0 +1,93 @@ +package com.api.lh.util; + +import com.alibaba.fastjson.JSONObject; +import weaver.general.Util; +import weaver.soa.workflow.request.Cell; +import weaver.soa.workflow.request.Property; + +import java.util.Arrays; + +/** + * @ClassName CreateProcessUtil + * @Description 创建流程 + * @Author louh + * @Date 2022/4/6 13:35 + * @Version 1.0 + */ +public class CreateProcessUtil { + + /** + * 拼接流程主表字段 + * @param p + * @param name 字段名 + * @param value 字段值 + * @return + */ + public static Property[] setProperty(Property[] p, String name, String value){ + if("".equals(Util.null2String(value).trim())){ + return p; + } + p = Arrays.copyOf(p, (p.length + 1)); + p[p.length - 1] = new Property(); + p[p.length - 1].setName(name); + p[p.length - 1].setValue(value); + return p; + } + + /** + * 拼接流程明细表字段 + * @param c + * @param name 字段名 + * @param value 字段值 + * @return + */ + public static Cell[] setCell(Cell[] c, String name, String value){ + if("".equals(Util.null2String(value).trim())){ + return c; + } + c = Arrays.copyOf(c, (c.length+1)); + c[c.length-1] = new Cell(); + c[c.length-1].setName(name); + c[c.length-1].setValue(value); + return c; + } + + + /** + * 判断流程是否成功 + * @param requestid + * @param + * @return + */ + public static JSONObject judge(String requestid){ + JSONObject jsonObject=new JSONObject(); + jsonObject.put("requestid",requestid); + String MSG=""; + String status = "1"; // 0.成功 1.失败 + if (requestid.equals("-1")) { + MSG="创建流程失败!"; + }else if (requestid.equals("-2")){ + MSG="用户没有流程创建权限!"; + }else if (requestid.equals("-3")) { + MSG="流程基本信息失败!"; + }else if (requestid.equals("-4")) { + MSG="流程表单主表信息失败!"; + }else if (requestid.equals("-5")) { + MSG="流程紧急程度失败!"; + }else if (requestid.equals("-6")) { + MSG="流程操作者失效!"; + }else if (requestid.equals("-7")) { + MSG="流转至下一节点失败!"; + }else if (requestid.equals("-8")) { + MSG="流程节点附加操作失败!"; + }else if (Integer.parseInt(requestid)>0) { + status = "0"; + MSG="流程创建成功!"; + } + jsonObject.put("status", status); + jsonObject.put("msg",MSG); + return jsonObject; + } + + +} diff --git a/src/main/youhong_ai_jitu_src/com/api/lh/util/DUtil.java b/src/main/youhong_ai_jitu_src/com/api/lh/util/DUtil.java new file mode 100644 index 0000000..5ebbb09 --- /dev/null +++ b/src/main/youhong_ai_jitu_src/com/api/lh/util/DUtil.java @@ -0,0 +1,60 @@ +package com.api.lh.util; + +import java.text.SimpleDateFormat; +import java.util.Calendar; + +/** + * @ClassName DateUtil + * @Description TODO + * @Author louh + * @Date 2022/6/7 14:30 + * @Version 1.0 + */ +public class DUtil { + + /** + * 获取指定月份的最后一天 + * @param yearMonth 格式yyyy-MM + * @return + */ + public static String getLastDayOfMonth(String yearMonth){ + int year = Integer.parseInt(yearMonth.split("-")[0]); //年 + int month = Integer.parseInt(yearMonth.split("-")[1]); //月 + Calendar cal = Calendar.getInstance(); + //设置年份 + cal.set(Calendar.YEAR, year); + //设置月份 + cal.set(Calendar.MONTH, month); + //获取某月的最小天数 + int lastDay = cal.getActualMinimum(Calendar.DAY_OF_MONTH); + cal.set(Calendar.DAY_OF_MONTH, lastDay - 1); + SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd"); + return sdf.format(cal.getTime()); + } + + + /** + * 获取指定月份的下个月第一天 + * @param yearMonth 格式yyyy-MM + * @return + */ + public static String getFirstDayOfNextMonth(String yearMonth){ + int year = Integer.parseInt(yearMonth.split("-")[0]); //年 + int month = Integer.parseInt(yearMonth.split("-")[1]); //月 + Calendar cal = Calendar.getInstance(); + //设置年份 + cal.set(Calendar.YEAR, year); + //设置月份 + cal.set(Calendar.MONTH, month - 1); + //获取某月的最大天数 + int lastDay = cal.getActualMaximum(Calendar.DAY_OF_MONTH); + cal.set(Calendar.DAY_OF_MONTH, lastDay + 1); + SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd"); + return sdf.format(cal.getTime()); + } + + public static void main(String[] args) { + System.out.println(getLastDayOfMonth("2022-06-11")); + System.out.println(getFirstDayOfNextMonth("2022-05-17")); + } +} diff --git a/src/main/youhong_ai_jitu_src/com/engine/demo/impl/BaseUtil.java b/src/main/youhong_ai_jitu_src/com/engine/demo/impl/BaseUtil.java new file mode 100644 index 0000000..9a7ab42 --- /dev/null +++ b/src/main/youhong_ai_jitu_src/com/engine/demo/impl/BaseUtil.java @@ -0,0 +1,1719 @@ +package com.engine.demo.impl; +import com.alibaba.fastjson.JSONArray; +import com.alibaba.fastjson.JSONObject; +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import selfdev.util.log.LogTool; +import weaver.conn.ConnStatement; +import weaver.conn.RecordSet; +import weaver.conn.RecordSetTrans; +import weaver.general.BaseBean; +import weaver.general.StaticObj; +import weaver.general.Util; +import weaver.interfaces.datasource.DataSource; +import weaver.sm.SM4Utils; +import javax.crypto.Cipher; +import javax.crypto.SecretKey; +import javax.crypto.SecretKeyFactory; +import javax.crypto.spec.DESKeySpec; +import javax.crypto.spec.IvParameterSpec; +import java.io.UnsupportedEncodingException; +import java.math.BigDecimal; +import java.net.URLEncoder; +import java.nio.charset.Charset; +import java.sql.Date; +import java.sql.*; +import java.text.DecimalFormat; +import java.text.SimpleDateFormat; +import java.util.*; +import java.util.regex.Pattern; + +public class BaseUtil { + + private final static LogTool loghr = new LogTool("/log/duban/",false); + private final static LogTool log1 = new LogTool("/log/duban/",false); + public static String getUserPasswordByRom(String password){ + String newpassword=""; + password= Util.null2String(password).trim(); + newpassword=password; + if (password.endsWith("_random_")) { + SM4Utils var50 = new SM4Utils(); + BaseBean var11 = new BaseBean(); + String var12 = Util.null2String(var11.getPropValue("weaver_client_pwd", "key")); + if (!"".equals(var12)) { + password = password.substring(0, password.lastIndexOf("_random_")); + newpassword = var50.decrypt(password, var12); + } + } + return newpassword; + } + + public static String encrypt(String srcStr, Charset charset, String sKey) { + byte[] src = srcStr.getBytes(charset); + byte[] buf = encrypt(src, sKey); + return parseByte2HexStr(buf); + } + + public static String decrypt(String hexStr, Charset charset, String sKey) throws Exception { + byte[] src = parseHexStr2Byte(hexStr); + byte[] buf = decrypt(src, sKey); + return new String(buf, charset); + } + + private static byte[] encrypt(byte[] data, String sKey) { + try { + byte[] key = sKey.getBytes(); + IvParameterSpec iv = new IvParameterSpec(key); + DESKeySpec desKey = new DESKeySpec(key); + SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES"); + SecretKey securekey = keyFactory.generateSecret(desKey); + Cipher cipher = Cipher.getInstance("DES/CBC/PKCS5Padding"); + cipher.init(Cipher.ENCRYPT_MODE, securekey, iv); + return cipher.doFinal(data); + } catch (Throwable e) { + e.printStackTrace(); + } + return null; + } + + private static byte[] decrypt(byte[] src, String sKey) throws Exception { + byte[] key = sKey.getBytes(); + IvParameterSpec iv = new IvParameterSpec(key); + DESKeySpec desKey = new DESKeySpec(key); + SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES"); + SecretKey securekey = keyFactory.generateSecret(desKey); + Cipher cipher = Cipher.getInstance("DES/CBC/PKCS5Padding"); + cipher.init(Cipher.DECRYPT_MODE, securekey, iv); + return cipher.doFinal(src); + } + + private static String parseByte2HexStr(byte buf[]) { + StringBuffer sb = new StringBuffer(); + for (int i = 0; i < buf.length; i++) { + String hex = Integer.toHexString(buf[i] & 0xFF); + if (hex.length() == 1) { + hex = '0' + hex; + } + sb.append(hex.toUpperCase()); + } + return sb.toString(); + } + + private static byte[] parseHexStr2Byte(String hexStr) { + if (hexStr.length() < 1) return null; + byte[] result = new byte[hexStr.length() / 2]; + for (int i = 0; i < hexStr.length() / 2; i++) { + int high = Integer.parseInt(hexStr.substring(i * 2, i * 2 + 1), 16); + int low = Integer.parseInt(hexStr.substring(i * 2 + 1, i * 2 + 2), 16); + result[i] = (byte) (high * 16 + low); + } + return result; + } + public static void main1(String[] args) { + + String encryptUserName=encrypt("xiaoh", Charset.forName("UTF-8"), "sloginfr"); + System.out.println("encryptUserName------>"+encryptUserName); + } + public static String getFormidId(String workflowid){ + StringBuffer lSQL = new StringBuffer(); + lSQL.append(" SELECT formid FROM workflow_base WHERE id='"+workflowid+"' "); + RecordSet rs = new RecordSet(); + rs.execute(lSQL.toString()); + String formid=""; + if(rs.next()){ + formid= Util.null2String(rs.getString("formid")); + formid=Math.abs(Integer.parseInt(formid))+""; + } + return formid; + } + public static String getFormidIdByrequestid(String requestid){ + StringBuffer lSQL = new StringBuffer(); + lSQL.append(" SELECT a.formid FROM workflow_base a,workflow_requestbase b WHERE b.requestid='"+requestid+"' and a.id=b.workflowid "); + RecordSet rs = new RecordSet(); + rs.execute(lSQL.toString()); + String formid=""; + if(rs.next()){ + formid= Util.null2String(rs.getString("formid")); + formid=Math.abs(Integer.parseInt(formid))+""; + } + return formid; + } + + /** + * 获取流程节点状态ID + * @param workflowid 流程ID + * @param type 流程节点类型 0:申请人 1:归档 + * @return 节点ID + */ + public String getworkflowNode(String workflowid,String type){ + String workflownodeid=""; + if("".equals(Util.null2String(type).trim())){ + type="0"; + } + RecordSet re=new RecordSet(); + String sql=""; + if("0".equals(Util.null2String(type).trim())){ + sql="select top 100 a.id from workflow_nodebase a,workflow_flownode b where a.id=b.nodeid and isstart='1' and workflowid='"+workflowid+"' "; + } + if("1".equals(Util.null2String(type).trim())){ + sql="select top 100 a.id from workflow_nodebase a,workflow_flownode b where a.id=b.nodeid and isend='1' and workflowid='"+workflowid+"' "; + } + + re.execute(sql); + while(re.next()){ + workflownodeid= Util.null2String(re.getString("id")).trim() ; + } + return workflownodeid; + } + /** + * 通过映射表定位流程字段对应的取值字段 + * + * @return 流程取值字段的集合 + */ + public Map setFieldMap(){ + Map map=new HashMap(); + //if("".equals(Util.null2String(field).trim())){ + //return map; + //} + String sql="select * from uf_wfmfield"; + RecordSet re=new RecordSet(); + re.execute(sql); + while(re.next()){ + String workflowfield= Util.null2String(re.getString("wffield")).trim().toLowerCase(); + String modelfield= Util.null2String(re.getString("mfield")).trim().toLowerCase(); + if("".equals(workflowfield)||"".equals(modelfield)){ + continue; + } + map.put(workflowfield, modelfield); + } + return map; + } + + + public String getWorkflowFieldid(String workflowid,String fieldname){ + if("".equals(Util.null2String(fieldname).trim())){ + return ""; + } + RecordSet re=new RecordSet(); + String fieldid=""; + String sql="select b.* from workflow_base a,workflow_billfield b where "+ + " a.formid=b.billid and a.id='"+workflowid+"' and lower(fieldname)='"+(Util.null2String(fieldname).trim().toLowerCase())+"' "; + + re.execute(sql) ; + while(re.next()){ + fieldid= Util.null2String(re.getString("id")).trim(); + } + return fieldid; + } + /* + * 获取字段名称 + */ + public String getWorkflowFieldName(String feildid){ + if("".equals(Util.null2String(feildid).trim())){ + return ""; + } + RecordSet re=new RecordSet(); + String fieldid=""; + String sql="select a.*,b.labelname from workflow_billfield a,HtmlLabelInfo b,uf_mwfl c where a.id=c.wffield and a.fieldlabel=b.indexid and b.languageid=7 and c.mfield='"+feildid+"'"; + + re.execute(sql) ; + while(re.next()){ + fieldid= Util.null2String(re.getString("labelname")).trim()+","; + } + return fieldid; + } + /* + * 获取下拉框的值 + */ + public String getSelectItemVakName(String feildid,String selectval){ + if("".equals(Util.null2String(feildid).trim())||"".equals(Util.null2String(selectval).trim())){ + return ""; + } + String selectname=""; + RecordSet re=new RecordSet(); + String sql="select * from workflow_SelectItem_model_v where mfield='"+ Util.null2String(feildid).trim()+"' and zsselectvalue in ("+ Util.null2String(selectval).trim()+") order by listorder"; + + re.execute(sql) ; + while(re.next()){ + selectname= Util.null2String(re.getString("selectname")).trim()+","; + } + if(selectname.endsWith(",")){ + selectname=selectname.substring(0,selectname.length()-1); + } + return selectname; + } + + public static boolean executeUpdateTran(String datesource,String sql,Object... params){ + boolean flag=true; + DataSource ds =null; + Connection conn = null; + PreparedStatement stmt =null; + //获取HR数据源 + try { + ds = (DataSource) StaticObj.getServiceByFullname(("datasource."+datesource), DataSource.class); + conn = ds.getConnection(); + stmt = conn.prepareStatement(sql); + //设置手工提交 + conn.setAutoCommit(false); + if(params != null && params.length>0) { + int i = 1; + for(Object para:params) { + if (((para instanceof Integer)) || ((para instanceof Long))){ + stmt.setInt(i, Util.getIntValue(""+para)); + }else if ((para instanceof Float)){ + stmt.setFloat(i, Util.getFloatValue(""+para)); + }else if (((para instanceof BigDecimal)) || ((para instanceof Double))){ + if((para instanceof BigDecimal)){ + stmt.setBigDecimal(i,(BigDecimal)para); + }else{ + double tBig= Util.getDoubleValue(""+para); + // BigDecimal temp=new BigDecimal(tBig); + stmt.setString(i,doubleToStr(tBig)); + } + }else if ((para instanceof Date)){ + stmt.setDate(i, (Date)para); + }else if (((para instanceof String)) || ((para instanceof Character))){ + stmt.setString(i, ""+para); + }else if (para == null){ + stmt.setNull(i, 0); + }else if ((para instanceof Clob)){ + stmt.setClob(i, (Clob)para); + }else if ((para instanceof Blob)){ + stmt.setBlob(i, (Blob)para); + }else { + stmt.setObject(i, para); + } + i++; + } + } + int len=stmt.executeUpdate(); + if(len>0){ + flag=true; + conn.commit(); + }else{ + flag=false; + } + stmt.close(); + }catch (Exception e){ + try { + stmt.close(); + conn.close(); + }catch(Exception e1){ + e1.printStackTrace(); + } + flag=false; + } + return flag; + } + public static boolean executeUpdateListTran(String datesource, List> list){ + boolean flag=true; + DataSource ds =null; + Connection conn = null; + PreparedStatement stmt =null; + //获取HR数据源 + try { + ds = (DataSource) StaticObj.getServiceByFullname(("datasource."+datesource), DataSource.class); + conn = ds.getConnection(); + conn.setAutoCommit(false); + for(Map sqls:list) { + if(sqls==null||sqls.size()<=0){ + continue; + } + String sql=(String)sqls.get("sql"); + log1.writeLog("executeUpdateListTran--->"+sql); + Object[] params=(Object[])sqls.get("params"); + log1.writeLog("executeUpdateListTran--->"+params.length); + if(params!=null&¶ms.length>0){ + Arrays.toString(params); + } + stmt = conn.prepareStatement(sql); + //设置手工提交 + + if (params != null && params.length > 0) { + int i = 1; + for (Object para : params) { + if (((para instanceof Integer)) || ((para instanceof Long))) { + stmt.setInt(i, Util.getIntValue("" + para)); + } else if ((para instanceof Float)) { + stmt.setFloat(i, Util.getFloatValue("" + para)); + } else if (((para instanceof BigDecimal)) || ((para instanceof Double))) { + if ((para instanceof BigDecimal)) { + stmt.setBigDecimal(i, (BigDecimal) para); + } else { + double tBig = Util.getDoubleValue("" + para); + // BigDecimal temp=new BigDecimal(tBig); + if(tBig==0){ + stmt.setString(i, null); + }else { + stmt.setString(i, doubleToStr(tBig)); + } + } + } else if ((para instanceof Date)) { + stmt.setDate(i, (Date) para); + } else if (((para instanceof String)) || ((para instanceof Character))) { + stmt.setString(i, "" + para); + } else if (para == null) { + stmt.setNull(i, 0); + } else if ((para instanceof Clob)) { + stmt.setClob(i, (Clob) para); + } else if ((para instanceof Blob)) { + stmt.setBlob(i, (Blob) para); + } else { + stmt.setObject(i, para); + } + i++; + } + } + int len = stmt.executeUpdate(); + log1.writeLog("len--->"+len); +// if (len > 0) { +// flag = true; +// } +// } else { +// flag = false; +// stmt.close(); +// conn.rollback(); +// break; +// } + } + conn.commit(); + conn.close(); + }catch (Exception e){ + log1.writeLog("executeUpdateListTranException"+e.getMessage()); + try { + conn.rollback(); + conn.close(); + }catch(Exception e1){ + e1.printStackTrace(); + } + flag=false; + } + return flag; + } + /** + * 采用缓存的 形式 + * @param list + * @return + */ + public static boolean executeUpdateListTran(List> list){ + boolean flag=true; + + //获取HR数据源 + try { + RecordSetTrans rest=new RecordSetTrans(); + rest.setAutoCommit(false); + for(Map sqls:list) { + if(sqls==null||sqls.size()<=0){ + continue; + } + String sql=(String)sqls.get("sql"); + log1.writeLog("executeUpdateListTran--->"+sql); + Object[] params=(Object[])sqls.get("params"); + Object[] newparams=null; + log1.writeLog("executeUpdateListTran--->"+params.length); + if(params!=null&¶ms.length>0){ + Arrays.toString(params); + } + //设置手工提交 + + if (params != null && params.length > 0) { + newparams=new Object[params.length ]; + int i = 0; + for (Object para : params) { + if (((para instanceof Integer)) || ((para instanceof Long))) { + //stmt.setInt(i, Util.getIntValue("" + para)); + //20210120 福福大帝 用于为空的时候设置为 null + if(para!=null){ + newparams[i]=Util.getIntValue("" + para); + } + } else if ((para instanceof Float)) { + //stmt.setFloat(i, Util.getFloatValue("" + para)); + newparams[i]=Util.getFloatValue("" + para); + } else if (((para instanceof BigDecimal)) || ((para instanceof Double))) { + if ((para instanceof BigDecimal)) { + //stmt.setBigDecimal(i, (BigDecimal) para); + newparams[i]=(BigDecimal) para; + } else { + double tBig = Util.getDoubleValue("" + para); + // BigDecimal temp=new BigDecimal(tBig); + if(tBig==0){ + //stmt.setString(i, null); + newparams[i]=null; + }else { + //stmt.setString(i, doubleToStr(tBig)); + newparams[i]=doubleToStr(tBig); + } + } + } else if ((para instanceof Date)) { + //stmt.setDate(i, (Date) para); + newparams[i]=""; + } else if (((para instanceof String)) || ((para instanceof Character))) { + //stmt.setString(i, "" + para); + newparams[i]="" + para; + } else if (para == null) { + //stmt.setNull(i, 0); + newparams[i]=null; + } else if ((para instanceof Clob)) { + //stmt.setClob(i, (Clob) para); + newparams[i]=null; + } else if ((para instanceof Blob)) { + //stmt.setBlob(i, (Blob) para); + newparams[i]=null; + } else { + //stmt.setObject(i, para); + newparams[i]=para; + } + i++; + } + }else{ + newparams=new Object[]{null}; + } + flag=rest.executeUpdate(sql,newparams); + if(!flag){ + rest.rollback(); + throw new Exception("执行异常"); + + } + } + rest.commit(); + + }catch (Exception e){ + log1.writeLog("executeUpdateListTranException"+e.getMessage()); + + flag=false; + } + return flag; + } + public static boolean executeUpdate(String sql,Object... params) throws Exception { + ConnStatement conn = new ConnStatement(); + + try { + conn.setStatementSql(sql); + if(params != null && params.length>0) { + int i = 1; + for(Object para:params) { + if (((para instanceof Integer)) || ((para instanceof Long))){ + conn.setInt(i, Util.getIntValue(""+para)); + }else if ((para instanceof Float)){ + conn.setFloat(i, Util.getFloatValue(""+para)); + }else if (((para instanceof BigDecimal)) || ((para instanceof Double))){ + if((para instanceof BigDecimal)){ + conn.setBigDecimal(i,(BigDecimal)para); + }else{ + double tBig= Util.getDoubleValue(""+para); + // BigDecimal temp=new BigDecimal(tBig); + conn.setString(i,doubleToStr(tBig)); + } + }else if ((para instanceof Date)){ + conn.setDate(i, (Date)para); + }else if (((para instanceof String)) || ((para instanceof Character))){ + conn.setString(i, ""+para); + }else if (para == null){ + conn.setNull(i, 0); + }else if ((para instanceof Clob)){ + conn.setClob(i, (Clob)para); + }else if ((para instanceof Blob)){ + conn.setBlob(i, (Blob)para); + }else { + conn.setObject(i, para); + } + i++; + } + } + conn.executeUpdate(); + + }catch(Exception e){ + //printLog(sql,params); + throw e; + }finally { + conn.close(); + } + return true; + } + /** + * 转换URL的中文 + * @param url + * @return + * @throws UnsupportedEncodingException + */ + private String convertURL(String url,String code) throws UnsupportedEncodingException { + String urlStr = ""; + //将中文分割出来 以UTF8编码 + String strs[] = url.split("/"); + if(strs.length==0) urlStr = url; + int i = 0; + for(String s : strs){ + if(i == (strs.length-1)){ + if(isChinese(s)){ + urlStr += URLEncoder.encode(s, code)+""; + }else{ + urlStr += s+""; + } + }else{ + if(isChinese(s)){ + urlStr += URLEncoder.encode(s, code)+"/"; + }else{ + urlStr += s+"/"; + } + } + i++; + } + return urlStr; + } + /** + * 判断是否包含中文字符 + * @param strName + * @return + */ + boolean isChinese(String strName) { + char[] ch = strName.toCharArray(); + for (int i = 0; i < ch.length; i++) { + char c = ch[i]; + if (isChinese(c) == true) { + return isChinese(c); + } else { + if(i == (ch.length-1)){ + return isChinese(c); + }else{ + continue; + } + } + } + return false; + } + boolean isChinese(char c) { + Character.UnicodeBlock ub = Character.UnicodeBlock.of(c); + if (ub == Character.UnicodeBlock.CJK_UNIFIED_IDEOGRAPHS + || ub == Character.UnicodeBlock.CJK_COMPATIBILITY_IDEOGRAPHS + || ub == Character.UnicodeBlock.CJK_UNIFIED_IDEOGRAPHS_EXTENSION_A + || ub == Character.UnicodeBlock.GENERAL_PUNCTUATION + || ub == Character.UnicodeBlock.CJK_SYMBOLS_AND_PUNCTUATION + || ub == Character.UnicodeBlock.HALFWIDTH_AND_FULLWIDTH_FORMS) { + return true; + } + return false; + } + public static String getTempFilename(String str){ + String tempName=""; + try{ + if(str==null||"".equals(str)){ + return ""; + } + if(str.indexOf("?")>1){ + str=str.substring(0,str.indexOf("?")); + } + tempName=str.substring(str.lastIndexOf("/")+1); + }catch(Exception e){ + + } + return tempName; + } + /** + * java dobule数据转字符串输出 + * @param tempX 需要被转换的数据 + * @return 默认保留4位小数输出 + */ + public static String doubleToStr(double tempX) { + double newStemp=round(tempX, 4); + DecimalFormat df = new DecimalFormat("0.0000"); + String newff = df.format(newStemp); + return newff; + } + /** + * 四舍五入 + * @param v + * @param scale 精确位数 + */ + public static double round(double v, int scale) { + if (scale < 0) { + throw new IllegalArgumentException( + "The scale must be a positive integer or zero"); + } + BigDecimal b = new BigDecimal(Double.toString(v)); + BigDecimal one = new BigDecimal("1"); + return b.divide(one, scale, BigDecimal.ROUND_HALF_UP).doubleValue(); + } + /** + * 四舍五入 + * @param v + * @param scale 精确位数 + */ + public static float roundF(double v, int scale) { + if (scale < 0) { + throw new IllegalArgumentException( + "The scale must be a positive integer or zero"); + } + BigDecimal b = new BigDecimal(Double.toString(v)); + BigDecimal one = new BigDecimal("1"); + return b.divide(one, scale, BigDecimal.ROUND_HALF_UP).floatValue(); + } + /* + 拼接文号 + */ + public static String getWh(int len){ + if(len<=0){ + return ""; + } + String str=""; + for(int i=0;i]*?>[\\s\\S]*?<\\/script> + // } + String regEx_style = "<[\\s]*?style[^>]*?>[\\s\\S]*?<[\\s]*?\\/[\\s]*?style[\\s]*?>"; // 定义style的正则表达式{或]*?>[\\s\\S]*?<\\/style> + // } + String regEx_html = "<[^>]+>"; // 定义HTML标签的正则表达式 + String regEx_html1 = "<[^>]+"; + p_script = Pattern.compile(regEx_script, Pattern.CASE_INSENSITIVE); + m_script = p_script.matcher(htmlStr); + htmlStr = m_script.replaceAll(""); // 过滤script标签 + + p_style = Pattern.compile(regEx_style, Pattern.CASE_INSENSITIVE); + m_style = p_style.matcher(htmlStr); + htmlStr = m_style.replaceAll(""); // 过滤style标签 + + p_html = Pattern.compile(regEx_html, Pattern.CASE_INSENSITIVE); + m_html = p_html.matcher(htmlStr); + htmlStr = m_html.replaceAll(""); // 过滤html标签 + + p_html1 = Pattern.compile(regEx_html1, Pattern.CASE_INSENSITIVE); + m_html1 = p_html1.matcher(htmlStr); + htmlStr = m_html1.replaceAll(""); // 过滤html标签 + + textStr = htmlStr; + + } catch (Exception e) { + //System.err.println("Html2Text: " + e.getMessage()); + textStr=""; + } + + return textStr;// 返回文本字符串 + } + /* + 获取字段ID + */ + public static String getFilebillid(String feildname,int bilid,int dettail){ + String fieldid=""; + RecordSet re=new RecordSet(); + String sql=""; + if(dettail<=0){//主表 + sql="select * from workflow_billfield where upper(fieldname)=upper('"+feildname+"') and billid=-"+bilid; + }else{//明细 + sql="select * from workflow_billfield where upper(fieldname)=upper('"+feildname+"') and detailtable='formtable_main_"+bilid+"_dt"+dettail+"' and billid=-"+bilid; + } + loghr.writeLog("getFilebillid---"+sql); + re.execute(sql); + while(re.next()){ + fieldid= Util.null2String(re.getString("id")).trim(); + } + return fieldid; + } + /* + 获取主流程的 requestid 以及requestmark + */ + public static Map getMainRequestbaseByreq(String requestid){ + Map main=new HashMap<>(); + RecordSet re=new RecordSet(); + String mainrequestid=""; + String mainrequestmark=""; + String sql="select b.requestid,b.requestmark from workflow_requestbase a left join workflow_requestbase b on a.mainrequestid=b.requestid where a.requestid='"+requestid+"' "; + log1.writeLog("getMainRequestbaseByreq--"+sql); + re.execute(sql); + while(re.next()){ + mainrequestid= Util.null2String(re.getString("requestid")).trim() ; + mainrequestmark= Util.null2String(re.getString("requestmark")).trim() ; + } + main.put("mainrequestid",mainrequestid); + main.put("mainrequestmark",mainrequestmark); + log1.writeLog("getMainRequestbaseByreq--"+main.toString()); + return main; + } + public static double getfloats(String demo,int len){ + //Logger log = Logger.getLogger(BigDecimal.class); + if(len==0){ + len=2; + } + String str= Util.null2String(demo); + if("".equals(str)||"".equals(str.trim())||"null".equalsIgnoreCase(str.trim())){ + return 0; + } + double fl=0.0f; + //String str=Util.null2String(demo); + try{ + if(str.trim().length()>0){ + BigDecimal b1 = new BigDecimal(str.trim()); + //System.out.println(b1.setScale(2,BigDecimal.ROUND_HALF_UP)); + fl=b1.setScale(len,BigDecimal.ROUND_HALF_UP).doubleValue(); + } + //log.error("getfloats"+fl); + }catch(Exception e){ + loghr.writeLog(demo+"getfloats异常"+e.getMessage()); + } + + return fl; + } + /* + 设置跟新的 数据的 标准的 数据 只是更新 一二级 分解 其他的不动 + */ + public static List> BaseUpdDate(String requestid){ + RecordSet re=new RecordSet(); + List> listMap=new ArrayList>(); + Map map = null;//new HashMap(); + String sql="select * from uf_zjljlhzbb where mainrequestid='"+requestid+"' and isnull(jb,-1) in (1,2) and isnull(sfyx,-1) in (0,-1)"; + re.execute(sql); + while(re.next()){ + String id= Util.null2String( re.getString("id")).trim(); + if(!"".equals(id)){ + //设置更新数据 建模 + Object[] objval = new Object[1];//存储值 + objval[0]=id; + map=new HashMap(); + map.put("sql","update uf_zjljlhzbb set sfyx='1' where id=?"); + map.put("params",objval); + listMap.add(map); + } + } + return listMap; + } + // 通过 主流程 获取 以及分解 流程requestid 以及 requestmark + public static Map getReqMarkByMainreq(String mainrequestid){ + RecordSet re=new RecordSet(); + Map map=new HashMap(); + //取一级分解 + String sql="select * from uf_zjljlhzbb where tragwfreq='"+mainrequestid+"' and isnull(jb,-1)=1 and isnull(sfyx,-1) in (0,-1)"; + re.execute(sql); + if(re.next()){ + String requestid= Util.null2String(re.getString("wfrequestid")); + String requestmark= Util.null2String(re.getString("wfrequestmark")); + map.put("requestid",requestid); + map.put("requestmark",requestmark); + } + return map; + } + //获取分部矩阵信息 + public static String getMax_1(String userid,String subid){ + String subidStr=""; + RecordSet re=new RecordSet(); + String sql="select * from matrixtable_1 where ','+CAST(jxsjxgy as varchar(800))+',' like ',"+userid+",' and id in ("+subid+")"; + log1.writeLog("getMax_1--->"+sql); + re.execute(sql); + while(re.next()){ + String id= Util.null2String(re.getString("id")).trim() ; + if("".equals(id)){ + continue; + } + subidStr=subidStr+id+","; + } + if(subidStr.endsWith(",")){ + subidStr=subidStr.substring(0,subidStr.length()-1); + } + return subidStr; + } + //通过部门以及人员获取分部矩阵信息 + public static String getMax_1ByDep(String userid,String depid){ + String subidStr=""; + RecordSet re=new RecordSet(); + String sql="select * from matrixtable_1 where ','+CAST(jxsjxgy as varchar(800))+',' like ',"+userid+",' and id in (select subcompanyid1 from hrmdepartment where id in ("+depid+"))"; + log1.writeLog("getMax_1ByDep--->"+sql); + re.execute(sql); + while(re.next()){ + String id= Util.null2String(re.getString("id")).trim() ; + if("".equals(id)){ + continue; + } + subidStr=subidStr+id+","; + } + if(subidStr.endsWith(",")){ + subidStr=subidStr.substring(0,subidStr.length()-1); + } + return subidStr; + } + //通过部门以及人员获取分部矩阵信息 + public static JSONObject getMax_2ByUser(String userid, String depid){ + JSONObject json=new JSONObject(); + String subidStr=""; + String depidStr=""; + RecordSet re=new RecordSet(); + String sql="select a.id,b.subcompanyid1 from matrixtable_2 a , HrmDepartment b where a.id=b.id and ','+CAST(a.bc as varchar(800))+',' like ',"+userid+",' and a.id in ("+depid+") "; + log1.writeLog("getMax_2ByUser--->"+sql); + re.execute(sql); + while(re.next()){ + String id= Util.null2String(re.getString("id")).trim() ; + String subcompanyid1= Util.null2String(re.getString("subcompanyid1")).trim() ; + if("".equals(id)){ + continue; + } + subidStr=subidStr+subcompanyid1+","; + depidStr=depidStr+id+","; + } + if(depidStr.endsWith(",")){ + depidStr=depidStr.substring(0,depidStr.length()-1); + } + if(subidStr.endsWith(",")){ + subidStr=subidStr.substring(0,subidStr.length()-1); + } + json.put("dep",depidStr); + json.put("sub",subidStr); + return json; + } + /* + 获取单位分部数据 + 添加判断还未设置完成的 不允许变更 或者有变更数据没有归档 + + 校验是否存在 分部 没分解 部门分解数据等 + + sudid 分部id + mainRequestid 主数据ID + 0:总经理分解 + 1:一级分解 + 2:二级分解 + */ + public static JSONObject getSubData(String sudid, String mainRequestid, String requestid){ + RecordSet re=new RecordSet(); + JSONObject resultjson=new JSONObject(); + JSONObject json=new JSONObject(); + JSONArray jsons=new JSONArray(); + + JSONObject levezjl=new JSONObject();//总经理 + + JSONObject leve1_dw=new JSONObject();//一级 单位 + JSONObject leve1_gr=new JSONObject();//一级 个人 + JSONObject leve1_dp=new JSONObject();//一级 大盘 + + + JSONObject leve2=new JSONObject();//二级 + + JSONObject fblxje=new JSONObject();//单位分解大盘金额 + JSONObject fblx=new JSONObject();//单位分解类型 + JSONObject bmlxje=new JSONObject();//单位分解大盘金额 + //不可存在在途变更流程 会造成数据混轮乱 + if(checkChangeWf(mainRequestid,requestid)){ + return resultjson; + } + String sql="select a.*,b.subcompanyname,c.departmentname,d.lastname from uf_zjljlhzbb a left join HrmSubCompany b on a.bjldwfb=b.id " + + " left join hrmdepartment c on a.jldwbm=c.id " + + " left join hrmresource d on a.xm=d.id " + + " where mainrequestid='"+mainRequestid+"' and isnull(sfyx,-1) in (0,-1) and a.bjldwfb in ("+sudid+")"; + log1.writeLog("getSubDatanew--->"+sql); + + re.execute(sql); + while(re.next()){ + json=new JSONObject(); + String id= Util.null2String(re.getString("id")).trim();//建模ID + String jb= Util.null2String(re.getString("jb")).trim();//级别 + if("".equals(jb)){ + continue; + } + + String sqjlje= Util.null2String(re.getString("sqjlje")).trim();//申请奖励金额 + String hrfbdpje= Util.null2String(re.getString("hrfbdpje")).trim();//划入分部大盘金额 + String fjlx= Util.null2String(re.getString("fjlx")).trim();//分解类型 + String bjldwfb= Util.null2String(re.getString("bjldwfb")).trim();//被奖励单位(分部) + String jljefb= Util.null2String(re.getString("jljefb")).trim();//奖励金额(分部) + String qzzcldjlje= Util.null2String(re.getString("qzzcldjlje")).trim();//其中中层领导奖励金额 + String qzjldwje= Util.null2String(re.getString("qzjldwje")).trim();//其中奖励单位金额 + String jlfpbz= Util.null2String(re.getString("jlfpbz")).trim();//奖励分配备注 + String zcld= Util.null2String(re.getString("zcld")).trim();//中层领导 + String zcldjlje= Util.null2String(re.getString("zcldjlje")).trim();//中层领导奖励金额 + String zcldfpbz= Util.null2String(re.getString("zcldfpbz")).trim();//中层领导分配备注 + String jldwbm= Util.null2String(re.getString("jldwbm")).trim();//奖励单位(部门) + String dwjljebm= Util.null2String(re.getString("dwjljebm")).trim();//单位奖励金额(部门) + String dwjlbz= Util.null2String(re.getString("dwjlbz")).trim();//单位奖励备注 + String xm= Util.null2String(re.getString("xm")).trim();//姓名 + String grjlje= Util.null2String(re.getString("grjlje")).trim();//个人奖励金额 + String grjlbz= Util.null2String(re.getString("grjlbz")).trim();//个人奖励备注 + String hrdpjebm= Util.null2String(re.getString("hrdpjebm")).trim();//划入大盘金额(部门) + String subcompanyname= Util.null2String(re.getString("subcompanyname")).trim();//分部名称 + String departmentname= Util.null2String(re.getString("departmentname")).trim();//部门名称 + String lastname= Util.null2String(re.getString("lastname")).trim();//姓名 + String mainrequestid= Util.null2String(re.getString("mainrequestid")).trim();//mainrequestid + String wfrequestid= Util.null2String(re.getString("wfrequestid")).trim();//mainrequestid + if("0".equals(jb)){ + + if("1".equals(levezjl.getString(bjldwfb))){ + continue; + } + levezjl.put(bjldwfb,"1"); + } + if("1".equals(jb)){ + fblxje.put(bjldwfb,hrfbdpje); + fblx.put(bjldwfb,fjlx); + if("0".equals(fjlx)){//单位 + //leve1_dw.put(bjldwfb,jldwbm); + if("".equals(Util.null2String(leve1_dw.getString(bjldwfb)).trim())){ + leve1_dw.put(bjldwfb,jldwbm+","); + }else{ + String bmstr= Util.null2String(leve1_dw.getString(bjldwfb)).trim(); + bmstr=bmstr+jldwbm+","; + leve1_dw.put(bjldwfb,bmstr); + } + } + if("1".equals(fjlx)){//个人 + leve1_gr.put(bjldwfb,"1"); + } + if("2".equals(fjlx)){//大盘 + leve1_dp.put(bjldwfb,"1"); + } + } + if("2".equals(jb)){ + leve2.put(jldwbm,"1"); + bmlxje.put(jldwbm,hrdpjebm ); + } + JSONArray demoJsons=resultjson.getJSONArray(jb); + if(demoJsons==null||demoJsons.size()<=0){ + demoJsons=new JSONArray(); + resultjson.put(jb,demoJsons); + } + json.put("jb",jb); + json.put("id",id); + json.put("sqjlje",sqjlje); + json.put("hrfbdpje",hrfbdpje); + json.put("fjlx",fjlx); + json.put("bjldwfb",bjldwfb); + json.put("jljefb",jljefb); + json.put("qzzcldjlje",qzzcldjlje); + json.put("qzjldwje",qzjldwje); + json.put("jlfpbz",jlfpbz); + json.put("zcld",zcld); + json.put("zcldjlje",zcldjlje); + json.put("zcldfpbz",zcldfpbz); + json.put("jldwbm",jldwbm); + json.put("dwjljebm",dwjljebm); + json.put("dwjlbz",dwjlbz); + json.put("xm",xm); + json.put("grjlje",grjlje); + json.put("grjlbz",grjlbz); + json.put("hrdpjebm",hrdpjebm); + json.put("subcompanyname",subcompanyname); + json.put("departmentname",departmentname); + json.put("lastname",lastname); + json.put("mainrequestid",mainrequestid); + json.put("wfrequestid",wfrequestid); + demoJsons.add(json); + + } + log1.writeLog(resultjson.toJSONString()); + log1.writeLog(levezjl.toJSONString()); + log1.writeLog(leve1_dw.toJSONString()); + log1.writeLog(leve1_gr.toJSONString()); + log1.writeLog(leve1_dp.toJSONString()); + log1.writeLog(leve2.toJSONString()); + log1.writeLog(fblxje.toJSONString()); + log1.writeLog(fblx.toJSONString()); + //检验数据 + if(levezjl.size()>0){ + Set fbkey= levezjl.keySet(); + for(String key:fbkey){ + String str1= Util.null2String(leve1_dw.getString(key)).trim() ; + String str2= Util.null2String(leve1_gr.getString(key)).trim() ; + String str3= Util.null2String(leve1_dp.getString(key)).trim() ; + if("".equals(str1)&&"".equals(str2)&&"".equals(str3)){ + + log1.writeLog("not sub data"+key); + return new JSONObject(); + } + if(!"".equals(str1)){ + String[] bmAll= str1.split(","); + for(String str:bmAll){ + + if(!"".equals(str)){ + if(!"1".equals(Util.null2String(leve2.getString(str)).trim())){ + log1.writeLog("not dep data"+str); + return new JSONObject(); + } + } + } + } + } + + }else{ + return new JSONObject(); + } + if(resultjson.size()>0){ + resultjson.put("fbje",fblxje); + resultjson.put("fblx",fblx); + resultjson.put("bmje",bmlxje); + } + return resultjson; + } + /* + 获取单位部门数据(用于只是修改二级分解个人数据) + sudid 分部id + mainRequestid 主数据ID + 0:总经理分解 + 1:一级分解 + 2:二级分解 + */ + public static JSONObject getDepData(String depid, String sudid, String mainRequestid){ + RecordSet re=new RecordSet(); + JSONObject resultjson=new JSONObject(); + JSONObject json=new JSONObject(); + JSONObject bmdpJson=new JSONObject(); + + JSONObject bmTofb=new JSONObject();//部门所属分部 + JSONObject userTobm=new JSONObject();//人员所属部门 + + JSONArray jsons=new JSONArray(); + JSONObject levezjl=new JSONObject(); + String sql="select a.*,b.subcompanyname,c.departmentname,d.lastname from uf_zjljlhzbb a left join HrmSubCompany b on a.bjldwfb=b.id " + + " left join hrmdepartment c on a.jldwbm=c.id " + + " left join hrmresource d on a.xm=d.id " + + " where mainrequestid='"+mainRequestid+"' and isnull(sfyx,-1) in (0,-1) and a.bjldwfb in ("+sudid+") and isnull(jb,-1)=0"+ + " union all "+ + "select a.*,b.subcompanyname,c.departmentname,d.lastname from uf_zjljlhzbb a left join HrmSubCompany b on a.bjldwfb=b.id " + + " left join hrmdepartment c on a.jldwbm=c.id " + + " left join hrmresource d on a.xm=d.id " + + " where mainrequestid='"+mainRequestid+"' and isnull(sfyx,-1) in (0,-1) and a.bjldwfb in ("+sudid+") and a.jldwbm in ("+depid+") and isnull(jb,-1)=1 and fjlx='0' "+ + " union all "+ + " select a.*,b.subcompanyname,c.departmentname,d.lastname from uf_zjljlhzbb a left join HrmSubCompany b on a.bjldwfb=b.id " + + " left join hrmdepartment c on a.jldwbm=c.id " + + " left join hrmresource d on a.xm=d.id " + + " where mainrequestid='"+mainRequestid+"' and isnull(sfyx,-1) in (0,-1) and a.bjldwfb in ("+sudid+") and a.jldwbm in ("+depid+") and isnull(jb,-1)=2"; + log1.writeLog("getDepData--->"+sql); + re.execute(sql); + while(re.next()){ + json=new JSONObject(); + String id= Util.null2String(re.getString("id")).trim();//建模ID + String jb= Util.null2String(re.getString("jb")).trim();//级别 + if("".equals(jb)){ + continue; + } + String sqjlje= Util.null2String(re.getString("sqjlje")).trim();//申请奖励金额 + String hrfbdpje= Util.null2String(re.getString("hrfbdpje")).trim();//划入分部大盘金额 + String fjlx= Util.null2String(re.getString("fjlx")).trim();//分解类型 + String bjldwfb= Util.null2String(re.getString("bjldwfb")).trim();//被奖励单位(分部) + String jljefb= Util.null2String(re.getString("jljefb")).trim();//奖励金额(分部) + String qzzcldjlje= Util.null2String(re.getString("qzzcldjlje")).trim();//其中中层领导奖励金额 + String qzjldwje= Util.null2String(re.getString("qzjldwje")).trim();//其中奖励单位金额 + String jlfpbz= Util.null2String(re.getString("jlfpbz")).trim();//奖励分配备注 + String zcld= Util.null2String(re.getString("zcld")).trim();//中层领导 + String zcldjlje= Util.null2String(re.getString("zcldjlje")).trim();//中层领导奖励金额 + String zcldfpbz= Util.null2String(re.getString("zcldfpbz")).trim();//中层领导分配备注 + String jldwbm= Util.null2String(re.getString("jldwbm")).trim();//奖励单位(部门) + String dwjljebm= Util.null2String(re.getString("dwjljebm")).trim();//单位奖励金额(部门) + String dwjlbz= Util.null2String(re.getString("dwjlbz")).trim();//单位奖励备注 + String xm= Util.null2String(re.getString("xm")).trim();//姓名 + String grjlje= Util.null2String(re.getString("grjlje")).trim();//个人奖励金额 + String grjlbz= Util.null2String(re.getString("grjlbz")).trim();//个人奖励备注 + String hrdpjebm= Util.null2String(re.getString("hrdpjebm")).trim();//划入大盘金额(部门) + String subcompanyname= Util.null2String(re.getString("subcompanyname")).trim();//分部名称 + String departmentname= Util.null2String(re.getString("departmentname")).trim();//部门名称 + String lastname= Util.null2String(re.getString("lastname")).trim();//姓名 + String mainrequestid= Util.null2String(re.getString("mainrequestid")).trim();//mainrequestid + if("".equals(bjldwfb)||"".equals(jldwbm)){ + continue; + } + if("0".equals(jb)){ + if("1".equals(levezjl.getString(bjldwfb))){ + continue; + } + levezjl.put(bjldwfb,"1"); + } + if("1".equals(jb)){//一级分解 + bmTofb.put(jldwbm,bjldwfb); + } + + JSONArray demoJsons=resultjson.getJSONArray(jb); + if(demoJsons==null||demoJsons.size()<=0){ + demoJsons=new JSONArray(); + resultjson.put(jb,demoJsons); + } + if("2".equals(jb)){ + bmdpJson.put(jldwbm,hrdpjebm); + userTobm.put(jldwbm,"1"); + } + json.put("jb",jb); + json.put("id",id); + json.put("sqjlje",sqjlje); + json.put("hrfbdpje",hrfbdpje); + json.put("fjlx",fjlx); + json.put("bjldwfb",bjldwfb); + json.put("jljefb",jljefb); + json.put("qzzcldjlje",qzzcldjlje); + json.put("qzjldwje",qzjldwje); + json.put("jlfpbz",jlfpbz); + json.put("zcld",zcld); + json.put("zcldjlje",zcldjlje); + json.put("zcldfpbz",zcldfpbz); + json.put("jldwbm",jldwbm); + json.put("dwjljebm",dwjljebm); + json.put("dwjlbz",dwjlbz); + json.put("xm",xm); + json.put("grjlje",grjlje); + json.put("grjlbz",grjlbz); + json.put("hrdpjebm",hrdpjebm); + json.put("subcompanyname",subcompanyname); + json.put("departmentname",departmentname); + json.put("lastname",lastname); + json.put("mainrequestid",mainrequestid); + demoJsons.add(json); + + } + //校验数据是否分解完毕 + //int fblen=0;//分部计数 + log1.writeLog(" levezjl-->"+levezjl.toJSONString()); + log1.writeLog(" bmTofb-->"+bmTofb.toJSONString()); + log1.writeLog(" userTobm-->"+userTobm.toJSONString()); + JSONObject fblen=new JSONObject();//分部计数 + if(levezjl.size()>0){ + //Set levezjlkey=levezjl.keySet(); + //for(String key:levezjlkey){ + + //} + + if(bmTofb.size()>0){ + Set bmTofbkey=bmTofb.keySet(); + for(String key:bmTofbkey){//key 代表分部 + String fbkey=bmTofb.getString(key); + String userTobmStr= Util.null2String(userTobm.getString(key)).trim() ; + if(!"1".equals(userTobmStr)){ + return new JSONObject(); + }else{ + fblen.put(fbkey,"-1"); + } + } + if(fblen.size()!=levezjl.size()){ + return new JSONObject(); + } + }else{ + return new JSONObject(); + } + + }else{ + return new JSONObject(); + } + if(resultjson.size()>0){ + resultjson.put("bmdp",bmdpJson); + } + + log1.writeLog(resultjson.toJSONString()); + + return resultjson; + } + /* + 获取单位部门数据(用于只是修改二级分解个人数据) + sudid 分部id + mainRequestid 主数据ID + 0:总经理分解 + 1:一级分解 + 2:二级分解 + */ + public static JSONObject getDepDataDetail(String depid, String sudid, String mainRequestid){ + RecordSet re=new RecordSet(); + boolean leve2l=false;//是否存在二级分部 + JSONObject resultjson=new JSONObject(); + JSONObject DetailJson=new JSONObject(); + JSONObject json=new JSONObject(); + JSONArray jsons=new JSONArray(); + String sql="select a.*,b.subcompanyname,c.departmentname,d.lastname from uf_zjljlhzbb a left join HrmSubCompany b on a.bjldwfb=b.id " + + " left join hrmdepartment c on a.jldwbm=c.id " + + " left join hrmresource d on a.xm=d.id " + + " where mainrequestid='"+mainRequestid+"' and isnull(sfyx,-1) in (0,-1) and a.bjldwfb in ("+sudid+") and isnull(jb,-1)=0"+ + " union all "+ + "select a.*,b.subcompanyname,c.departmentname,d.lastname from uf_zjljlhzbb a left join HrmSubCompany b on a.bjldwfb=b.id " + + " left join hrmdepartment c on a.jldwbm=c.id " + + " left join hrmresource d on a.xm=d.id " + + " where mainrequestid='"+mainRequestid+"' and isnull(sfyx,-1) in (0,-1) and a.bjldwfb in ("+sudid+") and a.jldwbm in ("+depid+") and isnull(jb,-1)=1 and fjlx='0' "+ + " union all "+ + " select a.*,b.subcompanyname,c.departmentname,d.lastname from uf_zjljlhzbb a left join HrmSubCompany b on a.bjldwfb=b.id " + + " left join hrmdepartment c on a.jldwbm=c.id " + + " left join hrmresource d on a.xm=d.id " + + " where mainrequestid='"+mainRequestid+"' and isnull(sfyx,-1) in (0,-1) and a.bjldwfb in ("+sudid+") and a.jldwbm in ("+depid+") and isnull(jb,-1)=2"; + log1.writeLog("getDepDataDetail--->"+sql); + re.execute(sql); + while(re.next()){ + json=new JSONObject(); + String id= Util.null2String(re.getString("id")).trim();//建模ID + String jb= Util.null2String(re.getString("jb")).trim();//级别 + if("".equals(jb)){ + continue; + } + if("2".equals(jb)){//存在部门分解 + leve2l=true; + } + if("0".equals(jb)||"2".equals(jb)){ + continue; + } + + String nf= Util.null2String(re.getString("nf")).trim();//年份 + String yf= Util.null2String(re.getString("yf")).trim();//月份 + String sqr= Util.null2String(re.getString("sqr")).trim();//申请人 + String jlxmmc= Util.null2String(re.getString("jlxmmc")).trim();//奖励项目名称 + + String sqjlje= Util.null2String(re.getString("sqjlje")).trim();//申请奖励金额 + String hrfbdpje= Util.null2String(re.getString("hrfbdpje")).trim();//划入分部大盘金额 + String fjlx= Util.null2String(re.getString("fjlx")).trim();//分解类型 + String bjldwfb= Util.null2String(re.getString("bjldwfb")).trim();//被奖励单位(分部) + String jljefb= Util.null2String(re.getString("jljefb")).trim();//奖励金额(分部) + String qzzcldjlje= Util.null2String(re.getString("qzzcldjlje")).trim();//其中中层领导奖励金额 + String qzjldwje= Util.null2String(re.getString("qzjldwje")).trim();//其中奖励单位金额 + String jlfpbz= Util.null2String(re.getString("jlfpbz")).trim();//奖励分配备注 + String zcld= Util.null2String(re.getString("zcld")).trim();//中层领导 + String zcldjlje= Util.null2String(re.getString("zcldjlje")).trim();//中层领导奖励金额 + String zcldfpbz= Util.null2String(re.getString("zcldfpbz")).trim();//中层领导分配备注 + String jldwbm= Util.null2String(re.getString("jldwbm")).trim();//奖励单位(部门) + String dwjljebm= Util.null2String(re.getString("dwjljebm")).trim();//单位奖励金额(部门) + String dwjlbz= Util.null2String(re.getString("dwjlbz")).trim();//单位奖励备注 + String xm= Util.null2String(re.getString("xm")).trim();//姓名 + String grjlje= Util.null2String(re.getString("grjlje")).trim();//个人奖励金额 + String grjlbz= Util.null2String(re.getString("grjlbz")).trim();//个人奖励备注 + String hrdpjebm= Util.null2String(re.getString("hrdpjebm")).trim();//划入大盘金额(部门) + String subcompanyname= Util.null2String(re.getString("subcompanyname")).trim();//分部名称 + String departmentname= Util.null2String(re.getString("departmentname")).trim();//部门名称 + String lastname= Util.null2String(re.getString("lastname")).trim();//姓名 + String mainrequestid= Util.null2String(re.getString("mainrequestid")).trim();//mainrequestid + + String ndjhxm= Util.null2String(re.getString("ndjhxm")).trim();//年度计划-项目 + String ndjhys= Util.null2String(re.getString("ndjhys")).trim();//年度计划-预算 + String ndjhsyed= Util.null2String(re.getString("ndjhsyed")).trim();//年度计划-剩余额度 + String qzjldwjezj= Util.null2String(re.getString("qzjldwjezj")).trim();//其中奖励单位金额总计 + String zcldjljehj= Util.null2String(re.getString("zcldjljehj")).trim();//中层领导奖励金额合计 + String wfrequestid= Util.null2String(re.getString("wfrequestid")).trim();//mainrequestid + json.put("jlxmmc",jlxmmc); + json.put("nf",nf); + json.put("yf",yf); + json.put("sqr",sqr); + json.put("jb",jb); + json.put("id",id); + json.put("sqjlje",sqjlje); + json.put("hrfbdpje",hrfbdpje); + json.put("fjlx",fjlx); + json.put("bjldwfb",bjldwfb); + json.put("jljefb",jljefb); + json.put("qzzcldjlje",qzzcldjlje); + json.put("qzjldwje",qzjldwje); + json.put("jlfpbz",jlfpbz); + json.put("zcld",zcld); + json.put("zcldjlje",zcldjlje); + json.put("zcldfpbz",zcldfpbz); + json.put("jldwbm",jldwbm); + json.put("dwjljebm",dwjljebm); + json.put("dwjlbz",dwjlbz); + json.put("xm",xm); + json.put("grjlje",grjlje); + json.put("grjlbz",grjlbz); + json.put("hrdpjebm",hrdpjebm); + json.put("subcompanyname",subcompanyname); + json.put("departmentname",departmentname); + json.put("lastname",lastname); + json.put("mainrequestid",mainrequestid); + + json.put("ndjhxm",ndjhxm); + json.put("ndjhys",ndjhys); + json.put("ndjhsyed",ndjhsyed); + json.put("qzjldwjezj",qzjldwjezj); + json.put("zcldjljehj",zcldjljehj); + json.put("wfrequestid",wfrequestid); + if("1".equals(jb)){ + + if(DetailJson.get(jldwbm)!=null){ + log1.writeLog("dep must only!"); + return new JSONObject(); + } + DetailJson.put(jldwbm,json); + } + //demoJsons.add(json); + + } + log1.writeLog(DetailJson.toJSONString()); + //resultjson.put("DetailJson",DetailJson); + return DetailJson; + } + /* + 获取单位分部数据 按部门区分 + sudid 分部id + mainRequestid 主数据ID + 0:总经理分解 + 1:一级分解 + 2:二级分解 + 返回 数据集合 以及 ID集合 + */ + public static JSONObject getSubDataDetail(String sudid, String mainRequestid){ + RecordSet re=new RecordSet(); + JSONObject DetailJson=new JSONObject(); + JSONObject Depjson=new JSONObject(); + JSONObject resultjson=null;//new JSONObject(); + JSONObject json=new JSONObject(); + JSONArray jsons=new JSONArray(); + String sql="select a.*,b.subcompanyname,c.departmentname,d.lastname from uf_zjljlhzbb a left join HrmSubCompany b on a.bjldwfb=b.id " + + " left join hrmdepartment c on a.jldwbm=c.id " + + " left join hrmresource d on a.xm=d.id " + + " where mainrequestid='"+mainRequestid+"' and isnull(sfyx,-1) in (0,-1) and a.bjldwfb in ("+sudid+")"; + log1.writeLog("getSubData--->"+sql); + re.execute(sql); + while(re.next()){ + json=new JSONObject(); + String jlxmmc= Util.null2String(re.getString("jlxmmc")).trim();//名称 + String sqr= Util.null2String(re.getString("sqr")).trim();//申请人 + String id= Util.null2String(re.getString("id")).trim();//建模ID + String jb= Util.null2String(re.getString("jb")).trim();//级别 + String nf= Util.null2String(re.getString("nf")).trim();//年份 + String yf= Util.null2String(re.getString("yf")).trim();//月份 + String sqjlje= Util.null2String(re.getString("sqjlje")).trim();//申请奖励金额 + String hrfbdpje= Util.null2String(re.getString("hrfbdpje")).trim();//划入分部大盘金额 + String fjlx= Util.null2String(re.getString("fjlx")).trim();//分解类型 + String bjldwfb= Util.null2String(re.getString("bjldwfb")).trim();//被奖励单位(分部) + String jljefb= Util.null2String(re.getString("jljefb")).trim();//奖励金额(分部) + String qzzcldjlje= Util.null2String(re.getString("qzzcldjlje")).trim();//其中中层领导奖励金额 + String qzjldwje= Util.null2String(re.getString("qzjldwje")).trim();//其中奖励单位金额 + String jlfpbz= Util.null2String(re.getString("jlfpbz")).trim();//奖励分配备注 + String zcld= Util.null2String(re.getString("zcld")).trim();//中层领导 + String zcldjlje= Util.null2String(re.getString("zcldjlje")).trim();//中层领导奖励金额 + String zcldfpbz= Util.null2String(re.getString("zcldfpbz")).trim();//中层领导分配备注 + String jldwbm= Util.null2String(re.getString("jldwbm")).trim();//奖励单位(部门) + String dwjljebm= Util.null2String(re.getString("dwjljebm")).trim();//单位奖励金额(部门) + String dwjlbz= Util.null2String(re.getString("dwjlbz")).trim();//单位奖励备注 + String xm= Util.null2String(re.getString("xm")).trim();//姓名 + String grjlje= Util.null2String(re.getString("grjlje")).trim();//个人奖励金额 + String grjlbz= Util.null2String(re.getString("grjlbz")).trim();//个人奖励备注 + String hrdpjebm= Util.null2String(re.getString("hrdpjebm")).trim();//划入大盘金额(部门) + String subcompanyname= Util.null2String(re.getString("subcompanyname")).trim();//分部名称 + String departmentname= Util.null2String(re.getString("departmentname")).trim();//部门名称 + String lastname= Util.null2String(re.getString("lastname")).trim();//姓名 + String mainrequestid= Util.null2String(re.getString("mainrequestid")).trim();//mainrequestid + String wfrequestid= Util.null2String(re.getString("wfrequestid")).trim();//wfrequestid + + String ndjhxm= Util.null2String(re.getString("ndjhxm")).trim();//年度计划-项目 + String ndjhys= Util.null2String(re.getString("ndjhys")).trim();//年度计划-预算 + String ndjhsyed= Util.null2String(re.getString("ndjhsyed")).trim();//年度计划-剩余额度 + String qzjldwjezj= Util.null2String(re.getString("qzjldwjezj")).trim();//其中奖励单位金额总计 + String zcldjljehj= Util.null2String(re.getString("zcldjljehj")).trim();//中层领导奖励金额合计 + + + if("".equals(jb)||"".equals(bjldwfb)){ + continue; + } + //DetailJson + resultjson= Depjson.getJSONObject(bjldwfb); + if(resultjson==null||resultjson.size()<=0){ + resultjson=new JSONObject(); + Depjson.put(bjldwfb,resultjson); + } + + JSONArray ModelJson=resultjson.getJSONArray(jb); + if(ModelJson==null||ModelJson.size()<=0){ + ModelJson=new JSONArray(); + resultjson.put(jb,ModelJson); + } + json.put("jlxmmc",jlxmmc); + json.put("sqr",sqr); + json.put("jb",jb); + json.put("id",id); + json.put("nf",nf); + json.put("yf",yf); + json.put("sqjlje",sqjlje); + json.put("hrfbdpje",hrfbdpje); + json.put("fjlx",fjlx); + json.put("bjldwfb",bjldwfb); + json.put("jljefb",jljefb); + json.put("qzzcldjlje",qzzcldjlje); + json.put("qzjldwje",qzjldwje); + json.put("jlfpbz",jlfpbz); + json.put("zcld",zcld); + json.put("zcldjlje",zcldjlje); + json.put("zcldfpbz",zcldfpbz); + json.put("jldwbm",jldwbm); + json.put("dwjljebm",dwjljebm); + json.put("dwjlbz",dwjlbz); + json.put("xm",xm); + json.put("grjlje",grjlje); + json.put("grjlbz",grjlbz); + json.put("hrdpjebm",hrdpjebm); + json.put("subcompanyname",subcompanyname); + json.put("departmentname",departmentname); + json.put("lastname",lastname); + json.put("mainrequestid",mainrequestid); + json.put("wfrequestid",wfrequestid); + + json.put("ndjhxm",ndjhxm); + json.put("ndjhys",ndjhys); + json.put("ndjhsyed",ndjhsyed); + json.put("qzjldwjezj",qzjldwjezj); + json.put("zcldjljehj",zcldjljehj); + ModelJson.add(json); + DetailJson.put(id,copyJson(json)); + + } + log1.writeLog(Depjson.toJSONString()); + Depjson.put("DetailJson",DetailJson); + return Depjson; + } + /* + 获取单位分部数据 按部门区分 + sudid 分部id + mainRequestid 主数据ID + 0:总经理分解 + 1:一级分解 + 2:二级分解 + 返回 数据集合 以及 ID集合 + */ + public static JSONObject getSubDataDetailJson(String sudid, String mainRequestid){ + RecordSet re=new RecordSet(); + JSONObject DetailJson=new JSONObject(); + JSONObject Depjson=new JSONObject(); + JSONObject resultjson=null;//new JSONObject(); + JSONObject json=new JSONObject(); + JSONArray jsons=new JSONArray(); + String sql="select a.*,b.subcompanyname,c.departmentname,d.lastname from uf_zjljlhzbb a left join HrmSubCompany b on a.bjldwfb=b.id " + + " left join hrmdepartment c on a.jldwbm=c.id " + + " left join hrmresource d on a.xm=d.id " + + " where mainrequestid='"+mainRequestid+"' and isnull(sfyx,-1) in (0,-1) and a.bjldwfb in ("+sudid+")"; + log1.writeLog("getSubData--->"+sql); + re.execute(sql); + while(re.next()){ + json=new JSONObject(); + String sqr= Util.null2String(re.getString("sqr")).trim();//申请人 + String id= Util.null2String(re.getString("id")).trim();//建模ID + String jb= Util.null2String(re.getString("jb")).trim();//级别 + String nf= Util.null2String(re.getString("nf")).trim();//年份 + String yf= Util.null2String(re.getString("yf")).trim();//月份 + String sqjlje= Util.null2String(re.getString("sqjlje")).trim();//申请奖励金额 + String hrfbdpje= Util.null2String(re.getString("hrfbdpje")).trim();//划入分部大盘金额 + String fjlx= Util.null2String(re.getString("fjlx")).trim();//分解类型 + String bjldwfb= Util.null2String(re.getString("bjldwfb")).trim();//被奖励单位(分部) + String jljefb= Util.null2String(re.getString("jljefb")).trim();//奖励金额(分部) + String qzzcldjlje= Util.null2String(re.getString("qzzcldjlje")).trim();//其中中层领导奖励金额 + String qzjldwje= Util.null2String(re.getString("qzjldwje")).trim();//其中奖励单位金额 + String jlfpbz= Util.null2String(re.getString("jlfpbz")).trim();//奖励分配备注 + String zcld= Util.null2String(re.getString("zcld")).trim();//中层领导 + String zcldjlje= Util.null2String(re.getString("zcldjlje")).trim();//中层领导奖励金额 + String zcldfpbz= Util.null2String(re.getString("zcldfpbz")).trim();//中层领导分配备注 + String jldwbm= Util.null2String(re.getString("jldwbm")).trim();//奖励单位(部门) + String dwjljebm= Util.null2String(re.getString("dwjljebm")).trim();//单位奖励金额(部门) + String dwjlbz= Util.null2String(re.getString("dwjlbz")).trim();//单位奖励备注 + String xm= Util.null2String(re.getString("xm")).trim();//姓名 + String grjlje= Util.null2String(re.getString("grjlje")).trim();//个人奖励金额 + String grjlbz= Util.null2String(re.getString("grjlbz")).trim();//个人奖励备注 + String hrdpjebm= Util.null2String(re.getString("hrdpjebm")).trim();//划入大盘金额(部门) + String subcompanyname= Util.null2String(re.getString("subcompanyname")).trim();//分部名称 + String departmentname= Util.null2String(re.getString("departmentname")).trim();//部门名称 + String lastname= Util.null2String(re.getString("lastname")).trim();//姓名 + String mainrequestid= Util.null2String(re.getString("mainrequestid")).trim();//mainrequestid + String wfrequestid= Util.null2String(re.getString("wfrequestid")).trim();//wfrequestid + + String ndjhxm= Util.null2String(re.getString("ndjhxm")).trim();//年度计划-项目 + String ndjhys= Util.null2String(re.getString("ndjhys")).trim();//年度计划-预算 + String ndjhsyed= Util.null2String(re.getString("ndjhsyed")).trim();//年度计划-剩余额度 + String qzjldwjezj= Util.null2String(re.getString("qzjldwjezj")).trim();//其中奖励单位金额总计 + String zcldjljehj= Util.null2String(re.getString("zcldjljehj")).trim();//中层领导奖励金额合计 + + if("".equals(jb)||"".equals(bjldwfb)){ + continue; + } + //DetailJson + resultjson= Depjson.getJSONObject(bjldwfb); + if(resultjson==null||resultjson.size()<=0){ + resultjson=new JSONObject(); + Depjson.put(bjldwfb,resultjson); + } + + JSONObject ModelJson=resultjson.getJSONObject(jb); + + if(ModelJson==null||ModelJson.size()<=0){ + ModelJson=new JSONObject(); + resultjson.put(jb,ModelJson); + } + json.put("sqr",sqr); + json.put("jb",jb); + json.put("id",id); + json.put("nf",nf); + json.put("yf",yf); + json.put("sqjlje",sqjlje); + json.put("hrfbdpje",hrfbdpje); + json.put("fjlx",fjlx); + json.put("bjldwfb",bjldwfb); + json.put("jljefb",jljefb); + json.put("qzzcldjlje",qzzcldjlje); + json.put("qzjldwje",qzjldwje); + json.put("jlfpbz",jlfpbz); + json.put("zcld",zcld); + json.put("zcldjlje",zcldjlje); + json.put("zcldfpbz",zcldfpbz); + json.put("jldwbm",jldwbm); + json.put("dwjljebm",dwjljebm); + json.put("dwjlbz",dwjlbz); + json.put("xm",xm); + json.put("grjlje",grjlje); + json.put("grjlbz",grjlbz); + json.put("hrdpjebm",hrdpjebm); + json.put("subcompanyname",subcompanyname); + json.put("departmentname",departmentname); + json.put("lastname",lastname); + json.put("mainrequestid",mainrequestid); + json.put("wfrequestid",wfrequestid); + + json.put("ndjhxm",ndjhxm); + json.put("ndjhys",ndjhys); + json.put("ndjhsyed",ndjhsyed); + json.put("qzjldwjezj",qzjldwjezj); + json.put("zcldjljehj",zcldjljehj); + ModelJson.put(id,json); + DetailJson.put(id,copyJson(json)); + + } + log1.writeLog(Depjson.toJSONString()); + Depjson.put("DetailJson",DetailJson); + return Depjson; + } + public static String getAdd(String d,String x,int len){ + String wsdj="0"; + if(d==null|| Util.null2String(d).trim().equals("")){ + d="0"; + } + if(x==null|| Util.null2String(x).trim().equals("")){ + x="0"; + } + try{ + BigDecimal allBig=new BigDecimal(d); + BigDecimal newslBig=new BigDecimal( x); + wsdj=allBig.add(newslBig).setScale(len,BigDecimal.ROUND_HALF_UP).toString(); + }catch(Exception e){ + + } + return wsdj; + } + /* + 获取部门所在的分部 + */ + public static String getSubByDep(String bm){ + RecordSet re=new RecordSet(); + String subcompanyid1=""; + String sql="select subcompanyid1 from hrmdepartment where id='"+bm+"'"; + re.execute(sql); + while(re.next()){ + subcompanyid1= Util.null2String( re.getString("subcompanyid1")).trim(); + } + return subcompanyid1; + } + public static JSONObject copyJson(JSONObject json){ + JSONObject newJson=new JSONObject(); + if(json==null||json.size()<=0){ + return newJson; + } + String str= JSONObject.toJSONString(json); + if(str!=null){ + try{ + newJson= JSONObject.parseObject(str); + }catch(Exception e){ + + } + } + return newJson; + } + /* + 同步分部ID获取分部 名称 + */ + public static String getSubNameBySubid(String id){ + RecordSet re=new RecordSet(); + String subcompanyname=""; + String sql="SELECT subcompanyname FROM HrmSubCompany where id='"+id+"'"; + re.execute(sql); + while(re.next()){ + subcompanyname= Util.null2String(re.getString("subcompanyname")).trim(); + } + return subcompanyname; + } + /* + check 判断是否存在 未变更数据 + */ + public static boolean checkChangeWf(String requestid,String bgrequestid){ + bgrequestid= Util.null2String(bgrequestid).trim(); + if("".equals(Util.null2String(requestid).trim())){ + return false; + } + RecordSet re=new RecordSet(); + String sql=" select a.requestid from formtable_main_107 a,workflow_requestbase b where a.requestid=b.requestid and b.currentnodetype in (1,2) and a.yzjljllc='"+requestid+"'" + + " union all " + + " select a.requestid from formtable_main_108 a,workflow_requestbase b where a.requestid=b.requestid and b.currentnodetype in (1,2) and a.yzjljllc='"+requestid+"'"; + re.execute(sql); + while(re.next()){ + String wfrequestid= Util.null2String("requestid").trim(); + if(wfrequestid.equals(bgrequestid)){ + continue; + } + return true; + } + return false; + } + /* + 获取部门名称 + */ + public static String getDepNameByid(String id){ + RecordSet re=new RecordSet(); + String departmentname=""; + String sql="select departmentname from HrmDepartment where id='"+id+"' "; + re.execute(sql); + while(re.next()){ + departmentname= Util.null2String(departmentname).trim(); + } + return departmentname; + } + /* + 获取当前部门的顶级部门 + */ + public static String getTopDepBydepid(String depid){ + String topdepid=""; + RecordSet re=new RecordSet(); + String sql="select * from hrmdepartment where id='"+depid+"'"; + re.execute(sql); + if(re.next()){ + int supdepid= Util.getIntValue(re.getString("supdepid"),0); + if(supdepid>0){ + topdepid=getTopDepBydepid(supdepid+""); + }else{ + topdepid=depid+""; + } + } + return topdepid; + } + public static String getUUid(){ + UUID uuid = UUID.randomUUID(); + String id = UUID.randomUUID().toString(); + return id; + } + /* + 获取制表日期 + */ + public static String getCreateDate(){ + String date=""; + try{ + SimpleDateFormat sim=new SimpleDateFormat("yyyy年MM月dd日"); + date=sim.format(new java.util.Date()); + + }catch(Exception e){ + + } + return date; + } + public void printParams(Object[] obj){ + if(obj!=null&& obj.length>0){ + for(Object single:obj){ + + } + } + + } + public static void main(String[] arg){ + System.out.println(Arrays.toString(new Object[0])); + } +} diff --git a/src/main/youhong_ai_jitu_src/com/engine/demo/impl/CubeSaveInterccept.java b/src/main/youhong_ai_jitu_src/com/engine/demo/impl/CubeSaveInterccept.java new file mode 100644 index 0000000..aa3b107 --- /dev/null +++ b/src/main/youhong_ai_jitu_src/com/engine/demo/impl/CubeSaveInterccept.java @@ -0,0 +1,316 @@ +package com.engine.demo.impl; + +import com.alibaba.fastjson.JSONArray; +import com.alibaba.fastjson.JSONObject; +import com.weaverboot.frame.ioc.anno.classAnno.WeaIocReplaceComponent; +import com.weaverboot.frame.ioc.anno.methodAnno.WeaReplaceAfter; +import com.weaverboot.frame.ioc.handler.replace.weaReplaceParam.impl.WeaAfterReplaceParam; +import selfdev.util.log.LogTool; +import weaver.conn.RecordSet; +import weaver.dateformat.DateTransformer; +import weaver.general.Util; +import weaver.hrm.HrmUserVarify; +import weaver.hrm.User; +import weaver.systeminfo.SystemEnv; + +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; +import java.util.Map; +import java.util.Set; + +/** + * 拦截 建模数据保存 日志 + */ +@WeaIocReplaceComponent +public class CubeSaveInterccept { + private final static LogTool log = new LogTool("/log/TransField/",false); + +// private static final String qyidField="field7267";//企业ID +// private static final String modiflyField="field7267";//修改的uuid 值 用于定位 修改 log +// private static final String bbrqField="field7267";//版本日期 +// private static final String modeId="84";//拦截 模块 +// public static final int CompanyMaintableFormid=-102;//企业主表 表ID + /** 生产 **/ + private static final String modiflyField="field893767";//""field7267";//修改的uuid 值 用于定位 修改 log uat field677323 + //private static final String qyidField="field7267";//企业ID + private static final String qyidField="field893807";//企业ID uat field659381 + //private static final String bbrqField="field7267";//版本日期 + private static final String bbrqField="field893806";//版本日期 uat field659380 + private static final String modeId="46040";//""84";//拦截 模块 uat 38501 + public static final String CompanyMaintable="uf_jingneiqiyexinxi";//企业主表 + public static final int CompanyMaintableFormid=-3055;//-102;//企业主表 表ID uat -1824 + public static final String CompanyVersionMaintable="formtable_main_3055";//企业版本主表 uat formtable_main_1824 + public static final String filterField=",operateType,detaildataid,fieldid,fieldvalue,detailtable,"; + + + /** 生产 **/ + +// /** 测试 **/ +// private static final String modiflyField="field677323";//""field7267";//修改的uuid 值 用于定位 修改 log uat field677323 +// //private static final String qyidField="field7267";//企业ID +// private static final String qyidField="field659381";//企业ID uat field659381 +// //private static final String bbrqField="field7267";//版本日期 +// private static final String bbrqField="field659380";//版本日期 uat field659380 +// private static final String modeId="38501";//""84";//拦截 模块 uat 38501 +// public static final String CompanyMaintable="uf_jingneiqiyexinxi";//企业主表 +// public static final int CompanyMaintableFormid=-1824;//-102;//企业主表 表ID uat -1824 +// public static final String CompanyVersionMaintable="formtable_main_1824";//企业版本主表 uat formtable_main_1824 +// public static final String filterField=",operateType,detaildataid,fieldid,fieldvalue,detailtable,"; +// /** 测试 **/ + + @WeaReplaceAfter(value = "/api/cube/new/card/doSubmit", order = 10010, description = "拦截 建模数据保存 日志") + public String cubeSaveInterccept(WeaAfterReplaceParam param){ + /** 常规获取参数 **/ + Map params= param.getParamMap(); + HttpServletRequest req =param.getRequest(); + HttpServletResponse resp =param.getResponse(); + String demo =param.getData(); + /** 只是拦截 type=2(编辑) 以及 modiflyField 字段不为空的 操作 **/ + String type=(String)params.get("type"); + String modeIdstr=(String)params.get("modeId"); + String formId=(String)params.get("formId"); + String billid=(String)params.get("billid"); + if("2".equals(type)&&modeId.equals(modeIdstr)){ + try{ + //解析表单参数 + log.writeLog("开始拦截!"); + JSONObject FormJson= JSONObject.parseObject((String)params.get("JSONStr"));// ; + if(FormJson!=null&&FormJson.size()>0){ + log.writeLog(FormJson.toJSONString()); + String modiflyFieldValue= Util.null2String(FormJson.getString(modiflyField)).trim() ; + if("".equals(modiflyFieldValue)){//为空不取日志数据 + return demo; + } + User user = HrmUserVarify.getUser(req, resp); + TransField transField=new TransField(Util.getIntValue(formId,0),billid,user); + transField.setQyid(Util.null2String(FormJson.getString(qyidField)).trim());//企业ID + transField.setBbrq(Util.null2String(FormJson.getString(bbrqField)).trim());//版本日期 + getMainLog(modiflyFieldValue,transField); + } + }catch(Exception e){ + log.writeLog("cubeSaveInterccept-->"+e.getMessage()); + } + } + return demo; + } + + public void getMainLog(String modiflyFieldValue,TransField transField){ + + RecordSet re=new RecordSet(); + JSONObject valJSon=new JSONObject(); + JSONObject detailValJSon=new JSONObject();//明细 + String viewlogid=""; + String sql="select * from ModeLogFieldDetail where viewlogid in (select viewlogid from ModeLogFieldDetail where modeid="+modeId+" and fieldid='"+(modiflyField.replaceAll("field",""))+"' and fieldvalue=?) and modeid="+modeId; + log.writeLog(modiflyFieldValue+""+sql); + re.executeQuery(sql,modiflyFieldValue); + while(re.next()){ + + viewlogid=Util.null2String(re.getString("viewlogid")).trim() ; + String fieldid=Util.null2String(re.getString("fieldid")).trim() ; + String fieldvalue= Util.null2String(re.getString("fieldvalue")).trim(); + String PREFIELDVALUE=Util.null2String(re.getString("PREFIELDVALUE")).trim(); + String detaildataid= Util.null2String(re.getString("detaildataid")).trim(); + String operateType= Util.null2String(re.getString("operateType")).trim();// operateType EDIT,ADD + String detailtable= Util.null2String(re.getString("detailtable")).trim(); + + if(fieldid.equals(modiflyField.replaceAll("field",""))){ + continue; + } + if("".equals(detaildataid)){ + valJSon.put(fieldid,fieldvalue);//主表 + }else{ + if(!"EDIT".equals(operateType)&&!"ADD".equals(operateType)&&!"DEL".equals(operateType)){//目前只是处理编辑以及 新增 不处理删除 + continue; + } + /** 明细表 **/ + String detailtableindex=detailtable.substring(detailtable.lastIndexOf("_")+1);//明细行的下标 + + JSONArray details= detailValJSon.getJSONArray(detailtableindex); + if(details==null||details.size()<=0){ + JSONArray demos=new JSONArray(); + JSONObject demo=new JSONObject(); + demo.put("operateType",operateType); + demo.put("detailtable",detailtable); + demo.put("detaildataid",detaildataid); + demo.put(fieldid,fieldvalue); + if("EDIT".equals(operateType)){ + /** 获取mainbillid **/ + demo.put("mainid",getMainbillid( detaildataid, detailtable)) ; + }else if("DEL".equals(operateType)){ + if(detailtable.indexOf("dt2")>-1&&"893946".equals(fieldid)){ + demo.put("mainid",PREFIELDVALUE) ; + }else if(detailtable.indexOf("dt3")>-1&&"893947".equals(fieldid)){ + demo.put("mainid",PREFIELDVALUE) ; + } + + } + demos.add(demo); + detailValJSon.put(detailtableindex,demos); + }else{ + JSONObject demo=new JSONObject(); + demo.put("operateType",operateType); + demo.put("detaildataid",detaildataid); + demo.put("fieldid",fieldid); + demo.put("fieldvalue",fieldvalue); + demo.put("PREFIELDVALUE",PREFIELDVALUE); + demo.put("detailtable",detailtable); + setJSONArraySingle(details, demo); + } + } + + } + transField.setViewlogid(viewlogid); + if(valJSon!=null&&valJSon.size()>0){ + //获取 value 对应的值 + JSONArray transFieldJSONs=new JSONArray(); + Set key=valJSon.keySet(); + for(String str:key){ + try { + //JSONObject transFieldJSON= ModeLogMainfield( viewlogid,Util.getIntValue(modeId,0),transField.getBillid(),str,valJSon.getString(str), transField); + JSONObject transFieldJSON= ModeLogMainfield( viewlogid,Util.getIntValue(modeId,0),str, transField); + if(transFieldJSON!=null&&transFieldJSON.size()>0){ + transFieldJSONs.add(transFieldJSON); + } + } catch (Exception e) { + e.printStackTrace(); + } + } + if(transFieldJSONs.size()>0){ + transField.setTransFieldJSONs(transFieldJSONs); + } + } + transField.updateCompanyInfo(valJSon,detailValJSon);//生产 sql + transField.updateallmodflyuuid();//更新明细 + } + public JSONObject ModeLogMainfield(String viewlogid,int modeId,String fieldid,TransField transField) throws Exception { + return ModeLogMainfield(viewlogid,modeId,fieldid,transField,"","",""); + } + //public JSONObject ModeLogMainfield(String viewlogid,int modeId,String billid,String fieldid,String value,TransField transField) throws Exception { + public JSONObject ModeLogMainfield(String viewlogid,int modeId,String fieldid,TransField transField,String detaildataid,String operateType,String detailtable) throws Exception { + RecordSet var3=new RecordSet(); + String var4 = "select a.id,a.fieldid,a.fieldvalue,a.prefieldvalue,c.fieldlabel,c.fieldname,c.fieldhtmltype,c.type,c.fielddbtype,c.viewtype from ModeLogFieldDetail a left join workflow_billfield c on a.fieldid=c.id where a.viewlogid = " + viewlogid + " and a.modeid = " + modeId + " and (a.detailtable='' or a.detailtable is null) and fieldid="+fieldid; + if(!"".equals(detaildataid)){ + var4=var4+" and detaildataid='"+detaildataid+"' and operateType='"+operateType+"' and detailtable='"+detailtable+"'"; + } + JSONObject var6 = new JSONObject(); + var3.execute(var4); + while(var3.next()) { + + String var7 = Util.null2String(var3.getString("fieldhtmltype")); + var6.put("htmltype", var7); + int var8 = Util.getIntValue(Util.null2String(var3.getString("type"))); + var6.put("type", var8); + String var9 = Util.null2String(var3.getString("fielddbtype")); + var6.put("dbtype", var9); + String var10 = Util.null2String(var3.getString("fieldid")); + var6.put("fieldid", var10); + String var11 = Util.null2String(var3.getString("viewtype")); + var6.put("viewtype", var11); + String var12 = Util.null2String(var3.getString("fieldvalue")); + String var13 = Util.null2String(var3.getString("prefieldvalue")); + if (var8 == 290) { + var12 = (new DateTransformer()).getLocaleDateTime(var12); + var13 = (new DateTransformer()).getLocaleDateTime(var13); + } + + var6.put("fieldvalue", var12); + var6.put("oldfieldvalue", var12); + var6.put("prefieldvalue", var13); + var6.put("oldprefieldvalue", var13); + String var14 = Util.null2String(SystemEnv.getHtmlLabelName(var3.getInt("fieldlabel"), 7));// 默认 中文 + var6.put("labelname", var14); + String var15 = Util.null2String(var3.getString("fieldname")); + var6.put("fieldname", var15); + var6.put("fieldlabelname", var14 + "(" + var15 + ")"); + //此处需要用到 反设置机制 + //transField.transFieldValue(fieldvalue, fieldhtmltype, fieldid, fielddbtype, viewtype, type) + String var16 = BaseUtil.Html2Text(Util.null2String(transField.transFieldValue(var12, var7, var10, var9, var11, var8))).replaceAll(" ","") ; + String var17 = BaseUtil.Html2Text(Util.null2String(transField.transFieldValue(var13, var7, var10, var9, var11, var8))).replaceAll(" ","") ; + if (!var16.equals(var17)) { + var6.put("fieldvalue", var16); + var6.put("prefieldvalue", var17); + } + } + + + return var6; + } + + public void updateFormLog(JSONObject json,TransField transField){ + if(json==null||json.size()<=0){ + return; + } + /** 开始跟新 **/ + String fieldname=Util.null2String(json.getString("fieldname")) ; + String fieldvalue=Util.null2String(json.getString("fieldvalue")); + + } + + /** + * 将 一个json字段信息 拆入到已有的明细表行 根据 detaildataid 来判断 + * @param jsons + * @param demo + */ + public void setJSONArraySingle(JSONArray jsons,JSONObject demo){ + if(jsons==null||jsons.size()<=0||demo==null||demo.size()<=0){ + return; + } + String detaildataid=Util.null2String(demo.getString("detaildataid")).trim() ; + if("".equals(detaildataid)){ + return; + } + boolean isvali=false; + for(int i=0;i-1&&"893946".equals(demo.getString("fieldid"))){ + demo.put("mainid",demo.getString("PREFIELDVALUE")) ; + }else if(demo.getString("detailtable").indexOf("dt3")>-1&&"893947".equals(demo.getString("fieldid"))){ + demo.put("mainid",demo.getString("PREFIELDVALUE")) ; + } + + } + isvali=true; + break; + } + } + if(!isvali){ + //不存在 则新能数据 + JSONObject demo2=new JSONObject(); + demo2.put("operateType",demo.getString("operateType")); + demo2.put("detailtable",demo.getString("detailtable")); + demo2.put("detaildataid",demo.getString("detaildataid")); + demo2.put(demo.getString("fieldid"),demo.getString("fieldvalue")); + if("EDIT".equals(demo.getString("operateType"))){ + /** 获取mainbillid **/ + demo2.put("mainid",getMainbillid( detaildataid,demo.getString("detailtable") )) ; + }else if("DEL".equals(demo.getString("operateType"))){ + if(demo.getString("detailtable").indexOf("dt2")>-1&&"893946".equals(demo.getString("fieldid"))){ + demo.put("mainid",demo.getString("PREFIELDVALUE")) ; + }else if(demo.getString("detailtable").indexOf("dt3")>-1&&"893947".equals(demo.getString("fieldid"))){ + demo.put("mainid",demo.getString("PREFIELDVALUE")) ; + } + + } + jsons.add(demo2); + } + } + + public String getMainbillid(String detaildataid,String table){ + String mainbillid=""; + RecordSet re=new RecordSet(); + re.executeQuery("select mainbillid from "+table+" where id="+detaildataid); + if(re.next()){ + mainbillid=Util.null2String(re.getString("mainbillid")) ; + } + return mainbillid; + } + +} diff --git a/src/main/youhong_ai_jitu_src/com/engine/demo/impl/HistoryDetail.java b/src/main/youhong_ai_jitu_src/com/engine/demo/impl/HistoryDetail.java new file mode 100644 index 0000000..df58b3b --- /dev/null +++ b/src/main/youhong_ai_jitu_src/com/engine/demo/impl/HistoryDetail.java @@ -0,0 +1,456 @@ +package com.engine.demo.impl; + +import com.alibaba.fastjson.JSONArray; +import com.alibaba.fastjson.JSONObject; +import selfdev.util.log.LogTool; +import weaver.conn.RecordSet; +import weaver.general.Util; + +import java.text.SimpleDateFormat; +import java.util.*; + +/** + * 历史数据拆分表 + * + */ +public class HistoryDetail { + private final static LogTool log = new LogTool("/log/TransField/",false); + private TransField transField=null; + private JSONObject detailValJSon=null; + + public HistoryDetail(TransField transField,JSONObject detailValJSon){ + this.transField=transField; + this.detailValJSon=detailValJSon; + } + //明细变更 + /** + * 如果存在明细表的变更的话 则需要对 版本的历史沿革以及 版本的 明细数据 以及 企业信息表的数据 做变更 + * 1).当前版本是最新的(跟新历史最新的数据只是跟新最新的一条数据 跟新主表数据) + * 2).当前版本是中间的版本(1不存在修改则更新所有之后的明细数据 以及跟新当前版本以及之后的所有新历史沿革最新的变更后数据 更新主表数据,2存在版本) + *如果 当前版本是之后的版本 只要跟新 历史沿革 + * **/ + public void DetailSplit(){ + SimpleDateFormat sim=new SimpleDateFormat("yyyy-MM-dd"); + String currentDate=sim.format(new Date()); + String AllVersionid= transField.getAllVersionid();//当前版本之后的所有版本 + String getOldAllVersion=transField.getOldAllVersion();//当前版本的 前版本 + log.writeLog("AllVersionid-->"+AllVersionid); + log.writeLog("getOldAllVersion-->"+getOldAllVersion); + List> sqlmaps=transField.getSqlmaps(); + String allmodflyuuid="";//所有的 新增明细的uuid + if(detailValJSon!=null&&detailValJSon.size()>0){ + log.writeLog(detailValJSon.toJSONString()); + Set detailKey= detailValJSon.keySet(); + for(String table:detailKey){ + JSONArray tableDatas=detailValJSon.getJSONArray(table); + String detailtabledesc="";//明细列描述 + String detailtableValue="";//所有的明细值 + String changeID="";//当前版本最后一次变更的ID + String oldchangeID="";//当前版本之前最后一次变更的ID + String currentVersionChange=""; + if(tableDatas!=null&&tableDatas.size()>0){ + + //此处插入的是 正式的数据 版本以及 企业信息 + + for(int k=0;k0){ + //开始遍历sql + String detaildataid= Util.null2String(K.getString("detaildataid")).trim() ; + String operateType=Util.null2String(K.getString("operateType")).trim() ; + log.writeLog("operateType--->"+operateType); + String mainid=Util.null2String(K.getString("mainid")).trim() ; + String detailtable=Util.null2String(K.getString("detailtable")).trim() ; + String betoowID="";//中间数据 + String betoowOldID="";//前面版本的中间数据 + //if("".equals(detailtabledesc)){ + detailtabledesc= transField.getFeildnameByNames(TransField.detailField.getString(detailtable+"desc"),CubeSaveInterccept.CompanyMaintableFormid);//获取字段的描述 + detailtableValue=transField.getDetailAllValue(detailtable,TransField.detailField.getString(detailtable+"desc"),transField.getBillid()); + changeID=transField.checkDetailFieldCheck(AllVersionid,detailtabledesc,1);//checkFieldCheck(AllVersionid, detailtabledesc);//变更版本 + oldchangeID=transField.checkDetailFieldCheck(getOldAllVersion,detailtabledesc,0); + currentVersionChange=transField.checkDetailFieldCheck(transField.getBillid(),detailtabledesc,1);//获取中间版本 + betoowID=transField.getBetoowVersion(transField.getBillid(),changeID, AllVersionid);// currentVersionChange + betoowOldID=transField.getBetoowVersion(oldchangeID,transField.getBillid(), getOldAllVersion); + if(!"".equals(betoowOldID)){ + //需要添加 之前的数据 betoowOldID + betoowOldID=oldchangeID+","+betoowOldID; + } + log.writeLog("detailtabledesc"+detailtabledesc); + log.writeLog("detailtableValue"+detailtableValue); + log.writeLog("changeID"+changeID); + log.writeLog("oldchangeID"+oldchangeID); + log.writeLog("currentVersionChange"+currentVersionChange); + log.writeLog("betoowID"+betoowID); + log.writeLog("betoowOldID"+betoowOldID); + + //} + Set kkey= K.keySet(); + if("EDIT".equals(operateType)){//编辑 &&!"".equals(mainid) 暂时去掉 mainid + Map map=new HashMap<>(); + String fieldsql=""; + String insertsql=""; + String insertsqlsplit=""; + Object[] kparams=new Object[0]; + for(String mykey:kkey){ + String fieldname=transField.getFieldNameByid(mykey); + if(CubeSaveInterccept.filterField.indexOf(","+fieldname+",")>-1||CubeSaveInterccept.filterField.indexOf(","+mykey+",")>-1||"".equals(fieldname)){ + continue; + } + //log.writeLog(fieldname); + fieldsql=fieldsql+fieldname+"=?,"; + insertsql=insertsql+fieldname+","; + insertsqlsplit=insertsqlsplit+"?,"; + kparams = Arrays.copyOf(kparams, (kparams.length+1)); + kparams[kparams.length-1] = K.get(mykey); + } + if(fieldsql.endsWith(",")){ + fieldsql=fieldsql.substring(0,fieldsql.length()-1); + } + if(insertsql.endsWith(",")){ + insertsql=insertsql.substring(0,insertsql.length()-1); + } + log.writeLog("Edit fieldsql-->"+fieldsql); + if(insertsqlsplit.endsWith(",")){ + insertsqlsplit=insertsqlsplit.substring(0,insertsqlsplit.length()-1); + } + if("".equals(AllVersionid)||"".equals(changeID)){//当前的最新版本 + //插入企业信息主表 + Map map1=new HashMap<>(); + map1.put("sql","update "+CubeSaveInterccept.CompanyMaintable+"_"+table+" set "+fieldsql+" where id="+mainid); + map1.put("params",kparams); + sqlmaps.add(map1); + } + if("".equals(currentVersionChange)&&"".equals(oldchangeID)){ + + } + if(!"".equals(betoowID)||("".equals(betoowID)&&"".equals(changeID)&&!"".equals(AllVersionid))){//存在之后的中间版本 + if("".equals(betoowID)&&"".equals(changeID)&&!"".equals(AllVersionid)){ + betoowID= AllVersionid; + } + String[] betoowIDs=betoowID.split(","); + for(String be:betoowIDs){ + if("".equals(Util.null2String(be).trim())){ + continue; + } + Map map1=new HashMap<>(); + //map1.put("sql","update "+CubeSaveInterccept.CompanyMaintable+"_"+table+" set "+fieldsql+" where id="+be+" and mainbillid="+mainid); + map1.put("sql","update "+CubeSaveInterccept.CompanyVersionMaintable+"_"+table+" set "+fieldsql+" where mainid="+be+" and mainbillid="+mainid); + map1.put("params",kparams); + sqlmaps.add(map1); + } + } + //跟新之前版本的版本数据以及 历史沿革 + if(!"".endsWith(betoowOldID)&&"".equals(currentVersionChange)){ + String[] betoowOldIDs=betoowOldID.split(","); + for(String be:betoowOldIDs){ + if("".equals(Util.null2String(be).trim())){ + continue; + } + String whereSql=getDeleteSqlWhere( detaildataid, table); + if("".equals(whereSql)){ + continue; + } + Map map1=new HashMap<>(); + //map1.put("sql","update "+CubeSaveInterccept.CompanyMaintable+"_"+table+" set "+fieldsql+" where id="+be+" and mainbillid="+mainid); + map1.put("sql","update "+CubeSaveInterccept.CompanyVersionMaintable+"_"+table+" set "+fieldsql+" where mainid="+be+" and "+whereSql); + map1.put("params",kparams); + sqlmaps.add(map1); + } + } + + }else if("ADD".equals(operateType)){//新建 + Map map=new HashMap<>(); + String fieldsql=""; + String splitsql=""; + Object[] kparams=new Object[0]; + Object[] kinsertparams=new Object[0]; + String modflyuuid= UUID.randomUUID().toString(); + allmodflyuuid=allmodflyuuid+table+","+modflyuuid+","; + for(String mykey:TransField.detailField.getString(detailtable).split(",")){ + String fieldname=mykey;//transField.getFieldNameByid(mykey); + if(CubeSaveInterccept.filterField.indexOf(","+fieldname+",")>-1||CubeSaveInterccept.filterField.indexOf(","+mykey+",")>-1){ + continue; + } + fieldsql=fieldsql+fieldname+","; + splitsql=splitsql+"?,"; + kparams = Arrays.copyOf(kparams, (kparams.length+1)); + kparams[kparams.length-1] = K.get(this.transField.getSingleFieldIdByName(mykey,detailtable)); + + } + fieldsql=fieldsql+"modflyuuid,mainid"; + splitsql=splitsql+"?,?"; + kparams = Arrays.copyOf(kparams, (kparams.length+1)); + kparams[kparams.length-1] = modflyuuid; + kparams = Arrays.copyOf(kparams, (kparams.length+1)); + kparams[kparams.length-1] = this.transField.getQyid(); + + if(fieldsql.endsWith(",")){ + fieldsql=fieldsql.substring(0,fieldsql.length()-1); + } + if(splitsql.endsWith(",")){ + splitsql=splitsql.substring(0,splitsql.length()-1); + } +// map.put("sql","insert into "+CubeSaveInterccept.CompanyMaintable+"_"+table+"("+fieldsql+") values("+splitsql+") "); +// map.put("params",kparams); +// sqlmaps.add(map); +// //新增的同时需要 修改 mainbillid +// map.put("sql","update "+CubeSaveInterccept.CompanyVersionMaintable+"_"+table+" set mainbillid=(select id from "+CubeSaveInterccept.CompanyMaintable+"_"+table+" where modflyuuid=?) where id="+mainid); +// map.put("params",new Object[]{modflyuuid}); +// sqlmaps.add(map); + if("".equals(AllVersionid)){// + //插入企业信息主表 + map.put("sql","insert into "+CubeSaveInterccept.CompanyMaintable+"_"+table+"("+fieldsql+",qymc1) values("+splitsql+",?) "); + kparams = Arrays.copyOf(kparams, (kparams.length+1)); + kparams[kparams.length-1] = this.transField.getQyid(); + map.put("params",kparams); + sqlmaps.add(map); + //新增的同时需要 修改 mainbillid + Map map2=new HashMap<>(); + map2.put("sql","update "+CubeSaveInterccept.CompanyVersionMaintable+"_"+table+" set mainbillid=(select id from "+CubeSaveInterccept.CompanyMaintable+"_"+table+" where modflyuuid=?) where id="+detaildataid); + map2.put("params",new Object[]{modflyuuid}); + sqlmaps.add(map2); + }else{ + if(!"".equals(betoowID)||("".equals(betoowID)&&"".equals(changeID)&&!"".equals(AllVersionid))){//存在之后的中间版本 + String oldbetoowID=betoowID;//记住之前的 betoowID + if("".equals(betoowID)&&"".equals(changeID)&&!"".equals(AllVersionid)){ + betoowID= AllVersionid; + } + String[] betoowIDs=betoowID.split(","); + for(String be:betoowIDs){ + if("".equals(Util.null2String(be).trim())){ + continue; + } + Map map3=new HashMap<>(); + map3.put("sql","insert into "+CubeSaveInterccept.CompanyVersionMaintable+"_"+table+"("+fieldsql+") values("+splitsql+") "); + Object[] kparamss=getNewObjects(kparams); + kparamss = Arrays.copyOf(kparamss, (kparamss.length+1)); + kparamss[kparamss.length-1] = modflyuuid; + kparamss = Arrays.copyOf(kparamss, (kparamss.length+1)); + kparamss[kparamss.length-1] = be; + map3.put("params",kparamss); + sqlmaps.add(map3); + } + //先插入主表 在删除 + Map mainMap=new HashMap<>(); + mainMap.put("sql","insert into "+CubeSaveInterccept.CompanyMaintable+"_"+table+"("+fieldsql+",qymc1) values("+splitsql+",?) "); + Object[] mainMapparams = Arrays.copyOf(kparams, (kparams.length+1)); + mainMapparams[mainMapparams.length-1] = this.transField.getQyid(); + mainMap.put("params",mainMapparams); + sqlmaps.add(mainMap); + //修改 关联企业信息表ID + Map map2=new HashMap<>(); + map2.put("sql","update "+CubeSaveInterccept.CompanyVersionMaintable+"_"+table+" set mainbillid=(select id from "+CubeSaveInterccept.CompanyMaintable+"_"+table+" where modflyuuid=?) where mainid in ("+betoowID+") and modflyuuid=?"); + map2.put("params",new Object[]{modflyuuid,modflyuuid}); + sqlmaps.add(map2); + //删除 + if(!"".equals(oldbetoowID)){ + Map deletemap=new HashMap<>(); + deletemap.put("sql","delete from "+CubeSaveInterccept.CompanyMaintable+"_"+table+" where modflyuuid=? and mainid="+this.transField.getQyid()); + deletemap.put("params",new Object[]{modflyuuid}); + sqlmaps.add(deletemap); + } + } + if(!"".endsWith(betoowOldID)&&"".equals(currentVersionChange)){ + String[] betoowOldIDs=betoowOldID.split(","); + for(String be:betoowOldIDs){ + if("".equals(Util.null2String(be).trim())){ + continue; + } + Map map3=new HashMap<>(); + map3.put("sql","insert into "+CubeSaveInterccept.CompanyVersionMaintable+"_"+table+"("+fieldsql+") values("+splitsql+",?) "); + Object[] kparamss=getNewObjects(kparams); + kparamss = Arrays.copyOf(kparamss, (kparamss.length+1)); + kparamss[kparamss.length-1] = modflyuuid; + kparamss = Arrays.copyOf(kparamss, (kparamss.length+1)); + kparamss[kparamss.length-1] = be; + map3.put("params",kparamss); + //sqlmaps.add(map3); 之前的数据不做处理 + } + } + } + }else if("DEL".equals(operateType)){//删除 + Map map=new HashMap<>(); + String fieldsql=""; + String splitsql=""; + Object[] kparams=new Object[0]; + Object[] kinsertparams=new Object[0]; + String modflyuuid= UUID.randomUUID().toString(); + allmodflyuuid=allmodflyuuid+table+","+modflyuuid+","; + for(String mykey:TransField.detailField.getString(detailtable).split(",")){ + String fieldname=mykey;//transField.getFieldNameByid(mykey); + if(CubeSaveInterccept.filterField.indexOf(","+fieldname+",")>-1||CubeSaveInterccept.filterField.indexOf(","+mykey+",")>-1){ + continue; + } + fieldsql=fieldsql+fieldname+","; + splitsql=splitsql+"?,"; + kparams = Arrays.copyOf(kparams, (kparams.length+1)); + kparams[kparams.length-1] = K.get(this.transField.getSingleFieldIdByName(mykey,detailtable)); + + } + fieldsql=fieldsql+"modflyuuid,mainid"; + splitsql=splitsql+"?,?"; + kparams = Arrays.copyOf(kparams, (kparams.length+1)); + kparams[kparams.length-1] = modflyuuid; + kparams = Arrays.copyOf(kparams, (kparams.length+1)); + kparams[kparams.length-1] = this.transField.getQyid(); + + if(fieldsql.endsWith(",")){ + fieldsql=fieldsql.substring(0,fieldsql.length()-1); + } + if(splitsql.endsWith(",")){ + splitsql=splitsql.substring(0,splitsql.length()-1); + } + if("".equals(AllVersionid)){// + //删除企业信息表数据 + //map.put("sql","insert into "+CubeSaveInterccept.CompanyMaintable+"_"+table+"("+fieldsql+") values("+splitsql+") "); + map.put("sql","delete from "+CubeSaveInterccept.CompanyMaintable+"_"+table+" where id=?"); + map.put("params",new Object[]{mainid}); + sqlmaps.add(map); + + }else{ + if(!"".equals(betoowID)||("".equals(betoowID)&&"".equals(changeID)&&!"".equals(AllVersionid))){//存在之后的中间版本 + if("".equals(betoowID)&&"".equals(changeID)&&!"".equals(AllVersionid)){ + betoowID= AllVersionid; + } + String[] betoowIDs=betoowID.split(","); + for(String be:betoowIDs){ + if("".equals(Util.null2String(be).trim())){ + continue; + } + String whereSql=getDeleteSqlWhere( detaildataid, table); + if("".equals(whereSql)){ + continue; + } + Map map3=new HashMap<>(); + //map3.put("sql","insert into "+CubeSaveInterccept.CompanyVersionMaintable+"_"+table+"("+fieldsql+",mainid) values("+splitsql+",?) "); + map3.put("sql","delete from "+CubeSaveInterccept.CompanyVersionMaintable+"_"+table+" where mainid=? and "+whereSql); +// Object[] kparamss=getNewObjects(kparams); +// kparamss = Arrays.copyOf(kparamss, (kparamss.length+1)); +// kparamss[kparamss.length-1] = modflyuuid; +// kparamss = Arrays.copyOf(kparamss, (kparamss.length+1)); +// kparamss[kparamss.length-1] = be; + map3.put("params",new Object[]{be}); + sqlmaps.add(map3); + } + } + if(!"".endsWith(betoowOldID)&&"".equals(currentVersionChange)){ + String[] betoowOldIDs=betoowOldID.split(","); + for(String be:betoowOldIDs){ + if("".equals(Util.null2String(be).trim())){ + continue; + } + String whereSql=getDeleteSqlWhere( detaildataid, table); + if("".equals(whereSql)){ + continue; + } + Map map3=new HashMap<>(); + //map3.put("sql","insert into "+CubeSaveInterccept.CompanyVersionMaintable+"_"+table+"("+fieldsql+",mainid) values("+splitsql+",?) "); + map3.put("sql","delete from "+CubeSaveInterccept.CompanyVersionMaintable+"_"+table+" where mainid=? and "+whereSql); +// Object[] kparamss=getNewObjects(kparams); +// kparamss = Arrays.copyOf(kparamss, (kparamss.length+1)); +// kparamss[kparamss.length-1] = modflyuuid; +// kparamss = Arrays.copyOf(kparamss, (kparamss.length+1)); +// kparamss[kparamss.length-1] = be; + map3.put("params",new Object[]{be}); + sqlmaps.add(map3); + } + } + } + } + //不管是跟新和编辑 都涉及到 历史沿革数据的修改 + /** + * 如果存在明细表的变更的话 则需要对 版本的历史沿革以及 版本的 明细数据 以及 企业信息表的数据 做变更 + * 1).当前版本是最新的(跟新历史最新的数据只是跟新最新的一条数据 跟新主表数据) + * 2).当前版本是中间的版本(1不存在修改则更新所有之后的明细数据 以及跟新当前版本以及之后的所有新历史沿革最新的变更后数据 更新主表数据,2存在版本) + *如果 当前版本是之后的版本 只要跟新 历史沿革 + * **/ + if("".equals(AllVersionid)){//为空则是最新的版本 + //如果存在 之前的变更 那么需要跟新 需要建立在 当前版本 没有变更过 明细的值 +// if(!"".equals(oldchangeID)&&"".equals(currentVersionChange)){ +// Map map=new HashMap<>(); +// map.put("sql","update "+CubeSaveInterccept.CompanyVersionMaintable+"_"+table+" set bgh=? where mainid="+oldchangeID+" and bgxm=?"); +// map.put("params",new Object[]{detailtableValue,detailtabledesc}); +// sqlmaps.add(map); +// } + //当前版本的 变更后 + if(!"".equals(currentVersionChange)) { + Map map1 = new HashMap<>(); + map1.put("sql", "update " + CubeSaveInterccept.CompanyVersionMaintable + "_dt1 set bgh=? where id in (select max(id) from "+CubeSaveInterccept.CompanyVersionMaintable+"_dt1 where mainid=" + transField.getBillid() + " and bgxm=?) "); + map1.put("params", new Object[]{detailtableValue, detailtabledesc}); + sqlmaps.add(map1); + }else{ + //新增历史沿革 不考虑变更 前面的 数据 + if(!"".equals(oldchangeID)){ + Map map2 = new HashMap<>(); + map2.put("sql", "insert into "+CubeSaveInterccept.CompanyVersionMaintable+"_dt1(rq,bgxm,bgq,bgh,mainid)values(?,?,?,?,?) "); + map2.put("params", new Object[]{currentDate, detailtabledesc,transField.getDetailAllValue(detailtable,TransField.detailField.getString(detailtable),oldchangeID),detailtabledesc,transField.getBillid()}); + sqlmaps.add(map2); + } + } + + }else{ + //中间版本 + if(!"".equals(oldchangeID)&&"".equals(currentVersionChange)){//更新之前的数据 + Map map=new HashMap<>(); + map.put("sql","update "+CubeSaveInterccept.CompanyVersionMaintable+"_dt1 set bgh=? where mainid="+oldchangeID+" and bgxm=?"); + map.put("params",new Object[]{detailtableValue,detailtabledesc}); + sqlmaps.add(map); + }else if(!"".equals(currentVersionChange)){ + Map map1 = new HashMap<>(); + map1.put("sql", "update " + CubeSaveInterccept.CompanyVersionMaintable + "_dt1 set bgh=? where id in (select max(id) from "+CubeSaveInterccept.CompanyVersionMaintable+"_dt1 where mainid=" + transField.getBillid() + " and bgxm=?) "); + map1.put("params", new Object[]{detailtableValue, detailtabledesc}); + sqlmaps.add(map1); + } + if(!"".equals(changeID)){//之后版本 + Map map=new HashMap<>(); + map.put("sql","update "+CubeSaveInterccept.CompanyVersionMaintable+"_dt1 set bgq=? where id in (select min(id) from "+CubeSaveInterccept.CompanyVersionMaintable+"_dt1 where mainid="+changeID+" and bgxm=?) "); + map.put("params",new Object[]{detailtableValue,detailtabledesc}); + sqlmaps.add(map); + } + } + } + + } + } + } + } + } + + public Object[] getNewObjects(Object[] objs){ + Object[] newobjs=new Object[0]; + if(objs!=null){ + for(Object demo:objs){ + newobjs = Arrays.copyOf(newobjs, (newobjs.length+1)); + newobjs[newobjs.length-1] = demo; + } + } + return newobjs; + } + + public String getDeleteSqlWhere(String detailid,String table){ + String whereSql=""; + RecordSet re=new RecordSet(); + String sql="select * from "+CubeSaveInterccept.CompanyVersionMaintable+"_"+table +" where id="+detailid; + log.writeLog(sql); + re.execute(sql); + if(re.next()){ + String modflyuuid=Util.null2String(re.getString("modflyuuid")).trim() ;//mainbillid + String mainbillid=Util.null2String( re.getString("mainbillid")).trim();//mainbillid + if(!"".equals(modflyuuid)){ + whereSql=whereSql+" modflyuuid='"+modflyuuid+"' "; + } + if(!"".equals(modflyuuid)&&!"".equals(mainbillid)){ + whereSql=whereSql+" or mainbillid='"+mainbillid+"' "; + }else{ + if(!"".equals(mainbillid)){ + whereSql=whereSql+" mainbillid='"+mainbillid+"' "; + } + } + } + if(!"".equals(whereSql)){ + whereSql="("+whereSql+")"; + } + return whereSql; + } + +} diff --git a/src/main/youhong_ai_jitu_src/com/engine/demo/impl/TransField.java b/src/main/youhong_ai_jitu_src/com/engine/demo/impl/TransField.java new file mode 100644 index 0000000..a676389 --- /dev/null +++ b/src/main/youhong_ai_jitu_src/com/engine/demo/impl/TransField.java @@ -0,0 +1,966 @@ +package com.engine.demo.impl; + +import com.alibaba.fastjson.JSONArray; +import com.alibaba.fastjson.JSONObject; +import com.api.cube.util.CubeSearchTransMethod; +import selfdev.util.log.LogTool; +import weaver.conn.RecordSet; +import weaver.docs.docs.DocImageManager; +import weaver.general.ThreadVarLanguage; +import weaver.general.Util; +import weaver.hrm.User; +import weaver.soa.workflow.request.Property; +import weaver.systeminfo.SystemEnv; + +import java.text.SimpleDateFormat; +import java.util.*; + +public class TransField { + private final static LogTool log = new LogTool("/log/TransField/",false); + private int formId; + private int modeId; + private int type; + private int layoutid; + private User user; + private String billid; + private String qyid="";//企业ID + private String bbrq="";//日期 + private String viewlogid=""; + private String allVersionid="";//当前版本之后的所有的版本 + //private String betoowID="";//中间版本 + private String allmodflyuuid="";//所有新增明细的uuid + + private boolean isModifyClrq=false;//判断是否是修改了成立日期 + private String newclrq="";//新成立日期 + + private JSONArray transFieldJSONs=new JSONArray(); + private List> sqlmaps=new ArrayList<>(); + static JSONObject detailField=new JSONObject(); + + static{ +// detailField.put("uf_configField_dt1","cs1,cs2"); +// detailField.put("uf_configField_dt1desc","cs1,cs2"); +// detailField.put("uf_configField_dt2","cs3,cs4"); +// detailField.put("uf_configField_dt2desc","cs3,cs4"); + +// uat +// detailField.put("formtable_main_1824_dt2","djgd,cgbl,cgfs,gfzl"); +// detailField.put("formtable_main_1824_dt2desc","djgd,cgbl,cgfs,gfzl,bz"); +// detailField.put("formtable_main_1824_dt3","zzzz"); +// detailField.put("formtable_main_1824_dt3desc","zzzz"); + //登记股东/持股比例/持股份数/股份种类 生产 + detailField.put("formtable_main_3055_dt2","djgd,cgbl,cgfs,gfzl,bz"); + detailField.put("formtable_main_3055_dt2desc","djgd,cgbl,cgfs,gfzl"); + detailField.put("formtable_main_3055_dt3","zzzz,fjsc,bz"); + detailField.put("formtable_main_3055_dt3desc","zzzz"); + } + public TransField(int formId,String billid,User user){ + this.formId=formId; + this.billid=billid; + this.user=user; + } + public TransField(){ + } + public String transFieldValue(String var1, JSONObject fieldjson) throws Exception { + if(fieldjson==null||fieldjson.size()<=0){ + return var1; + } + //(fieldvalue, fieldhtmltype, fieldid, fielddbtype, viewtype, type) + log.writeLog("begin!"); + log.writeLog(fieldjson.getString("fieldhtmltype")+"==="+fieldjson.getString("fieldid")+"==="+fieldjson.getString("fielddbtype")+"==="+fieldjson.getString("viewtype")+"==="+Util.getIntValue(fieldjson.getString("type"),0)); + return transFieldValue(var1,fieldjson.getString("fieldhtmltype"),fieldjson.getString("fieldid"),fieldjson.getString("fielddbtype"),fieldjson.getString("viewtype"),Util.getIntValue(fieldjson.getString("type"),0) ); + } + public String transFieldValue(String var1, String var2, String var3, String var4, String var5, int var6) throws Exception { + CubeSearchTransMethod var7 = CubeSearchTransMethod.INSTANCE; + String var8 = ""; + RecordSet var9 = new RecordSet(); + if (var2.equals("6")) { + DocImageManager var10 = new DocImageManager(); + if (!var1.equals("")) { + ArrayList var11 = Util.TokenizerString(var1, ","); + int var12 = -1; + + for(int var13 = 0; var13 < var11.size(); ++var13) { + ++var12; + if (var12 > 0) { + var8 = var8 + "
"; + } + String var14 = Util.null2String(var11.get(var13)); + String var15 = "select id,docsubject,accessorycount from docdetail where id = " + var14 + " order by id asc"; + var9.executeSql(var15); + if (!var9.next()) { + var8 = var8 + "ID:" + var14 + SystemEnv.getHtmlLabelName(384364, this.user.getLanguage()) + ""; + } else { + String var16 = Util.null2String(var9.getString(1)); + String var17 = Util.toScreen(var9.getString(2), this.user.getLanguage()); + int var18 = var9.getInt(3); + var10.resetParameter(); + var10.setDocid(Integer.parseInt(var16)); + var10.selectDocImageInfo(); + String var19 = ""; + String var20 = ""; + String var21 = ""; + if (var10.next()) { + var19 = var10.getImagefileid(); + var20 = var10.getImagefilename(); + var21 = var20.substring(var20.lastIndexOf(".") + 1).toLowerCase(); + } + + if (var18 != 1 || !var21.equalsIgnoreCase("xls") && !var21.equalsIgnoreCase("doc") && !var21.equalsIgnoreCase("pdf") && !var21.equalsIgnoreCase("xlsx") && !var21.equalsIgnoreCase("docx")) { + var8 = var8 + "" + var17 + " "; + } else { + var8 = var8 + "" + var20 + " "; + } + } + } + } + } else { + String var22 = this.billid + "+" + var3 + "+" + var2 + "+" + var6 + "+" + this.user.getLanguage() + "+1+" + var4 + "+0+-1+" + this.formId + "+" + var5; + var8 = var7.getOthers(var1, var22); + if (var8.indexOf("class='empty-columns'") >= 0) { + var8 = ""; + } + } + + if (var2.equals("4")) { + if (var1.equals("1")) { + var8 = "" + SystemEnv.getHtmlLabelName(163, ThreadVarLanguage.getLang()) + ""; + } else { + var8 = "" + SystemEnv.getHtmlLabelName(25105, ThreadVarLanguage.getLang()) + ""; + } + } + if(var6==161){ + //var8=var8.substring(0,var8.length()-" ".length()); &&var8.endsWith(" ") + var8=var8.replaceAll(" ",""); + } + //log.writeLog(var6+"-->"+var8); + return var8; + } + + public String getAllmodflyuuid() { + return allmodflyuuid; + } + + public void setAllmodflyuuid(String allmodflyuuid) { + this.allmodflyuuid = allmodflyuuid; + } + + public String getAllVersionid() { + return allVersionid; + } + + public void setAllVersionid(String allVersionid) { + this.allVersionid = allVersionid; + } + + public List> getSqlmaps() { + return sqlmaps; + } + + public void setSqlmaps(List> sqlmaps) { + this.sqlmaps = sqlmaps; + } + + public String getViewlogid() { + return viewlogid; + } + + public void setViewlogid(String viewlogid) { + this.viewlogid = viewlogid; + } + + public static JSONObject getDetailField() { + return detailField; + } + + public static void setDetailField(JSONObject detailField) { + TransField.detailField = detailField; + } + + public JSONArray getTransFieldJSONs() { + return transFieldJSONs; + } + + public void setTransFieldJSONs(JSONArray transFieldJSONs) { + this.transFieldJSONs = transFieldJSONs; + } + + public int getFormId() { + return formId; + } + + public void setFormId(int formId) { + this.formId = formId; + } + + public int getModeId() { + return modeId; + } + + public void setModeId(int modeId) { + this.modeId = modeId; + } + + public int getType() { + return type; + } + + public void setType(int type) { + this.type = type; + } + + public int getLayoutid() { + return layoutid; + } + + public void setLayoutid(int layoutid) { + this.layoutid = layoutid; + } + + public User getUser() { + return user; + } + + public void setUser(User user) { + this.user = user; + } + + public String getBillid() { + return billid; + } + + public void setBillid(String billid) { + this.billid = billid; + } + + public String getQyid() { + return qyid; + } + + public void setQyid(String qyid) { + this.qyid = qyid; + } + + public String getBbrq() { + return bbrq; + } + + public void setBbrq(String bbrq) { + this.bbrq = bbrq; + } + + public void updateCompanyInfo(JSONObject valJSon,JSONObject detailValJSon){ + //组装 sql + String detailindex=""; + + if(valJSon!=null||valJSon.size()>0){ + Map map=new HashMap<>(); + Set mainkey=valJSon.keySet(); + String fieldsql=""; + + Object[] params=new Object[valJSon.size()]; + int i=0; + for(String str:mainkey){ + fieldsql=fieldsql+str+"=?,"; + params[i]=valJSon.get(str); + } + if(fieldsql.endsWith(",")){ + fieldsql=fieldsql.substring(0,fieldsql.length()-1); + } + map.put("sql","update "+CubeSaveInterccept.CompanyMaintable+" set "+fieldsql+" where id='"+this.qyid+"'"); + map.put("params",params); + //sqlmaps.add(map); + } + //明细表的sql 有两个 明细表 +// if(detailValJSon!=null&&detailValJSon.size()>0){ +// Set detailKey= detailValJSon.keySet(); +// for(String table:detailKey){ +// JSONArray tableDatas=detailValJSon.getJSONArray(table); +// if(tableDatas!=null&&tableDatas.size()>0){ +// for(int k=0;k0){ +// //开始遍历sql +// String operateType=Util.null2String(K.getString("operateType")).trim() ; +// String mainid=Util.null2String(K.getString("mainid")).trim() ; +// String detailtable=Util.null2String(K.getString("detailtable")).trim() ; +// Set kkey= K.keySet(); +// if("EDIT".equals(operateType)&&!"".equals(mainid)){//编辑 +// Set mainkey=valJSon.keySet(); +// Map map=new HashMap<>(); +// String fieldsql=""; +// Object[] kparams=new Object[0]; +// for(String mykey:kkey){ +// String fieldname=getFieldNameByid(mykey); +// if(CubeSaveInterccept.filterField.indexOf(","+fieldname+",")>-1||CubeSaveInterccept.filterField.indexOf(","+mykey+",")>-1){ +// continue; +// } +// fieldsql=fieldsql+fieldname+"=?,"; +// kparams = Arrays.copyOf(kparams, (kparams.length+1)); +// kparams[kparams.length-1] = K.get(mykey); +// } +// if(fieldsql.endsWith(",")){ +// fieldsql=fieldsql.substring(0,fieldsql.length()-1); +// } +// map.put("sql","update "+CubeSaveInterccept.CompanyMaintable+"_"+table+" set "+fieldsql+" where id="+mainid); +// map.put("params",kparams); +// sqlmaps.add(map); +// }else if("ADD".equals(operateType)){//新建 +// Set mainkey=valJSon.keySet(); +// Map map=new HashMap<>(); +// String fieldsql=""; +// String splitsql=""; +// Object[] kparams=new Object[0]; +// for(String mykey:kkey){ +// String fieldname=getFieldNameByid(mykey); +// if(CubeSaveInterccept.filterField.indexOf(","+fieldname+",")>-1||CubeSaveInterccept.filterField.indexOf(","+mykey+",")>-1){ +// continue; +// } +// fieldsql=fieldsql+fieldname+","; +// splitsql=splitsql+"?,"; +// kparams = Arrays.copyOf(kparams, (kparams.length+1)); +// kparams[kparams.length-1] = K.get(mykey); +// } +// +// if(fieldsql.endsWith(",")){ +// fieldsql=fieldsql.substring(0,fieldsql.length()-1); +// } +// if(splitsql.endsWith(",")){ +// splitsql=splitsql.substring(0,splitsql.length()-1); +// } +// map.put("sql","insert into "+CubeSaveInterccept.CompanyMaintable+"_"+table+"("+fieldsql+") values("+splitsql+") "); +// map.put("params",kparams); +// sqlmaps.add(map); +// } +// } +// } +// } +// } +// } + //明细表 + + + //跟新 历史沿革 记录 判断当期当前是什么版本 前后有没有 + allVersionid= getAllVersion("1");//获取所有版本的ID + if(transFieldJSONs.size()>0){ + for(int i=0;i"+isModifyClrq+" newclrq-->"+newclrq+"this.billid-->"+this.billid); + if(isModifyClrq&&!"".equals(Util.null2String(newclrq).trim())){ + //跟新所有版本的成立日期 以及 第一个版本的 版本日期 + String oldVersion= getOldAllVersion(); + String fristVersion=""; + if("".equals(oldVersion)){ + fristVersion=this.billid; + }else{ + if(oldVersion.endsWith(",")) { + oldVersion = oldVersion.substring(0, oldVersion.length() - 1); + //int index = oldVersion.lastIndexOf(","); + } + int index = oldVersion.lastIndexOf(","); + if(index>-1){ + fristVersion=Util.null2String(oldVersion.substring(index+1)) ; + } + } + if(!"".equals(fristVersion)){ + Map map=new HashMap<>(); + Object[] params=new Object[1]; + params[0]=newclrq; + map.put("sql","update "+CubeSaveInterccept.CompanyVersionMaintable+" set bbrq=? where qyid='"+this.qyid +"' and id in ("+fristVersion+")"); + map.put("params",params); + sqlmaps.add(map); + } + Map map=new HashMap<>(); + Object[] params=new Object[1]; + params[0]=newclrq; + map.put("sql","update "+CubeSaveInterccept.CompanyVersionMaintable+" set clrq=? where qyid='"+this.qyid +"' "); + map.put("params",params); + sqlmaps.add(map); + } + } + + //明细变更 + /** + * 如果存在明细表的变更的话 则需要对 版本的历史沿革以及 版本的 明细数据 以及 企业信息表的数据 做变更 + * 1).当前版本是最新的(跟新历史最新的数据只是跟新最新的一条数据 跟新主表数据) + * 2).当前版本是中间的版本(1不存在修改则更新所有之后的明细数据 以及跟新当前版本以及之后的所有新历史沿革最新的变更后数据 更新主表数据,2存在版本) + *如果 当前版本是之后的版本 只要跟新 历史沿革 + * **/ +// if(detailValJSon!=null&&detailValJSon.size()>0){ +// Set detailKey= detailValJSon.keySet(); +// for(String table:detailKey){ +// JSONArray tableDatas=detailValJSon.getJSONArray(table); +// if(tableDatas!=null&&tableDatas.size()>0){ +// for(int k=0;k0){ +// //开始遍历sql +// String detaildataid=Util.null2String(K.getString("detaildataid")).trim() ; +// String operateType=Util.null2String(K.getString("operateType")).trim() ; +// String mainid=Util.null2String(K.getString("mainid")).trim() ; +// String detailtable=Util.null2String(K.getString("detailtable")).trim() ; +// Set kkey= K.keySet(); +// if("EDIT".equals(operateType)&&!"".equals(mainid)){//编辑 +// Set mainkey=valJSon.keySet(); +// Map map=new HashMap<>(); +// String fieldsql=""; +// Object[] kparams=new Object[0]; +// for(String mykey:kkey){ +// String fieldname=getFieldNameByid(mykey); +// if(CubeSaveInterccept.filterField.indexOf(","+fieldname+",")>-1||CubeSaveInterccept.filterField.indexOf(","+mykey+",")>-1){ +// continue; +// } +// fieldsql=fieldsql+fieldname+"=?,"; +// kparams = Arrays.copyOf(kparams, (kparams.length+1)); +// kparams[kparams.length-1] = K.get(mykey); +// } +// if(fieldsql.endsWith(",")){ +// fieldsql=fieldsql.substring(0,fieldsql.length()-1); +// } +// map.put("sql","update "+CubeSaveInterccept.CompanyMaintable+"_"+table+" set "+fieldsql+" where id="+mainid); +// map.put("params",kparams); +// sqlmaps.add(map); +// +// }else if("ADD".equals(operateType)){//新建 +// Set mainkey=valJSon.keySet(); +// Map map=new HashMap<>(); +// String fieldsql=""; +// String splitsql=""; +// Object[] kparams=new Object[0]; +// String modflyuuid=UUID.randomUUID().toString(); +// for(String mykey:kkey){ +// String fieldname=getFieldNameByid(mykey); +// if(CubeSaveInterccept.filterField.indexOf(","+fieldname+",")>-1||CubeSaveInterccept.filterField.indexOf(","+mykey+",")>-1){ +// continue; +// } +// fieldsql=fieldsql+fieldname+","; +// splitsql=splitsql+"?,"; +// kparams = Arrays.copyOf(kparams, (kparams.length+1)); +// kparams[kparams.length-1] = K.get(mykey); +// } +// fieldsql=fieldsql+"modflyuuid,"; +// kparams = Arrays.copyOf(kparams, (kparams.length+1)); +// kparams[kparams.length-1] = modflyuuid; +// +// if(fieldsql.endsWith(",")){ +// fieldsql=fieldsql.substring(0,fieldsql.length()-1); +// } +// if(splitsql.endsWith(",")){ +// splitsql=splitsql.substring(0,splitsql.length()-1); +// } +// map.put("sql","insert into "+CubeSaveInterccept.CompanyMaintable+"_"+table+"("+fieldsql+") values("+splitsql+") "); +// map.put("params",kparams); +// sqlmaps.add(map); +// //新增的同时需要 修改 mainbillid +// map.put("sql","update "+CubeSaveInterccept.CompanyVersionMaintable+"_"+table+" set mainbillid=(select id from "+CubeSaveInterccept.CompanyMaintable+"_"+table+" where modflyuuid=?) where id="+mainid); +// map.put("params",new Object[]{modflyuuid}); +// sqlmaps.add(map); +// } +// } +// } +// } +// } +// } + HistoryDetail historyDetail=new HistoryDetail( this, detailValJSon); + historyDetail.DetailSplit();//解析明细 + printLog();//sql + /** 写入SQL **/ + if(this.sqlmaps!=null&&this.sqlmaps.size()>0){ + boolean flag= BaseUtil.executeUpdateListTran(this.sqlmaps); + if(!flag){ + log.writeLog("未写入成功"); + } + } + + } + + public void printLog(){ + if(this.sqlmaps!=null&&this.sqlmaps.size()>0){ + for(Map sqls:sqlmaps) { + if (sqls == null || sqls.size() <= 0) { + continue; + } + String sql = (String) sqls.get("sql"); + log.writeLog("executeUpdateListTran--->" + sql); + Object[] params = (Object[]) sqls.get("params"); + //log.writeLog("executeUpdateListTran--->" + params.length); + if (params != null && params.length > 0) { + + log.writeLog("executeUpdateListTran--->" + Arrays.toString(params)); + } + } + } + } + /** + * 添加大于当前版本的明细 + * @param versionids + */ + public void addHistoryDetail(String versionids){ + + } + /** + *登记股东/持股比例/持股份数/股份种类 + * 主数据 1.当前最新版本 修改主数据 2.中间版本 + * 历史沿革 1.当前最新版本 修改主数据的历史沿革最新数据 2.中间版本 当前版本跟新 则更新最新 补不存在 则插入(存在历史变更) + * + * + * + * 主表字段的修改 + * 生产sql shuju + * @param singlejson + * @return + */ + public void ParaSqlMap(JSONObject singlejson,String allVersionid,List> sqlmaps){ + SimpleDateFormat sim=new SimpleDateFormat("yyyy-MM-dd"); + String currentDate=sim.format(new Date()); + Map sqlmap=new HashMap<>(); + if(singlejson==null||singlejson.size()<=0){ + return ; + } + log.writeLog(singlejson.toJSONString()); + String fieldvalue=Util.null2String(singlejson.getString("fieldvalue")) ;//新值 oldfieldvalue + String oldfieldvalue=Util.null2String(singlejson.getString("oldfieldvalue")) ;//新值 + String fieldname=Util.null2String(singlejson.getString("fieldname")) ;//数据库字段名 + String labelname=Util.null2String(singlejson.getString("labelname")) ;//字段名称 + String prefieldvalue=Util.null2String(singlejson.getString("prefieldvalue")) ;//旧值 + String oldprefieldvalue=Util.null2String(singlejson.getString("oldprefieldvalue")) ;//旧值描述 + String changeID=checkFieldCheck(allVersionid, labelname);//之后变更版本 + String currentVersionChange=checkDetailFieldCheck(this.getBillid(),labelname,1);//获取中间版本 存在说明当前版本 有修改痕迹 + String getOldAllVersion=getOldAllVersion();//当前版本的 前版本 + String oldchangeID=checkDetailFieldCheck(getOldAllVersion,labelname,0); + if(!isModifyClrq&&"clrq".equals(fieldname)){ + newclrq=oldfieldvalue; + isModifyClrq=true; + } + log.writeLog("changeID->"+changeID); + log.writeLog("currentVersionChange->"+currentVersionChange); + log.writeLog("getOldAllVersion->"+getOldAllVersion); + log.writeLog("oldchangeID->"+oldchangeID); + if("".equals(changeID)||(allVersionid.equals(this.billid+"")||allVersionid.endsWith(","+this.billid))){//说明从来没有变更过(变更主表数据 ) 或者是 最新的版本 + Map map=new HashMap<>(); + Object[] params=new Object[1]; + params[0]=oldfieldvalue; + map.put("sql","update "+CubeSaveInterccept.CompanyMaintable+" set "+fieldname+"=? where id='"+this.qyid+"'"); + map.put("params",params); + sqlmaps.add(map); + + + /** 跟新下属版本的所有值 **/ + Map map4=new HashMap<>(); + Object[] params4=new Object[1]; + params4[0]=oldfieldvalue;//获取动态的值 + map4.put("sql","update "+CubeSaveInterccept.CompanyVersionMaintable+" set "+fieldname+"=? where qyid='"+this.qyid+"' and id>"+this.billid); + map4.put("params",params4); + sqlmaps.add(map4); + + /** 跟新下属版本的所有历史沿革值 **/ + Map map5=new HashMap<>(); + Object[] params5=new Object[2]; + params5[0]=fieldvalue;//获取动态的值 qyid='"+this.qyid+"' and + params5[1]=labelname; + map5.put("sql","update "+CubeSaveInterccept.CompanyVersionMaintable+"_dt1 set bgh=? where mainid="+this.billid+" and bgxm=? "); + map5.put("params",params5); + sqlmaps.add(map5); + }else{//存在变更(跟新 changeID之前的版本字段数据 以及跟新 changeID的变更前 数据 以及 当前版本的变更后) 考虑到最新版本 + String betoowID=getBetoowVersion(billid,changeID, allVersionid);//获取中间版本 + if(!"".equals(betoowID)){ + Map map=new HashMap<>(); + Object[] params=new Object[1]; + params[0]=oldfieldvalue; + map.put("sql","update "+CubeSaveInterccept.CompanyMaintable+" set "+fieldname+"=? where id='"+this.qyid +"' and id in ("+betoowID+")"); + map.put("params",params); + sqlmaps.add(map); + } + if(!"".equals(changeID)){ + //中间版本的数据 真实 数据 + /** 跟新历史changeID沿革字段 **/ + Map map2=new HashMap<>(); + Object[] params2=new Object[2]; + params2[0]=fieldvalue;//获取动态的值 + params2[1]=labelname; + map2.put("sql","update "+CubeSaveInterccept.CompanyVersionMaintable+"_dt1 set bgq=? where id in (select min(id) from "+CubeSaveInterccept.CompanyVersionMaintable+"_dt1 where mainid="+changeID+" and bgxm=? ) "); + map2.put("params",params2); + sqlmaps.add(map2); + } + + } + + //跟新当前节点的 变更后 通用设置 + if(!"".equals(currentVersionChange)){ + Map map3=new HashMap<>(); + Object[] params3=new Object[2]; + params3[0]=fieldvalue;//获取动态的值 + params3[1]=labelname; + map3.put("sql","update "+CubeSaveInterccept.CompanyVersionMaintable+"_dt1 set bgh=? where id in (select max(id) from "+CubeSaveInterccept.CompanyVersionMaintable+"_dt1 where mainid='"+billid+"' and bgxm=?) "); + map3.put("params",params3); + sqlmaps.add(map3); + }else{ + if(!"".equals(oldchangeID)){ + /** 历史沿革 更新 **/ + Map map2 = new HashMap<>(); + map2.put("sql", "insert into "+CubeSaveInterccept.CompanyVersionMaintable+"_dt1(rq,bgxm,bgq,bgh,mainid)values(?,?,?,?,?) "); + map2.put("params", new Object[]{currentDate, labelname,oldprefieldvalue,fieldvalue,getBillid()}); + sqlmaps.add(map2); + + + } + } + } + + /** + * 获取区间版本 + * @param current + * @param lastversion + * @param allversion + * @return + */ + public static String getBetoowVersion(String current,String lastversion,String allversion){ + current=Util.null2String(current); + lastversion=Util.null2String(lastversion); + if("".equals(lastversion)){//如果不存在中间版本直接 返回空数据 + return ""; + } + if("".equals(current)){//如果不存在中间版本直接 返回空数据 + return ""; + } + allversion=Util.null2String(allversion); + String betoowID=""; + boolean isbegin=false; + String[] allversions=allversion.split(","); + for(String str:allversions){ + str=Util.null2String(str).trim(); + if("".equals(str)){ + continue; + } + if(current.equals(str)){ + isbegin=true; + continue; + } + if(lastversion.equals(str)){ + break; + } + if(isbegin){ + betoowID=betoowID+str+","; + } + } + if(betoowID.endsWith(",")){ + betoowID=betoowID.substring(0,betoowID.length()-1); + } + return betoowID; + } + /** + * 获取版本ID + * @param type 0上一个版本 1 下一个版本 + */ + public String getAllVersion(String type){ + JSONObject version=new JSONObject(); + RecordSet re=new RecordSet(); + String ids=""; + String sql="select * from "+CubeSaveInterccept.CompanyVersionMaintable+" where qyid='"+this.qyid+"' and bbrq>'"+this.bbrq+"' order by bbrq asc";; +// if("0".equals(type)){ +// sql=sql+" and bbrq<'"+this.bbrq+"' order by desc"; +// } +// if("1".equals(type)){ +// sql=sql+" and bbrq>'"+this.bbrq+"' order by asc"; +// }else{ +// return version; +// } + re.executeQuery(sql); + log.writeLog(sql); + while(re.next()){ + String id=Util.null2String(re.getString("id")) ; + ids=ids+id+","; + } + if(ids.endsWith(",")){ + ids=ids.substring(0,ids.length()-1); + } + return ids; + } + public String getOldAllVersion(){ + JSONObject version=new JSONObject(); + RecordSet re=new RecordSet(); + String ids=""; + String sql="select * from "+CubeSaveInterccept.CompanyVersionMaintable+" where qyid='"+this.qyid+"' and bbrq<'"+this.bbrq+"' order by bbrq desc";; +// if("0".equals(type)){ +// sql=sql+" and bbrq<'"+this.bbrq+"' order by desc"; +// } +// if("1".equals(type)){ +// sql=sql+" and bbrq>'"+this.bbrq+"' order by asc"; +// }else{ +// return version; +// } + re.executeQuery(sql); + log.writeLog(sql); + while(re.next()){ + String id=Util.null2String(re.getString("id")) ; + ids=ids+id+","; + } + if(ids.endsWith(",")){ + ids=ids.substring(0,ids.length()-1); + } + return ids; + } + /** + * 返回 字段最新的 修改版本的ID + * @param ids 所有版本的 iD + * @param fieldname 字段名称 + * @return + */ + public String checkFieldCheck(String ids,String fieldname){ + String id=""; + RecordSet re=new RecordSet(); + boolean flag=false; + String sql="select a.id from "+CubeSaveInterccept.CompanyVersionMaintable+" a, "+CubeSaveInterccept.CompanyVersionMaintable+"_dt1 b where a.id=b.mainid and a.qyid='"+this.qyid+"' and a.id in ("+ids+") and bgxm=? order by a.bbrq asc"; + re.executeQuery(sql,fieldname); + log.writeLog(sql); + if(re.next()){ + id=Util.null2String(re.getString("id")) ; + } + return id; + } + + /** + * 明细表 返回 字段最新的 修改版本的ID + * @param ids 所有版本的 iD + * @param type 大于0 的版本 小于 0 之前的版本 + * @return + */ + public String checkDetailFieldCheck(String ids,String bgxm,int type){ + String id=""; + RecordSet re=new RecordSet(); + boolean flag=false; + //String sql="select a.relatedid from ModeViewLog_84 a,ModeLogFieldDetail b where a.id=b.viewlogid and a.operateType=2 and (a.relatedid in ("+ids+") or a.relatedid="+billid+" ) and b.detailtable='"+tablename+"' "; + String sql="select a.id from "+CubeSaveInterccept.CompanyVersionMaintable+" a, "+CubeSaveInterccept.CompanyVersionMaintable+"_dt1 b where a.id=b.mainid and a.qyid='"+this.qyid+"' and a.id in ("+ids+") and bgxm=? "; + //改为按照版本日期 排序 + if(type>0){ + sql=sql+" order by a.bbrq asc"; + }else{ + sql=sql+" order by a.bbrq desc"; + } +// if(type>0){ +// sql=sql+" order by a.id asc"; +// }else{ +// sql=sql+" order by a.id desc"; +// } + re.executeQuery(sql,bgxm); + log.writeLog(sql); + if(re.next()){ + id=Util.null2String(re.getString("id")) ; + } + return id; + } + + public String getFieldNameByid(String fieldid){ + RecordSet re=new RecordSet(); + String fieldname=""; + String sql="select fieldname from workflow_billfield where id="+fieldid; + re.execute(sql); + if(re.next()){ + fieldname=Util.null2String(re.getString("fieldname")) ; + } + return fieldname; + } + //(fieldvalue, fieldhtmltype, fieldid, fielddbtype, viewtype, type) + + public JSONObject getFieldIdByName(String fieldname,String detailtable){ + RecordSet re=new RecordSet(); + JSONObject json=new JSONObject(); + String sql=" select c.id,fieldhtmltype, fielddbtype, viewtype, type from workflow_billfield c where c.billid="+formId+" and fieldname=? "; + if(formId<=0&&!"".equals(Util.null2String(detailtable).trim())){ + sql=" select c.id,fieldhtmltype, fielddbtype, viewtype, type from workflow_billfield c where fieldname=? "; + } + if(!"".equals(Util.null2String(detailtable) )){ + sql=sql+" and detailtable='"+detailtable+"'"; + } + log.writeLog(sql); + re.executeQuery(sql,fieldname); + if(re.next()){ + String id=Util.null2String(re.getString("id")) ; + String fieldhtmltype=Util.null2String(re.getString("fieldhtmltype")) ; + String fielddbtype=Util.null2String(re.getString("fielddbtype")) ; + String viewtype=Util.null2String(re.getString("viewtype")) ; + String type=Util.null2String(re.getString("type")) ; + json.put("fieldid",id); + json.put("fieldhtmltype",fieldhtmltype); + json.put("fielddbtype",fielddbtype); + json.put("viewtype",viewtype); + json.put("type",type); + } + return json; + } + public String getSingleFieldIdByName(String fieldname,String detailtable){ + RecordSet re=new RecordSet(); + JSONObject json=new JSONObject(); + String sql=" select c.id,fieldhtmltype, fielddbtype, viewtype, type from workflow_billfield c where c.billid="+formId+" and fieldname=? "; + if(!"".equals(Util.null2String(detailtable) )){ + sql=sql+" and detailtable='"+detailtable+"'"; + } + String id=""; + re.executeQuery(sql,fieldname); + if(re.next()){ + id=Util.null2String(re.getString("id")) ; + } + return id; + } + /** + * 获取明细表的 所有值 + * @param detailtable + * @param fields + * @return + */ + public String getDetailAllValue(String detailtable,String fields,String billidval){ + String result=""; + detailtable=Util.null2String(detailtable).trim(); + fields=Util.null2String(fields); + if("".equals(detailtable)||"".equals(fields)){ + return ""; + } + String[] fieldss=fields.split(","); + RecordSet re=new RecordSet(); + String sql="select * from "+detailtable+" where mainid="; + if(!"".equals(billidval)){ + sql=sql+""+billidval; + } + re.execute(sql); + while(re.next()){ + String demostr=""; + for(String str:fieldss){ + str=Util.null2String(str).trim(); + if(str.equals("")){ + continue; + } + String fieldvalue=Util.null2String(re.getString(str)) ; + String newfieldvalue=""; + try { + newfieldvalue=BaseUtil.Html2Text(transFieldValue(fieldvalue, getFieldIdByName(str,detailtable))) ; + } catch (Exception e) { + e.printStackTrace(); + } + demostr=demostr+newfieldvalue+"/"; + } + if(demostr.endsWith("/")){ + demostr=demostr.substring(0,demostr.length()-1); + } + result=result+demostr+"、\n"; + } +// if(result.endsWith("|")){ +// result=result.substring(0,result.length()-1); +// } + return result; + } + //更新历史 版本的 新增的明细表对用的 企业信息明细ID + public void updateallmodflyuuid(){ + RecordSet recordSet=new RecordSet(); + String[] allmodflyuuids=Util.null2String(this.allmodflyuuid).trim().split(","); + for(String str:allmodflyuuids){ + str=Util.null2String(str).trim(); + if("".equals(str)||str.indexOf(",")<1){ + continue; + } + String tableindex=str.substring(0,str.indexOf(",")); + log.writeLog(str+"update "+CubeSaveInterccept.CompanyVersionMaintable+"_"+tableindex+" set mainbillid=(select id from "+CubeSaveInterccept.CompanyMaintable+"_"+tableindex+" where modflyuuid=?) where modflyuuid=?"); + recordSet.executeUpdate("update "+CubeSaveInterccept.CompanyVersionMaintable+"_"+tableindex+" set mainbillid=(select id from "+CubeSaveInterccept.CompanyMaintable+"_"+tableindex+" where modflyuuid=?) where modflyuuid=?",str); + } + } + + public String getFeildnameByNames(String names,int formid){ + String resultnames=""; + String result=""; + names=Util.null2String(names).trim(); + if("djgd,cgbl,cgfs,gfzl".equals(names)){ + return "登记股东/持股比例/持股份数/股份种类"; + } + String namesValue=","+names+","; + String[] namess=names.split(","); + for(String str:namess){ + str=Util.null2String(str).trim(); + if("".equals(str)){ + continue; + } + result=result+"'"+str+"',"; + } + if(result.endsWith(",")){ + result=result.substring(0,result.length()-1); + } + if(!"".equals(result)){ + RecordSet re=new RecordSet(); + log.writeLog("select fieldname,fieldlabel from workflow_billfield where billid="+formid+" and fieldname in ("+result+")"); + re.execute("select fieldname,fieldlabel from workflow_billfield where billid="+formid+" and fieldname in ("+result+")"); + + while(re.next()){ + String fieldnameStr=Util.null2String(re.getString("fieldname")); + String fieldname=SystemEnv.getHtmlLabelName(re.getInt("fieldlabel"), 7);//Util.null2String(re.getString("fieldname")) .trim(); + if("".equals(fieldname)){ + continue; + } + namesValue=namesValue.replaceAll(","+fieldnameStr+",",","+fieldname+","); + resultnames=resultnames+fieldname+"/"; + } + if(namesValue.endsWith(",")){ + namesValue=namesValue.substring(0,namesValue.length()-1); + } + if(namesValue.startsWith(",")){ + namesValue=namesValue.substring(1); + } + namesValue=namesValue.replaceAll(",","/"); + if(resultnames.endsWith("/")){ + resultnames=resultnames.substring(0,resultnames.length()-1); + } + } + return namesValue; + } + + /** + * + * @param names + * @param tablename + * @param type 0主表 1明细表 + * @return + */ + public String getFeildnameByNames(String names,String tablename,int type){ + String resultnames=""; + String result=""; + names=Util.null2String(names).trim(); + String[] namess=names.split(","); + for(String str:namess){ + str=Util.null2String(str).trim(); + if("".equals(str)){ + continue; + } + result=result+"'"+str+"',"; + } + if(result.endsWith(",")){ + result=result.substring(0,result.length()-1); + } + log.writeLog(result+" "+tablename+" "+type); + if(!"".equals(result)){ + RecordSet re=new RecordSet(); + //log.writeLog("select fieldname,fieldlabel from workflow_billfield where billid="+formid+" and fieldname in ("+result+")"); + if(type==0){ + re.executeQuery("select a.fieldname,a.fieldlabel from workflow_billfield a,workflow_bill b where a.billid=b.id and a.fieldname in ("+result+") and b.tablename=?",tablename); + }else{ + log.writeLog("select a.fieldname,a.fieldlabel from workflow_billfield a,workflow_bill b where a.billid=b.id and a.fieldname in ("+result+") and a.detailtable=?"+tablename); + re.executeQuery("select a.fieldname,a.fieldlabel from workflow_billfield a,workflow_bill b where a.billid=b.id and a.fieldname in ("+result+") and a.detailtable=?",tablename); + } + + + while(re.next()){ + String fieldname=SystemEnv.getHtmlLabelName(re.getInt("fieldlabel"), 7);//Util.null2String(re.getString("fieldname")) .trim(); + if("".equals(fieldname)){ + continue; + } + resultnames=resultnames+fieldname+"/"; + } + if(resultnames.endsWith("/")){ + resultnames=resultnames.substring(0,resultnames.length()-1); + } + } + return resultnames; + } + + public static void main(String[] arg){ + System.out.println(getBetoowVersion("3","21","1,2,3,21,4,5")); + } +} diff --git a/src/main/youhong_ai_jitu_src/com/jet/action/ApplyForFee.java b/src/main/youhong_ai_jitu_src/com/jet/action/ApplyForFee.java new file mode 100644 index 0000000..60ec5d4 --- /dev/null +++ b/src/main/youhong_ai_jitu_src/com/jet/action/ApplyForFee.java @@ -0,0 +1,56 @@ +package com.jet.action; + +import weaver.soa.workflow.request.RequestInfo; +import weaver.workflow.action.BaseAction; +import weaver.conn.RecordSet; +import weaver.general.Util; + +import com.working.util.LogTool; +import com.working.util.WorkflowUtil; + +/** + * 02-费用报销申请-J&T中国 + * @author lwt + * + */ +public class ApplyForFee extends BaseAction{ + + LogTool log = new LogTool("/log/feeChina/",false); + + @Override + public String execute(RequestInfo requestInfo) { + // TODO Auto-generated method stub + String requestid = requestInfo.getRequestid(); + RecordSet rs = new RecordSet(); + RecordSet rs1 = new RecordSet(); + String mainTable = WorkflowUtil.getMainTable(requestid); + String detail8Table = mainTable + "_dt8"; + int mainId = requestInfo.getRequestManager().getBillid();//主表数据id + rs.execute("select * from " + detail8Table + " where mainid = '" + mainId + "' order by id desc"); + String bxlx = "";//报销类型 + String tdhdVal = "0";//团队活动费 + String clVal = "0";//差旅费 + while (rs.next()) { + bxlx = Util.null2String(rs.getString("BXLX")); + if (bxlx!=null) { + if (bxlx.equals("27")) {//团队活动费 + tdhdVal = "1"; + } else if (bxlx.equals("3")) {//差旅费 + clVal = "1"; + } + } + } + if (tdhdVal.equals("0")&&clVal.equals("0")) {//既没有团队活动费也没有差旅费,设置主表的报销类型为其他 + rs1.execute("update " + mainTable + " set bxlxzb = '2' where requestid = '" + requestid +"'"); + } else if (tdhdVal.equals("1")&&clVal.equals("0")) {//只有团队活动费,设置主表的报销类型为团队活动费 + rs1.execute("update " + mainTable + " set bxlxzb = '0' where requestid = '" + requestid +"'"); + } else if (tdhdVal.equals("0")&&clVal.equals("1")) {//只有差旅费,设置主表的报销类型为差旅费 + rs1.execute("update " + mainTable + " set bxlxzb = '1' where requestid = '" + requestid +"'"); + } else if (tdhdVal.equals("1")&&clVal.equals("1")) {//既有团队活动费也有差旅费,设置主表的报销类型为团队活动费&差旅费 + rs1.execute("update " + mainTable + " set bxlxzb = '3' where requestid = '" + requestid +"'"); + } + + return SUCCESS; + } + +} diff --git a/src/main/youhong_ai_jitu_src/com/jet/action/BusinessTripIntoHRAction.java b/src/main/youhong_ai_jitu_src/com/jet/action/BusinessTripIntoHRAction.java new file mode 100644 index 0000000..efee31f --- /dev/null +++ b/src/main/youhong_ai_jitu_src/com/jet/action/BusinessTripIntoHRAction.java @@ -0,0 +1,202 @@ +package com.jet.action; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.JSONObject; +import com.alibaba.fastjson.serializer.SerializerFeature; +import com.working.third.JwtUtil; +import com.working.util.HttpManager; +import com.working.util.WorkflowUtil; +import selfdev.util.log.LogTool; +import weaver.conn.RecordSet; +import weaver.file.Prop; +import weaver.general.Util; +import weaver.soa.workflow.request.RequestInfo; +import weaver.workflow.action.BaseAction; + +import java.io.IOException; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +/** + * @Author Administrator + * @Description OA出差申请数据写入东宝HR系统 + * @Date 2020/10/20 16:26 + *

+ * 这两个值后需要写在配置文件中 + * 正式环境 + * https://hr.jtexpress.com.cn + * clientId:TPFKAGB3QGPM2LBD + * 测试环境 + * http://121.36.223.187:9011 + * clientId: P3F28BIFKGFL0ANX + */ +public class BusinessTripIntoHRAction extends BaseAction { + + @Override + public String execute(RequestInfo requestInfo) { + LogTool log = new LogTool("/log/selfdev/action", false); + log.writeLog("-----------------------开始OA出差申请数据写入东宝HR系统-----------------------"); + String requestId = requestInfo.getRequestid(); //获取requestid + log.writeLog("------------requestId值为:" + requestId); + + String mainTable = WorkflowUtil.getMainTable(requestId); + +// String clientId = Prop.getPropValue("db_work", "clientId"); + String clientId = "P3F28BIFKGFL0ANX"; + String secret = Prop.getPropValue("db_work", "secret"); + int second = Integer.parseInt(Prop.getPropValue("db_work", "second")); + +// String batchCardDataUrl = Prop.getPropValue("db_work", "batchCardDataUrl"); + String batchCardDataUrl = "http://121.36.223.187:9011/third/api"; + + String code = "saveBusinessTripOrderToThirdNew"; + String moduleCode = "attBusinessTripOrderService"; + String token = JwtUtil.createThirdToken(clientId, secret, second).getToken(); + + HashMap headMap = new HashMap(); // 存放head的值 + headMap.put("code", code); + headMap.put("moduleCode", moduleCode); + headMap.put("token", token); + headMap.put("clientId", clientId); + + HashMap bodyMap = new HashMap(); // 存放body的值 + + String userId = ""; // 申请人id + String workCode = ""; //人员编号 + + String trip_category = "2"; // 出差类型(1-外出,2-出差) + String trip_area = ""; // 出差区域(1-市内,2-省内,3-国内,4-海外) 暂时只分3和4 + String trip_way = "4"; // 出差方式(1-整天,2-上半天,3-下半天,4-连续时间段,5-每天固定时间) + + String begin_date = ""; // 开始日期 + String end_date = ""; // 结束日期 + String begin_time = ""; // 开始时间 + String end_time = ""; // 结束时间 + String reason = ""; // 出差事由 + String origin = ""; // 出发地 + String destination = ""; // 目的地 + + String is_overtime = "1"; // 是否出差计加班(默认传入1) + String audit_status = "1"; // 提交状态 0-保存 1-提交 + + RecordSet rs = new RecordSet(); + String sql = " select * from " + mainTable + " where requestid='" + requestId + "'"; + rs.execute(sql); + while (rs.next()) { + HashMap empOrderMap = new HashMap(); // 存放empOrder的值 + HashMap businessTripOrderMap = new HashMap(); // 存放businessTripOrder的值 + + userId = Util.null2String(rs.getString("sqr"));// 人员转换唯一标识 + workCode = Util.null2String(WorkflowUtil.getUserInfo(userId).get("workcode")); + log.writeLog("------------人员转换唯一标识值为:" + workCode); + + String trip_area1 = Util.null2String(rs.getString("cclb")); // 出差类别 + if ("0".equals(trip_area1)) { + trip_area = "3"; // 国内 + } + if ("1".equals(trip_area1)) { + trip_area = "4"; // 国外 + } + + begin_date = Util.null2String(rs.getString("fsrq")); // 开始日期 + end_date = Util.null2String(rs.getString("jsrq")); // 结束日期 + reason = Util.null2String(rs.getString("ccsy")); // 出差事由 + origin = Util.null2String(rs.getString("cfd")); // 出发地 + destination = Util.null2String(rs.getString("mdd")); // 目的地 + + String[] s = begin_date.split(" "); + begin_time = s[1]; + String[] s1 = end_date.split(" "); + end_time = s1[1]; + + List> scheduleList = new ArrayList>(); // 出差行程记录 + Map scheduleMap1 = new HashMap(); + scheduleMap1.put("name", "出发地"); + scheduleMap1.put("place", origin); + scheduleMap1.put("longitude", ""); + scheduleMap1.put("latitude", ""); + scheduleMap1.put("id", ""); + + Map scheduleMap2 = new HashMap(); + scheduleMap2.put("name", "目的地"); + scheduleMap2.put("place", destination); + scheduleMap2.put("longitude", ""); + scheduleMap2.put("latitude", ""); + scheduleMap2.put("id", ""); + scheduleList.add(scheduleMap1); + scheduleList.add(scheduleMap2); + + log.writeLog("------------出差类型值为:" + trip_category); + log.writeLog("------------出差区域值为:" + trip_area); + log.writeLog("------------出差方式值为:" + trip_way); + log.writeLog("------------开始日期值为:" + begin_date); + log.writeLog("------------结束日期值为:" + end_date); + log.writeLog("------------开始时间值为:" + begin_time); + log.writeLog("------------结束时间值为:" + end_time); + log.writeLog("------------出差事由值为:" + reason); + log.writeLog("------------出发地值为:" + origin); + log.writeLog("------------目的地值为:" + destination); + + empOrderMap.put("empKey", workCode); + empOrderMap.put("empRule", "1"); // 人员转换规则(0-无,1-工号,2-身份证,3邮箱,4-手机号码) + + businessTripOrderMap.put("trip_category", trip_category); + businessTripOrderMap.put("trip_area", trip_area); + businessTripOrderMap.put("trip_way", trip_way); + businessTripOrderMap.put("begin_date", begin_date); + businessTripOrderMap.put("end_date", end_date); + businessTripOrderMap.put("begin_time", begin_time); + businessTripOrderMap.put("end_time", end_time); + businessTripOrderMap.put("reason", reason); + + businessTripOrderMap.put("is_overtime", is_overtime); + businessTripOrderMap.put("audit_status", audit_status); + businessTripOrderMap.put("isChangeTripOrder", false); // 是否变更出差单(默认传入false) + + businessTripOrderMap.put("scheduleList", scheduleList); + + empOrderMap.put("businessTripOrder", businessTripOrderMap); + bodyMap.put("empOrder", empOrderMap); + } + + HashMap paramMap = new HashMap(); + paramMap.put("header", headMap); + paramMap.put("body", bodyMap); + + try { + String param = JSON.toJSONString(paramMap, SerializerFeature.DisableCircularReferenceDetect); + log.writeLog("---------------paramMap的值为:" + param); + String result = HttpManager.postMap(batchCardDataUrl, headMap, param); + log.writeLog("-----------发送请求返回的结果值为:" + result); + + JSONObject jsonObject = JSONObject.parseObject(result); + String returnCode = Util.null2String(jsonObject.get("code")); + String data = Util.null2String(jsonObject.get("data")); + String message = Util.null2String(jsonObject.get("message")); + String id = Util.null2String(jsonObject.get("id")); + + log.writeLog("--------发送请求返回的code值为:" + returnCode); + log.writeLog("--------发送请求返回的数据值为:" + data); + log.writeLog("--------发送请求返回的信息为:" + message); + log.writeLog("--------发送请求返回的id值为:" + id); + + if (!"".equals(result) && result != null) { + if ("200".equals(returnCode)) { + return SUCCESS; + } else { + requestInfo.getRequestManager().setMessagecontent("写入HR系统失败,失败信息为:" + message); + return "0"; + } + } else { + requestInfo.getRequestManager().setMessagecontent("写入HR系统失败,发送请求返回的结果值为" + result); + return "0"; + } + + } catch (IOException ioException) { + requestInfo.getRequestManager().setMessagecontent("发生异常了,写入HR系统失败"); + return "0"; + } + } +} diff --git a/src/main/youhong_ai_jitu_src/com/jet/action/CheckPayAction.java b/src/main/youhong_ai_jitu_src/com/jet/action/CheckPayAction.java new file mode 100644 index 0000000..7ddef7a --- /dev/null +++ b/src/main/youhong_ai_jitu_src/com/jet/action/CheckPayAction.java @@ -0,0 +1,124 @@ +package com.jet.action; + +import weaver.conn.RecordSet; +import weaver.general.BaseBean; +import weaver.general.Util; +import weaver.interfaces.workflow.action.Action; +import weaver.soa.workflow.request.RequestInfo; +import selfdev.util.base.BaseUtil; +import selfdev.util.log.LogTool; + +/** + * 付款申请流程申请节点提交时的校验判断 + * 1、判断支付明细中的本次付款金额是否超出未付款金额 + * 2、判断一个付款流程不能同时选择两行以上相同的批次 + * @author KangMD + * 2019-11-04 + */ +public class CheckPayAction extends BaseBean implements Action { + + public String execute(RequestInfo ri) { + LogTool log=new LogTool("/log/selfdev/action", false); + //获取requestid + String requestid=ri.getRequestid(); + String workflowid=ri.getWorkflowid(); + //获取用户语言 + int language=ri.getRequestManager().getUser().getLanguage(); + log.writeLog("language---------->"+language); + String workflowname=BaseUtil.getBaseInfoByParm("workflowname", "workflow_base", "id", workflowid, ""); + log.writeLog("---------------"+workflowname+"开始-------------requestId:" + requestid); + try { + RecordSet rs=new RecordSet(); + String mainid="";//主键ID + String htxx="";//建模合同ID + //获取表名 + String tablename=BaseUtil.getBaseInfoByParm("tablename", "workflow_bill", "1", "1", " and id in (select formid from workflow_base where id="+workflowid+")");; + String sql="select * from "+tablename+" where requestid="+requestid; + rs.execute(sql); + while(rs.next()){ + mainid=Util.null2String(rs.getString("id")); + htxx=Util.null2String(rs.getString("htxx")); + } + String sfcc="0";//流程是否可通过 0表示可通过 1表示不可通过 + String msg="";//提示信息 + //查询1个流程中是否填写了2行相同付款批次 + sql="select a.pc_num,b.* from (select fkpc,count(*) as pc_num from "+tablename+"_dt5 where mainid= "+mainid+" GROUP BY fkpc having count(*)>1) a left join V_uf_httz_dt1 b on a.fkpc=b.id"; + log.writeLog("查询付款明细中不能有重复批次的SQL---------->"+sql); + rs.execute(sql); + while(rs.next()){ + sfcc="1";//重复 + if(language==0||language==7){//简体 + msg+="明细中批次为【"+Util.null2String(rs.getString("fkpc"))+"】的付款重复选择了;
";//超出提示信息 + }else if(language==8){//英语 + msg+="明细中批次为【"+Util.null2String(rs.getString("fkpc"))+"】的付款重复选择了;
";//超出提示信息 + }else if(language==9){//繁体 + msg+="明细中批次为【"+Util.null2String(rs.getString("fkpc"))+"】的付款重复选择了;
";//超出提示信息 + }else if(language==22){//印尼语 + msg+="明细中批次为【"+Util.null2String(rs.getString("fkpc"))+"】的付款重复选择了;
";//超出提示信息 + } + } + if("0".equals(sfcc)){ + //当前明细汇总本次支付金额与批次未付金额对比,若超出未付金额,则不可提交 + sql="select a.*,b.bcfkje from V_uf_httz_dt1 a,(select fkpc as fkpcid,sum(TO_NUMBER(replace(bcfkje,',',''))) as bcfkje from "+tablename+"_dt5 where mainid="+mainid+" GROUP BY fkpc ) b where a.id=b.fkpcid and a.wfkje"+sql); + rs.execute(sql); + while(rs.next()){ + sfcc="1";//超出了 + if(language==0||language==7){//简体 + msg+="批次【"+Util.null2String(rs.getString("fkpc"))+"】未付金额【"+Util.null2String(rs.getString("wfkje"))+"】元,本次申请支付金额【"+Util.null2String(rs.getString("bcfkje"))+"】元已超出未付金额;
";//超出提示信息 + }else if(language==8){//英语 + msg+="批次【"+Util.null2String(rs.getString("fkpc"))+"】未付金额【"+Util.null2String(rs.getString("wfkje"))+"】元,本次申请支付金额【"+Util.null2String(rs.getString("bcfkje"))+"】元已超出未付金额;
";//超出提示信息 + }else if(language==9){//繁体 + msg+="批次【"+Util.null2String(rs.getString("fkpc"))+"】未付金额【"+Util.null2String(rs.getString("wfkje"))+"】元,本次申请支付金额【"+Util.null2String(rs.getString("bcfkje"))+"】元已超出未付金额;
";//超出提示信息 + }else if(language==22){//印尼语 + msg+="批次【"+Util.null2String(rs.getString("fkpc"))+"】未付金额【"+Util.null2String(rs.getString("wfkje"))+"】元,本次申请支付金额【"+Util.null2String(rs.getString("bcfkje"))+"】元已超出未付金额;
";//超出提示信息 + } + } + } + if("0".equals(sfcc)){ + //当前明细汇总本次支付金额+在途流程金额与批次未付金额对比,若超出未付金额,则不可提交 + sql="select a.*,b.bcfkje,nvl(c.bcfkje_zt,0) as bcfkje_zt from V_uf_httz_dt1 a " + + "left join (select fkpc as fkpcid,sum(TO_NUMBER(replace(bcfkje,',',''))) as bcfkje from "+tablename+"_dt5 where mainid="+mainid+" GROUP BY fkpc ) b on a.id=b.fkpcid " + + "left join (select a.fkpc as fkpcid,sum(TO_NUMBER(replace(a.bcfkje,',',''))) as bcfkje_zt from "+tablename+"_dt5 a,"+tablename+" b,workflow_requestbase c where a.mainid=b.id and b.requestid=c.requestid and c.currentnodetype not in(0,3) and b.htxx='"+htxx+"' GROUP BY a.fkpc ) c on a.id=c.fkpcid " + + "where a.wfkje"+sql); + rs.execute(sql); + while(rs.next()){ + sfcc="1";//超出了 + if(language==0||language==7){//简体 + msg+="批次【"+Util.null2String(rs.getString("fkpc"))+"】未付金额【"+Util.null2String(rs.getString("wfkje"))+"】元,已提交OA流程在途审批中【"+Util.null2String(rs.getString("bcfkje_zt"))+"】元,本次申请支付金额【"+Util.null2String(rs.getString("bcfkje"))+"】元已超出未付金额;
";//超出提示信息 + }else if(language==8){//英语 + msg+="批次【"+Util.null2String(rs.getString("fkpc"))+"】未付金额【"+Util.null2String(rs.getString("wfkje"))+"】元,已提交OA流程在途审批中【"+Util.null2String(rs.getString("bcfkje_zt"))+"】元,本次申请支付金额【"+Util.null2String(rs.getString("bcfkje"))+"】元已超出未付金额;
";//超出提示信息 + }else if(language==9){//繁体 + msg+="批次【"+Util.null2String(rs.getString("fkpc"))+"】未付金额【"+Util.null2String(rs.getString("wfkje"))+"】元,已提交OA流程在途审批中【"+Util.null2String(rs.getString("bcfkje_zt"))+"】元,本次申请支付金额【"+Util.null2String(rs.getString("bcfkje"))+"】元已超出未付金额;
";//超出提示信息 + }else if(language==22){//印尼语 + msg+="批次【"+Util.null2String(rs.getString("fkpc"))+"】未付金额【"+Util.null2String(rs.getString("wfkje"))+"】元,已提交OA流程在途审批中【"+Util.null2String(rs.getString("bcfkje_zt"))+"】元,本次申请支付金额【"+Util.null2String(rs.getString("bcfkje"))+"】元已超出未付金额;
";//超出提示信息 + } + } + } + //超出未支付金额,则进行提醒,并阻止流程提交 + if("1".equals(sfcc)){ + ri.getRequestManager().setMessage("111100"); + ri.getRequestManager().setMessagecontent(msg); + return "0"; + } + } catch (Exception e) { + e.printStackTrace(); + String error_msg="付款流程提交失败,错误信息为:------>"+e.toString(); + if(language==0||language==7){//简体 + + }else if(language==8){//英语 + error_msg="付款流程提交失败,错误信息为:------>"+e.toString(); + }else if(language==9){//繁体 + error_msg="付款流程提交失败,错误信息为:------>"+e.toString(); + }else if(language==22){//印尼语 + error_msg="付款流程提交失败,错误信息为:------>"+e.toString(); + } + log.writeLog(error_msg); + ri.getRequestManager().setMessage("111100"); + ri.getRequestManager().setMessagecontent(error_msg); + return "0"; + } + return SUCCESS; + } +} diff --git a/src/main/youhong_ai_jitu_src/com/jet/action/CheckReimbursementAction.java b/src/main/youhong_ai_jitu_src/com/jet/action/CheckReimbursementAction.java new file mode 100644 index 0000000..d2ea039 --- /dev/null +++ b/src/main/youhong_ai_jitu_src/com/jet/action/CheckReimbursementAction.java @@ -0,0 +1,122 @@ +package com.jet.action; + +import weaver.conn.RecordSet; +import weaver.general.BaseBean; +import weaver.general.Util; +import weaver.interfaces.workflow.action.Action; +import weaver.soa.workflow.request.RequestInfo; +import selfdev.util.base.BaseUtil; +import selfdev.util.log.LogTool; + +/** + * 费用报销流程申请节点提交时的校验判断 + * 1、报销明细若存在团队招待费,则明细dt2中的合计金额需与报销明细中的团队招待费金额相等 + * 2、报销明细若存在客户招待费,则明细dt3中的合计金额需与报销明细中的客户招待费金额相等 + * @author KangMD + * 2019-11-07 + */ +public class CheckReimbursementAction extends BaseBean implements Action { + + public String execute(RequestInfo ri) { + LogTool log=new LogTool("/log/selfdev/action", false); + //获取requestid + String requestid=ri.getRequestid(); + String workflowid=ri.getWorkflowid(); + //获取用户语言 + int language=ri.getRequestManager().getUser().getLanguage(); + log.writeLog("language---------->"+language); + String workflowname=BaseUtil.getBaseInfoByParm("workflowname", "workflow_base", "id", workflowid, ""); + log.writeLog("---------------"+workflowname+"开始-------------requestId:" + requestid); + try { + RecordSet rs=new RecordSet(); + String mainid="";//主键ID + //获取表名 + String tablename=BaseUtil.getBaseInfoByParm("tablename", "workflow_bill", "1", "1", " and id in (select formid from workflow_base where id="+workflowid+")");; + String sql="select * from "+tablename+" where requestid="+requestid; + rs.execute(sql); + while(rs.next()){ + mainid=Util.null2String(rs.getString("id")); + } + double tdzdf=0;//团队招待费(报销明细) + double khzdf=0;//客户招待费(报销明细) + double tdzdf_dt2=0;//团队招待费(团队招待费明细) + double khzdf_dt3=0;//客户招待费(客户招待费明细) + //查询报销明细中是否存在团队招待费和客户招待费的类型 + sql="select bxlx1,sum(TO_NUMBER(replace(je,',',''))) as je from "+tablename+"_dt8 where mainid="+mainid+" and bxlx1 in ('3-05.02','3-05.03') group by bxlx1 "; + rs.execute(sql); + while(rs.next()){ + if("3-05.02".equals(rs.getString("bxlx1"))){ + khzdf=rs.getDouble("je");//客户招待费 + }else if("3-05.03".equals(rs.getString("bxlx1"))){ + tdzdf=rs.getDouble("je");//团队招待费 + } + } + //查询团队招待费明细中金额合计 + sql="select nvl(sum(TO_NUMBER(replace(je,',',''))),0) as je from "+tablename+"_dt2 where mainid="+mainid; + rs.execute(sql); + while(rs.next()){ + tdzdf_dt2=rs.getDouble("je"); + } + //查询客户招待费明细中金额合计 + sql="select nvl(sum(TO_NUMBER(replace(je,',',''))),0) as je from "+tablename+"_dt3 where mainid="+mainid; + rs.execute(sql); + while(rs.next()){ + khzdf_dt3=rs.getDouble("je"); + } + + String sftg="0";//流程是否可通过 0表示可通过 1表示不可通过 + String msg="";//提示信息 + + //团队招待费校验 + if(tdzdf!=tdzdf_dt2){ + sftg="1";// + if(language==0||language==7){//简体 + msg+="报销明细中报销类型为【团队招待费】金额需与团队招待费明细中的金额合计相等;
";//提示信息 + }else if(language==8){//英语 + msg+="报销明细中报销类型为【团队招待费】金额需与团队招待费明细中的金额合计相等;
";//提示信息 + }else if(language==9){//繁体 + msg+="报销明细中报销类型为【团队招待费】金额需与团队招待费明细中的金额合计相等;
";//提示信息 + }else if(language==22){//印尼语 + msg+="报销明细中报销类型为【团队招待费】金额需与团队招待费明细中的金额合计相等;
";//提示信息 + } + } + //客户招待费校验 + if(khzdf!=khzdf_dt3){ + sftg="1";// + if(language==0||language==7){//简体 + msg+="报销明细中报销类型为【客户招待费】金额需与客户招待费明细中的金额合计相等;
";//提示信息 + }else if(language==8){//英语 + msg+="报销明细中报销类型为【客户招待费】金额需与客户招待费明细中的金额合计相等;
";//提示信息 + }else if(language==9){//繁体 + msg+="报销明细中报销类型为【客户招待费】金额需与客户招待费明细中的金额合计相等;
";//提示信息 + }else if(language==22){//印尼语 + msg+="报销明细中报销类型为【客户招待费】金额需与客户招待费明细中的金额合计相等;
";//提示信息 + } + } + + //不通过则进行提醒,并阻止流程提交 + if("1".equals(sftg)){ + ri.getRequestManager().setMessage("111100"); + ri.getRequestManager().setMessagecontent(msg); + return "0"; + } + } catch (Exception e) { + e.printStackTrace(); + String error_msg="报销流程提交失败,错误信息为:------>"+e.toString(); + if(language==0||language==7){//简体 + + }else if(language==8){//英语 + error_msg="报销流程提交失败,错误信息为:------>"+e.toString(); + }else if(language==9){//繁体 + error_msg="报销流程提交失败,错误信息为:------>"+e.toString(); + }else if(language==22){//印尼语 + error_msg="报销流程提交失败,错误信息为:------>"+e.toString(); + } + log.writeLog(error_msg); + ri.getRequestManager().setMessage("111100"); + ri.getRequestManager().setMessagecontent(error_msg); + return "0"; + } + return SUCCESS; + } +} diff --git a/src/main/youhong_ai_jitu_src/com/jet/action/CreateBxAP.java b/src/main/youhong_ai_jitu_src/com/jet/action/CreateBxAP.java new file mode 100644 index 0000000..95916bf --- /dev/null +++ b/src/main/youhong_ai_jitu_src/com/jet/action/CreateBxAP.java @@ -0,0 +1,296 @@ +package com.jet.action; + +import java.text.SimpleDateFormat; +import java.util.Date; + +import org.apache.log4j.Logger; + +import com.alibaba.fastjson.JSONArray; +import com.alibaba.fastjson.JSONObject; +import com.jet.util.InvokeHelper; + +import weaver.conn.RecordSet; +import weaver.general.BaseBean; +import weaver.general.Util; +import weaver.interfaces.workflow.action.Action; +import weaver.soa.workflow.request.Cell; +import weaver.soa.workflow.request.DetailTable; +import weaver.soa.workflow.request.DetailTableInfo; +import weaver.soa.workflow.request.MainTableInfo; +import weaver.soa.workflow.request.Property; +import weaver.soa.workflow.request.RequestInfo; +import weaver.soa.workflow.request.Row; + +public class CreateBxAP extends BaseBean implements Action{ + public String execute(RequestInfo request) { + Logger log = Logger.getLogger(JSONObject.class); + RecordSet urlre=new RecordSet(); + String urlsql="select * from uf_urlinfo where ms='model'"; + + urlre.execute(urlsql); + String url=""; + String username=""; + String password1=""; + String dbid1=""; + String uuid1=""; + String password2=""; + while(urlre.next()){ + url=Util.null2String(urlre.getString("url")); + username=Util.null2String(urlre.getString("username")); + password1=Util.null2String(urlre.getString("password")); + dbid1=Util.null2String(urlre.getString("dbid")); + uuid1=Util.null2String(urlre.getString("uuid")); + password2=Util.null2String(urlre.getString("password1")); + } + String baseis=username+":"+password1; + + // TODO Auto-generated method stub + SimpleDateFormat sim=new SimpleDateFormat("yyyy-MM-dd"); + String CurretDate=sim.format(new Date()); + String requestid=request.getRequestid(); + String sfxr="";//是否写入标识 + writeLog("CreateBxAP---->"+requestid); + MainTableInfo MainTableInfo=request.getMainTableInfo(); + Property[] props=MainTableInfo.getProperty(); + String zt="";//账套 + String zz="";//组织 + String K3depCode="";//K3部门编号 + JSONObject MainJson=new JSONObject(); + JSONObject FBillTypeID=new JSONObject(); + FBillTypeID.put("FNumber", "YFD01_SYS"); + MainJson.put("FBillTypeID", FBillTypeID);//默认应付单 + MainJson.put("FDATE", CurretDate);//单据日期 + MainJson.put("FENDDATE_H", CurretDate);//到期日 + MainJson.put("FBUSINESSTYPE", "CG"); + MainJson.put("FMatchMethodID", "0");//核销方式 + MainJson.put("F_RTA_InvoiceNo", CurretDate+requestid+"66");//发票 + MainJson.put("F_RTA_BusinessType", ""); + //相关资料 json + JSONObject FSUPPLIERID=new JSONObject();//供应商 + JSONObject FCURRENCYID=new JSONObject();//币别 + JSONObject FCURRENCYID2=new JSONObject();//币别2 + JSONObject FSETTLEORGID=new JSONObject();//结算组织 + JSONObject FTaxType =new JSONObject();//税务分类 + FTaxType.put("FNumber", "PKP"); + JSONObject FPAYORGID=new JSONObject();//付款组织 + MainJson.put("FSUPPLIERID", FSUPPLIERID); + MainJson.put("FCURRENCYID", FCURRENCYID); + MainJson.put("FSETTLEORGID", FSETTLEORGID); + MainJson.put("FTaxType", FTaxType); + MainJson.put("FPAYORGID", FPAYORGID); + //初始化其他供应商信息 + JSONArray FsubHeadSuppilers=new JSONArray(); + JSONObject FsubHeadSuppiler=new JSONObject(); + MainJson.put("FsubHeadSuppiler", FsubHeadSuppiler); + for(Property prop:props){ + String name=prop.getName(); + String value=prop.getValue(); + if("bxzje".equals(name)){//FALLAMOUNTFOR:合计金额 + MainJson.put("FALLAMOUNTFOR", value);//默认应付单 + writeLog("bxzje---->"+value); + } + if("gys".equals(name)){//FSUPPLIERID:供应商 + FSUPPLIERID.put("FNumber", value); + JSONObject FORDERID=new JSONObject(); + FORDERID.put("FNumber", value); + JSONObject FTRANSFERID=new JSONObject(); + FTRANSFERID.put("FNumber", value); + JSONObject FChargeId=new JSONObject(); + FChargeId.put("FNumber", value); + FsubHeadSuppiler.put("FEntryId", 0); + FsubHeadSuppiler.put("FORDERID", FORDERID); + FsubHeadSuppiler.put("FTRANSFERID", FTRANSFERID); + FsubHeadSuppiler.put("FChargeId", FChargeId); + //FsubHeadSuppilers.add(FsubHeadSuppiler); + writeLog("gys---->"+value); + } + if("k3bmbh".equals(name)){//FPURCHASEDEPTID:采购组织 + //MainJson.put("FPURCHASEDEPTID", value); + K3depCode=value; + writeLog("k3bmbh---->"+value); + } + if("bz".equals(name)){//FCURRENCYID:币种 + FCURRENCYID.put("FNumber", value);//默认应付单 + FCURRENCYID2.put("FNumber", value);//默认应付单 + writeLog("bz---->"+value); + } + if("zz".equals(name)){//FSETTLEORGID:结算组织 FPAYORGID:付款组织 + FSETTLEORGID.put("FNumber", value); + FPAYORGID.put("FNumber", value); + zz=value; + writeLog("zz---->"+value); + } + if("bxms".equals(name)){//FAP_Remark:备注 + MainJson.put("FAP_Remark", value); + writeLog("bxms---->"+value); + } + if("sfxr".equals(name)){ + sfxr=value; + writeLog("sfxr---->"+value); + } + if("zt".equals(name)){ + zt=value; + } + + } + String K3bmID=getK3Departmet(K3depCode,zt,zz);//获取K3部门ID + if("".equals(K3depCode)){ + request.getRequestManager().setMessageid("失败"); + request.getRequestManager().setMessage("失败");//提醒信息id + request.getRequestManager().setMessagecontent("写入K3系统不成功:为获取采购组织");//提醒信息内容 + return FAILURE_AND_CONTINUE; + } + JSONObject FPURCHASEDEPTID=new JSONObject(); + FPURCHASEDEPTID.put("FNumber", K3depCode); + MainJson.put("FPURCHASEDEPTID", FPURCHASEDEPTID); + //初始化其他财务信息 FsubHeadFinc + + JSONObject FsubHeadFinc=new JSONObject(); + //JSONObject FMAINBOOKSTDCURRID=new JSONObject(); + JSONObject FEXCHANGETYPE=new JSONObject(); + FEXCHANGETYPE.put("FNumber", "HLTX01_SYS"); + FsubHeadFinc.put("FEntryId", 0); + FsubHeadFinc.put("FACCNTTIMEJUDGETIME", CurretDate); + FsubHeadFinc.put("FMAINBOOKSTDCURRID", FCURRENCYID2); + FsubHeadFinc.put("FExchangeRate", 1); + FsubHeadFinc.put("FTaxAmountFor", MainJson.get("FALLAMOUNTFOR")); + FsubHeadFinc.put("FNoTaxAmountFor", MainJson.get("FALLAMOUNTFOR")); + MainJson.put("FsubHeadFinc", FsubHeadFinc); + //拼接明细表数据 + JSONArray FEntityDetails=new JSONArray(); + JSONArray FEntityPlans=new JSONArray(); + MainJson.put("FEntityDetail", FEntityDetails) ; + MainJson.put("FEntityPlan", FEntityPlans) ; + JSONObject FEntityDetail=null;//new JSONObject(); + JSONObject FEntityPlan=null; + FEntityPlan=new JSONObject(); + DetailTableInfo DetailTableInfo=request.getDetailTableInfo(); + DetailTable DetailTable=DetailTableInfo.getDetailTable(7); + Row[] Rows=DetailTable.getRow(); + for(Row r:Rows){ + FEntityDetail=new JSONObject(); + + JSONObject FMATERIALID=new JSONObject();//物料 + JSONObject FPRICEUNITID=new JSONObject();//单位 + JSONObject FMATERIALID1=new JSONObject();//物料 + JSONObject FPRICEUNITID1=new JSONObject();//单位 +// FEntityPlan.put("FPRICEUNITID", FPRICEUNITID1); +// FEntityPlan.put("FMATERIALID", FMATERIALID1); + //FEntityPlan.put("FEntityPlan", CurretDate); + FEntityDetail.put("FPriceQty","1"); + FEntityDetail.put("FBASICUNITQTY","1"); + + FPRICEUNITID.put("FNumber", "Pcs"); + FPRICEUNITID1.put("FNumber", "Pcs"); + + FEntityDetail.put("FPRICEUNITID", FPRICEUNITID); + FEntityDetail.put("FMATERIALID", FMATERIALID); + FEntityDetail.put("F_RTA_FakturPajakNo_d", "-"); + FEntityDetail.put("F_RTA_AccumulatedAmount", 0); + Cell[] Cells=r.getCell(); + for(Cell Cell:Cells){ + String name=Cell.getName(); + String value=Cell.getValue(); + if("bxlx1".equals(name)){//物料编号 + FMATERIALID.put("FNumber", value); + FMATERIALID1.put("FNumber", value); + writeLog("bxlx1---->"+value); + } + if("je".equals(name)){//金额 + FEntityDetail.put("FPrice", value); + FEntityDetail.put("FTaxPrice", value); + FEntityDetail.put("FNoTaxAmountFor_D", value); + FEntityDetail.put("FALLAMOUNTFOR_D", value); + + writeLog("je---->"+value); + } + if("bz".equals(name)){//备注 + FEntityDetail.put("F_RTA_EntryRemarks", value); + writeLog("bz---->"+value); + } + } + FEntityDetails.add(FEntityDetail); + + } + FEntityPlan.put("FPAYRATE",100); + FEntityPlan.put("FENDDATE", CurretDate); + FEntityPlan.put("FPAYAMOUNTFOR", MainJson.get("FALLAMOUNTFOR")); + FEntityPlan.put("FPAYAMOUNT", MainJson.get("FALLAMOUNTFOR")); + FEntityPlan.put("FPRICE_P", MainJson.get("FALLAMOUNTFOR")); + FEntityPlan.put("FQTY_P", 1); + FEntityPlans.add(FEntityPlan); + //数据提交 + writeLog("FEntityDetails---->"+FEntityDetails.toJSONString()); + writeLog("MainJson---->"+MainJson.toJSONString()); + JSONObject Model=new JSONObject(); + Model.put("NeedReturnFields", new String[]{"BillNo"}); + Model.put("IsAutoSubmitAndAudit", true); + Model.put("Model", MainJson); + + //数据写入 + writeLog("Model--->"+Model.toJSONString()); + if(Model!=null&&Model.size()>0&&("".equals(sfxr)||"1".equals(sfxr))){ + RecordSet updRec=new RecordSet(); + com.jet.util.InvokeHelper.POST_K3CloudURL="http://k3.jet.co.id:8880/k3cloud/"; + String dbid="5d48f604c8361e";//dbid1;//"5d48f604c8361e";//"5a964ecc967246"; + String uuid=uuid1; + String password=password2; + org.json.JSONObject resultjson=null; + int lang=2052; + try { + boolean flag=InvokeHelper.Login(dbid, uuid, password, lang); + //out.print(flag); + if(flag){//登陆成功 + resultjson=com.jet.util.InvokeHelper.Save("AP_Payable",Model.toJSONString()); + boolean flag1=resultjson.getBoolean("flag"); + String resultstr=resultjson.getString("sResult"); + log.error("resultstr"+resultstr); + if(flag1){ + JSONObject HAHA=JSONObject.parseObject(resultstr); + JSONObject Result=HAHA.getJSONObject("Result"); + JSONObject ResponseStatus=Result.getJSONObject("ResponseStatus"); + boolean IsSuccess=ResponseStatus.getBoolean("IsSuccess"); + if(IsSuccess){ + JSONArray SuccessEntitys=ResponseStatus.getJSONArray("SuccessEntitys"); + String Number=SuccessEntitys.getJSONObject(0).getString("Number"); + updRec.execute("update formtable_main_22 set sfxr='0',yfdbh='"+Number+"' where requestid='"+requestid+"' "); + + }else{ + //out.print("失败"); + request.getRequestManager().setMessageid("失败"); + request.getRequestManager().setMessage("失败");//提醒信息id + request.getRequestManager().setMessagecontent("写入K3系统不成功,系统反馈信息如下:"+HAHA.toString());//提醒信息内容 + + return Action.FAILURE_AND_CONTINUE; + } + }else{ + //out.print("失败"+resultstr); + request.getRequestManager().setMessageid("失败"); + request.getRequestManager().setMessage("失败");//提醒信息id + request.getRequestManager().setMessagecontent("写入K3系统不成功,系统反馈信息如下:"+resultstr.toString());//提醒信息内容 + + return Action.FAILURE_AND_CONTINUE; + } + + } + } catch (Exception e) { + //TODO Auto-generated catch block + log.error("AP_Payable--Exception"+e.getMessage()); + e.printStackTrace(); + } + } + return SUCCESS; + } + //获取K3 部门ID + public String getK3Departmet(String k3bm,String zt,String zz){ + String bmID=""; + RecordSet re=new RecordSet(); + String sql="select b.ENTRYID from uf_K3baseinfo a,uf_K3baseinfo_dt1 b where a.id=b.mainid and a.zt='"+zt+"' and a.lx='FFLEX5' and b.FORGNAME='"+zz+"' and bh='"+k3bm+"' "; + writeLog("getK3Departmet--->"+sql); + re.execute(sql); + while(re.next()){ + bmID=re.getString("ENTRYID"); + } + return bmID; + } +} diff --git a/src/main/youhong_ai_jitu_src/com/jet/action/CreateJD.java b/src/main/youhong_ai_jitu_src/com/jet/action/CreateJD.java new file mode 100644 index 0000000..01c3de0 --- /dev/null +++ b/src/main/youhong_ai_jitu_src/com/jet/action/CreateJD.java @@ -0,0 +1,266 @@ +package com.jet.action; + +import java.util.*; +import weaver.soa.workflow.request.RequestInfo; +import weaver.workflow.action.BaseAction; +import weaver.conn.RecordSet; +import com.alibaba.fastjson.JSONArray; +import com.alibaba.fastjson.JSONObject; +import weaver.hrm.HrmUserVarify; +import weaver.hrm.User; +import weaver.general.BaseBean; +import weaver.general.Util; +import org.apache.log4j.Logger; +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import java.text.SimpleDateFormat; +import java.sql.Connection; +import java.sql.ResultSet; +import java.sql.Statement; +import weaver.general.StaticObj; +import weaver.interfaces.datasource.DataSource; +import weaver.formmode.setup.ModeRightInfo; +import java.sql.Connection; +import java.sql.ResultSet; +import java.sql.SQLException; +import java.sql.Statement; +import weaver.general.StaticObj; +import weaver.interfaces.datasource.DataSource; +import weaver.interfaces.workflow.action.Action; + +import java.math.BigDecimal; +import java.io.BufferedReader; +import java.io.IOException; +import java.io.InputStreamReader; +import java.io.PrintWriter; +import java.net.URL; +import java.net.URLConnection; +import org.apache.http.Header; +import org.apache.http.HttpResponse; +import org.apache.http.HttpStatus; +import org.apache.http.client.HttpClient; +import org.apache.http.client.methods.HttpPost; +import org.apache.http.entity.*; +import org.apache.http.*; +import org.apache.http.util.*; +import org.apache.http.impl.client.DefaultHttpClient; +import org.apache.http.params.CoreConnectionPNames; +import java.util.UUID; +import java.nio.charset.Charset; +import java.io.BufferedReader; +import java.io.ByteArrayOutputStream; +import java.io.FileNotFoundException; +import java.io.IOException; +import java.io.InputStream; +import java.io.InputStreamReader; +import weaver.conn.RecordSetTrans; +import java.io.PrintWriter; + +public class CreateJD extends BaseAction{ + @Override + public String execute(RequestInfo requestInfo) { + // TODO Auto-generated method stub + Logger log = Logger.getLogger(JSONObject.class); + Map Hswd=new HashMap();//核算维度对照表 + Hswd.put("FFLEX4","gys");//供应商 + Hswd.put("FFLEX6","kh");//客户 + Hswd.put("FFLEX7","yg");//员工 + Hswd.put("FFLEX5","bm");//部门 + Hswd.put("FFLEX9","fyxm");//费用项目 + Hswd.put("FFLEX8","wl");//物料 + Hswd.put("FFLEX10","zc");//资产 + Hswd.put("FFLEX12","wlz");//物料组 + Hswd.put("FFLEX13","khz");//客户组 + + List jlist=new ArrayList();//借方 + List dlist=new ArrayList();//贷方 + String requestid=requestInfo.getRequestid();// + String mainid="";// + String zt="";//账套 + String zz="";//组织 + String zb="";//账薄 + String zzjdhl="";//做账节点汇率 + String bz="";//币种 + RecordSet re=new RecordSet(); + String jsql=""; + String dsql=""; + float zje=0.0f; + String sql="select a.zzjdhl,a.bz,a.id,a.zt,a.zz,a.zb,sum(je) je,b.bxr,b.bxlx from formtable_main_22 a,formtable_main_22_dt8 b where a.id=b.mainid and a.requestid='"+requestid+"' group by a.zzjdhl,a.bz,a.id,a.zt,a.zz,a.zb,b.bxr,b.bxlx"; + log.error(requestid+"CreateJD"+sql); + re.execute(sql); + while(re.next()){ + mainid=Util.null2String(re.getString("id")).trim(); + zzjdhl=Util.null2String(re.getString("zzjdhl")).trim(); + if("".equals(zzjdhl.trim())){ + zzjdhl="1"; + } + bz=Util.null2String(re.getString("bz")).trim(); + int xsw=getXsw(bz); + zt=Util.null2String(re.getString("zt")).trim(); + zz=Util.null2String(re.getString("zz")).trim(); + zb=Util.null2String(re.getString("zb")).trim(); + String bxlx= re.getString("bxlx");//报销科目 + String je= Util.null2String(re.getString("je")).trim();//报销金额 + //je=getfloats(je,zzjdhl,xsw)+""; + zje=getfloats1(je,zje+"",2); + String FDIMENSION=getFzhx(bxlx,zt,zz,zb,Hswd); + String accountname=getKmname(bxlx,zt,zz,zb); + + jsql="insert into formtable_main_22_dt4(mainid,jfkmbm,jfkmmc,hswd,yje,zy)values("+mainid+",'"+bxlx+"','"+accountname+"','"+FDIMENSION+"',"+je+",'')"; + jlist.add(jsql); + } + if(jlist.size()>0){ + //插入贷方 + jlist.add("insert into formtable_main_22_dt5(mainid,dfkmbm,dfkmmc,hswd,yje,zy)values("+mainid+",'2000.01','AccountPayableIDR','',"+zje+",'')"); + } + if(jlist.size()>0){ + log.error(jlist.toString()); + boolean flag=SynInsert1(jlist); + if(!flag){ + requestInfo.getRequestManager().setMessageid("创建借贷失败"); + requestInfo.getRequestManager().setMessage("创建借贷失败");//提醒信息id + requestInfo.getRequestManager().setMessagecontent("创建借贷失败");//提醒信息内容 + + return Action.FAILURE_AND_CONTINUE; + } + } + return SUCCESS; + } + //获取赋值核算类型 + public String getFzhx(String km,String zt,String zz,String zb,Map Hswd){ + String FDIMENSION="";//核算维度 + RecordSet re=new RecordSet(); + String sql="select b.FDIMENSION from uf_accountinfo a,uf_accountinfo_dt1 b where a.id=b.mainid and a.zt='"+zt+"' and b.FNUMBER='"+km+"' and b.forgnumber='"+zz+"' and FAcctBookNumber='"+zb+"' "; + //out.print(sql); + re.execute(sql); + while(re.next()){ + String str=Util.null2String(re.getString("FDIMENSION")).trim() ; + String[] FDIMENSIONs=str.split(","); + for(String demo:FDIMENSIONs){ + if(demo!=null&&!"".equals(demo)){ + FDIMENSION=FDIMENSION+Hswd.get(FDIMENSION)+","; + } + } + } + return FDIMENSION; + } + //insert 事务 + public boolean SynInsert1(List array){ + if(array==null||array.size()<=0){ + return false; + } + Logger log = Logger.getLogger(DataSource.class); + RecordSetTrans RecordSetTrans=new RecordSetTrans(); + RecordSetTrans.setAutoCommit(false); + boolean flag=true; + + try{ + RecordSetTrans.setAutoCommit(false); + // stmt = conn.createStatement(); + for(String str:array){ + //int index =RecordSetTrans.executeUpdate(str); + flag=RecordSetTrans.executeSql(str); + log.error("SynInsert--"+str); + if(!flag){ + //flag=false; + break; + } + } + if(!flag){//事务回滚 + RecordSetTrans.rollback(); + }else{ + RecordSetTrans.commit(); + } + }catch(Exception e){ + log.error("SynInsert--Exception "+e.getMessage()); + flag=false; + } + + return flag; + } + //获取科目名称 + public String getKmname(String km,String zt,String zz,String zb){ + String FNAME="";//核算维度 + RecordSet re=new RecordSet(); + String sql="select b.FNAME from uf_accountinfo a,uf_accountinfo_dt1 b where a.id=b.mainid and a.zt='"+zt+"' and b.FNUMBER='"+km+"' and b.forgnumber='"+zz+"' and FAcctBookNumber='"+zb+"' "; + re.execute(sql); + while(re.next()){ + FNAME=Util.null2String(re.getString("FNAME")); + } + return FNAME; + } + //获取币种的小数位 + public int getXsw(String bz){ + int xsw=0; + RecordSet re=new RecordSet(); + String sql="select * from uf_k3bz where bh='"+bz+"'"; + re.execute(sql); + while(re.next()){ + xsw=Integer.parseInt(Util.null2o(re.getString("xsw"))) ; + } + return xsw; + } + + //浮点型转换 + public static float getfloats(String demo,String demo1,int len){ + Logger log = Logger.getLogger(BigDecimal.class); + if(len==0){ + len=0; + } + String str=Util.null2String(demo); + String str1=Util.null2String(demo1); + if("".equals(str)||"".equals(str.trim())||"null".equalsIgnoreCase(str.trim())){ + return 0; + } + if("".equals(str1)||"".equals(str.trim())||"null".equalsIgnoreCase(str1.trim())){ + str1="1"; + } + float fl=0.0f; + //String str=Util.null2String(demo); + try{ + if(str.trim().length()>0){ + BigDecimal b1 = new BigDecimal(str.trim()); + BigDecimal b2 = new BigDecimal(str1.trim()); + BigDecimal b3=b1.multiply(b2); + //System.out.println(b1.setScale(2,BigDecimal.ROUND_HALF_UP)); + fl=b3.setScale(len,BigDecimal.ROUND_HALF_UP).floatValue(); + } + log.error("getfloats"+fl); + }catch(Exception e){ + log.error(demo+"getfloats异常"+e.getMessage()); + } + return fl; + } + + + //浮点型转换 + public static float getfloats1(String demo,String demo1,int len){ + Logger log = Logger.getLogger(BigDecimal.class); + if(len==0){ + len=0; + } + String str=Util.null2String(demo); + String str1=Util.null2String(demo1); + if("".equals(str)||"".equals(str.trim())||"null".equalsIgnoreCase(str.trim())){ + str="0"; + } + if("".equals(str1)||"".equals(str.trim())||"null".equalsIgnoreCase(str1.trim())){ + str1="0"; + } + float fl=0.0f; + //String str=Util.null2String(demo); + try{ + if(str.trim().length()>0){ + BigDecimal b1 = new BigDecimal(str.trim()); + BigDecimal b2 = new BigDecimal(str1.trim()); + BigDecimal b3=b1.add(b2); + //System.out.println(b1.setScale(2,BigDecimal.ROUND_HALF_UP)); + fl=b3.setScale(len,BigDecimal.ROUND_HALF_UP).floatValue(); + } + log.error("getfloats"+fl); + }catch(Exception e){ + log.error(demo+"getfloats异常"+e.getMessage()); + } + return fl; + } +} diff --git a/src/main/youhong_ai_jitu_src/com/jet/action/CreateJkJD.java b/src/main/youhong_ai_jitu_src/com/jet/action/CreateJkJD.java new file mode 100644 index 0000000..bda34f1 --- /dev/null +++ b/src/main/youhong_ai_jitu_src/com/jet/action/CreateJkJD.java @@ -0,0 +1,398 @@ +package com.jet.action; + +import java.util.*; +import weaver.soa.workflow.request.RequestInfo; +import weaver.workflow.action.BaseAction; +import weaver.conn.RecordSet; +import com.alibaba.fastjson.JSONArray; +import com.alibaba.fastjson.JSONObject; +import weaver.general.Util; +import org.apache.log4j.Logger; +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import java.text.SimpleDateFormat; +import java.sql.Connection; +import java.sql.ResultSet; +import java.sql.Statement; +import weaver.general.StaticObj; +import weaver.interfaces.datasource.DataSource; +import weaver.formmode.setup.ModeRightInfo; +import java.sql.Connection; +import java.sql.ResultSet; +import java.sql.SQLException; +import java.sql.Statement; +import weaver.general.StaticObj; +import weaver.interfaces.datasource.DataSource; +import weaver.interfaces.workflow.action.Action; + +import java.math.BigDecimal; +import java.io.BufferedReader; +import java.io.IOException; +import java.io.InputStreamReader; +import java.io.PrintWriter; +import java.net.URL; +import java.net.URLConnection; +import org.apache.http.Header; +import org.apache.http.HttpResponse; +import org.apache.http.HttpStatus; +import org.apache.http.client.HttpClient; +import org.apache.http.client.methods.HttpPost; +import org.apache.http.entity.*; +import org.apache.http.*; +import org.apache.http.util.*; +import org.apache.http.impl.client.DefaultHttpClient; +import org.apache.http.params.CoreConnectionPNames; +import java.util.UUID; +import java.nio.charset.Charset; +import java.io.BufferedReader; +import java.io.ByteArrayOutputStream; +import java.io.FileNotFoundException; +import java.io.IOException; +import java.io.InputStream; +import java.io.InputStreamReader; +import weaver.conn.RecordSetTrans; +import java.io.PrintWriter; + +public class CreateJkJD extends BaseAction{ + @Override + public String execute(RequestInfo requestInfo) { + // TODO Auto-generated method stub + //创建借款的借贷方 + //0:贷方现金  + //1:借方还款(职员)  + //2:借方借款(职员) + Logger log = Logger.getLogger(JSONObject.class); + Map Hswd=new HashMap();//核算维度对照表 + Hswd.put("FFLEX4","gys");//供应商 + Hswd.put("FFLEX6","kh");//客户 + Hswd.put("FFLEX7","yg");//员工 + Hswd.put("FFLEX5","bm");//部门 + Hswd.put("FFLEX9","fyxm");//费用项目 + Hswd.put("FFLEX8","wl");//物料 + Hswd.put("FFLEX10","zc");//资产 + Hswd.put("FFLEX12","wlz");//物料组 + Hswd.put("FFLEX13","khz");//客户组 + RecordSet urlre=new RecordSet(); + String urlsql="select * from uf_urlinfo "; + + String url=""; + String username=""; + String password=""; + urlre.execute(urlsql); + while(urlre.next()){ + url=Util.null2String(urlre.getString("url")); + username=Util.null2String(urlre.getString("username")); + password=Util.null2String(urlre.getString("password")); + } + List jlist=new ArrayList();//借方 + List dlist=new ArrayList();//贷方 + String requestid=requestInfo.getRequestid();// + String mainid="";// + String zt="";//账套 + String zz="";//组织 + String zb="";//账薄 + String zzjdhl="";//做账节点汇率 + String bz="";//币种 + String fkyh="";//付款银行 + String je="";//借款金额 + String jklx="";//借款类型 + String dls="";//代理商 + String emp="";//代理商 + RecordSet re=new RecordSet(); + String jsql=""; + String dsql=""; + String sql="select * from formtable_main_24 where requestid='"+requestid+"'"; + log.error(requestid+"CreateJkJD"+sql); + re.execute(sql); + while(re.next()){ + emp=Util.null2String(re.getString("emp")).trim(); + mainid=Util.null2String(re.getString("id")).trim(); + zz=Util.null2String(re.getString("zz")).trim();//组织 + zt=Util.null2String(re.getString("zt")).trim();//账套 + zb=Util.null2String(re.getString("zb")).trim();//账薄 + + fkyh=Util.null2String(re.getString("fkyxzh")).trim();//付款银行 + je=Util.null2String(re.getString("jkje")).trim();//金额 + jklx=Util.null2String(re.getString("jklx")).trim();//借款类型 + dls=Util.null2String(re.getString("dls")).trim();//代理商 + } + //判定借方科目 + String jfkm="";//借方科目 + String jfkmDesc="";//借方科目 + String dfkm="";//贷方科目 + String dfkmDesc="";//贷方科目 + if("0".equals(jklx)){//个人 + jfkm=SpelKm(zt,zz,zb,"2"); + if("".equals(fkyh)){//现金 + dfkm=SpelKm(zt,zz,zb,"0"); + }else{//转账 + dfkm=fkyh; + } + }else{//代理商 + if("".equals(fkyh)){//现金 + dfkm=SpelKm(zt,zz,zb,"0"); + }else{//转账 + dfkm=fkyh; + } + //通过接口 获取贷方科目 + if(!"".equals(dls)){ + String result=sendGet(url+"CusGlbalance/"+dls,"",username+":"+password); + //out.print(result); + Map map=getJSONToMap(result); + jfkm=Util.null2String(map.get("FAcctNumber")); + } + } + if(!"".equals(jfkm)){ + jfkmDesc=getKmname(jfkm,zt,zz,zb); + } + if(!"".equals(dfkm)){ + dfkmDesc=getKmname(dfkm,zt,zz,zb); + } + if("0".equals(jklx)){ + dls=""; + } + jlist.add("insert into formtable_main_24_dt1(mainid,jfkmbm,jfkmmc,jfje,kh,yg)values('"+mainid+"','"+jfkm+"','"+jfkmDesc+"','"+je+"','"+dls+"','"+emp+"')"); + jlist.add("insert into formtable_main_24_dt2(mainid,dfkmbm,dfkmmc,dfje)values('"+mainid+"','"+dfkm+"','"+dfkmDesc+"','"+je+"')"); + if(jlist.size()>0){ + log.error(jlist.toString()); + boolean flag=SynInsert1(jlist); + if(!flag){ + requestInfo.getRequestManager().setMessageid("创建借贷失败"); + requestInfo.getRequestManager().setMessage("创建借贷失败");//提醒信息id + requestInfo.getRequestManager().setMessagecontent("创建借贷失败");//提醒信息内容 + + return Action.FAILURE_AND_CONTINUE; + } + } + return super.execute(requestInfo); + } + //将JSON 解析成 Map + public Map getJSONToMap(String str){ + Map map=new HashMap(); + try{ + JSONArray jsons=JSONObject.parseArray(str); + if(jsons!=null&&jsons.size()>0){ + JSONObject json=(JSONObject)jsons.get(0); + Set set=json.keySet(); + for(String demo:set){ + map.put(demo,Util.null2String(json.getString(demo))); + } + } + }catch(Exception e){ + + } + return map; + } + //取特殊科目编号 + public String SpelKm(String zt,String zz,String zb,String lx){ + Logger log = Logger.getLogger(BigDecimal.class); + RecordSet re=new RecordSet(); + String km="";//科目 + re.execute("select * from uf_k3tskm a,uf_k3tskm_dt1 b where a.id=b.mainid and zt='"+zt+"' and zz='"+zz+"' and zb='"+zb+"' and lx='"+lx+"'"); + while(re.next()){ + km=re.getString("km"); + } + return km; + } + //获取赋值核算类型 + public String getFzhx(String km,String zt,String zz,String zb,Map Hswd){ + String FDIMENSION="";//核算维度 + RecordSet re=new RecordSet(); + String sql="select b.FDIMENSION from uf_accountinfo a,uf_accountinfo_dt1 b where a.id=b.mainid and a.zt='"+zt+"' and b.FNUMBER='"+km+"' and b.forgnumber='"+zz+"' and FAcctBookNumber='"+zb+"' "; + //out.print(sql); + re.execute(sql); + while(re.next()){ + String str=Util.null2String(re.getString("FDIMENSION")).trim() ; + String[] FDIMENSIONs=str.split(","); + for(String demo:FDIMENSIONs){ + if(demo!=null&&!"".equals(demo)){ + FDIMENSION=FDIMENSION+Hswd.get(FDIMENSION)+","; + } + } + } + return FDIMENSION; + } + //insert 事务 + public boolean SynInsert1(List array){ + if(array==null||array.size()<=0){ + return false; + } + Logger log = Logger.getLogger(DataSource.class); + RecordSetTrans RecordSetTrans=new RecordSetTrans(); + RecordSetTrans.setAutoCommit(false); + boolean flag=true; + + try{ + RecordSetTrans.setAutoCommit(false); + // stmt = conn.createStatement(); + for(String str:array){ + //int index =RecordSetTrans.executeUpdate(str); + flag=RecordSetTrans.executeSql(str); + log.error("SynInsert--"+str); + if(!flag){ + //flag=false; + break; + } + } + if(!flag){//事务回滚 + RecordSetTrans.rollback(); + }else{ + RecordSetTrans.commit(); + } + }catch(Exception e){ + log.error("SynInsert--Exception "+e.getMessage()); + flag=false; + } + + return flag; + } + //获取科目名称 + public String getKmname(String km,String zt,String zz,String zb){ + String FNAME="";//核算维度 + RecordSet re=new RecordSet(); + String sql="select b.FNAME from uf_accountinfo a,uf_accountinfo_dt1 b where a.id=b.mainid and a.zt='"+zt+"' and b.FNUMBER='"+km+"' and b.forgnumber='"+zz+"' and FAcctBookNumber='"+zb+"' "; + re.execute(sql); + while(re.next()){ + FNAME=Util.null2String(re.getString("FNAME")); + } + return FNAME; + } + //获取币种的小数位 + public int getXsw(String bz){ + int xsw=0; + RecordSet re=new RecordSet(); + String sql="select * from uf_k3bz where bh='"+bz+"'"; + re.execute(sql); + while(re.next()){ + xsw=Integer.parseInt(Util.null2o(re.getString("xsw"))) ; + } + return xsw; + } + + //浮点型转换 + public static float getfloats(String demo,String demo1,int len){ + Logger log = Logger.getLogger(BigDecimal.class); + if(len==0){ + len=0; + } + String str=Util.null2String(demo); + String str1=Util.null2String(demo1); + if("".equals(str)||"".equals(str.trim())||"null".equalsIgnoreCase(str.trim())){ + return 0; + } + if("".equals(str1)||"".equals(str.trim())||"null".equalsIgnoreCase(str1.trim())){ + str1="1"; + } + float fl=0.0f; + //String str=Util.null2String(demo); + try{ + if(str.trim().length()>0){ + BigDecimal b1 = new BigDecimal(str.trim()); + BigDecimal b2 = new BigDecimal(str1.trim()); + BigDecimal b3=b1.multiply(b2); + //System.out.println(b1.setScale(2,BigDecimal.ROUND_HALF_UP)); + fl=b3.setScale(len,BigDecimal.ROUND_HALF_UP).floatValue(); + } + log.error("getfloats"+fl); + }catch(Exception e){ + log.error(demo+"getfloats异常"+e.getMessage()); + } + return fl; + } + + + //浮点型转换 + public static float getfloats1(String demo,String demo1,int len){ + Logger log = Logger.getLogger(BigDecimal.class); + if(len==0){ + len=0; + } + String str=Util.null2String(demo); + String str1=Util.null2String(demo1); + if("".equals(str)||"".equals(str.trim())||"null".equalsIgnoreCase(str.trim())){ + str="0"; + } + if("".equals(str1)||"".equals(str.trim())||"null".equalsIgnoreCase(str1.trim())){ + str1="0"; + } + float fl=0.0f; + //String str=Util.null2String(demo); + try{ + if(str.trim().length()>0){ + BigDecimal b1 = new BigDecimal(str.trim()); + BigDecimal b2 = new BigDecimal(str1.trim()); + BigDecimal b3=b1.add(b2); + //System.out.println(b1.setScale(2,BigDecimal.ROUND_HALF_UP)); + fl=b3.setScale(len,BigDecimal.ROUND_HALF_UP).floatValue(); + } + log.error("getfloats"+fl); + }catch(Exception e){ + log.error(demo+"getfloats异常"+e.getMessage()); + } + return fl; + } + public static String sendGet(String url, String param,String basis) { + String result = ""; + InputStream in = null; + try { + String urlNameString = url ; + URL realUrl = new URL(urlNameString); + URLConnection connection = realUrl.openConnection(); + String auth="JNT:JNT2019"; + String code = new sun.misc.BASE64Encoder().encode(auth.getBytes()); + connection.setRequestProperty("Authorization", "Basic " + code); + connection.connect(); + Map> map = connection.getHeaderFields(); + + + for (String key : map.keySet()) { + System.out.println(key + "--->" + map.get(key)); + } + //接收核心返回过来的数据 xml  需要解析 + in =connection.getInputStream(); + byte[] b =getBytes(in); + if(b.length>0){ + result=new String(b); + } + System.out.println(b.length); + } catch (Exception e) { + + System.out.println(e.getMessage()); + e.printStackTrace(); + }finally { + try { + if (in != null) { + in.close(); + } + } catch (Exception e2) { + System.out.println(e2.getMessage()); + e2.printStackTrace(); + } + } + //System.out.println("de"+result); + return result; + } + public static byte[] getBytes(InputStream fis){ + Logger log = Logger.getLogger(Logger.class); + byte[] buffer = null; + try { + //File file = new File(filePath); + //FileInputStream fis = new FileInputStream(file); + ByteArrayOutputStream bos = new ByteArrayOutputStream(1000); + byte[] b = new byte[10000]; + int n; + while ((n = fis.read(b)) != -1) { + bos.write(b, 0, n); + } + fis.close(); + bos.close(); + buffer = bos.toByteArray(); + } catch (FileNotFoundException e) { + e.printStackTrace(); + } catch (IOException e) { + e.printStackTrace(); + } + System.out.println("buffer--->"+buffer.length); + return buffer; + } +} diff --git a/src/main/youhong_ai_jitu_src/com/jet/action/CreateK3PayBillAction.java b/src/main/youhong_ai_jitu_src/com/jet/action/CreateK3PayBillAction.java new file mode 100644 index 0000000..238dc49 --- /dev/null +++ b/src/main/youhong_ai_jitu_src/com/jet/action/CreateK3PayBillAction.java @@ -0,0 +1,319 @@ +package com.jet.action; + +import java.text.DecimalFormat; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +import kingdee.bos.webapi.client.K3CloudApiClient; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.JSONArray; +import com.alibaba.fastjson.JSONObject; +import com.alibaba.fastjson.serializer.SerializerFeature; +import com.jet.k3.K3Connect; + +import weaver.conn.RecordSet; +import weaver.general.BaseBean; +import weaver.general.Util; +import weaver.interfaces.workflow.action.Action; +import weaver.soa.workflow.request.RequestInfo; +import selfdev.util.base.BaseUtil; +import selfdev.util.base.TimeCommonUtil; +import selfdev.util.log.LogTool; + +/** + * 付款申请流程在AP付款节点提交时将数据写入K3生成付款单 + * @author KangMD + * 2019-11-29 + */ +public class CreateK3PayBillAction extends BaseBean implements Action { + + public String execute(RequestInfo ri) { + LogTool log=new LogTool("/log/selfdev/action", false); + //获取requestid + String requestid=ri.getRequestid(); + String workflowid=ri.getWorkflowid(); + //获取用户语言 + int language=ri.getRequestManager().getUser().getLanguage(); + log.writeLog("language---------->"+language); + String workflowname=BaseUtil.getBaseInfoByParm("workflowname", "workflow_base", "id", workflowid, ""); + log.writeLog("---------------"+workflowname+"开始写入K3生成付款单-------------requestId:" + requestid); + //获取表名 + String tablename=BaseUtil.getBaseInfoByParm("tablename", "workflow_bill", "1", "1", " and id in (select formid from workflow_base where id="+workflowid+")");; + RecordSet rs=new RecordSet(); + try { + //获取当前系统日期 + String nowDate=TimeCommonUtil.obtainDate(0).substring(0,10); + String mainid="";//主键ID + String fkfs="";//付款方式 + String gysmc="";//供应商名称 + String gysmc2="";//供应商名称(无合同) + String fphm="";//发票号码 + String fksm="";//付款说明 + String zfrq="";//支付日期 + String sfyht="";//是否有合同 + double bcfkje=0;//本次付款金额 + double bcfkje2=0;//本次付款金额(无合同) + String bz="";//币种 + String zz="";//组织 + String k3yfdh="";//K3应付单号 + String fkyxzh="";//付款银行账号 + double fpcfkje=0;//分批次付款金额 + String sfpcfk="";//是否批次付款 + double pcyfkzje=0;//批次已付款总金额 + String htxx="";//相关合同 + String sql="select * from "+tablename+" where requestid="+requestid; + rs.execute(sql); + while(rs.next()){ + mainid=Util.null2String(rs.getString("id")); + fkfs=Util.null2String(rs.getString("fkfs")); + gysmc=Util.null2String(rs.getString("gysmc")); + gysmc2=Util.null2String(rs.getString("gysmc2")); + fphm=Util.null2String(rs.getString("fphm")); + fksm=Util.null2String(rs.getString("fksm")); + zfrq=Util.null2String(rs.getString("zfrq")); + sfyht=Util.null2String(rs.getString("sfyht")); + bcfkje=Double.parseDouble(Util.null2o(rs.getString("bcfkje")).replaceAll(",", "")); + bcfkje2=Double.parseDouble(Util.null2o(rs.getString("bcfkje2")).replaceAll(",", "")); + bz=Util.null2String(rs.getString("bz")); + zz=Util.null2String(rs.getString("zz")); + k3yfdh=Util.null2String(rs.getString("k3yfdh")); + fkyxzh=Util.null2String(rs.getString("fkyxzh")); + fpcfkje=Double.parseDouble(Util.null2o(rs.getString("fpcfkje")).replaceAll(",", "")); + sfpcfk=Util.null2String(rs.getString("sfpcfk")); + htxx=Util.null2String(rs.getString("htxx")); + pcyfkzje=Double.parseDouble(Util.null2o(rs.getString("pcyfkzje")).replaceAll(",", "")); + } + //没有合同 + if("1".equals(sfyht)){ + gysmc=gysmc2; + bcfkje=bcfkje2; + } + //付款方式 + if("0".equals(fkfs)){//银行 + fkfs="JSFS03_SYS"; + }else{ + fkfs="JSFS01_SYS";//现金 + } + + String msg=""; + double je_k3=0;//传入K3金额 + DecimalFormat df=new DecimalFormat( "###############0.00 ");// 16位整数位,两小数位 + //本流程还需要付款金额=流程中本次付款金额-批次已付款总金额 + double blchxfkje=bcfkje-pcyfkzje; + if("0".equals(sfpcfk)){//批次付款,则取输入的分批次付款金额 + if(fpcfkje>blchxfkje){ + msg="本流程需要付款金额"+df.format(bcfkje)+",批次已付款总金额"+df.format(pcyfkzje)+",当前批次付款金额"+df.format(fpcfkje)+",已超出剩余未付款金额"+df.format(blchxfkje); + //将错误信息更新至表单字段中 + rs.execute("update "+tablename+" set sfcgsck3yfd='1',k3jkfhxx='"+msg.replaceAll("'", "''")+"' where requestid="+requestid); + //写入K3失败则进行提醒,并阻止流程提交 + ri.getRequestManager().setMessage("111100"); + ri.getRequestManager().setMessagecontent(msg); + return "0"; + } + je_k3=fpcfkje; + }else{//全部付款 + je_k3=blchxfkje; + } + double pcyfkzje_new=pcyfkzje+je_k3;//批次已付款金额(本次写入K3之后) + + //***************************************拼接K3 Cloud付款单所需的JSON字符串***********************************************// + Map data=new HashMap(); + + Map Model=new HashMap(); + //单据类型(必填项)--------默认为采购业务付款单FKDLX01_SYS + Map FBillTypeID=new HashMap(); + FBillTypeID.put("FNUMBER", "FKDLX01_SYS"); + Model.put("FBillTypeID", FBillTypeID); + //业务日期(必填项)--------默认为当前系统日期 + Model.put("FDATE", nowDate); + //往来单位类型,默认为供应商 + Model.put("FCONTACTUNITTYPE", "BD_Supplier"); + //往来单位(必填项)-------- + Map FCONTACTUNIT=new HashMap(); + FCONTACTUNIT.put("FNUMBER", gysmc); + Model.put("FCONTACTUNIT", FCONTACTUNIT); + + //收款单位类型,默认为供应商 + Model.put("FRECTUNITTYPE", "BD_Supplier"); + //收款单位(必填项)-------- + Map FRECTUNIT=new HashMap(); + FRECTUNIT.put("FNUMBER", gysmc); + Model.put("FRECTUNIT", FRECTUNIT); + + //币别(必填项)-------- + Map FCURRENCYID=new HashMap(); + FCURRENCYID.put("FNUMBER", bz); + Model.put("FCURRENCYID", FCURRENCYID); + Model.put("FEXCHANGERATE", 1.0);//汇率 + Model.put("FSETTLERATE", 1.0);//结算汇率 + + //采购部门************** + Map FPURCHASEDEPTID=new HashMap(); + FPURCHASEDEPTID.put("FNUMBER", "BM000001"); + Model.put("FPURCHASEDEPTID", FPURCHASEDEPTID); + + //结算组织(必填项)---- + Map FSETTLEORGID=new HashMap(); + FSETTLEORGID.put("FNumber", zz); + Model.put("FSETTLEORGID", FSETTLEORGID);//结算组织(必填项)---- + //采购组织 + Model.put("FPURCHASEORGID", FSETTLEORGID); + //备注 + Model.put("FREMARK", fksm); + //期望付款日期 + Model.put("FBookingDate", nowDate); + Model.put("FDOCUMENTSTATUS", "Z");//单据状态 + Model.put("FCancelStatus", "A");//作废状态(必填项)----默认为A + //结算组织 + Model.put("FPAYORGID", FSETTLEORGID); + //结算币别 + Model.put("FSETTLECUR", FCURRENCYID); + //结算本位币 + Model.put("FSETTLEMAINBOOKID", FCURRENCYID); + + //-----------------付款单明细 start-----------------// + List> FPAYBILLENTRY=new ArrayList>(); + //定义一行明细 + Map PAYBILLENTRY=new HashMap(); + //结算方式 + Map FSETTLETYPEID=new HashMap(); + FSETTLETYPEID.put("FNUMBER", fkfs); + PAYBILLENTRY.put("FSETTLETYPEID", FSETTLETYPEID); + + //付款用途,默认为SFKYT08_SYS采购付款 + Map FPURPOSEID=new HashMap(); + FPURPOSEID.put("FNUMBER", "SFKYT08_SYS"); + PAYBILLENTRY.put("FPURPOSEID", FPURPOSEID); + + PAYBILLENTRY.put("FPAYTOTALAMOUNTFOR", je_k3);//表体-应付金额 + PAYBILLENTRY.put("FPAYAMOUNTFOR_E", je_k3);//付款金额 + PAYBILLENTRY.put("FSETTLEPAYAMOUNTFOR", je_k3);//折后金额 + PAYBILLENTRY.put("FREALPAYAMOUNTFOR_D", je_k3);//表体-实付金额 + //我方银行账号 + Map FACCOUNTID=new HashMap(); + FACCOUNTID.put("FNUMBER", fkyxzh); + PAYBILLENTRY.put("FACCOUNTID", FACCOUNTID); + + PAYBILLENTRY.put("FPAYAMOUNT_E", je_k3);//付款金额本位币 + PAYBILLENTRY.put("FPOSTDATE", nowDate);//登账日期 + PAYBILLENTRY.put("FRuZhangType", "1");//入账类型 + PAYBILLENTRY.put("FPayType", "A");//支付类型 + + //将MAP添加至List中 + FPAYBILLENTRY.add(PAYBILLENTRY); + + Model.put("FPAYBILLENTRY", FPAYBILLENTRY);// + //-----------------付款单明细 end-----------------// + + + //-----------------付款单源单明细 start-----------------// + List> FPAYBILLSRCENTRY=new ArrayList>(); + //定义一行明细 + Map PAYBILLSRCENTRY=new HashMap(); + //源单类型 + PAYBILLSRCENTRY.put("FSOURCETYPE", "AP_Payable"); + //源单编号,取K3应付单号 + PAYBILLSRCENTRY.put("FSRCBILLNO", k3yfdh); + //本次付款金额 + PAYBILLSRCENTRY.put("FREALPAYAMOUNT_S", je_k3); + //应付金额 + PAYBILLSRCENTRY.put("FAFTTAXTOTALAMOUNT", bcfkje); + //计划付款金额 + PAYBILLSRCENTRY.put("FPLANPAYAMOUNT", bcfkje); + //源单币别 + PAYBILLSRCENTRY.put("FSRCCURRENCYID", FCURRENCYID); + //到期日 + PAYBILLSRCENTRY.put("FEXPIRY", nowDate); + + //将MAP添加至List中 + FPAYBILLSRCENTRY.add(PAYBILLSRCENTRY); + Model.put("FPAYBILLSRCENTRY", FPAYBILLSRCENTRY);// + + //-----------------付款单源单明细 end-----------------// + + data.put("Model", Model); + + //将MAP转JSON,fastjson默认开启引用检测将相同的对象写成引用的形式,所以必须加上SerializerFeature.DisableCircularReferenceDetect,否则转换的字符串会出现$ref + String jsonStr = JSON.toJSONString(data, SerializerFeature.DisableCircularReferenceDetect); + log.writeLog("调用付款单保存接口传入数据jsonStr---------->"+jsonStr); + //连接K3 + K3CloudApiClient client =K3Connect.connect(); + if(client!=null){ + //调用付款单保存接口 + String sResult = client.excuteOperation("AP_PAYBILL", "save", jsonStr); + log.writeLog("调用付款单保存接口返回数据sResult---------->"+sResult); + //解析K3返回的JSO字符串 + JSONObject jsonObject = JSONObject.parseObject(sResult); + JSONObject ResponseStatus=jsonObject.getJSONObject("Result").getJSONObject("ResponseStatus"); + //是否成功写入K3 + String IsSuccess=ResponseStatus.get("IsSuccess").toString(); + log.writeLog("是否成功写入K3结果IsSuccess---------->"+IsSuccess); + //成功写入K3 + if("true".equals(IsSuccess)){ + JSONArray SuccessJSONArray=ResponseStatus.getJSONArray("SuccessEntitys"); + String Id="";//单据ID + String Number="";//单据编号 + for(int p=0;p"+Id+",Number------>"+Number); + //将付款单号更新至表单字段中 + rs.execute("update "+tablename+" set sfcgsck3yfd='0',k3fkdh='"+Number+"',fpcfkje='',k3jkfhxx='',pcyfkzje=TO_CHAR("+pcyfkzje_new+",'FM999,999,999,999,999,999,990.00') where requestid="+requestid); + //将付款信息插入至付款明细中 + rs.execute("insert into "+tablename+"_dt1 (mainid,fkyxzh,fkrq,fkje,k3fkdh) values('"+mainid+"','"+fkyxzh+"','"+nowDate+"',TO_CHAR("+je_k3+",'FM999,999,999,999,999,999,990.00'),'"+Number+"')"); + + //存在合同并且是(不需要分批次付款或者分批次的最后一次付款),则将付款信息更新至至建模合同台账中 + if("0".equals(sfyht)&&bcfkje==pcyfkzje+je_k3){ + //更新至建模的批次明细中 + sql="update uf_httz_dt1 a set (yfkje,fkzt)=(select TO_CHAR(to_number(replace(nvl(a.yfkje,0),',',''))+to_number(replace(nvl(b.bcfkje,0),',','')),'FM999,999,999,999,999,999,990.00'),(case when to_number(replace(nvl(a.yfkje,0),',',''))+to_number(replace(nvl(b.bcfkje,0),',',''))=to_number(replace(nvl(a.fkje,0),',','')) then 0 else 2 end) from "+tablename+"_dt5 b where a.id=b.fkpc and b.mainid='"+mainid+"') where a.mainid='"+htxx+"'"; + log.writeLog("流程中支付金额更新至合同建模明细中的金额SQL---------->"+sql); + rs.execute(sql); + //更新至建模的主表中 + sql="update uf_httz a set yfkje=TO_CHAR(to_number(replace(nvl(a.yfkje,0),',',''))+"+je_k3+",'FM999,999,999,999,999,999,990.00') where id='"+htxx+"'"; + log.writeLog("流程中支付金额更新至合同建模主表中的金额SQL---------->"+sql); + rs.execute(sql); + } + }else{ + JSONArray ErrorsJSONArray=ResponseStatus.getJSONArray("Errors"); + for(int p=0;p"+language); + String workflowname=BaseUtil.getBaseInfoByParm("workflowname", "workflow_base", "id", workflowid, ""); + log.writeLog("---------------"+workflowname+"开始写入K3生成应付单-------------requestId:" + requestid); + //获取表名 + String tablename=BaseUtil.getBaseInfoByParm("tablename", "workflow_bill", "1", "1", " and id in (select formid from workflow_base where id="+workflowid+")");; + RecordSet rs=new RecordSet(); + try { + //获取当前系统日期 + String nowDate=TimeCommonUtil.obtainDate(0).substring(0,10); + String fkfs="";//付款方式 + String fygsbm="";//财务K3所属部门 + String gysmc="";//供应商名称 + String gysmc2="";//供应商名称(无合同) + String fphm="";//发票号码 + String fksm="";//付款说明 + String zfrq="";//支付日期 + String sfyht="";//是否有合同 + String bcfkje="";//本次付款金额 + String bcfkje2="";//本次付款金额(无合同) + String sqje="";//税前金额 + String zzs="";//增值税 + //String dks="";//代扣税 + String bz="";//币种 + String zz="";//组织 + String sql="select * from "+tablename+" where requestid="+requestid; + rs.execute(sql); + while(rs.next()){ + fkfs=Util.null2String(rs.getString("fkfs")); + gysmc=Util.null2String(rs.getString("gysmc")); + gysmc2=Util.null2String(rs.getString("gysmc2")); + fphm=Util.null2String(rs.getString("fphm")); + fksm=Util.null2String(rs.getString("fksm")).replaceAll(" ", " "); + zfrq=Util.null2String(rs.getString("zfrq")); + sfyht=Util.null2String(rs.getString("sfyht")); + bcfkje=Util.null2o(rs.getString("bcfkje")).replace(",", ""); + bcfkje2=Util.null2o (rs.getString("bcfkje2")).replace(",", ""); + bz=Util.null2String(rs.getString("bz")); + zz=Util.null2String(rs.getString("zz")); + fygsbm=Util.null2String(rs.getString("fygsbm")); + sqje=Util.null2o(rs.getString("sqje")).replace(",", ""); + zzs=Util.null2o(rs.getString("zzs")).replace(",", ""); + //dks=Util.null2o(rs.getString("dks")).replace(",", ""); + } + //K3中表头备注字段最多只能存储255位,将付款说明进行截取 + if(fksm.length()>255){ + fksm=fksm.substring(0,255); + } + + //没有合同 + if("1".equals(sfyht)){ + gysmc=gysmc2; + bcfkje=bcfkje2; + } + //付款方式 + if("0".equals(fkfs)){//银行 + fkfs="JSFS03_SYS"; + }else{ + fkfs="JSFS01_SYS";//现金 + } + + //含税单价=税前金额+增值税 + String hsdj=new BigDecimal(sqje).add(new BigDecimal(zzs)).setScale(2, BigDecimal.ROUND_HALF_UP).toString(); + + //***************************************拼接K3 Cloud应付单所需的JSON字符串***********************************************// + Map data=new LinkedHashMap(); + + Map Model=new LinkedHashMap(); + //单据类型(必填项)--------默认为标准应付单YFD01_SYS + Map FBillTypeID=new LinkedHashMap(); + FBillTypeID.put("FNUMBER", "YFD01_SYS"); + Model.put("FBillTypeID", FBillTypeID); + + //是否期初单据 + Model.put("FISINIT", false); + //业务日期(必填项)--------默认为当前系统日期 + Model.put("FDATE", nowDate); + //到期日(必填项)-------- + Model.put("FENDDATE_H", nowDate); + //单据状态,默认为创建 Z + Model.put("FDOCUMENTSTATUS", "Z"); + + //供应商(必填项)-------- + Map FSUPPLIERID=new LinkedHashMap(); + FSUPPLIERID.put("FNUMBER", gysmc); + Model.put("FSUPPLIERID", FSUPPLIERID); + + //币别(必填项)-------- + Map FCURRENCYID=new LinkedHashMap(); + FCURRENCYID.put("FNUMBER", bz); + Model.put("FCURRENCYID", FCURRENCYID); + + Model.put("FISPRICEEXCLUDETAX", true);//价外税 + Model.put("FBUSINESSTYPE", "CG");//业务类型(必填项)----默认为CG + Model.put("FISTAX", true);//按含税单价录入---- + + //结算组织(必填项)---- + Map FSETTLEORGID=new LinkedHashMap(); + FSETTLEORGID.put("FNumber", zz); + Model.put("FSETTLEORGID", FSETTLEORGID);//结算组织(必填项)---- + + //采购部门---- + Map FPURCHASEDEPTID=new LinkedHashMap(); + FPURCHASEDEPTID.put("FNUMBER", fygsbm); + Model.put("FPURCHASEDEPTID", FPURCHASEDEPTID); + + //付款组织(必填项)---- + Map FPAYORGID=new LinkedHashMap(); + FPAYORGID.put("FNUMBER", zz); + Model.put("FPAYORGID", FPAYORGID); + + //作废状态(必填项)----默认为A + Model.put("FCancelStatus", "A"); + //Invoice No(必填项)---- + Model.put("F_RTA_InvoiceNo", fphm); + //business type(必填项)----默认为服务类S + Model.put("F_RTA_BusinessType", "S"); + //备注 + Model.put("FAP_Remark", fksm); + + //PPH By Company + Model.put("F_RTA_PPHByComp", false); + + + //-----------------表头供应商 start-----------------// + Map FsubHeadSuppiler=new LinkedHashMap(); + FsubHeadSuppiler.put("FORDERID", FSUPPLIERID);//订货方 + FsubHeadSuppiler.put("FTRANSFERID", FSUPPLIERID);//供货方 + FsubHeadSuppiler.put("FChargeId", FSUPPLIERID);//收款方 + Model.put("FsubHeadSuppiler", FsubHeadSuppiler);//将供应商信息加入至Map中 + //-----------------表头供应商 end-----------------// + + //-----------------表头财务 start-----------------// + Map FsubHeadFinc=new LinkedHashMap(); + FsubHeadFinc.put("FACCNTTIMEJUDGETIME", zfrq);//到期日计算日期(必填项)---- + //结算方式 + Map FSettleTypeID=new LinkedHashMap(); + FSettleTypeID.put("FNUMBER", fkfs); + FsubHeadFinc.put("FSettleTypeID", FSettleTypeID); + //本位币 + FsubHeadFinc.put("FMAINBOOKSTDCURRID", FCURRENCYID); + Model.put("FsubHeadFinc", FsubHeadFinc);// + //-----------------表头财务 end-----------------// + + //-----------------明细 start-----------------// + List> FEntityDetail=new ArrayList>(); + //定义一行明细 + Map EntityDetail=new LinkedHashMap(); + //物料编码 + Map FMATERIALID=new LinkedHashMap(); + FMATERIALID.put("FNUMBER", "100013"); + EntityDetail.put("FMATERIALID", FMATERIALID); + //K3中明细备注字段最多只能存储50位,将付款说明进行截取 + if(fksm.length()>50){ + fksm=fksm.substring(0,50); + } + EntityDetail.put("F_RTA_EntryRemarks", fksm);//备 注 + //计价单位 + Map FPRICEUNITID=new LinkedHashMap(); + FPRICEUNITID.put("FNUMBER", "Pcs"); + EntityDetail.put("FPRICEUNITID", FPRICEUNITID); + + EntityDetail.put("FPrice", sqje);//单价 + EntityDetail.put("FPriceQty", 1.0);//计价数量 + EntityDetail.put("FTaxPrice", hsdj);//含税单价=税前单价+增值税 + //EntityDetail.put("F_RTA_PPHAmount", dks);//代扣税 + EntityDetail.put("FPriceWithTax", bcfkje);//含税净价 + //PPN Type + Map F_RTA_VATType_d=new LinkedHashMap(); + F_RTA_VATType_d.put("FNUMBER", "000"); + EntityDetail.put("F_RTA_VATType_d", F_RTA_VATType_d); + + EntityDetail.put("FNoTaxAmountFor_D", sqje);//不含税金额 + EntityDetail.put("FTAXAMOUNTFOR_D", 0);//税额 + EntityDetail.put("FALLAMOUNTFOR_D", bcfkje);//价税合计bcfkje + EntityDetail.put("F_RTA_FakturPajakNo_d", "-");//Faktur Pajak No + EntityDetail.put("F_RTA_SUPPLIER_D", FSUPPLIERID);//表体供应商(用于校验税票号唯一) + //将MAP添加至List中 + FEntityDetail.add(EntityDetail); + Model.put("FEntityDetail", FEntityDetail);// + //-----------------明细 end-----------------// + + //-----------------付款计划 start-----------------// + List> FEntityPlan=new ArrayList>(); + Map FPlan=new LinkedHashMap(); + FPlan.put("FENDDATE", zfrq);//表头计划 - 到期日 + FPlan.put("FPAYAMOUNTFOR", bcfkje);//应付金额 + FPlan.put("FPAYRATE", 100);//应付比例(%) + FEntityPlan.add(FPlan); + Model.put("FEntityPlan", FEntityPlan);// + //-----------------付款计划 end-----------------// + data.put("Model", Model); + + + //将MAP转JSON,fastjson默认开启引用检测将相同的对象写成引用的形式,所以必须加上SerializerFeature.DisableCircularReferenceDetect,否则转换的字符串会出现$ref + String jsonStr = JSON.toJSONString(data, SerializerFeature.DisableCircularReferenceDetect); + log.writeLog("调用应付单保存接口传入数据jsonStr---------->"+jsonStr); + //连接K3 + K3CloudApiClient client =K3Connect.connect(); + if(client!=null){ + //调用应付单保存接口 + String sResult = client.excuteOperation("AP_Payable", "save", jsonStr); + log.writeLog("调用应付单保存接口返回数据sResult---------->"+sResult); + //解析K3返回的JSO字符串 + JSONObject jsonObject = JSONObject.parseObject(sResult); + JSONObject ResponseStatus=jsonObject.getJSONObject("Result").getJSONObject("ResponseStatus"); + //是否成功写入K3 + String IsSuccess=ResponseStatus.get("IsSuccess").toString(); + log.writeLog("是否成功写入K3结果IsSuccess---------->"+IsSuccess); + //成功写入K3 + if("true".equals(IsSuccess)){ + JSONArray SuccessJSONArray=ResponseStatus.getJSONArray("SuccessEntitys"); + String Id="";//单据ID + String Number="";//单据编号 + for(int p=0;p"+Id+",Number------>"+Number); + //将应付单号更新至表单字段中 + rs.execute("update "+tablename+" set sfcgsck3yfd='0',sfpcfk='1',fpcfkje='"+bcfkje+"',pcyfkzje='0',gysmc='"+gysmc+"',bcfkje='"+bcfkje+"',k3yfdh='"+Number+"',k3jkfhxx='' where requestid="+requestid); + }else{ + JSONArray ErrorsJSONArray=ResponseStatus.getJSONArray("Errors"); + String msg=""; + for(int p=0;p"+language); + String workflowname=BaseUtil.getBaseInfoByParm("workflowname", "workflow_base", "id", workflowid, ""); + log.writeLog("---------------"+workflowname+"开始写入K3生成应付单或者其他应付单-------------requestId:" + requestid); + //获取表名 + String tablename=BaseUtil.getBaseInfoByParm("tablename", "workflow_bill", "1", "1", " and id in (select formid from workflow_base where id="+workflowid+")");; + RecordSet rs=new RecordSet(); + try { + //获取当前系统日期 + String nowDate=TimeCommonUtil.obtainDate(0).substring(0,10); + String zffs="";//付款方式 + String fygsbm="";//财务K3所属部门 + String jklx="";//借款类型 + String fphm="OA-"+requestid;//发票号码 + String jkyy="";//借款原因 + String dls="";//代理商 + String jkrq="";//期望支付日期 + String jkje="";//借款金额 + String bz="";//币种 + String zz="";//组织 + String jkrdyk3ygbh="";//借款人对应K3员工编号 + String sql="select * from "+tablename+" where requestid="+requestid; + rs.execute(sql); + while(rs.next()){ + zffs=Util.null2String(rs.getString("zffs")); + jklx=Util.null2String(rs.getString("jklx")); + fygsbm=Util.null2String(rs.getString("fygsbm")); + jkyy=Util.null2String(rs.getString("jkyy")).replaceAll(" ", " "); + dls=Util.null2String(rs.getString("dls")); + jkrq=Util.null2String(rs.getString("jkrq")); + jkje=Util.null2String(rs.getString("jkje")); + bz=Util.null2String(rs.getString("bz")); + zz=Util.null2String(rs.getString("zz")); + jkrdyk3ygbh=Util.null2String(rs.getString("jkrdyk3ygbh")); + } + + //K3中表头备注字段最多只能存储255位,将付款说明进行截取 + if(jkyy.length()>255){ + jkyy=jkyy.substring(0,255); + } + + //付款方式 + if("0".equals(zffs)){//银行 + zffs="JSFS03_SYS"; + }else{ + zffs="JSFS01_SYS";//现金 + } + //K3接口名 + String interfaceName="AP_Payable"; + //K3接口描述 + String interfaceDesc="应付单"; + //***************************************拼接K3 Cloud (其他)应付单所需的JSON字符串***********************************************// + Map data=new HashMap(); + Map Model=new HashMap(); + + if("0".equals(jklx)){//员工借款,生成K3的其他应付单 + interfaceName="AP_OtherPayable"; + interfaceDesc="其他应付单"; + //单据类型(必填项)--------默认为其他应付单QTYFD01_SYS + Map FBillTypeID=new HashMap(); + FBillTypeID.put("FNUMBER", "QTYFD01_SYS"); + Model.put("FBillTypeID", FBillTypeID); + + Model.put("FDATE", nowDate);//业务日期(必填项)--------默认为申请日期 + Model.put("FENDDATE_H", nowDate);//到期日(必填项)-------- + Model.put("FCONTACTUNITTYPE", "BD_Empinfo");//往来单位类型,默认为员工BD_Empinfo + + //往来单位编码(即员工编码) + Map FCONTACTUNIT=new HashMap(); + FCONTACTUNIT.put("FNUMBER", jkrdyk3ygbh); + Model.put("FCONTACTUNIT", FCONTACTUNIT); + + //币别(必填项)-------- + Map FCURRENCYID=new HashMap(); + FCURRENCYID.put("FNUMBER", bz); + Model.put("FCURRENCYID", FCURRENCYID); + + Model.put("FTOTALAMOUNTFOR_H", jkje);//总金额 + Model.put("FNOTSETTLEAMOUNTFOR", jkje);//未结算金额 + + //申请部门 + Map FDEPARTMENTID=new HashMap(); + FDEPARTMENTID.put("FNumber", fygsbm); + Model.put("FDEPARTMENTID", FDEPARTMENTID); + + //付款组织(必填项)---- + Map FPAYORGID=new HashMap(); + FPAYORGID.put("FNUMBER", zz); + Model.put("FPAYORGID", FPAYORGID); + //结算组织 + Model.put("FSETTLEORGID", FPAYORGID); + //采购组织 + Model.put("FPURCHASEORGID", FPAYORGID); + //采购部门 + Model.put("FPURCHASEDEPTID", FDEPARTMENTID); + //本位币 + Model.put("FMAINBOOKSTDCURRID", FCURRENCYID); + + //到期日计算日期(期望支付日期) + Model.put("FACCNTTIMEJUDGETIME", jkrq); + //作废状态 + Model.put("FCancelStatus", "A"); + //备注 + Model.put("FRemarks", jkyy); + + //-----------------明细 start-----------------// + List> FEntity=new ArrayList>(); + //定义一行明细 + Map EntityDetail=new HashMap(); + //费用项目编码,默认为CI074 + Map FCOSTID=new HashMap(); + FCOSTID.put("FNUMBER", "CI074"); + EntityDetail.put("FCOSTID", FCOSTID); + //费用归属部门 + EntityDetail.put("FCOSTDEPARTMENTID", FDEPARTMENTID); + //不含税金额 + EntityDetail.put("FNOTAXAMOUNTFOR", jkje); + //总金额 + EntityDetail.put("FTOTALAMOUNTFOR", jkje); + //未结算金额 + EntityDetail.put("FNOTSETTLEAMOUNTFOR_D", jkje); + //不含税金额本位币 + EntityDetail.put("FNOTAXAMOUNT_D", jkje); + //发票类型 + //EntityDetail.put("FINVOICETYPE", ""); + //K3中明细备注字段最多只能存储50位,将借款原因进行截取 + if(jkyy.length()>50){ + jkyy=jkyy.substring(0,50); + } + //备注 + EntityDetail.put("FCOMMENT", jkyy); + //将MAP添加至List中 + FEntity.add(EntityDetail); + Model.put("FEntity", FEntity);// + //-----------------明细 end-----------------// + }else{//代理商借款,生成K3的应付单 + + //单据类型(必填项)--------默认为标准应付单YFD01_SYS + Map FBillTypeID=new HashMap(); + FBillTypeID.put("FNUMBER", "YFD01_SYS"); + Model.put("FBillTypeID", FBillTypeID); + + //是否期初单据 + Model.put("FISINIT", false); + //业务日期(必填项)--------默认为当前系统日期 + Model.put("FDATE", nowDate); + //到期日(必填项)-------- + Model.put("FENDDATE_H", nowDate); + //单据状态,默认为创建 Z + Model.put("FDOCUMENTSTATUS", "Z"); + + //供应商(必填项)-------- + Map FSUPPLIERID=new HashMap(); + FSUPPLIERID.put("FNUMBER", dls); + Model.put("FSUPPLIERID", FSUPPLIERID); + + //币别(必填项)-------- + Map FCURRENCYID=new HashMap(); + FCURRENCYID.put("FNUMBER", bz); + Model.put("FCURRENCYID", FCURRENCYID); + + Model.put("FISPRICEEXCLUDETAX", true);//价外税 + Model.put("FBUSINESSTYPE", "CG");//业务类型(必填项)----默认为CG + Model.put("FISTAX", true);//按含税单价录入---- + + //结算组织(必填项)---- + Map FSETTLEORGID=new HashMap(); + FSETTLEORGID.put("FNumber", zz); + Model.put("FSETTLEORGID", FSETTLEORGID);//结算组织(必填项)---- + + //采购部门---- + Map FPURCHASEDEPTID=new HashMap(); + FPURCHASEDEPTID.put("FNUMBER", fygsbm); + Model.put("FPURCHASEDEPTID", FPURCHASEDEPTID); + + //付款组织(必填项)---- + Map FPAYORGID=new HashMap(); + FPAYORGID.put("FNUMBER", zz); + Model.put("FPAYORGID", FPAYORGID); + + //作废状态(必填项)----默认为A + Model.put("FCancelStatus", "A"); + //Invoice No(必填项)---- + Model.put("F_RTA_InvoiceNo", fphm); + //business type(必填项)----默认为服务类S + Model.put("F_RTA_BusinessType", "S"); + //备注 + Model.put("FAP_Remark", jkyy); + + //-----------------表头供应商 start-----------------// + Map FsubHeadSuppiler=new HashMap(); + FsubHeadSuppiler.put("FORDERID", FSUPPLIERID);//订货方 + FsubHeadSuppiler.put("FTRANSFERID", FSUPPLIERID);//供货方 + FsubHeadSuppiler.put("FChargeId", FSUPPLIERID);//收款方 + Model.put("FsubHeadSuppiler", FsubHeadSuppiler);//将供应商信息加入至Map中 + //-----------------表头供应商 end-----------------// + + //-----------------表头财务 start-----------------// + Map FsubHeadFinc=new HashMap(); + FsubHeadFinc.put("FACCNTTIMEJUDGETIME", jkrq);//到期日计算日期(必填项)---- + //结算方式 + Map FSettleTypeID=new HashMap(); + FSettleTypeID.put("FNUMBER",zffs); + FsubHeadFinc.put("FSettleTypeID", FSettleTypeID); + //本位币 + FsubHeadFinc.put("FMAINBOOKSTDCURRID", FCURRENCYID); + Model.put("FsubHeadFinc", FsubHeadFinc);// + //-----------------表头财务 end-----------------// + + //-----------------明细 start-----------------// + List> FEntityDetail=new ArrayList>(); + //定义一行明细 + Map EntityDetail=new HashMap(); + //物料编码 + Map FMATERIALID=new HashMap(); + FMATERIALID.put("FNUMBER", "100013"); + EntityDetail.put("FMATERIALID", FMATERIALID); + + //K3中明细备注字段最多只能存储50位,将借款原因进行截取 + if(jkyy.length()>50){ + jkyy=jkyy.substring(0,50); + } + EntityDetail.put("F_RTA_EntryRemarks", jkyy);//备 注 + //计价单位 + Map FPRICEUNITID=new HashMap(); + FPRICEUNITID.put("FNUMBER", "Pcs"); + EntityDetail.put("FPRICEUNITID", FPRICEUNITID); + + EntityDetail.put("FPrice", jkje);//单价 + EntityDetail.put("FPriceQty", 1.0);//计价数量 + EntityDetail.put("FTaxPrice", jkje);//含税单价 + EntityDetail.put("FPriceWithTax", jkje);//含税净价 + //PPN Type + Map F_RTA_VATType_d=new HashMap(); + F_RTA_VATType_d.put("FNUMBER", "000"); + EntityDetail.put("F_RTA_VATType_d", F_RTA_VATType_d); + + EntityDetail.put("FNoTaxAmountFor_D", jkje);//不含税金额 + EntityDetail.put("FTAXAMOUNTFOR_D", 0);//税额 + EntityDetail.put("FALLAMOUNTFOR_D", jkje);//价税合计 + EntityDetail.put("F_RTA_FakturPajakNo_d", "-");//Faktur Pajak No + EntityDetail.put("F_RTA_SUPPLIER_D", FSUPPLIERID);//表体供应商(用于校验税票号唯一) + //将MAP添加至List中 + FEntityDetail.add(EntityDetail); + Model.put("FEntityDetail", FEntityDetail);// + //-----------------明细 end-----------------// + + //-----------------付款计划 start-----------------// + List> FEntityPlan=new ArrayList>(); + Map FPlan=new HashMap(); + FPlan.put("FENDDATE", jkrq);//表头计划 - 到期日 + FPlan.put("FPAYAMOUNTFOR", jkje);//应付金额 + FPlan.put("FPAYRATE", 100);//应付比例(%) + FEntityPlan.add(FPlan); + Model.put("FEntityPlan", FEntityPlan);// + //-----------------付款计划 end-----------------// + } + + data.put("Model", Model); + + //将MAP转JSON,fastjson默认开启引用检测将相同的对象写成引用的形式,所以必须加上SerializerFeature.DisableCircularReferenceDetect,否则转换的字符串会出现$ref + String jsonStr = JSON.toJSONString(data, SerializerFeature.DisableCircularReferenceDetect); + log.writeLog("调用"+interfaceDesc+"保存接口传入数据jsonStr---------->"+jsonStr); + //连接K3 + K3CloudApiClient client =K3Connect.connect(); + if(client!=null){ + //调用应付单保存接口 + String sResult = client.excuteOperation(interfaceName, "save", jsonStr); + log.writeLog("调用"+interfaceDesc+"保存接口返回数据sResult---------->"+sResult); + //解析K3返回的JSO字符串 + JSONObject jsonObject = JSONObject.parseObject(sResult); + JSONObject ResponseStatus=jsonObject.getJSONObject("Result").getJSONObject("ResponseStatus"); + //是否成功写入K3 + String IsSuccess=ResponseStatus.get("IsSuccess").toString(); + log.writeLog("是否成功写入K3结果IsSuccess---------->"+IsSuccess); + //成功写入K3 + if("true".equals(IsSuccess)){ + JSONArray SuccessJSONArray=ResponseStatus.getJSONArray("SuccessEntitys"); + String Id="";//单据ID + String Number="";//单据编号 + for(int p=0;p"+Id+",Number------>"+Number); + //将应付单号更新至表单字段中 + rs.execute("update "+tablename+" set sfcgsck3yfd='0',k3yfdh='"+Number+"',k3jkfhxx='' where requestid="+requestid); + }else{ + JSONArray ErrorsJSONArray=ResponseStatus.getJSONArray("Errors"); + String msg=""; + for(int p=0;p"+language); + String workflowname=BaseUtil.getBaseInfoByParm("workflowname", "workflow_base", "id", workflowid, ""); + log.writeLog("---------------"+workflowname+"开始写入K3生成应付单-------------requestId:" + requestid); + //获取表名 + String tablename=BaseUtil.getBaseInfoByParm("tablename", "workflow_bill", "1", "1", " and id in (select formid from workflow_base where id="+workflowid+")");; + RecordSet rs=new RecordSet(); + try { + //获取当前系统日期 + String nowDate=TimeCommonUtil.obtainDate(0).substring(0,10); + String mainid="";//主键ID + String bxfs="";//报销方式 + String fygsbm="";//财务K3所属部门 + String gysmc="";//供应商名称 + //String fphm="";//发票号码 + String bxms="";//报销说明 + String zfrq="";//支付日期 + String bxzje="";//报销总金额 + String bz="";//币种 + String zz="";//组织 + String sql="select * from "+tablename+" where requestid="+requestid; + rs.execute(sql); + while(rs.next()){ + mainid=Util.null2String(rs.getString("id")); + bxfs=Util.null2String(rs.getString("bxfs")); + fygsbm=Util.null2String(rs.getString("fygsbm")); + zfrq=Util.null2String(rs.getString("zfrq")); + bxzje=Util.null2String(rs.getString("bxzje")); + bz=Util.null2String(rs.getString("bz")); + zz=Util.null2String(rs.getString("zz")); + bxms=Util.null2String(rs.getString("bxms")).replaceAll(" ", " "); + } + + //K3中表头备注字段最多只能存储255位,将付款说明进行截取 + if(bxms.length()>255){ + bxms=bxms.substring(0,255); + } + + //付款方式 + if("0".equals(bxfs)){//银行 + bxfs="JSFS03_SYS"; + }else{ + bxfs="JSFS01_SYS";//现金 + } + //根据K3部门查询K3供应商 + gysmc=BaseUtil.getBaseInfoByParm("k3gys", "uf_bm_gys_K3", "k3bm", fygsbm, ""); + + log.writeLog("gysmc-------->"+gysmc); + if("".equals(gysmc)){ + String error_msg="当前K3部门编码【"+fygsbm+"】未维护对应的供应商,请先维护对应关系!"; + if(language==0||language==7){//简体 + + }else if(language==8){//英语 + error_msg="当前K3部门编码【"+fygsbm+"】未维护对应的供应商,请先维护对应关系!"; + }else if(language==9){//繁体 + error_msg="当前K3部门编码【"+fygsbm+"】未维护对应的供应商,请先维护对应关系!"; + }else if(language==22){//印尼语 + error_msg="当前K3部门编码【"+fygsbm+"】未维护对应的供应商,请先维护对应关系!"; + } + ri.getRequestManager().setMessage("111100"); + ri.getRequestManager().setMessagecontent(error_msg); + return "0"; + } + + + //***************************************拼接K3 Cloud应付单所需的JSON字符串***********************************************// + Map data=new HashMap(); + + Map Model=new HashMap(); + //单据类型(必填项)--------默认为标准应付单YFD01_SYS + Map FBillTypeID=new HashMap(); + FBillTypeID.put("FNUMBER", "YFD01_SYS"); + Model.put("FBillTypeID", FBillTypeID); + + //是否期初单据 + Model.put("FISINIT", false); + //业务日期(必填项)--------默认为当前系统日期 + Model.put("FDATE", nowDate); + //到期日(必填项)-------- + Model.put("FENDDATE_H", nowDate); + //单据状态,默认为创建 Z + Model.put("FDOCUMENTSTATUS", "Z"); + + //供应商(必填项)-------- + Map FSUPPLIERID=new HashMap(); + FSUPPLIERID.put("FNUMBER", gysmc); + Model.put("FSUPPLIERID", FSUPPLIERID); + + //币别(必填项)-------- + Map FCURRENCYID=new HashMap(); + FCURRENCYID.put("FNUMBER", bz); + Model.put("FCURRENCYID", FCURRENCYID); + + Model.put("FISPRICEEXCLUDETAX", true);//价外税 + Model.put("FBUSINESSTYPE", "CG");//业务类型(必填项)----默认为CG + Model.put("FISTAX", true);//按含税单价录入---- + + //结算组织(必填项)---- + Map FSETTLEORGID=new HashMap(); + FSETTLEORGID.put("FNumber", zz); + Model.put("FSETTLEORGID", FSETTLEORGID);//结算组织(必填项)---- + + //采购部门---- + Map FPURCHASEDEPTID=new HashMap(); + FPURCHASEDEPTID.put("FNUMBER", fygsbm); + Model.put("FPURCHASEDEPTID", FPURCHASEDEPTID); + + //付款组织(必填项)---- + Map FPAYORGID=new HashMap(); + FPAYORGID.put("FNUMBER", zz); + Model.put("FPAYORGID", FPAYORGID); + + //作废状态(必填项)----默认为A + Model.put("FCancelStatus", "A"); + //Invoice No(必填项)----//requestid + Model.put("F_RTA_InvoiceNo", "OA-"+requestid); + //business type(必填项)----默认为服务类S + Model.put("F_RTA_BusinessType", "S"); + //备注 + Model.put("FAP_Remark", bxms); + + //-----------------表头供应商 start-----------------// + Map FsubHeadSuppiler=new HashMap(); + FsubHeadSuppiler.put("FORDERID", FSUPPLIERID);//订货方 + FsubHeadSuppiler.put("FTRANSFERID", FSUPPLIERID);//供货方 + FsubHeadSuppiler.put("FChargeId", FSUPPLIERID);//收款方 + Model.put("FsubHeadSuppiler", FsubHeadSuppiler);//将供应商信息加入至Map中 + //-----------------表头供应商 end-----------------// + + //-----------------表头财务 start-----------------// + Map FsubHeadFinc=new HashMap(); + FsubHeadFinc.put("FACCNTTIMEJUDGETIME", zfrq);//到期日计算日期(必填项)---- + //结算方式 + Map FSettleTypeID=new HashMap(); + FSettleTypeID.put("FNUMBER", bxfs); + FsubHeadFinc.put("FSettleTypeID", FSettleTypeID); + //本位币 + FsubHeadFinc.put("FMAINBOOKSTDCURRID", FCURRENCYID); + Model.put("FsubHeadFinc", FsubHeadFinc);// + //-----------------表头财务 end-----------------// + + + + //-----------------明细 start-----------------// + sql="select * from "+tablename+"_dt8 where mainid="+mainid; + rs.execute(sql); + List> FEntityDetail=new ArrayList>(); + while(rs.next()){ + String je=Util.null2String(rs.getString("je")); + //定义一行明细 + Map EntityDetail=new HashMap(); + //物料编码 + Map FMATERIALID=new HashMap(); + FMATERIALID.put("FNUMBER", Util.null2String(rs.getString("bxlx1"))); + EntityDetail.put("FMATERIALID", FMATERIALID); + + String beizhu=Util.null2String(rs.getString("bz")).replaceAll(" ", " "); + //K3中明细备注字段最多只能存储50位,将付款说明进行截取 + if(beizhu.length()>50){ + beizhu=beizhu.substring(0,50); + } + + EntityDetail.put("F_RTA_EntryRemarks", beizhu);//备 注 + //计价单位 + Map FPRICEUNITID=new HashMap(); + FPRICEUNITID.put("FNUMBER", "Pcs"); + EntityDetail.put("FPRICEUNITID", FPRICEUNITID); + + EntityDetail.put("FPrice", je);//单价 + EntityDetail.put("FPriceQty", 1.0);//计价数量 + EntityDetail.put("FTaxPrice", je);//含税单价 + EntityDetail.put("FPriceWithTax", je);//含税净价 + //PPN Type + Map F_RTA_VATType_d=new HashMap(); + F_RTA_VATType_d.put("FNUMBER", "000"); + EntityDetail.put("F_RTA_VATType_d", F_RTA_VATType_d); + + EntityDetail.put("FNoTaxAmountFor_D", je);//不含税金额 + EntityDetail.put("FTAXAMOUNTFOR_D", 0);//税额 + EntityDetail.put("FALLAMOUNTFOR_D", je);//价税合计 + EntityDetail.put("F_RTA_FakturPajakNo_d", "-");//Faktur Pajak No + EntityDetail.put("F_RTA_SUPPLIER_D", FSUPPLIERID);//表体供应商(用于校验税票号唯一) + //将MAP添加至List中 + FEntityDetail.add(EntityDetail); + } + + Model.put("FEntityDetail", FEntityDetail);// + //-----------------明细 end-----------------// + + //-----------------付款计划 start-----------------// + List> FEntityPlan=new ArrayList>(); + Map FPlan=new HashMap(); + FPlan.put("FENDDATE", zfrq);//表头计划 - 到期日 + FPlan.put("FPAYAMOUNTFOR", bxzje);//应付金额 + FPlan.put("FPAYRATE", 100);//应付比例(%) + FEntityPlan.add(FPlan); + Model.put("FEntityPlan", FEntityPlan);// + //-----------------付款计划 end-----------------// + data.put("Model", Model); + + //将MAP转JSON,fastjson默认开启引用检测将相同的对象写成引用的形式,所以必须加上SerializerFeature.DisableCircularReferenceDetect,否则转换的字符串会出现$ref + String jsonStr = JSON.toJSONString(data, SerializerFeature.DisableCircularReferenceDetect); + log.writeLog("调用应付单保存接口传入数据jsonStr---------->"+jsonStr); + //连接K3 + K3CloudApiClient client =K3Connect.connect(); + if(client!=null){ + //调用应付单保存接口 + String sResult = client.excuteOperation("AP_Payable", "save", jsonStr); + log.writeLog("调用应付单保存接口返回数据sResult---------->"+sResult); + //解析K3返回的JSO字符串 + JSONObject jsonObject = JSONObject.parseObject(sResult); + JSONObject ResponseStatus=jsonObject.getJSONObject("Result").getJSONObject("ResponseStatus"); + //是否成功写入K3 + String IsSuccess=ResponseStatus.get("IsSuccess").toString(); + log.writeLog("是否成功写入K3结果IsSuccess---------->"+IsSuccess); + //成功写入K3 + if("true".equals(IsSuccess)){ + JSONArray SuccessJSONArray=ResponseStatus.getJSONArray("SuccessEntitys"); + String Id="";//单据ID + String Number="";//单据编号 + for(int p=0;p"+Id+",Number------>"+Number); + //将应付单号更新至表单字段中 + rs.execute("update "+tablename+" set sfcgsck3yfd='0',k3yfdh='"+Number+"',k3jkfhxx='' where requestid="+requestid); + }else{ + JSONArray ErrorsJSONArray=ResponseStatus.getJSONArray("Errors"); + String msg=""; + for(int p=0;p Hswd=new HashMap();//核算维度对照表 + JSONObject VOUCHER=new JSONObject();//VOUCHER + JSONArray Models=new JSONArray();//ModelS + JSONObject Model=new JSONObject();//Model + Hswd.put("FFLEX4","gys");//供应商 + Hswd.put("FFLEX6","kh");//客户 + Hswd.put("FFLEX7","yg");//员工 + Hswd.put("FFLEX5","bm");//部门 + Hswd.put("FFLEX9","fyxm");//费用项目 + Hswd.put("FFLEX8","wl");//物料 + Hswd.put("FFLEX10","zc");//资产 + Hswd.put("FFLEX12","wlz");//物料组 + Hswd.put("FFLEX13","khz");//客户组 + Map fxHswd=new HashMap();//核算维度对照表 + fxHswd.put("gys","FFLEX4");//供应商 + fxHswd.put("kh","FFLEX6");//客户 + fxHswd.put("yg","FFLEX7");//员工 + fxHswd.put("bm","FFLEX5");//部门 + fxHswd.put("fyxm","FFLEX9");//费用项目 + fxHswd.put("wl","FFLEX8");//物料 + fxHswd.put("zc","FFLEX10");//资产 + fxHswd.put("wlz","FFLEX12");//物料组 + fxHswd.put("khz","FFLEX13");//客户组 + SimpleDateFormat sim=new SimpleDateFormat("yyyy-MM-dd"); + List jlist=new ArrayList();//借方 + List dlist=new ArrayList();//贷方 + String requestid=requestInfo.getRequestid();// + String mainid="";// + String zt="";//账套 + String zz="";//组织 + String zb="";//账薄 + String zzjdhl="";//做账节点汇率 + String bz="";//币种 + String sfxr="";//是否写入 + RecordSet re=new RecordSet(); + String errormess=""; + float zje=0.0f; + //1:借方 2:贷方 + String sql= " select a.sfxr,a.zzjdhl,a.bz,a.id,a.zt,a.zz,a.zb,b.jfkmbm kmbh,b.zy,b.jfje je,b.bm,b.yg,b.kh,b.gys,b.fyxm,b.wl,b.zc,b.wlz,b.khz,b.jfkmmc kmmc,b.hswd,b.yje,'1' entrylx from formtable_main_22 a,formtable_main_22_dt4 b where a.id=b.mainid and a.requestid='"+requestid+"'"+ + " union all "+ + " select a.sfxr,a.zzjdhl,a.bz,a.id,a.zt,a.zz,a.zb,b.dfkmbm kmbh,b.zy,b.dfje je,b.bm,b.yg,b.kh,b.gys,b.fyxm,b.wl,b.zc,b.wlz,b.khz,b.dfkmmc kmmc,b.hswd,b.yje,'2' entrylx from formtable_main_22 a,formtable_main_22_dt5 b where a.id=b.mainid and a.requestid='"+requestid+"' "; + log.error(requestid+"CreateVoucherBx"+sql); + //out.print(sql); + + re.execute(sql); + JSONArray FEntity=new JSONArray(); + lable1:while(re.next()){ + //拼接科目信息 + sfxr=Util.null2String(re.getString("sfxr")).trim(); + zt=Util.null2String(re.getString("zt")).trim(); + zz=Util.null2String(re.getString("zz")).trim(); + zb=Util.null2String(re.getString("zb")).trim(); + JSONObject FEntityDetail=new JSONObject(); + String FEXPLANATION=Util.null2String(re.getString("zy"));//摘要 + FEntityDetail.put("FEXPLANATION",FEXPLANATION); + JSONObject FACCOUNTID=new JSONObject();//科目 FNumber + String demoKm=Util.null2String(re.getString("kmbh")).trim(); + if("".equals(demoKm)){ + errormess="科目编号不能为空";//科目编号不能为空 + break; + }else{ + FACCOUNTID.put("FNumber",demoKm); + } + FEntityDetail.put("FACCOUNTID",FACCOUNTID); + JSONObject FDetailID=new JSONObject();//辅助核算项 FDETAILID__FFLEX10 FNumber + //获取科目的辅助核算项 + String demoHswd=getFzhx(demoKm,zt,zz,zb,Hswd); + //out.print("demoHswd--"+demoHswd); + if(demoHswd!=null&&!"".equals(demoHswd.trim())){ + String[] demoHswds=demoHswd.split(","); + for(String str:demoHswds){ + if(str!=null&&!"".equals(str)){ + JSONObject Hswdjson=new JSONObject(); + String number=Util.null2String(re.getString(str)).trim(); + if(!"".equals(number)){ + Hswdjson.put("FNumber",number); + FDetailID.put("FDETAILID__"+fxHswd.get(str),Hswdjson); + }else{ + errormess=str+"核算维度没有设置值!"; + break lable1; + } + + } + } + } + FEntityDetail.put("FDetailID",FDetailID); + JSONObject FCURRENCYID=new JSONObject();//币别 FNumber + FCURRENCYID.put("FNumber","IDR");//默认印尼盾 + FEntityDetail.put("FCURRENCYID",FCURRENCYID); + JSONObject FEXCHANGERATETYPE=new JSONObject();;//汇率类型 + FEXCHANGERATETYPE.put("FNumber","HLTX01_SYS");//默认 + FEntityDetail.put("FEXCHANGERATETYPE",FEXCHANGERATETYPE); + String FEXCHANGERATE ="1";//汇率 + FEntityDetail.put("FEXCHANGERATE",FEXCHANGERATE); + String FUnitId ="";//单位 + //FEntityDetail.put("FUnitId",FUnitId); + String FPrice="0";//单价 + //FEntityDetail.put("FPrice",FPrice); + String FQty="0";//数量 + //FEntityDetail.put("FQty",FQty); + String FAMOUNTFOR="";//原币金额 + String entrylx=Util.null2String(re.getString("entrylx")); + String FDEBIT="";//借方金额 + String FCREDIT="";//贷方金额 + String FDC="";//借贷方向 + if("1".equals(entrylx)){//借方 + FDEBIT=Util.null2String(re.getString("je")); + FDC="1"; + }else{ + FCREDIT=Util.null2String(re.getString("je")); + FDC="0"; + } + FEntityDetail.put("FCREDIT",FCREDIT); + FEntityDetail.put("FDEBIT",FDEBIT); + FEntityDetail.put("FDC",FDC); + String FSettleTypeID="";//结束方式 FNumber + String FSETTLENO ="";//结算号 + + String FAcctFullName=getKmname(demoKm,zt,zz,zb);//科目全称 + String FACCOUNTNAME=getKmname(demoKm,zt,zz,zb);//科目名称 + //FEntityDetail.put("FAcctFullName",FAcctFullName); + //FEntityDetail.put("FACCOUNTNAME",FACCOUNTNAME); + FEntity.add(FEntityDetail); + } + if(!"".equals(errormess)){ + requestInfo.getRequestManager().setMessageid(errormess); + requestInfo.getRequestManager().setMessage(errormess);//提醒信息id + requestInfo.getRequestManager().setMessagecontent("写入K3系统不成功,系统反馈信息如下:"+errormess);//提醒信息内容 + + return Action.FAILURE_AND_CONTINUE; + } + //out.print("errormess"+errormess); + //out.print("FEntityDetail"+FEntity.toJSONString()); + //设置主数据 + JSONObject FAccountBookID=new JSONObject();//账薄 + FAccountBookID.put("FNumber",zb); + Model.put("FAccountBookID",FAccountBookID); + String FDate=sim.format(new Date()); + Model.put("FDate",FDate); + JSONObject FVOUCHERGROUPID=new JSONObject();//凭证字默认AP + FVOUCHERGROUPID.put("FNumber","PZZ3"); + Model.put("FVOUCHERGROUPID",FVOUCHERGROUPID); + String FYEAR=sim.format(new Date()).split("-")[0];//会计年度 + String FPERIOD =sim.format(new Date()).split("-")[1];//期间 + Model.put("FYEAR",FYEAR); + Model.put("FPERIOD",FPERIOD); + String FDEBITTOTAL=getjfZje(requestid);//借方总金额:FDEBITTOTAL + String FCREDITTOTAL=getdfZje(requestid);//贷方总金额:FCREDITTOTAL + Model.put("FDEBITTOTAL",FDEBITTOTAL); + Model.put("FCREDITTOTAL",FCREDITTOTAL); + String FCreateDate=sim.format(new Date());//创建日期:FCreateDate + JSONObject FACCBOOKORGID=new JSONObject();//核算组织:FACCBOOKORGID + FACCBOOKORGID.put("FNumber",zz); + Model.put("FACCBOOKORGID",FACCBOOKORGID); + //Model.put("FCreateDate",FCreateDate); + String FPRINTTIMES="0";//打印次数:FPRINTTIMES + String FCurrentYear=sim.format(new Date()).split("-")[0];//当前年度:FCurrentYear + String FCurrentPeriod=sim.format(new Date()).split("-")[1];//当前期间:FCurrentPeriod + Model.put("FPRINTTIMES",FPRINTTIMES); + //Model.put("FCurrentYear",FCurrentYear); + //Model.put("FCurrentPeriod",FCurrentPeriod); + Model.put("FEntity",FEntity); + //Models.add(Model); + //凭借主数据 + VOUCHER.put("NeedReturnFields","[\"FVOUCHERID\",\"FVOUCHERGROUPNO\"]"); + VOUCHER.put("IsAutoSubmitAndAudit",true); + VOUCHER.put("Model",Model); + log.error(VOUCHER.toJSONString()); + /*开始调用接口 + 1;登陆 + 2;调用接口 + */ + //String Fv=getFv(Queryurl+"595130",baseis,out); + //out.print(Fv); + if(VOUCHER!=null&&VOUCHER.size()>0&&("".equals(sfxr)||"1".equals(sfxr))){ + RecordSet updRec=new RecordSet(); + com.jet.util.InvokeHelper.POST_K3CloudURL="http://k3.jet.co.id:8880/k3cloud/"; + String dbid="5d48f604c8361e";//dbid1;//"5d48f604c8361e";//"5a964ecc967246"; + String uuid=uuid1; + String password=password2; + org.json.JSONObject resultjson=null; + int lang=2052; + try { + boolean flag=InvokeHelper.Login(dbid, uuid, password, lang); + //out.print(flag); + if(flag){//登陆成功 + resultjson=com.jet.util.InvokeHelper.Save("GL_VOUCHER",VOUCHER.toJSONString()); + boolean flag1=resultjson.getBoolean("flag"); + String resultstr=resultjson.getString("sResult"); + log.error("resultstr"+resultstr); + if(flag1){ + JSONObject HAHA=JSONObject.parseObject(resultstr); + JSONObject Result=HAHA.getJSONObject("Result"); + JSONObject ResponseStatus=Result.getJSONObject("ResponseStatus"); + boolean IsSuccess=ResponseStatus.getBoolean("IsSuccess"); + if(IsSuccess){ + updRec.execute("update formtable_main_22 set sfxr='0' where requestid='"+requestid+"' "); + String FVOUCHERID=Result.getString("Id"); + String Fv=getFv(Queryurl+""+FVOUCHERID,baseis); + updRec.execute("update formtable_main_22 set pzbhdyc='"+Fv+"' where requestid='"+requestid+"' "); + //out.print("成功"+FVOUCHERID); + + }else{ + //out.print("失败"); + requestInfo.getRequestManager().setMessageid("失败"); + requestInfo.getRequestManager().setMessage("失败");//提醒信息id + requestInfo.getRequestManager().setMessagecontent("写入K3系统不成功,系统反馈信息如下:"+HAHA.toString());//提醒信息内容 + + return Action.FAILURE_AND_CONTINUE; + } + }else{ + //out.print("失败"+resultstr); + requestInfo.getRequestManager().setMessageid("失败"); + requestInfo.getRequestManager().setMessage("失败");//提醒信息id + requestInfo.getRequestManager().setMessagecontent("写入K3系统不成功,系统反馈信息如下:"+resultstr.toString());//提醒信息内容 + + return Action.FAILURE_AND_CONTINUE; + } + + } + } catch (Exception e) { + //TODO Auto-generated catch block + log.error("GL_VOUCHER--Exception"+e.getMessage()); + e.printStackTrace(); + } + } + return SUCCESS; + } + + //更具ID获取凭证编号 + public String getFv(String url,String basis)throws Exception{ + String Fv=""; + //out.print("url-"+url+" basis"+basis+" "); + try{ + String result=sendGet(url,"",basis); + // out.print("url-"+url+" basis"+basis+" result"+result); + JSONArray json=JSONArray.parseArray(result); + if(json!=null&&json.size()>0){ + for(int i=0;i> map = connection.getHeaderFields(); + + + for (String key : map.keySet()) { + System.out.println(key + "--->" + map.get(key)); + } + //接收核心返回过来的数据 xml  需要解析 + in =connection.getInputStream(); + byte[] b =getBytes(in); + if(b.length>0){ + result=new String(b); + } + System.out.println(b.length); + } catch (Exception e) { + + System.out.println(e.getMessage()); + e.printStackTrace(); + }finally { + try { + if (in != null) { + in.close(); + } + } catch (Exception e2) { + System.out.println(e2.getMessage()); + e2.printStackTrace(); + } + } + //System.out.println("de"+result); + return result; + } + public static byte[] getBytes(InputStream fis){ + Logger log = Logger.getLogger(Logger.class); + byte[] buffer = null; + try { + //File file = new File(filePath); + //FileInputStream fis = new FileInputStream(file); + ByteArrayOutputStream bos = new ByteArrayOutputStream(1000); + byte[] b = new byte[10000]; + int n; + while ((n = fis.read(b)) != -1) { + bos.write(b, 0, n); + } + fis.close(); + bos.close(); + buffer = bos.toByteArray(); + } catch (FileNotFoundException e) { + e.printStackTrace(); + } catch (IOException e) { + e.printStackTrace(); + } + System.out.println("buffer--->"+buffer.length); + return buffer; + } + //获取借方总金额 + public static String getjfZje(String requestid){ + RecordSet re=new RecordSet(); + String je=""; + String sql="select sum(jfje) jfje from formtable_main_22 a,formtable_main_22_dt4 b where a.id=b.mainid and a.requestid='"+requestid+"'"; + re.execute(sql); + while(re.next()){ + je=re.getString("jfje") ; + } + return je; + } + //获取贷方总金额 + public static String getdfZje(String requestid){ + RecordSet re=new RecordSet(); + String je=""; + String sql="select sum(dfje) dfje from formtable_main_22 a,formtable_main_22_dt5 b where a.id=b.mainid and a.requestid='"+requestid+"'"; + re.execute(sql); + while(re.next()){ + je=re.getString("dfje") ; + } + return je; + } + //获取赋值核算类型 + public String getFzhx(String km,String zt,String zz,String zb,Map Hswd ){ + String FDIMENSION="";//核算维度 + RecordSet re=new RecordSet(); + String sql="select b.FDIMENSION from uf_accountinfo a,uf_accountinfo_dt1 b where a.id=b.mainid and a.zt='"+zt+"' and b.FNUMBER='"+km+"' and b.forgnumber='"+zz+"' and FAcctBookNumber='"+zb+"' "; + //out.print(sql); + re.execute(sql); + while(re.next()){ + String str=Util.null2String(re.getString("FDIMENSION")).trim() ; + String[] FDIMENSIONs=str.split(","); + for(String demo:FDIMENSIONs){ + if(demo!=null&&!"".equals(demo)){ + FDIMENSION=FDIMENSION+Hswd.get(demo)+","; + } + } + } + if(FDIMENSION.endsWith(",")){ + FDIMENSION=FDIMENSION.substring(0,FDIMENSION.length()-1); + } + return FDIMENSION; + } + //insert 事务 + public boolean SynInsert1(List array){ + if(array==null||array.size()<=0){ + return false; + } + Logger log = Logger.getLogger(DataSource.class); + RecordSetTrans RecordSetTrans=new RecordSetTrans(); + RecordSetTrans.setAutoCommit(false); + boolean flag=true; + + try{ + RecordSetTrans.setAutoCommit(false); + // stmt = conn.createStatement(); + for(String str:array){ + //int index =RecordSetTrans.executeUpdate(str); + flag=RecordSetTrans.executeSql(str); + log.error("SynInsert--"+str); + if(!flag){ + //flag=false; + break; + } + } + if(!flag){//事务回滚 + RecordSetTrans.rollback(); + }else{ + RecordSetTrans.commit(); + } + }catch(Exception e){ + log.error("SynInsert--Exception "+e.getMessage()); + flag=false; + } + + return flag; + } + //获取科目名称 + public String getKmname(String km,String zt,String zz,String zb){ + String FNAME="";//核算维度 + RecordSet re=new RecordSet(); + String sql="select b.FNAME from uf_accountinfo a,uf_accountinfo_dt1 b where a.id=b.mainid and a.zt='"+zt+"' and b.FNUMBER='"+km+"' and b.forgnumber='"+zz+"' and FAcctBookNumber='"+zb+"' "; + re.execute(sql); + while(re.next()){ + FNAME=Util.null2String(re.getString("FNAME")); + } + return FNAME; + } + //获取币种的小数位 + public int getXsw(String bz){ + int xsw=0; + RecordSet re=new RecordSet(); + String sql="select * from uf_k3bz where bh='"+bz+"'"; + re.execute(sql); + while(re.next()){ + xsw=Integer.parseInt(Util.null2o(re.getString("xsw"))) ; + } + return xsw; + } + + //浮点型转换 + public static float getfloats(String demo,String demo1,int len){ + Logger log = Logger.getLogger(BigDecimal.class); + if(len==0){ + len=0; + } + String str=Util.null2String(demo); + String str1=Util.null2String(demo1); + if("".equals(str)||"".equals(str.trim())||"null".equalsIgnoreCase(str.trim())){ + return 0; + } + if("".equals(str1)||"".equals(str.trim())||"null".equalsIgnoreCase(str1.trim())){ + str1="1"; + } + float fl=0.0f; + //String str=Util.null2String(demo); + try{ + if(str.trim().length()>0){ + BigDecimal b1 = new BigDecimal(str.trim()); + BigDecimal b2 = new BigDecimal(str1.trim()); + BigDecimal b3=b1.multiply(b2); + //System.out.println(b1.setScale(2,BigDecimal.ROUND_HALF_UP)); + fl=b3.setScale(len,BigDecimal.ROUND_HALF_UP).floatValue(); + } + log.error("getfloats"+fl); + }catch(Exception e){ + log.error(demo+"getfloats异常"+e.getMessage()); + } + return fl; + } + + + //浮点型转换 + public static float getfloats1(String demo,String demo1,int len){ + Logger log = Logger.getLogger(BigDecimal.class); + if(len==0){ + len=0; + } + String str=Util.null2String(demo); + String str1=Util.null2String(demo1); + if("".equals(str)||"".equals(str.trim())||"null".equalsIgnoreCase(str.trim())){ + str="0"; + } + if("".equals(str1)||"".equals(str.trim())||"null".equalsIgnoreCase(str1.trim())){ + str1="0"; + } + float fl=0.0f; + //String str=Util.null2String(demo); + try{ + if(str.trim().length()>0){ + BigDecimal b1 = new BigDecimal(str.trim()); + BigDecimal b2 = new BigDecimal(str1.trim()); + BigDecimal b3=b1.add(b2); + //System.out.println(b1.setScale(2,BigDecimal.ROUND_HALF_UP)); + fl=b3.setScale(len,BigDecimal.ROUND_HALF_UP).floatValue(); + } + log.error("getfloats"+fl); + }catch(Exception e){ + log.error(demo+"getfloats异常"+e.getMessage()); + } + return fl; + } + +} diff --git a/src/main/youhong_ai_jitu_src/com/jet/action/CreateVoucherBx2.java b/src/main/youhong_ai_jitu_src/com/jet/action/CreateVoucherBx2.java new file mode 100644 index 0000000..671011c --- /dev/null +++ b/src/main/youhong_ai_jitu_src/com/jet/action/CreateVoucherBx2.java @@ -0,0 +1,787 @@ +package com.jet.action; + +import weaver.soa.workflow.request.RequestInfo; +import weaver.workflow.action.BaseAction; +import weaver.conn.RecordSet; +import com.alibaba.fastjson.JSONArray; +import com.alibaba.fastjson.JSONObject; + +import weaver.hrm.HrmUserVarify; +import weaver.hrm.User; +import weaver.general.BaseBean; +import weaver.general.Util; +import org.apache.log4j.Logger; +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import java.text.SimpleDateFormat; +import java.sql.Connection; +import java.sql.ResultSet; +import java.sql.Statement; +import weaver.general.StaticObj; +import weaver.interfaces.datasource.DataSource; +import weaver.formmode.setup.ModeRightInfo; +import java.sql.Connection; +import java.sql.ResultSet; +import java.sql.SQLException; +import java.sql.Statement; +import weaver.general.StaticObj; +import weaver.interfaces.datasource.DataSource; +import weaver.interfaces.workflow.action.Action; + +import java.math.BigDecimal; +import java.io.BufferedReader; +import java.io.IOException; +import java.io.InputStreamReader; +import java.io.PrintWriter; +import java.net.URL; +import java.net.URLConnection; +import org.apache.http.Header; +import org.apache.http.HttpResponse; +import org.apache.http.HttpStatus; +import org.apache.http.client.HttpClient; +import org.apache.http.client.methods.HttpPost; +import org.apache.http.entity.*; +import org.apache.http.*; +import org.apache.http.util.*; +import org.apache.http.impl.client.DefaultHttpClient; +import org.apache.http.params.CoreConnectionPNames; + +import java.util.ArrayList; +import java.util.Date; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.UUID; +import java.nio.charset.Charset; +import java.io.BufferedReader; +import java.io.ByteArrayOutputStream; +import java.io.FileNotFoundException; +import java.io.IOException; +import java.io.InputStream; +import java.io.InputStreamReader; +import weaver.conn.RecordSetTrans; +import java.io.PrintWriter; +import com.jet.util.*; +import org.json.*; +public class CreateVoucherBx2 extends BaseAction{ + @Override + public String execute(RequestInfo requestInfo) { + // TODO Auto-generated method stub + Logger log = Logger.getLogger(JSONObject.class); + RecordSet urlre=new RecordSet(); + String urlsql="select * from uf_urlinfo where ms='model'"; + log.error(requestInfo.getRequestid()+"CreateVoucherBx2"); + urlre.execute(urlsql); + String url=""; + String username=""; + String password1=""; + String dbid1=""; + String uuid1=""; + String password2=""; + while(urlre.next()){ + url=Util.null2String(urlre.getString("url")); + username=Util.null2String(urlre.getString("username")); + password1=Util.null2String(urlre.getString("password")); + dbid1=Util.null2String(urlre.getString("dbid")); + uuid1=Util.null2String(urlre.getString("uuid")); + password2=Util.null2String(urlre.getString("password1")); + } + String baseis=username+":"+password1; + String Queryurl=url+"GlVoucher/"; + //log.error("deeded"); + //out.print("haha"); + Map Hswd=new HashMap();//核算维度对照表 + JSONObject VOUCHER=new JSONObject();//VOUCHER + JSONArray Models=new JSONArray();//ModelS + JSONObject Model=new JSONObject();//Model + Hswd.put("FFLEX4","gys");//供应商 + Hswd.put("FFLEX6","kh");//客户 + Hswd.put("FFLEX7","yg");//员工 + Hswd.put("FFLEX5","bm");//部门 + Hswd.put("FFLEX9","fyxm");//费用项目 + Hswd.put("FFLEX8","wl");//物料 + Hswd.put("FFLEX10","zc");//资产 + Hswd.put("FFLEX12","wlz");//物料组 + Hswd.put("FFLEX13","khz");//客户组 + Map fxHswd=new HashMap();//核算维度对照表 + fxHswd.put("gys","FFLEX4");//供应商 + fxHswd.put("kh","FFLEX6");//客户 + fxHswd.put("yg","FFLEX7");//员工 + fxHswd.put("bm","FFLEX5");//部门 + fxHswd.put("fyxm","FFLEX9");//费用项目 + fxHswd.put("wl","FFLEX8");//物料 + fxHswd.put("zc","FFLEX10");//资产 + fxHswd.put("wlz","FFLEX12");//物料组 + fxHswd.put("khz","FFLEX13");//客户组 + SimpleDateFormat sim=new SimpleDateFormat("yyyy-MM-dd"); + List jlist=new ArrayList();//借方 + List dlist=new ArrayList();//贷方 + String requestid="8015";// + String mainid="";// + String zt="";//账套 + String zz="";//组织 + String zb="";//账薄 + String zzjdhl="";//做账节点汇率 + String bz="";//币种 + String sfxr="";//是否写入 + String cnfkjdhl="";//出纳汇率 + String fkyxzh="";//付款银行账号 + String pzbhdyc="";//凭证编号(第一次) + RecordSet re=new RecordSet(); + String errormess=""; + float zje=0.0f; + //1:借方 2:贷方 + String sql= " select a.* from formtable_main_22 a where a.requestid='"+requestid+"'"; + re.execute(sql); + while(re.next()){ + zt=Util.null2String(re.getString("zt")).trim(); + zz=Util.null2String(re.getString("zz")).trim(); + zb=Util.null2String(re.getString("zb")).trim(); + cnfkjdhl=Util.null2String(re.getString("cnfkjdhl")).trim(); + fkyxzh=Util.null2String(re.getString("fkyxzh")).trim(); + pzbhdyc=Util.null2String(re.getString("pzbhdyc")).trim(); + } + String tskm =SpelKm(zt,zz,zb,"3");//获取特殊科目 汇率差设置 + + float dje=getfloats(getDteJe5(requestid),"1",0);//第一次贷方金额 + String ysje=getDteJe(requestid);//原始金额 + float newdje=getfloats(ysje,cnfkjdhl,0);//原始换算之后的金额 + //获取金额差 + JSONArray FEntitys=null; + float hlcJe= getfloats2(newdje+"",dje+"",0);//汇率差 + //out.print("ysje"+ysje); + //out.print("cnfkjdhl"+cnfkjdhl); + //out.print("hlcJe"+hlcJe); + //out.print("dje"+dje); + //out.print("newdje"+newdje); + if(dje==newdje){ + + JSONObject FEntity=new JSONObject(); + Map objMap=getModel(requestid,Hswd,fxHswd); + Boolean.getBoolean((String)objMap.get("flag")); + boolean flag=(Boolean)objMap.get("flag"); + if(flag){ + FEntitys=(JSONArray)objMap.get("FEntity"); + }else{ + errormess= (String)objMap.get("mess"); + } + //生成贷方 + FEntity.put("FEXPLANATION","FEXPLANATION");//摘要 + FEntity.put("FACCOUNTID",fkyxzh);//科目 + JSONObject FCURRENCYID=new JSONObject();//币别 FNumber + FCURRENCYID.put("FNumber","IDR");//默认印尼盾 + FEntity.put("FCURRENCYID",FCURRENCYID); + JSONObject FEXCHANGERATETYPE=new JSONObject();;//汇率类型 + FEXCHANGERATETYPE.put("FNumber","HLTX01_SYS");//默认 + FEntity.put("FEXCHANGERATETYPE",FEXCHANGERATETYPE); + String FEXCHANGERATE ="1";//汇率 + FEntity.put("FEXCHANGERATE",FEXCHANGERATE); + FEntity.put("FCREDIT",newdje); + FEntity.put("FDEBIT",""); + FEntity.put("FDC","0"); + FEntitys.add(FEntity); + + + //FEntity.put("FEXPLANATION","FEXPLANATION");//摘要 + //FEntity.put("FEXPLANATION","FEXPLANATION");//摘要 + }else{ //付款小于 做账金额 + //贷银行存款 借汇率差以及 第一次凭证的贷方 + JSONObject FEntity=new JSONObject(); + Map objMap=getModel(requestid,Hswd,fxHswd); + + //Boolean.getBoolean((String)objMap.get("flag")); + boolean flag=(Boolean)objMap.get("flag"); + //out.print(flag); + if(flag){ + FEntitys=(JSONArray)objMap.get("FEntity"); + }else{ + errormess= (String)objMap.get("mess"); + } + //out.print(objMap.toString()); + //借汇率差 + JSONObject FACCOUNTID=new JSONObject();//科目 FNumber + FACCOUNTID.put("FNumber",tskm); + FEntity.put("FEXPLANATION","FEXPLANATION");//摘要 + FEntity.put("FACCOUNTID",FACCOUNTID);//科目 + JSONObject FCURRENCYID=new JSONObject();//币别 FNumber + FCURRENCYID.put("FNumber","IDR");//默认印尼盾 + FEntity.put("FCURRENCYID",FCURRENCYID); + JSONObject FEXCHANGERATETYPE=new JSONObject();;//汇率类型 + FEXCHANGERATETYPE.put("FNumber","HLTX01_SYS");//默认 + FEntity.put("FEXCHANGERATETYPE",FEXCHANGERATETYPE); + String FEXCHANGERATE ="1";//汇率 + FEntity.put("FEXCHANGERATE",FEXCHANGERATE); + FEntity.put("FCREDIT",""); + FEntity.put("FDEBIT",hlcJe); + FEntity.put("FDC","1"); + FEntitys.add(FEntity); + //贷银行 + JSONObject FACCOUNTID1=new JSONObject();//科目 FNumber + FACCOUNTID1.put("FNumber",fkyxzh); + JSONObject FEntity1=new JSONObject(); + FEntity1.put("FEXPLANATION","FEXPLANATION");//摘要 + FEntity1.put("FACCOUNTID",FACCOUNTID1);//科目 + JSONObject FCURRENCYID2=new JSONObject();//币别 FNumber + FCURRENCYID2.put("FNumber","IDR");//默认印尼盾 + FEntity1.put("FCURRENCYID",FCURRENCYID2); + JSONObject FEXCHANGERATETYPE2=new JSONObject();;//汇率类型 + FEXCHANGERATETYPE2.put("FNumber","HLTX01_SYS");//默认 + FEntity1.put("FEXCHANGERATETYPE",FEXCHANGERATETYPE2); + String FEXCHANGERATE2 ="1";//汇率 + FEntity1.put("FEXCHANGERATE",FEXCHANGERATE2); + FEntity1.put("FCREDIT",newdje); + FEntity1.put("FDEBIT",""); + FEntity1.put("FDC","0"); + FEntitys.add(FEntity1); + } + if(!"".equals(errormess)){ + requestInfo.getRequestManager().setMessageid(errormess); + requestInfo.getRequestManager().setMessage(errormess);//提醒信息id + requestInfo.getRequestManager().setMessagecontent("写入K3系统不成功,系统反馈信息如下:"+errormess);//提醒信息内容 + + return Action.FAILURE_AND_CONTINUE; + } + + JSONObject FAccountBookID=new JSONObject();//账薄 + FAccountBookID.put("FNumber",zb); + Model.put("FAccountBookID",FAccountBookID); + String FDate=sim.format(new Date()); + Model.put("FDate",FDate); + JSONObject FVOUCHERGROUPID=new JSONObject();//凭证字默认AP + FVOUCHERGROUPID.put("FNumber","PZZ3"); + Model.put("FVOUCHERGROUPID",FVOUCHERGROUPID); + String FYEAR=sim.format(new Date()).split("-")[0];//会计年度 + String FPERIOD =sim.format(new Date()).split("-")[1];//期间 + Model.put("FYEAR",FYEAR); + Model.put("FPERIOD",FPERIOD); + String FDEBITTOTAL=newdje+"";//借方总金额:FDEBITTOTAL + String FCREDITTOTAL=newdje+"";//贷方总金额:FCREDITTOTAL + Model.put("FDEBITTOTAL",FDEBITTOTAL); + Model.put("FCREDITTOTAL",FCREDITTOTAL); + String FCreateDate=sim.format(new Date());//创建日期:FCreateDate + JSONObject FACCBOOKORGID=new JSONObject();//核算组织:FACCBOOKORGID + FACCBOOKORGID.put("FNumber",zz); + Model.put("FACCBOOKORGID",FACCBOOKORGID); + //Model.put("FCreateDate",FCreateDate); + String FPRINTTIMES="0";//打印次数:FPRINTTIMES + String FCurrentYear=sim.format(new Date()).split("-")[0];//当前年度:FCurrentYear + String FCurrentPeriod=sim.format(new Date()).split("-")[1];//当前期间:FCurrentPeriod + Model.put("FPRINTTIMES",FPRINTTIMES); + //Model.put("FCurrentYear",FCurrentYear); + //Model.put("FCurrentPeriod",FCurrentPeriod); + Model.put("FEntity",FEntitys); + //Models.add(Model); + Model.put("F_RTA_Remarks",pzbhdyc); + //凭借主数据 + VOUCHER.put("NeedReturnFields","[\"FVOUCHERID\",\"FVOUCHERGROUPNO\"]"); + VOUCHER.put("IsAutoSubmitAndAudit",true); + VOUCHER.put("Model",Model); + log.error("CreateVoucherBx2"+VOUCHER.toJSONString()); + /*开始调用接口 + 1;登陆 + 2;调用接口 + */ + //String Fv=getFv(Queryurl+"595130",baseis,out); + //out.print(Fv); + if(VOUCHER!=null&&VOUCHER.size()>0&&("".equals(sfxr)||"1".equals(sfxr))){ + RecordSet updRec=new RecordSet(); + com.jet.util.InvokeHelper.POST_K3CloudURL="http://k3.jet.co.id:8880/k3cloud/"; + String dbid="5d48f604c8361e";//dbid1;//"5d48f604c8361e";//"5a964ecc967246"; + String uuid=uuid1; + String password=password2; + org.json.JSONObject resultjson=null; + int lang=2052; + try { + boolean flag=InvokeHelper.Login(dbid, uuid, password, lang); + //out.print(flag); + if(flag){//登陆成功 + resultjson=com.jet.util.InvokeHelper.Save("GL_VOUCHER",VOUCHER.toJSONString()); + boolean flag1=resultjson.getBoolean("flag"); + String resultstr=resultjson.getString("sResult"); + log.error("resultstr"+resultstr); + if(flag1){ + JSONObject HAHA=JSONObject.parseObject(resultstr); + JSONObject Result=HAHA.getJSONObject("Result"); + JSONObject ResponseStatus=Result.getJSONObject("ResponseStatus"); + boolean IsSuccess=ResponseStatus.getBoolean("IsSuccess"); + if(IsSuccess){ + updRec.execute("update formtable_main_22 set sfxr='0' where requestid='"+requestid+"' "); + String FVOUCHERID=Result.getString("Id"); + String Fv=getFv(Queryurl+""+FVOUCHERID,baseis); + updRec.execute("update formtable_main_22 set pzbhdec='"+Fv+"' where requestid='"+requestid+"' "); + //out.print("成功"+FVOUCHERID); + + }else{ + //out.print("失败"); + requestInfo.getRequestManager().setMessageid("失败"); + requestInfo.getRequestManager().setMessage("失败");//提醒信息id + requestInfo.getRequestManager().setMessagecontent("写入K3系统不成功,系统反馈信息如下:"+HAHA.toString());//提醒信息内容 + + return Action.FAILURE_AND_CONTINUE; + } + }else{ + //out.print("失败"+resultstr); + requestInfo.getRequestManager().setMessageid("失败"); + requestInfo.getRequestManager().setMessage("失败");//提醒信息id + requestInfo.getRequestManager().setMessagecontent("写入K3系统不成功,系统反馈信息如下:"+resultstr.toString());//提醒信息内容 + + return Action.FAILURE_AND_CONTINUE; + } + + } + } catch (Exception e) { + //TODO Auto-generated catch block + log.error("GL_VOUCHER--Exception"+e.getMessage()); + e.printStackTrace(); + } + } + return SUCCESS; + } + + //更具ID获取凭证编号 + public String getFv(String url,String basis)throws Exception{ + String Fv=""; + //out.print("url-"+url+" basis"+basis+" "); + try{ + String result=sendGet(url,"",basis); + // out.print("url-"+url+" basis"+basis+" result"+result); + JSONArray json=JSONArray.parseArray(result); + if(json!=null&&json.size()>0){ + for(int i=0;i> map = connection.getHeaderFields(); + + + for (String key : map.keySet()) { + System.out.println(key + "--->" + map.get(key)); + } + //接收核心返回过来的数据 xml  需要解析 + in =connection.getInputStream(); + byte[] b =getBytes(in); + if(b.length>0){ + result=new String(b); + } + System.out.println(b.length); + } catch (Exception e) { + + System.out.println(e.getMessage()); + e.printStackTrace(); + }finally { + try { + if (in != null) { + in.close(); + } + } catch (Exception e2) { + System.out.println(e2.getMessage()); + e2.printStackTrace(); + } + } + //System.out.println("de"+result); + return result; + } + public static byte[] getBytes(InputStream fis){ + Logger log = Logger.getLogger(Logger.class); + byte[] buffer = null; + try { + //File file = new File(filePath); + //FileInputStream fis = new FileInputStream(file); + ByteArrayOutputStream bos = new ByteArrayOutputStream(1000); + byte[] b = new byte[10000]; + int n; + while ((n = fis.read(b)) != -1) { + bos.write(b, 0, n); + } + fis.close(); + bos.close(); + buffer = bos.toByteArray(); + } catch (FileNotFoundException e) { + e.printStackTrace(); + } catch (IOException e) { + e.printStackTrace(); + } + System.out.println("buffer--->"+buffer.length); + return buffer; + } + //封装借贷方 Model + public Map getModel(String requestid, Map Hswd, Map fxHswd){ + RecordSet re=new RecordSet(); + boolean flag=true; + Map map=new HashMap(); + String errormess="";// + String sql= " select a.sfxr,a.zzjdhl,a.bz,a.id,a.zt,a.zz,a.zb,b.dfkmbm kmbh,b.zy,b.dfje je,b.bm,b.yg,b.kh,b.gys,b.fyxm,b.wl,b.zc,b.wlz,b.khz,b.dfkmmc kmmc,b.hswd,b.yje,'1' entrylx from formtable_main_22 a,formtable_main_22_dt5 b where a.id=b.mainid and a.requestid='"+requestid+"' "; + //log.error("deeded"+); + re.execute(sql); + JSONArray FEntity=new JSONArray(); + lable1:while(re.next()){ + //拼接科目信息 + String sfxr=Util.null2String(re.getString("sfxr")).trim(); + String zt=Util.null2String(re.getString("zt")).trim(); + String zz=Util.null2String(re.getString("zz")).trim(); + String zb=Util.null2String(re.getString("zb")).trim(); + JSONObject FEntityDetail=new JSONObject(); + String FEXPLANATION=Util.null2String(re.getString("zy"));//摘要 + FEntityDetail.put("FEXPLANATION",FEXPLANATION); + JSONObject FACCOUNTID=new JSONObject();//科目 FNumber + String demoKm=Util.null2String(re.getString("kmbh")).trim(); + if("".equals(demoKm)){ + errormess="科目编号不能为空";//科目编号不能为空 + break; + }else{ + FACCOUNTID.put("FNumber",demoKm); + } + FEntityDetail.put("FACCOUNTID",FACCOUNTID); + JSONObject FDetailID=new JSONObject();//辅助核算项 FDETAILID__FFLEX10 FNumber + //获取科目的辅助核算项 + String demoHswd=getFzhx(demoKm,zt,zz,zb,Hswd); + //out.print("demoHswd--"+demoHswd); + if(demoHswd!=null&&!"".equals(demoHswd.trim())){ + String[] demoHswds=demoHswd.split(","); + for(String str:demoHswds){ + if(str!=null&&!"".equals(str)){ + JSONObject Hswdjson=new JSONObject(); + String number=Util.null2String(re.getString(str)).trim(); + if(!"".equals(number)){ + Hswdjson.put("FNumber",number); + FDetailID.put("FDETAILID__"+fxHswd.get(str),Hswdjson); + }else{ + //errormess=str+"核算维度没有设置值!"; + //break lable1; + } + + } + } + } + FEntityDetail.put("FDetailID",FDetailID); + JSONObject FCURRENCYID=new JSONObject();//币别 FNumber + FCURRENCYID.put("FNumber","IDR");//默认印尼盾 + FEntityDetail.put("FCURRENCYID",FCURRENCYID); + JSONObject FEXCHANGERATETYPE=new JSONObject();;//汇率类型 + FEXCHANGERATETYPE.put("FNumber","HLTX01_SYS");//默认 + FEntityDetail.put("FEXCHANGERATETYPE",FEXCHANGERATETYPE); + String FEXCHANGERATE ="1";//汇率 + FEntityDetail.put("FEXCHANGERATE",FEXCHANGERATE); + String FUnitId ="";//单位 + //FEntityDetail.put("FUnitId",FUnitId); + String FPrice="0";//单价 + //FEntityDetail.put("FPrice",FPrice); + String FQty="0";//数量 + //FEntityDetail.put("FQty",FQty); + String FAMOUNTFOR="";//原币金额 + String entrylx=Util.null2String(re.getString("entrylx")); + String FDEBIT="";//借方金额 + String FCREDIT="";//贷方金额 + String FDC="";//借贷方向 + if("1".equals(entrylx)){//借方 + FDEBIT=getfloats(Util.null2String(re.getString("je")),"1",0)+""; + FDC="1"; + }else{ + FCREDIT=getfloats(Util.null2String(re.getString("je")),"1",0)+""; + FDC="0"; + } + FEntityDetail.put("FCREDIT",FCREDIT); + FEntityDetail.put("FDEBIT",FDEBIT); + FEntityDetail.put("FDC",FDC); + String FSettleTypeID="";//结束方式 FNumber + String FSETTLENO ="";//结算号 + + String FAcctFullName=getKmname(demoKm,zt,zz,zb);//科目全称 + String FACCOUNTNAME=getKmname(demoKm,zt,zz,zb);//科目名称 + //FEntityDetail.put("FAcctFullName",FAcctFullName); + //FEntityDetail.put("FACCOUNTNAME",FACCOUNTNAME); + FEntity.add(FEntityDetail); + } + if(!"".equals(errormess)){ + map.put("flag",false); + flag=false; + map.put("mess",errormess); + } + if(FEntity.size()<=0){ + map.put("flag",false); + flag=false; + map.put("mess","无法获取原始借贷方"); + } + map.put("flag",flag); + map.put("FEntity",FEntity); + return map; + } + //获取赋值核算类型 + public String getFzhx1(String km,String zt,String zz,String zb,Map Hswd){ + String FDIMENSION="";//核算维度 + RecordSet re=new RecordSet(); + String sql="select b.FDIMENSION from uf_accountinfo a,uf_accountinfo_dt1 b where a.id=b.mainid and a.zt='"+zt+"' and b.FNUMBER='"+km+"' and b.forgnumber='"+zz+"' and FAcctBookNumber='"+zb+"' "; + //out.print(sql); + re.execute(sql); + while(re.next()){ + String str=Util.null2String(re.getString("FDIMENSION")).trim() ; + String[] FDIMENSIONs=str.split(","); + for(String demo:FDIMENSIONs){ + if(demo!=null&&!"".equals(demo)){ + FDIMENSION=FDIMENSION+Hswd.get(demo)+","; + } + } + } + if(FDIMENSION.endsWith(",")){ + FDIMENSION=FDIMENSION.substring(0,FDIMENSION.length()-1); + } + return FDIMENSION; + } + //获取原始报销金额 + public String getDteJe(String requestid){ + RecordSet re=new RecordSet(); + String je=""; + String sql="select sum(je) je from formtable_main_22 a,formtable_main_22_dt8 b where a.id=b.mainid and a.requestid='"+requestid+"'"; + re.execute(sql); + while(re.next()){ + je=re.getString("je") ; + } + return je; + } + //获取贷方总金额 + public String getDteJe5(String requestid){ + RecordSet re=new RecordSet(); + String je=""; + String sql="select sum(dfje) je from formtable_main_22 a,formtable_main_22_dt5 b where a.id=b.mainid and a.requestid='"+requestid+"'"; + re.execute(sql); + while(re.next()){ + je=re.getString("je") ; + } + return je; + } + + + //获取借方总金额 + public static String getjfZje(String requestid){ + RecordSet re=new RecordSet(); + String je=""; + String sql="select sum(jfje) jfje from formtable_main_22 a,formtable_main_22_dt4 b where a.id=b.mainid and a.requestid='"+requestid+"'"; + re.execute(sql); + while(re.next()){ + je=re.getString("jfje") ; + } + return je; + } + //获取贷方总金额 + public static String getdfZje(String requestid){ + RecordSet re=new RecordSet(); + String je=""; + String sql="select sum(dfje) dfje from formtable_main_22 a,formtable_main_22_dt5 b where a.id=b.mainid and a.requestid='"+requestid+"'"; + re.execute(sql); + while(re.next()){ + je=re.getString("dfje") ; + } + return je; + } + //获取赋值核算类型 + public String getFzhx(String km,String zt,String zz,String zb,Map Hswd){ + String FDIMENSION="";//核算维度 + RecordSet re=new RecordSet(); + String sql="select b.FDIMENSION from uf_accountinfo a,uf_accountinfo_dt1 b where a.id=b.mainid and a.zt='"+zt+"' and b.FNUMBER='"+km+"' and b.forgnumber='"+zz+"' and FAcctBookNumber='"+zb+"' "; + //out.print(sql); + re.execute(sql); + while(re.next()){ + String str=Util.null2String(re.getString("FDIMENSION")).trim() ; + String[] FDIMENSIONs=str.split(","); + for(String demo:FDIMENSIONs){ + if(demo!=null&&!"".equals(demo)){ + FDIMENSION=FDIMENSION+Hswd.get(demo)+","; + } + } + } + if(FDIMENSION.endsWith(",")){ + FDIMENSION=FDIMENSION.substring(0,FDIMENSION.length()-1); + } + return FDIMENSION; + } + //insert 事务 + public boolean SynInsert1(List array){ + if(array==null||array.size()<=0){ + return false; + } + Logger log = Logger.getLogger(DataSource.class); + RecordSetTrans RecordSetTrans=new RecordSetTrans(); + RecordSetTrans.setAutoCommit(false); + boolean flag=true; + + try{ + RecordSetTrans.setAutoCommit(false); + // stmt = conn.createStatement(); + for(String str:array){ + //int index =RecordSetTrans.executeUpdate(str); + flag=RecordSetTrans.executeSql(str); + log.error("SynInsert--"+str); + if(!flag){ + //flag=false; + break; + } + } + if(!flag){//事务回滚 + RecordSetTrans.rollback(); + }else{ + RecordSetTrans.commit(); + } + }catch(Exception e){ + log.error("SynInsert--Exception "+e.getMessage()); + flag=false; + } + + return flag; + } + //获取科目名称 + public String getKmname(String km,String zt,String zz,String zb){ + String FNAME="";//核算维度 + RecordSet re=new RecordSet(); + String sql="select b.FNAME from uf_accountinfo a,uf_accountinfo_dt1 b where a.id=b.mainid and a.zt='"+zt+"' and b.FNUMBER='"+km+"' and b.forgnumber='"+zz+"' and FAcctBookNumber='"+zb+"' "; + re.execute(sql); + while(re.next()){ + FNAME=Util.null2String(re.getString("FNAME")); + } + return FNAME; + } + //获取币种的小数位 + public int getXsw(String bz){ + int xsw=0; + RecordSet re=new RecordSet(); + String sql="select * from uf_k3bz where bh='"+bz+"'"; + re.execute(sql); + while(re.next()){ + xsw=Integer.parseInt(Util.null2o(re.getString("xsw"))) ; + } + return xsw; + } + + //浮点型转换 + public static float getfloats(String demo,String demo1,int len){ + Logger log = Logger.getLogger(BigDecimal.class); + if(len==0){ + len=0; + } + String str=Util.null2String(demo); + String str1=Util.null2String(demo1); + if("".equals(str)||"".equals(str.trim())||"null".equalsIgnoreCase(str.trim())){ + return 0; + } + if("".equals(str1)||"".equals(str.trim())||"null".equalsIgnoreCase(str1.trim())){ + str1="1"; + } + float fl=0.0f; + //String str=Util.null2String(demo); + try{ + if(str.trim().length()>0){ + BigDecimal b1 = new BigDecimal(str.trim()); + BigDecimal b2 = new BigDecimal(str1.trim()); + BigDecimal b3=b1.multiply(b2); + //System.out.println(b1.setScale(2,BigDecimal.ROUND_HALF_UP)); + fl=b3.setScale(len,BigDecimal.ROUND_HALF_UP).floatValue(); + } + log.error("getfloats"+fl); + }catch(Exception e){ + log.error(demo+"getfloats异常"+e.getMessage()); + } + return fl; + } + + + //浮点型转换 + public static float getfloats1(String demo,String demo1,int len){ + Logger log = Logger.getLogger(BigDecimal.class); + if(len==0){ + len=0; + } + String str=Util.null2String(demo); + String str1=Util.null2String(demo1); + if("".equals(str)||"".equals(str.trim())||"null".equalsIgnoreCase(str.trim())){ + str="0"; + } + if("".equals(str1)||"".equals(str.trim())||"null".equalsIgnoreCase(str1.trim())){ + str1="0"; + } + float fl=0.0f; + //String str=Util.null2String(demo); + try{ + if(str.trim().length()>0){ + BigDecimal b1 = new BigDecimal(str.trim()); + BigDecimal b2 = new BigDecimal(str1.trim()); + BigDecimal b3=b1.add(b2); + //System.out.println(b1.setScale(2,BigDecimal.ROUND_HALF_UP)); + fl=b3.setScale(len,BigDecimal.ROUND_HALF_UP).floatValue(); + } + log.error("getfloats"+fl); + }catch(Exception e){ + log.error(demo+"getfloats异常"+e.getMessage()); + } + return fl; + } + //浮点型转换 金额差 + public static float getfloats2(String demo,String demo1,int len){ + Logger log = Logger.getLogger(BigDecimal.class); + if(len==0){ + len=0; + } + String str=Util.null2String(demo); + String str1=Util.null2String(demo1); + if("".equals(str)||"".equals(str.trim())||"null".equalsIgnoreCase(str.trim())){ + str="0"; + } + if("".equals(str1)||"".equals(str.trim())||"null".equalsIgnoreCase(str1.trim())){ + str1="0"; + } + float fl=0.0f; + //String str=Util.null2String(demo); + try{ + if(str.trim().length()>0){ + BigDecimal b1 = new BigDecimal(str.trim()); + BigDecimal b2 = new BigDecimal(str1.trim()); + BigDecimal b3=b1.subtract(b2); + //System.out.println(b1.setScale(2,BigDecimal.ROUND_HALF_UP)); + fl=b3.setScale(len,BigDecimal.ROUND_HALF_UP).floatValue(); + } + log.error("getfloats"+fl); + }catch(Exception e){ + log.error(demo+"getfloats异常"+e.getMessage()); + } + return fl; + } + public static float getFloat(String val){ + float floatval=0.0f; + if(val==null||"".equals(Util.null2String(val).trim())){ + return 0.0f; + } + try{ + BigDecimal bg = new BigDecimal(val); + floatval=bg.setScale(2, BigDecimal.ROUND_HALF_UP).floatValue(); + }catch(Exception e){ + + } + return floatval; + } + //取特殊科目编号 + public String SpelKm(String zt,String zz,String zb,String lx){ + Logger log = Logger.getLogger(BigDecimal.class); + RecordSet re=new RecordSet(); + String km="";//科目 + re.execute("select * from uf_k3tskm a,uf_k3tskm_dt1 b where a.id=b.mainid and zt='"+zt+"' and zz='"+zz+"' and zb='"+zb+"' and lx='"+lx+"'"); + while(re.next()){ + km=re.getString("km"); + } + return km; + } +} diff --git a/src/main/youhong_ai_jitu_src/com/jet/action/CreateVoucherHk.java b/src/main/youhong_ai_jitu_src/com/jet/action/CreateVoucherHk.java new file mode 100644 index 0000000..cdd107e --- /dev/null +++ b/src/main/youhong_ai_jitu_src/com/jet/action/CreateVoucherHk.java @@ -0,0 +1,570 @@ +package com.jet.action; + +import weaver.soa.workflow.request.RequestInfo; +import weaver.workflow.action.BaseAction; +import weaver.conn.RecordSet; +import com.alibaba.fastjson.JSONArray; +import com.alibaba.fastjson.JSONObject; + +import weaver.hrm.HrmUserVarify; +import weaver.hrm.User; +import weaver.general.BaseBean; +import weaver.general.Util; +import org.apache.log4j.Logger; +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import java.text.SimpleDateFormat; +import java.sql.Connection; +import java.sql.ResultSet; +import java.sql.Statement; +import weaver.general.StaticObj; +import weaver.interfaces.datasource.DataSource; +import weaver.formmode.setup.ModeRightInfo; +import java.sql.Connection; +import java.sql.ResultSet; +import java.sql.SQLException; +import java.sql.Statement; +import weaver.general.StaticObj; +import weaver.interfaces.datasource.DataSource; +import weaver.interfaces.workflow.action.Action; + +import java.math.BigDecimal; +import java.io.BufferedReader; +import java.io.IOException; +import java.io.InputStreamReader; +import java.io.PrintWriter; +import java.net.URL; +import java.net.URLConnection; +import org.apache.http.Header; +import org.apache.http.HttpResponse; +import org.apache.http.HttpStatus; +import org.apache.http.client.HttpClient; +import org.apache.http.client.methods.HttpPost; +import org.apache.http.entity.*; +import org.apache.http.*; +import org.apache.http.util.*; +import org.apache.http.impl.client.DefaultHttpClient; +import org.apache.http.params.CoreConnectionPNames; + +import java.util.ArrayList; +import java.util.Date; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.UUID; +import java.nio.charset.Charset; +import java.io.BufferedReader; +import java.io.ByteArrayOutputStream; +import java.io.FileNotFoundException; +import java.io.IOException; +import java.io.InputStream; +import java.io.InputStreamReader; +import weaver.conn.RecordSetTrans; +import java.io.PrintWriter; +import com.jet.util.*; +import org.json.*; + +public class CreateVoucherHk extends BaseAction{ + @Override + public String execute(RequestInfo requestInfo) { + // TODO Auto-generated method stub + Logger log = Logger.getLogger(JSONObject.class); + RecordSet urlre=new RecordSet(); + String urlsql="select * from uf_urlinfo where ms='model'"; + + urlre.execute(urlsql); + String url=""; + String username=""; + String password1=""; + String dbid1=""; + String uuid1=""; + String password2=""; + while(urlre.next()){ + url=Util.null2String(urlre.getString("url")); + username=Util.null2String(urlre.getString("username")); + password1=Util.null2String(urlre.getString("password")); + dbid1=Util.null2String(urlre.getString("dbid")); + uuid1=Util.null2String(urlre.getString("uuid")); + password2=Util.null2String(urlre.getString("password1")); + } + String baseis=username+":"+password1; + String Queryurl=url+"GlVoucher/"; + Map Hswd=new HashMap();//核算维度对照表 + JSONObject VOUCHER=new JSONObject();//VOUCHER + JSONArray Models=new JSONArray();//ModelS + JSONObject Model=new JSONObject();//Model + Hswd.put("FFLEX4","gys");//供应商 + Hswd.put("FFLEX6","kh");//客户 + Hswd.put("FFLEX7","yg");//员工 + Hswd.put("FFLEX5","bm");//部门 + Hswd.put("FFLEX9","fyxm");//费用项目 + Hswd.put("FFLEX8","wl");//物料 + Hswd.put("FFLEX10","zc");//资产 + Hswd.put("FFLEX12","wlz");//物料组 + Hswd.put("FFLEX13","khz");//客户组 + Map fxHswd=new HashMap();//核算维度对照表 + fxHswd.put("gys","FFLEX4");//供应商 + fxHswd.put("kh","FFLEX6");//客户 + fxHswd.put("yg","FFLEX7");//员工 + fxHswd.put("bm","FFLEX5");//部门 + fxHswd.put("fyxm","FFLEX9");//费用项目 + fxHswd.put("wl","FFLEX8");//物料 + fxHswd.put("zc","FFLEX10");//资产 + fxHswd.put("wlz","FFLEX12");//物料组 + fxHswd.put("khz","FFLEX13");//客户组 + SimpleDateFormat sim=new SimpleDateFormat("yyyy-MM-dd"); + List jlist=new ArrayList();//借方 + List dlist=new ArrayList();//贷方 + String requestid=requestInfo.getRequestid();// + String mainid="";// + String zt="";//账套 + String zz="";//组织 + String zb="";//账薄 + String zzjdhl="";//做账节点汇率 + String bz="";//币种 + String sfxr="";//是否写入 + RecordSet re=new RecordSet(); + String errormess=""; + float zje=0.0f; + //1:借方 2:贷方 + String sql= " select a.sfxr,a.hklx,a.id,a.zt,a.zz,a.zb,b.jfkmbm kmbh,b.jfkmmc kmmc,b.jfje je,b.zy ,'' yg,'' kh,'1' entrylx from formtable_main_25 a,formtable_main_25_dt1 b where a.id=b.mainid and a.requestid='"+requestid+"'"+ + " union all "+ + " select a.sfxr,a.hklx,a.id,a.zt,a.zz,a.zb,b.dfkmbm kmbh,b.dfkmmc kmmc,b.dfje je,b.zy ,b.yg,b.kh,'2' entrylx from formtable_main_25 a,formtable_main_25_dt2 b where a.id=b.mainid and a.requestid='"+requestid+"' "; + log.error(requestid+"CreateVoucherHk"+sql); + re.execute(sql); + JSONArray FEntity=new JSONArray(); + lable1:while(re.next()){ + //拼接科目信息 + sfxr=Util.null2String(re.getString("sfxr")); + String entrylx=Util.null2String(re.getString("entrylx")); + String hklx=Util.null2String(re.getString("hklx"));//还款类型 0:个人 1:客户 + zt=Util.null2String(re.getString("zt")).trim(); + zz=Util.null2String(re.getString("zz")).trim(); + zb=Util.null2String(re.getString("zb")).trim(); + String yg=Util.null2String(re.getString("yg")).trim();//员工 + String kh=Util.null2String(re.getString("kh")).trim();//客户 + zb=Util.null2String(re.getString("zb")).trim(); + JSONObject FEntityDetail=new JSONObject(); + String FEXPLANATION=Util.null2String(re.getString("zy"));//摘要 + FEntityDetail.put("FEXPLANATION",FEXPLANATION); + JSONObject FACCOUNTID=new JSONObject();//科目 FNumber + String demoKm=Util.null2String(re.getString("kmbh")).trim(); + if("".equals(demoKm)){ + errormess="科目编号不能为空";//科目编号不能为空 + break; + }else{ + FACCOUNTID.put("FNumber",demoKm); + } + FEntityDetail.put("FACCOUNTID",FACCOUNTID); + JSONObject FDetailID=new JSONObject();//辅助核算项 FDETAILID__FFLEX10 FNumber + //获取科目的辅助核算项 + if("2".equals(entrylx)){//贷方甚至核算项 + JSONObject Hswdjson=new JSONObject(); + if("0".equals(hklx)){ + if("".equals(yg)){ + errormess="核算维度没有设置值!"; + break lable1; + }else{ + Hswdjson.put("FNumber",yg); + FDetailID.put("FDETAILID__FFLEX7",Hswdjson); + } + + }else{ + if("".equals(kh)){ + //errormess="核算维度没有设置值!"; + //break lable1; + }else{ + //Hswdjson.put("FNumber",kh); + //FDetailID.put("FDETAILID__FFLEX6",Hswdjson); + } + + } + } + + + FEntityDetail.put("FDetailID",FDetailID); + JSONObject FCURRENCYID=new JSONObject();//币别 FNumber + FCURRENCYID.put("FNumber","IDR");//默认印尼盾 + FEntityDetail.put("FCURRENCYID",FCURRENCYID); + JSONObject FEXCHANGERATETYPE=new JSONObject();;//汇率类型 + FEXCHANGERATETYPE.put("FNumber","HLTX01_SYS");//默认 + FEntityDetail.put("FEXCHANGERATETYPE",FEXCHANGERATETYPE); + String FEXCHANGERATE ="1";//汇率 + FEntityDetail.put("FEXCHANGERATE",FEXCHANGERATE); + String FUnitId ="";//单位 + //FEntityDetail.put("FUnitId",FUnitId); + String FPrice="0";//单价 + //FEntityDetail.put("FPrice",FPrice); + String FQty="0";//数量 + //FEntityDetail.put("FQty",FQty); + String FAMOUNTFOR="";//原币金额 + + String FDEBIT="";//借方金额 + String FCREDIT="";//贷方金额 + String FDC="";//借贷方向 + if("1".equals(entrylx)){//借方 + FDEBIT=Util.null2String(re.getString("je")); + FDC="1"; + }else{ + FCREDIT=Util.null2String(re.getString("je")); + FDC="0"; + } + FEntityDetail.put("FCREDIT",FCREDIT); + FEntityDetail.put("FDEBIT",FDEBIT); + FEntityDetail.put("FDC",FDC); + String FSettleTypeID="";//结束方式 FNumber + String FSETTLENO ="";//结算号 + + String FAcctFullName=getKmname(demoKm,zt,zz,zb);//科目全称 + String FACCOUNTNAME=getKmname(demoKm,zt,zz,zb);//科目名称 + //FEntityDetail.put("FAcctFullName",FAcctFullName); + //FEntityDetail.put("FACCOUNTNAME",FACCOUNTNAME); + FEntity.add(FEntityDetail); + } + if(!"".equals(errormess)){ + requestInfo.getRequestManager().setMessageid(errormess); + requestInfo.getRequestManager().setMessage(errormess);//提醒信息id + requestInfo.getRequestManager().setMessagecontent("写入K3系统不成功,系统反馈信息如下:"+errormess);//提醒信息内容 + + return Action.FAILURE_AND_CONTINUE; + } + //out.print("errormess"+errormess); + //out.print("FEntityDetail"+FEntity.toJSONString()); + //设置主数据 + JSONObject FAccountBookID=new JSONObject();//账薄 + FAccountBookID.put("FNumber",zb); + Model.put("FAccountBookID",FAccountBookID); + String FDate=sim.format(new Date()); + Model.put("FDate",FDate); + JSONObject FVOUCHERGROUPID=new JSONObject();//凭证字默认AP + FVOUCHERGROUPID.put("FNumber","PZZ3"); + Model.put("FVOUCHERGROUPID",FVOUCHERGROUPID); + String FYEAR=sim.format(new Date()).split("-")[0];//会计年度 + String FPERIOD =sim.format(new Date()).split("-")[1];//期间 + Model.put("FYEAR",FYEAR); + Model.put("FPERIOD",FPERIOD); + String FDEBITTOTAL=getjfZje(requestid);//借方总金额:FDEBITTOTAL + String FCREDITTOTAL=getdfZje(requestid);//贷方总金额:FCREDITTOTAL + Model.put("FDEBITTOTAL",FDEBITTOTAL); + Model.put("FCREDITTOTAL",FCREDITTOTAL); + String FCreateDate=sim.format(new Date());//创建日期:FCreateDate + JSONObject FACCBOOKORGID=new JSONObject();//核算组织:FACCBOOKORGID + FACCBOOKORGID.put("FNumber",zz); + Model.put("FACCBOOKORGID",FACCBOOKORGID); + //Model.put("FCreateDate",FCreateDate); + String FPRINTTIMES="0";//打印次数:FPRINTTIMES + String FCurrentYear=sim.format(new Date()).split("-")[0];//当前年度:FCurrentYear + String FCurrentPeriod=sim.format(new Date()).split("-")[1];//当前期间:FCurrentPeriod + Model.put("FPRINTTIMES",FPRINTTIMES); + //Model.put("FCurrentYear",FCurrentYear); + //Model.put("FCurrentPeriod",FCurrentPeriod); + Model.put("FEntity",FEntity); + Models.add(Model); + //凭借主数据 + VOUCHER.put("NeedReturnFields","[\"FVOUCHERID\",\"FVOUCHERGROUPNO\"]"); + VOUCHER.put("Model",Model); + VOUCHER.put("IsAutoSubmitAndAudit",true); + log.error(VOUCHER.toJSONString()); + /*开始调用接口 + 1;登陆 + 2;调用接口 + */ + if(VOUCHER!=null&&VOUCHER.size()>0&&("".equals(sfxr)||"1".equals(sfxr))){ + RecordSet updRec=new RecordSet(); + com.jet.util.InvokeHelper.POST_K3CloudURL="http://k3.jet.co.id:8880/k3cloud/"; + String dbid="5d48f604c8361e";//dbid1;//"5d48f604c8361e";//"5a964ecc967246"; + String uuid=uuid1; + String password=password2; + org.json.JSONObject resultjson=null; + int lang=2052; + try { + boolean flag=InvokeHelper.Login(dbid, uuid, password, lang); + //out.print(flag); + if(flag){//登陆成功 + resultjson=com.jet.util.InvokeHelper.Save("GL_VOUCHER",VOUCHER.toJSONString()); + boolean flag1=resultjson.getBoolean("flag"); + String resultstr=resultjson.getString("sResult"); + log.error("resultstr"+resultstr); + if(flag1){ + JSONObject HAHA=JSONObject.parseObject(resultstr); + JSONObject Result=HAHA.getJSONObject("Result"); + JSONObject ResponseStatus=Result.getJSONObject("ResponseStatus"); + boolean IsSuccess=ResponseStatus.getBoolean("IsSuccess"); + if(IsSuccess){ + updRec.execute("update formtable_main_25 set sfxr='0' where requestid='"+requestid+"' "); + String FVOUCHERID=Result.getString("Id"); + String Fv=getFv(Queryurl+""+FVOUCHERID,baseis); + updRec.execute("update formtable_main_25 set pzbh='"+Fv+"' where requestid='"+requestid+"' "); + //out.print("成功"+FVOUCHERID); + }else{ + //out.print("失败"); + requestInfo.getRequestManager().setMessageid("失败"); + requestInfo.getRequestManager().setMessage("失败");//提醒信息id + requestInfo.getRequestManager().setMessagecontent("写入K3系统不成功,系统反馈信息如下:"+HAHA.toString());//提醒信息内容 + + return Action.FAILURE_AND_CONTINUE; + } + }else{ + requestInfo.getRequestManager().setMessageid("失败"); + requestInfo.getRequestManager().setMessage("失败");//提醒信息id + requestInfo.getRequestManager().setMessagecontent("写入K3系统不成功,系统反馈信息如下:"+resultstr.toString());//提醒信息内容 + + return Action.FAILURE_AND_CONTINUE; + } + + } + } catch (Exception e) { + //TODO Auto-generated catch block + log.error("GL_VOUCHER--Exception"+e.getMessage()); + e.printStackTrace(); + } + } + return SUCCESS; + } + +//更具ID获取凭证编号 + public String getFv(String url,String basis)throws Exception{ + String Fv=""; + //out.print("url-"+url+" basis"+basis+" "); + try{ + String result=sendGet(url,"",basis); + // out.print("url-"+url+" basis"+basis+" result"+result); + JSONArray json=JSONArray.parseArray(result); + if(json!=null&&json.size()>0){ + for(int i=0;i> map = connection.getHeaderFields(); + + + for (String key : map.keySet()) { + System.out.println(key + "--->" + map.get(key)); + } + //接收核心返回过来的数据 xml  需要解析 + in =connection.getInputStream(); + byte[] b =getBytes(in); + if(b.length>0){ + result=new String(b); + } + System.out.println(b.length); + } catch (Exception e) { + + System.out.println(e.getMessage()); + e.printStackTrace(); + }finally { + try { + if (in != null) { + in.close(); + } + } catch (Exception e2) { + System.out.println(e2.getMessage()); + e2.printStackTrace(); + } + } + //System.out.println("de"+result); + return result; + } + public static byte[] getBytes(InputStream fis){ + Logger log = Logger.getLogger(Logger.class); + byte[] buffer = null; + try { + //File file = new File(filePath); + //FileInputStream fis = new FileInputStream(file); + ByteArrayOutputStream bos = new ByteArrayOutputStream(1000); + byte[] b = new byte[10000]; + int n; + while ((n = fis.read(b)) != -1) { + bos.write(b, 0, n); + } + fis.close(); + bos.close(); + buffer = bos.toByteArray(); + } catch (FileNotFoundException e) { + e.printStackTrace(); + } catch (IOException e) { + e.printStackTrace(); + } + System.out.println("buffer--->"+buffer.length); + return buffer; + } + //获取借方总金额 + public static String getjfZje(String requestid){ + RecordSet re=new RecordSet(); + String je=""; + String sql="select sum(jfje) jfje from formtable_main_22 a,formtable_main_22_dt4 b where a.id=b.mainid and a.requestid='"+requestid+"'"; + re.execute(sql); + while(re.next()){ + je=re.getString("jfje") ; + } + return je; + } + //获取贷方总金额 + public static String getdfZje(String requestid){ + RecordSet re=new RecordSet(); + String je=""; + String sql="select sum(dfje) dfje from formtable_main_22 a,formtable_main_22_dt5 b where a.id=b.mainid and a.requestid='"+requestid+"'"; + re.execute(sql); + while(re.next()){ + je=re.getString("dfje") ; + } + return je; + } + //获取赋值核算类型 + public String getFzhx(String km,String zt,String zz,String zb,Map Hswd ){ + String FDIMENSION="";//核算维度 + RecordSet re=new RecordSet(); + String sql="select b.FDIMENSION from uf_accountinfo a,uf_accountinfo_dt1 b where a.id=b.mainid and a.zt='"+zt+"' and b.FNUMBER='"+km+"' and b.forgnumber='"+zz+"' and FAcctBookNumber='"+zb+"' "; + //out.print(sql); + re.execute(sql); + while(re.next()){ + String str=Util.null2String(re.getString("FDIMENSION")).trim() ; + String[] FDIMENSIONs=str.split(","); + for(String demo:FDIMENSIONs){ + if(demo!=null&&!"".equals(demo)){ + FDIMENSION=FDIMENSION+Hswd.get(demo)+","; + } + } + } + if(FDIMENSION.endsWith(",")){ + FDIMENSION=FDIMENSION.substring(0,FDIMENSION.length()-1); + } + return FDIMENSION; + } + //insert 事务 + public boolean SynInsert1(List array){ + if(array==null||array.size()<=0){ + return false; + } + Logger log = Logger.getLogger(DataSource.class); + RecordSetTrans RecordSetTrans=new RecordSetTrans(); + RecordSetTrans.setAutoCommit(false); + boolean flag=true; + + try{ + RecordSetTrans.setAutoCommit(false); + // stmt = conn.createStatement(); + for(String str:array){ + //int index =RecordSetTrans.executeUpdate(str); + flag=RecordSetTrans.executeSql(str); + log.error("SynInsert--"+str); + if(!flag){ + //flag=false; + break; + } + } + if(!flag){//事务回滚 + RecordSetTrans.rollback(); + }else{ + RecordSetTrans.commit(); + } + }catch(Exception e){ + log.error("SynInsert--Exception "+e.getMessage()); + flag=false; + } + + return flag; + } + //获取科目名称 + public String getKmname(String km,String zt,String zz,String zb){ + String FNAME="";//核算维度 + RecordSet re=new RecordSet(); + String sql="select b.FNAME from uf_accountinfo a,uf_accountinfo_dt1 b where a.id=b.mainid and a.zt='"+zt+"' and b.FNUMBER='"+km+"' and b.forgnumber='"+zz+"' and FAcctBookNumber='"+zb+"' "; + re.execute(sql); + while(re.next()){ + FNAME=Util.null2String(re.getString("FNAME")); + } + return FNAME; + } + //获取币种的小数位 + public int getXsw(String bz){ + int xsw=0; + RecordSet re=new RecordSet(); + String sql="select * from uf_k3bz where bh='"+bz+"'"; + re.execute(sql); + while(re.next()){ + xsw=Integer.parseInt(Util.null2o(re.getString("xsw"))) ; + } + return xsw; + } + + //浮点型转换 + public static float getfloats(String demo,String demo1,int len){ + Logger log = Logger.getLogger(BigDecimal.class); + if(len==0){ + len=0; + } + String str=Util.null2String(demo); + String str1=Util.null2String(demo1); + if("".equals(str)||"".equals(str.trim())||"null".equalsIgnoreCase(str.trim())){ + return 0; + } + if("".equals(str1)||"".equals(str.trim())||"null".equalsIgnoreCase(str1.trim())){ + str1="1"; + } + float fl=0.0f; + //String str=Util.null2String(demo); + try{ + if(str.trim().length()>0){ + BigDecimal b1 = new BigDecimal(str.trim()); + BigDecimal b2 = new BigDecimal(str1.trim()); + BigDecimal b3=b1.multiply(b2); + //System.out.println(b1.setScale(2,BigDecimal.ROUND_HALF_UP)); + fl=b3.setScale(len,BigDecimal.ROUND_HALF_UP).floatValue(); + } + log.error("getfloats"+fl); + }catch(Exception e){ + log.error(demo+"getfloats异常"+e.getMessage()); + } + return fl; + } + + + //浮点型转换 + public static float getfloats1(String demo,String demo1,int len){ + Logger log = Logger.getLogger(BigDecimal.class); + if(len==0){ + len=0; + } + String str=Util.null2String(demo); + String str1=Util.null2String(demo1); + if("".equals(str)||"".equals(str.trim())||"null".equalsIgnoreCase(str.trim())){ + str="0"; + } + if("".equals(str1)||"".equals(str.trim())||"null".equalsIgnoreCase(str1.trim())){ + str1="0"; + } + float fl=0.0f; + //String str=Util.null2String(demo); + try{ + if(str.trim().length()>0){ + BigDecimal b1 = new BigDecimal(str.trim()); + BigDecimal b2 = new BigDecimal(str1.trim()); + BigDecimal b3=b1.add(b2); + //System.out.println(b1.setScale(2,BigDecimal.ROUND_HALF_UP)); + fl=b3.setScale(len,BigDecimal.ROUND_HALF_UP).floatValue(); + } + log.error("getfloats"+fl); + }catch(Exception e){ + log.error(demo+"getfloats异常"+e.getMessage()); + } + return fl; + } +} diff --git a/src/main/youhong_ai_jitu_src/com/jet/action/CreateVoucherJk.java b/src/main/youhong_ai_jitu_src/com/jet/action/CreateVoucherJk.java new file mode 100644 index 0000000..1e3f5f8 --- /dev/null +++ b/src/main/youhong_ai_jitu_src/com/jet/action/CreateVoucherJk.java @@ -0,0 +1,566 @@ +package com.jet.action; + +import weaver.soa.workflow.request.RequestInfo; +import weaver.workflow.action.BaseAction; +import weaver.conn.RecordSet; +import com.alibaba.fastjson.JSONArray; +import com.alibaba.fastjson.JSONObject; +import weaver.hrm.HrmUserVarify; +import weaver.hrm.User; +import weaver.general.BaseBean; +import weaver.general.Util; +import org.apache.log4j.Logger; +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import java.text.SimpleDateFormat; +import java.sql.Connection; +import java.sql.ResultSet; +import java.sql.Statement; +import weaver.general.StaticObj; +import weaver.interfaces.datasource.DataSource; +import weaver.formmode.setup.ModeRightInfo; +import java.sql.Connection; +import java.sql.ResultSet; +import java.sql.SQLException; +import java.sql.Statement; +import weaver.general.StaticObj; +import weaver.interfaces.datasource.DataSource; +import weaver.interfaces.workflow.action.Action; + +import java.math.BigDecimal; +import java.io.BufferedReader; +import java.io.IOException; +import java.io.InputStreamReader; +import java.io.PrintWriter; +import java.net.URL; +import java.net.URLConnection; +import org.apache.http.Header; +import org.apache.http.HttpResponse; +import org.apache.http.HttpStatus; +import org.apache.http.client.HttpClient; +import org.apache.http.client.methods.HttpPost; +import org.apache.http.entity.*; +import org.apache.http.*; +import org.apache.http.util.*; +import org.apache.http.impl.client.DefaultHttpClient; +import org.apache.http.params.CoreConnectionPNames; + +import java.util.ArrayList; +import java.util.Date; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.UUID; +import java.nio.charset.Charset; +import java.io.BufferedReader; +import java.io.ByteArrayOutputStream; +import java.io.FileNotFoundException; +import java.io.IOException; +import java.io.InputStream; +import java.io.InputStreamReader; +import weaver.conn.RecordSetTrans; +import java.io.PrintWriter; +import com.jet.util.*; +import org.json.*; + +public class CreateVoucherJk extends BaseAction{ + @Override + public String execute(RequestInfo request) { + // TODO Auto-generated method stub + Logger log = Logger.getLogger(JSONObject.class); + RecordSet urlre=new RecordSet(); + String urlsql="select * from uf_urlinfo where ms='model'"; + + urlre.execute(urlsql); + String url=""; + String username=""; + String password1=""; + String dbid1=""; + String uuid1=""; + String password2=""; + while(urlre.next()){ + url=Util.null2String(urlre.getString("url")); + username=Util.null2String(urlre.getString("username")); + password1=Util.null2String(urlre.getString("password")); + dbid1=Util.null2String(urlre.getString("dbid")); + uuid1=Util.null2String(urlre.getString("uuid")); + password2=Util.null2String(urlre.getString("password1")); + } + String baseis=username+":"+password1; + String Queryurl=url+"GlVoucher/"; + Map Hswd=new HashMap();//核算维度对照表 + JSONObject VOUCHER=new JSONObject();//VOUCHER + JSONArray Models=new JSONArray();//ModelS + JSONObject Model=new JSONObject();//Model + Hswd.put("FFLEX4","gys");//供应商 + Hswd.put("FFLEX6","kh");//客户 + Hswd.put("FFLEX7","yg");//员工 + Hswd.put("FFLEX5","bm");//部门 + Hswd.put("FFLEX9","fyxm");//费用项目 + Hswd.put("FFLEX8","wl");//物料 + Hswd.put("FFLEX10","zc");//资产 + Hswd.put("FFLEX12","wlz");//物料组 + Hswd.put("FFLEX13","khz");//客户组 + Map fxHswd=new HashMap();//核算维度对照表 + fxHswd.put("gys","FFLEX4");//供应商 + fxHswd.put("kh","FFLEX6");//客户 + fxHswd.put("yg","FFLEX7");//员工 + fxHswd.put("bm","FFLEX5");//部门 + fxHswd.put("fyxm","FFLEX9");//费用项目 + fxHswd.put("wl","FFLEX8");//物料 + fxHswd.put("zc","FFLEX10");//资产 + fxHswd.put("wlz","FFLEX12");//物料组 + fxHswd.put("khz","FFLEX13");//客户组 + SimpleDateFormat sim=new SimpleDateFormat("yyyy-MM-dd"); + List jlist=new ArrayList();//借方 + List dlist=new ArrayList();//贷方 + String requestid=request.getRequestid();// + String mainid="";// + String zt="";//账套 + String zz="";//组织 + String zb="";//账薄 + String zzjdhl="";//做账节点汇率 + String bz="";//币种 + String sfxr="";//是否写入 + RecordSet re=new RecordSet(); + String errormess=""; + float zje=0.0f; + //1:借方 2:贷方 + String sql= " select a.sfxr,a.jklx,a.id,a.zt,a.zz,a.zb,b.jfkmbm kmbh,b.jfkmmc kmmc,b.jfje je,b.zy ,b.yg ,b.kh ,'1' entrylx from formtable_main_24 a,formtable_main_24_dt1 b where a.id=b.mainid and a.requestid='"+requestid+"'"+ + " union all "+ + " select a.sfxr,a.jklx,a.id,a.zt,a.zz,a.zb,b.dfkmbm kmbh,b.dfkmmc kmmc,b.dfje je,b.zy ,'' yg,'' kh,'2' entrylx from formtable_main_24 a,formtable_main_24_dt2 b where a.id=b.mainid and a.requestid='"+requestid+"' "; + log.error(request+"CreateVoucherJk"+sql); + re.execute(sql); + JSONArray FEntity=new JSONArray(); + lable1:while(re.next()){ + //拼接科目信息 + sfxr=Util.null2String(re.getString("sfxr")); + String entrylx=Util.null2String(re.getString("entrylx")); + String jklx=Util.null2String(re.getString("jklx"));//借款类型 0:个人 1:客户 + zt=Util.null2String(re.getString("zt")).trim(); + zz=Util.null2String(re.getString("zz")).trim(); + zb=Util.null2String(re.getString("zb")).trim(); + String yg=Util.null2String(re.getString("yg")).trim();//员工 + String kh=Util.null2String(re.getString("kh")).trim();//客户 + zb=Util.null2String(re.getString("zb")).trim(); + JSONObject FEntityDetail=new JSONObject(); + String FEXPLANATION=Util.null2String(re.getString("zy"));//摘要 + FEntityDetail.put("FEXPLANATION",FEXPLANATION); + JSONObject FACCOUNTID=new JSONObject();//科目 FNumber + String demoKm=Util.null2String(re.getString("kmbh")).trim(); + if("".equals(demoKm)){ + errormess="科目编号不能为空";//科目编号不能为空 + break; + }else{ + FACCOUNTID.put("FNumber",demoKm); + } + FEntityDetail.put("FACCOUNTID",FACCOUNTID); + JSONObject FDetailID=new JSONObject();//辅助核算项 FDETAILID__FFLEX10 FNumber + //获取科目的辅助核算项 + if("1".equals(entrylx)){//贷方甚至核算项 + JSONObject Hswdjson=new JSONObject(); + if("0".equals(jklx)){ + if("".equals(yg)){ + errormess="核算维度没有设置值!"; + break lable1; + }else{ + Hswdjson.put("FNumber",yg); + FDetailID.put("FDETAILID__FFLEX7",Hswdjson); + } + + }else{ + if("".equals(kh)){ + errormess="核算维度没有设置值!"; + break lable1; + }else{ + Hswdjson.put("FNumber",kh); + FDetailID.put("FDETAILID__FFLEX6",Hswdjson); + } + + } + } + + + FEntityDetail.put("FDetailID",FDetailID); + JSONObject FCURRENCYID=new JSONObject();//币别 FNumber + FCURRENCYID.put("FNumber","IDR");//默认印尼盾 + FEntityDetail.put("FCURRENCYID",FCURRENCYID); + JSONObject FEXCHANGERATETYPE=new JSONObject();;//汇率类型 + FEXCHANGERATETYPE.put("FNumber","HLTX01_SYS");//默认 + FEntityDetail.put("FEXCHANGERATETYPE",FEXCHANGERATETYPE); + String FEXCHANGERATE ="1";//汇率 + FEntityDetail.put("FEXCHANGERATE",FEXCHANGERATE); + String FUnitId ="";//单位 + //FEntityDetail.put("FUnitId",FUnitId); + String FPrice="0";//单价 + //FEntityDetail.put("FPrice",FPrice); + String FQty="0";//数量 + //FEntityDetail.put("FQty",FQty); + String FAMOUNTFOR="";//原币金额 + + String FDEBIT="";//借方金额 + String FCREDIT="";//贷方金额 + String FDC="";//借贷方向 + if("1".equals(entrylx)){//借方 + FDEBIT=Util.null2String(re.getString("je")); + FDC="1"; + }else{ + FCREDIT=Util.null2String(re.getString("je")); + FDC="0"; + } + FEntityDetail.put("FCREDIT",FCREDIT); + FEntityDetail.put("FDEBIT",FDEBIT); + FEntityDetail.put("FDC",FDC); + String FSettleTypeID="";//结束方式 FNumber + String FSETTLENO ="";//结算号 + + String FAcctFullName=getKmname(demoKm,zt,zz,zb);//科目全称 + String FACCOUNTNAME=getKmname(demoKm,zt,zz,zb);//科目名称 + //FEntityDetail.put("FAcctFullName",FAcctFullName); + //FEntityDetail.put("FACCOUNTNAME",FACCOUNTNAME); + FEntity.add(FEntityDetail); + } + if(!"".equals(errormess)){ + request.getRequestManager().setMessageid(errormess); + request.getRequestManager().setMessage(errormess);//提醒信息id + request.getRequestManager().setMessagecontent("写入K3系统不成功,系统反馈信息如下:"+errormess);//提醒信息内容 + + return Action.FAILURE_AND_CONTINUE; + } + //out.print("FEntityDetail"+FEntity.toJSONString()); + //设置主数据 + JSONObject FAccountBookID=new JSONObject();//账薄 + FAccountBookID.put("FNumber",zb); + Model.put("FAccountBookID",FAccountBookID); + String FDate=sim.format(new Date()); + Model.put("FDate",FDate); + JSONObject FVOUCHERGROUPID=new JSONObject();//凭证字默认AP + FVOUCHERGROUPID.put("FNumber","PZZ3"); + Model.put("FVOUCHERGROUPID",FVOUCHERGROUPID); + String FYEAR=sim.format(new Date()).split("-")[0];//会计年度 + String FPERIOD =sim.format(new Date()).split("-")[1];//期间 + Model.put("FYEAR",FYEAR); + Model.put("FPERIOD",FPERIOD); + String FDEBITTOTAL=getjfZje(requestid);//借方总金额:FDEBITTOTAL + String FCREDITTOTAL=getdfZje(requestid);//贷方总金额:FCREDITTOTAL + Model.put("FDEBITTOTAL",FDEBITTOTAL); + Model.put("FCREDITTOTAL",FCREDITTOTAL); + String FCreateDate=sim.format(new Date());//创建日期:FCreateDate + JSONObject FACCBOOKORGID=new JSONObject();//核算组织:FACCBOOKORGID + FACCBOOKORGID.put("FNumber",zz); + Model.put("FACCBOOKORGID",FACCBOOKORGID); + //Model.put("FCreateDate",FCreateDate); + String FPRINTTIMES="0";//打印次数:FPRINTTIMES + String FCurrentYear=sim.format(new Date()).split("-")[0];//当前年度:FCurrentYear + String FCurrentPeriod=sim.format(new Date()).split("-")[1];//当前期间:FCurrentPeriod + Model.put("FPRINTTIMES",FPRINTTIMES); + //Model.put("FCurrentYear",FCurrentYear); + //Model.put("FCurrentPeriod",FCurrentPeriod); + Model.put("FEntity",FEntity); + Models.add(Model); + //凭借主数据 + VOUCHER.put("NeedReturnFields","[\"FVOUCHERID\",\"FVOUCHERGROUPNO\"]"); + VOUCHER.put("Model",Model); + log.error(VOUCHER.toJSONString()); + /*开始调用接口 + 1;登陆 + 2;调用接口 + */ + if(VOUCHER!=null&&VOUCHER.size()>0&&("".equals(sfxr)||"1".equals(sfxr))){ + RecordSet updRec=new RecordSet(); + com.jet.util.InvokeHelper.POST_K3CloudURL="http://k3.jet.co.id:8880/k3cloud/"; + String dbid="5d48f604c8361e";//dbid1;//"5d48f604c8361e";//"5a964ecc967246"; + String uuid=uuid1; + String password=password2; + org.json.JSONObject resultjson=null; + int lang=2052; + try { + boolean flag=InvokeHelper.Login(dbid, uuid, password, lang); + //out.print(flag); + if(flag){//登陆成功 + resultjson=com.jet.util.InvokeHelper.Save("GL_VOUCHER",VOUCHER.toJSONString()); + boolean flag1=resultjson.getBoolean("flag"); + String resultstr=resultjson.getString("sResult"); + log.error("resultstr"+resultstr); + if(flag1){ + JSONObject HAHA=JSONObject.parseObject(resultstr); + JSONObject Result=HAHA.getJSONObject("Result"); + JSONObject ResponseStatus=Result.getJSONObject("ResponseStatus"); + boolean IsSuccess=ResponseStatus.getBoolean("IsSuccess"); + if(IsSuccess){ + updRec.execute("update formtable_main_24 set sfxr='0' where requestid='"+requestid+"' "); + String FVOUCHERID=Result.getString("Id"); + String Fv=getFv(Queryurl+""+FVOUCHERID,baseis); + updRec.execute("update formtable_main_24 set pzbh='"+Fv+"' where requestid='"+requestid+"' "); + //out.print("成功"+FVOUCHERID); + }else{ + request.getRequestManager().setMessageid("失败"); + request.getRequestManager().setMessage("失败");//提醒信息id + request.getRequestManager().setMessagecontent("写入K3系统不成功,系统反馈信息如下:"+HAHA.toString());//提醒信息内容 + + return Action.FAILURE_AND_CONTINUE; + } + }else{ + request.getRequestManager().setMessageid("失败"); + request.getRequestManager().setMessage("失败");//提醒信息id + request.getRequestManager().setMessagecontent("写入K3系统不成功,系统反馈信息如下:"+resultstr.toString());//提醒信息内容 + + return Action.FAILURE_AND_CONTINUE; + } + + } + } catch (Exception e) { + //TODO Auto-generated catch block + log.error("GL_VOUCHER--Exception"+e.getMessage()); + e.printStackTrace(); + } + } + return SUCCESS; + } + //更具ID获取凭证编号 + public String getFv(String url,String basis)throws Exception{ + String Fv=""; + //out.print("url-"+url+" basis"+basis+" "); + try{ + String result=sendGet(url,"",basis); + // out.print("url-"+url+" basis"+basis+" result"+result); + JSONArray json=JSONArray.parseArray(result); + if(json!=null&&json.size()>0){ + for(int i=0;i> map = connection.getHeaderFields(); + + + for (String key : map.keySet()) { + System.out.println(key + "--->" + map.get(key)); + } + //接收核心返回过来的数据 xml  需要解析 + in =connection.getInputStream(); + byte[] b =getBytes(in); + if(b.length>0){ + result=new String(b); + } + System.out.println(b.length); + } catch (Exception e) { + + System.out.println(e.getMessage()); + e.printStackTrace(); + }finally { + try { + if (in != null) { + in.close(); + } + } catch (Exception e2) { + System.out.println(e2.getMessage()); + e2.printStackTrace(); + } + } + //System.out.println("de"+result); + return result; + } + public static byte[] getBytes(InputStream fis){ + Logger log = Logger.getLogger(Logger.class); + byte[] buffer = null; + try { + //File file = new File(filePath); + //FileInputStream fis = new FileInputStream(file); + ByteArrayOutputStream bos = new ByteArrayOutputStream(1000); + byte[] b = new byte[10000]; + int n; + while ((n = fis.read(b)) != -1) { + bos.write(b, 0, n); + } + fis.close(); + bos.close(); + buffer = bos.toByteArray(); + } catch (FileNotFoundException e) { + e.printStackTrace(); + } catch (IOException e) { + e.printStackTrace(); + } + System.out.println("buffer--->"+buffer.length); + return buffer; + } + //获取借方总金额 + public static String getjfZje(String requestid){ + RecordSet re=new RecordSet(); + String je=""; + String sql="select sum(jfje) jfje from formtable_main_22 a,formtable_main_22_dt4 b where a.id=b.mainid and a.requestid='"+requestid+"'"; + re.execute(sql); + while(re.next()){ + je=re.getString("jfje") ; + } + return je; + } + //获取贷方总金额 + public static String getdfZje(String requestid){ + RecordSet re=new RecordSet(); + String je=""; + String sql="select sum(dfje) dfje from formtable_main_22 a,formtable_main_22_dt5 b where a.id=b.mainid and a.requestid='"+requestid+"'"; + re.execute(sql); + while(re.next()){ + je=re.getString("dfje") ; + } + return je; + } + //获取赋值核算类型 + public String getFzhx(String km,String zt,String zz,String zb,Map Hswd ){ + String FDIMENSION="";//核算维度 + RecordSet re=new RecordSet(); + String sql="select b.FDIMENSION from uf_accountinfo a,uf_accountinfo_dt1 b where a.id=b.mainid and a.zt='"+zt+"' and b.FNUMBER='"+km+"' and b.forgnumber='"+zz+"' and FAcctBookNumber='"+zb+"' "; + //out.print(sql); + re.execute(sql); + while(re.next()){ + String str=Util.null2String(re.getString("FDIMENSION")).trim() ; + String[] FDIMENSIONs=str.split(","); + for(String demo:FDIMENSIONs){ + if(demo!=null&&!"".equals(demo)){ + FDIMENSION=FDIMENSION+Hswd.get(demo)+","; + } + } + } + if(FDIMENSION.endsWith(",")){ + FDIMENSION=FDIMENSION.substring(0,FDIMENSION.length()-1); + } + return FDIMENSION; + } + //insert 事务 + public boolean SynInsert1(List array){ + if(array==null||array.size()<=0){ + return false; + } + Logger log = Logger.getLogger(DataSource.class); + RecordSetTrans RecordSetTrans=new RecordSetTrans(); + RecordSetTrans.setAutoCommit(false); + boolean flag=true; + + try{ + RecordSetTrans.setAutoCommit(false); + // stmt = conn.createStatement(); + for(String str:array){ + //int index =RecordSetTrans.executeUpdate(str); + flag=RecordSetTrans.executeSql(str); + log.error("SynInsert--"+str); + if(!flag){ + //flag=false; + break; + } + } + if(!flag){//事务回滚 + RecordSetTrans.rollback(); + }else{ + RecordSetTrans.commit(); + } + }catch(Exception e){ + log.error("SynInsert--Exception "+e.getMessage()); + flag=false; + } + + return flag; + } + //获取科目名称 + public String getKmname(String km,String zt,String zz,String zb){ + String FNAME="";//核算维度 + RecordSet re=new RecordSet(); + String sql="select b.FNAME from uf_accountinfo a,uf_accountinfo_dt1 b where a.id=b.mainid and a.zt='"+zt+"' and b.FNUMBER='"+km+"' and b.forgnumber='"+zz+"' and FAcctBookNumber='"+zb+"' "; + re.execute(sql); + while(re.next()){ + FNAME=Util.null2String(re.getString("FNAME")); + } + return FNAME; + } + //获取币种的小数位 + public int getXsw(String bz){ + int xsw=0; + RecordSet re=new RecordSet(); + String sql="select * from uf_k3bz where bh='"+bz+"'"; + re.execute(sql); + while(re.next()){ + xsw=Integer.parseInt(Util.null2o(re.getString("xsw"))) ; + } + return xsw; + } + + //浮点型转换 + public static float getfloats(String demo,String demo1,int len){ + Logger log = Logger.getLogger(BigDecimal.class); + if(len==0){ + len=0; + } + String str=Util.null2String(demo); + String str1=Util.null2String(demo1); + if("".equals(str)||"".equals(str.trim())||"null".equalsIgnoreCase(str.trim())){ + return 0; + } + if("".equals(str1)||"".equals(str.trim())||"null".equalsIgnoreCase(str1.trim())){ + str1="1"; + } + float fl=0.0f; + //String str=Util.null2String(demo); + try{ + if(str.trim().length()>0){ + BigDecimal b1 = new BigDecimal(str.trim()); + BigDecimal b2 = new BigDecimal(str1.trim()); + BigDecimal b3=b1.multiply(b2); + //System.out.println(b1.setScale(2,BigDecimal.ROUND_HALF_UP)); + fl=b3.setScale(len,BigDecimal.ROUND_HALF_UP).floatValue(); + } + log.error("getfloats"+fl); + }catch(Exception e){ + log.error(demo+"getfloats异常"+e.getMessage()); + } + return fl; + } + + + //浮点型转换 + public static float getfloats1(String demo,String demo1,int len){ + Logger log = Logger.getLogger(BigDecimal.class); + if(len==0){ + len=0; + } + String str=Util.null2String(demo); + String str1=Util.null2String(demo1); + if("".equals(str)||"".equals(str.trim())||"null".equalsIgnoreCase(str.trim())){ + str="0"; + } + if("".equals(str1)||"".equals(str.trim())||"null".equalsIgnoreCase(str1.trim())){ + str1="0"; + } + float fl=0.0f; + //String str=Util.null2String(demo); + try{ + if(str.trim().length()>0){ + BigDecimal b1 = new BigDecimal(str.trim()); + BigDecimal b2 = new BigDecimal(str1.trim()); + BigDecimal b3=b1.add(b2); + //System.out.println(b1.setScale(2,BigDecimal.ROUND_HALF_UP)); + fl=b3.setScale(len,BigDecimal.ROUND_HALF_UP).floatValue(); + } + log.error("getfloats"+fl); + }catch(Exception e){ + log.error(demo+"getfloats异常"+e.getMessage()); + } + return fl; + } + +} diff --git a/src/main/youhong_ai_jitu_src/com/jet/action/CreatehkJD.java b/src/main/youhong_ai_jitu_src/com/jet/action/CreatehkJD.java new file mode 100644 index 0000000..7dcc2b1 --- /dev/null +++ b/src/main/youhong_ai_jitu_src/com/jet/action/CreatehkJD.java @@ -0,0 +1,384 @@ +package com.jet.action; +import java.util.*; +import weaver.soa.workflow.request.RequestInfo; +import weaver.workflow.action.BaseAction; +import weaver.conn.RecordSet; +import com.alibaba.fastjson.JSONArray; +import com.alibaba.fastjson.JSONObject; +import weaver.general.Util; +import org.apache.log4j.Logger; +import weaver.interfaces.datasource.DataSource; +import weaver.interfaces.workflow.action.Action; + +import java.math.BigDecimal; +import java.io.IOException; +import java.net.URL; +import java.net.URLConnection; +import java.io.ByteArrayOutputStream; +import java.io.FileNotFoundException; +import java.io.InputStream; +import weaver.conn.RecordSetTrans; + + +public class CreatehkJD extends BaseAction{ + @Override + public String execute(RequestInfo requestInfo) { + // TODO Auto-generated method stub + //创建还款的借贷方 + //0:贷方现金  + //1:借方还款(职员)  + //2:借方借款(职员) + Logger log = Logger.getLogger(JSONObject.class); + Map Hswd=new HashMap();//核算维度对照表 + Hswd.put("FFLEX4","gys");//供应商 + Hswd.put("FFLEX6","kh");//客户 + Hswd.put("FFLEX7","yg");//员工 + Hswd.put("FFLEX5","bm");//部门 + Hswd.put("FFLEX9","fyxm");//费用项目 + Hswd.put("FFLEX8","wl");//物料 + Hswd.put("FFLEX10","zc");//资产 + Hswd.put("FFLEX12","wlz");//物料组 + Hswd.put("FFLEX13","khz");//客户组 + RecordSet urlre=new RecordSet(); + String urlsql="select * from uf_urlinfo "; + + String url=""; + String username=""; + String password=""; + urlre.execute(urlsql); + while(urlre.next()){ + url=Util.null2String(urlre.getString("url")); + username=Util.null2String(urlre.getString("username")); + password=Util.null2String(urlre.getString("password")); + } + List jlist=new ArrayList();//借方 + List dlist=new ArrayList();//贷方 + String requestid=requestInfo.getRequestid();// + String mainid="";// + String zt="";//账套 + String zz="";//组织 + String zb="";//账薄 + String zzjdhl="";//做账节点汇率 + String bz="";//币种 + String fkyh="";//付款银行 + String je="";//借款金额 + String jklx="";//借款类型 + String dls="";//代理商 + String emp="";//职员 + RecordSet re=new RecordSet(); + String jsql=""; + String dsql=""; + String sql="select * from formtable_main_25 where requestid='"+requestid+"'"; + log.error(requestid+"CreatehkJD"+sql); + re.execute(sql); + while(re.next()){ + mainid=Util.null2String(re.getString("id")).trim(); + zz=Util.null2String(re.getString("zz")).trim();//组织 + zt=Util.null2String(re.getString("zt")).trim();//账套 + zb=Util.null2String(re.getString("zb")).trim();//账薄 + + fkyh=Util.null2String(re.getString("hkzh")).trim();//付款银行 + je=Util.null2String(re.getString("hkje")).trim();//金额 + jklx=Util.null2String(re.getString("hklx")).trim();//借款类型 + dls=Util.null2String(re.getString("dls")).trim();//代理商 + emp=Util.null2String(re.getString("emp")).trim();//职员 + } + //判定借方科目 还款与 借款的 借贷方向 相反 借银行或现金 贷供应商或个人 + String jfkm="";//借方科目 + String jfkmDesc="";//借方科目 + String dfkm="";//贷方科目 + String dfkmDesc="";//贷方科目 + if("0".equals(jklx)){//个人 + //jfkm=SpelKm(zt,zz,zb,"2"); + //if("".equals(fkyh)){//现金 + //dfkm=SpelKm(zt,zz,zb,"0"); + //}else{//转账 + //dfkm=fkyh; + //} + dfkm=SpelKm(zt,zz,zb,"2"); + if("".equals(fkyh)){//现金 + jfkm=SpelKm(zt,zz,zb,"0"); + }else{ + jfkm=fkyh; + } + }else{//代理商 + //if("".equals(fkyh)){//现金 + //dfkm=SpelKm(zt,zz,zb,"0"); + //}else{//转账 + //dfkm=fkyh; + //} + if("".equals(fkyh)){//现金 + jfkm=SpelKm(zt,zz,zb,"0"); + }else{//转账 + jfkm=fkyh; + } + //通过接口 获取贷方科目 + if(!"".equals(dls)){ + String result=sendGet(url+"CusGlbalance/"+dls,"",username+":"+password); + //out.print(result); + Map map=getJSONToMap(result); + dfkm=Util.null2String(map.get("FAcctNumber")); + } + //通过接口 获取贷方科目 + //if(!"".equals(dls)){ + //String result=sendGet(url+"CusGlbalance/"+dls,"",username+":"+password); + //out.print(result); + // Map map=getJSONToMap(result); + //jfkm=Util.null2String(map.get("FAcctNumber")); + //} + } + if(!"".equals(jfkm)){ + jfkmDesc=getKmname(jfkm,zt,zz,zb); + } + if(!"".equals(dfkm)){ + dfkmDesc=getKmname(dfkm,zt,zz,zb); + } + if("0".equals(jklx)){ + dls=""; + } + jlist.add("insert into formtable_main_25_dt1(mainid,jfkmbm,jfkmmc,jfje)values('"+mainid+"','"+jfkm+"','"+jfkmDesc+"','"+je+"')"); + jlist.add("insert into formtable_main_25_dt2(mainid,dfkmbm,dfkmmc,dfje,kh,yg)values('"+mainid+"','"+dfkm+"','"+dfkmDesc+"','"+je+"','"+dls+"','"+emp+"')"); + if(jlist.size()>0){ + log.error(jlist.toString()); + boolean flag=SynInsert1(jlist); + if(!flag){ + requestInfo.getRequestManager().setMessageid("创建借贷失败"); + requestInfo.getRequestManager().setMessage("创建借贷失败");//提醒信息id + requestInfo.getRequestManager().setMessagecontent("创建借贷失败");//提醒信息内容 + + return Action.FAILURE_AND_CONTINUE; + } + //out.print(flag); + } + return SUCCESS; + } + //将JSON 解析成 Map + public Map getJSONToMap(String str){ + Map map=new HashMap(); + try{ + JSONArray jsons=JSONObject.parseArray(str); + if(jsons!=null&&jsons.size()>0){ + JSONObject json=(JSONObject)jsons.get(0); + Set set=json.keySet(); + for(String demo:set){ + map.put(demo,Util.null2String(json.getString(demo))); + } + } + }catch(Exception e){ + + } + return map; + } + //取特殊科目编号 + public String SpelKm(String zt,String zz,String zb,String lx){ + Logger log = Logger.getLogger(BigDecimal.class); + RecordSet re=new RecordSet(); + String km="";//科目 + re.execute("select * from uf_k3tskm a,uf_k3tskm_dt1 b where a.id=b.mainid and zt='"+zt+"' and zz='"+zz+"' and zb='"+zb+"' and lx='"+lx+"'"); + while(re.next()){ + km=re.getString("km"); + } + return km; + } + //获取赋值核算类型 + public String getFzhx(String km,String zt,String zz,String zb,Map Hswd){ + String FDIMENSION="";//核算维度 + RecordSet re=new RecordSet(); + String sql="select b.FDIMENSION from uf_accountinfo a,uf_accountinfo_dt1 b where a.id=b.mainid and a.zt='"+zt+"' and b.FNUMBER='"+km+"' and b.forgnumber='"+zz+"' and FAcctBookNumber='"+zb+"' "; + //out.print(sql); + re.execute(sql); + while(re.next()){ + String str=Util.null2String(re.getString("FDIMENSION")).trim() ; + String[] FDIMENSIONs=str.split(","); + for(String demo:FDIMENSIONs){ + if(demo!=null&&!"".equals(demo)){ + FDIMENSION=FDIMENSION+Hswd.get(FDIMENSION)+","; + } + } + } + return FDIMENSION; + } + //insert 事务 + public boolean SynInsert1(List array){ + if(array==null||array.size()<=0){ + return false; + } + Logger log = Logger.getLogger(DataSource.class); + RecordSetTrans RecordSetTrans=new RecordSetTrans(); + RecordSetTrans.setAutoCommit(false); + boolean flag=true; + + try{ + RecordSetTrans.setAutoCommit(false); + // stmt = conn.createStatement(); + for(String str:array){ + //int index =RecordSetTrans.executeUpdate(str); + flag=RecordSetTrans.executeSql(str); + log.error("SynInsert--"+str); + if(!flag){ + //flag=false; + break; + } + } + if(!flag){//事务回滚 + RecordSetTrans.rollback(); + }else{ + RecordSetTrans.commit(); + } + }catch(Exception e){ + log.error("SynInsert--Exception "+e.getMessage()); + flag=false; + } + + return flag; + } + //获取科目名称 + public String getKmname(String km,String zt,String zz,String zb){ + String FNAME="";//核算维度 + RecordSet re=new RecordSet(); + String sql="select b.FNAME from uf_accountinfo a,uf_accountinfo_dt1 b where a.id=b.mainid and a.zt='"+zt+"' and b.FNUMBER='"+km+"' and b.forgnumber='"+zz+"' and FAcctBookNumber='"+zb+"' "; + re.execute(sql); + while(re.next()){ + FNAME=Util.null2String(re.getString("FNAME")); + } + return FNAME; + } + //获取币种的小数位 + public int getXsw(String bz){ + int xsw=0; + RecordSet re=new RecordSet(); + String sql="select * from uf_k3bz where bh='"+bz+"'"; + re.execute(sql); + while(re.next()){ + xsw=Integer.parseInt(Util.null2o(re.getString("xsw"))) ; + } + return xsw; + } + + //浮点型转换 + public static float getfloats(String demo,String demo1,int len){ + Logger log = Logger.getLogger(BigDecimal.class); + if(len==0){ + len=0; + } + String str=Util.null2String(demo); + String str1=Util.null2String(demo1); + if("".equals(str)||"".equals(str.trim())||"null".equalsIgnoreCase(str.trim())){ + return 0; + } + if("".equals(str1)||"".equals(str.trim())||"null".equalsIgnoreCase(str1.trim())){ + str1="1"; + } + float fl=0.0f; + //String str=Util.null2String(demo); + try{ + if(str.trim().length()>0){ + BigDecimal b1 = new BigDecimal(str.trim()); + BigDecimal b2 = new BigDecimal(str1.trim()); + BigDecimal b3=b1.multiply(b2); + //System.out.println(b1.setScale(2,BigDecimal.ROUND_HALF_UP)); + fl=b3.setScale(len,BigDecimal.ROUND_HALF_UP).floatValue(); + } + log.error("getfloats"+fl); + }catch(Exception e){ + log.error(demo+"getfloats异常"+e.getMessage()); + } + return fl; + } + + + //浮点型转换 + public static float getfloats1(String demo,String demo1,int len){ + Logger log = Logger.getLogger(BigDecimal.class); + if(len==0){ + len=0; + } + String str=Util.null2String(demo); + String str1=Util.null2String(demo1); + if("".equals(str)||"".equals(str.trim())||"null".equalsIgnoreCase(str.trim())){ + str="0"; + } + if("".equals(str1)||"".equals(str.trim())||"null".equalsIgnoreCase(str1.trim())){ + str1="0"; + } + float fl=0.0f; + //String str=Util.null2String(demo); + try{ + if(str.trim().length()>0){ + BigDecimal b1 = new BigDecimal(str.trim()); + BigDecimal b2 = new BigDecimal(str1.trim()); + BigDecimal b3=b1.add(b2); + //System.out.println(b1.setScale(2,BigDecimal.ROUND_HALF_UP)); + fl=b3.setScale(len,BigDecimal.ROUND_HALF_UP).floatValue(); + } + log.error("getfloats"+fl); + }catch(Exception e){ + log.error(demo+"getfloats异常"+e.getMessage()); + } + return fl; + } + public static String sendGet(String url, String param,String basis) { + String result = ""; + InputStream in = null; + try { + String urlNameString = url ; + URL realUrl = new URL(urlNameString); + URLConnection connection = realUrl.openConnection(); + String auth="JNT:JNT2019"; + String code = new sun.misc.BASE64Encoder().encode(auth.getBytes()); + connection.setRequestProperty("Authorization", "Basic " + code); + connection.connect(); + Map> map = connection.getHeaderFields(); + + + for (String key : map.keySet()) { + System.out.println(key + "--->" + map.get(key)); + } + //接收核心返回过来的数据 xml  需要解析 + in =connection.getInputStream(); + byte[] b =getBytes(in); + if(b.length>0){ + result=new String(b); + } + System.out.println(b.length); + } catch (Exception e) { + + System.out.println(e.getMessage()); + e.printStackTrace(); + }finally { + try { + if (in != null) { + in.close(); + } + } catch (Exception e2) { + System.out.println(e2.getMessage()); + e2.printStackTrace(); + } + } + //System.out.println("de"+result); + return result; + } + public static byte[] getBytes(InputStream fis){ + Logger log = Logger.getLogger(Logger.class); + byte[] buffer = null; + try { + //File file = new File(filePath); + //FileInputStream fis = new FileInputStream(file); + ByteArrayOutputStream bos = new ByteArrayOutputStream(1000); + byte[] b = new byte[10000]; + int n; + while ((n = fis.read(b)) != -1) { + bos.write(b, 0, n); + } + fis.close(); + bos.close(); + buffer = bos.toByteArray(); + } catch (FileNotFoundException e) { + e.printStackTrace(); + } catch (IOException e) { + e.printStackTrace(); + } + System.out.println("buffer--->"+buffer.length); + return buffer; + } +} diff --git a/src/main/youhong_ai_jitu_src/com/jet/action/UpdateContractByPayAction.java b/src/main/youhong_ai_jitu_src/com/jet/action/UpdateContractByPayAction.java new file mode 100644 index 0000000..0201164 --- /dev/null +++ b/src/main/youhong_ai_jitu_src/com/jet/action/UpdateContractByPayAction.java @@ -0,0 +1,66 @@ +package com.jet.action; + + +import weaver.conn.RecordSet; +import weaver.general.BaseBean; +import weaver.general.Util; +import weaver.interfaces.workflow.action.Action; +import weaver.soa.workflow.request.RequestInfo; +import selfdev.util.base.BaseUtil; +import selfdev.util.log.LogTool; + +/** + * 付款申请流程归档时更新合同台账数据 + * @author KangMD + * 2019-12-06 + */ +public class UpdateContractByPayAction extends BaseBean implements Action { + + public String execute(RequestInfo ri) { + LogTool log=new LogTool("/log/selfdev/action", false); + //获取requestid + String requestid=ri.getRequestid(); + String workflowid=ri.getWorkflowid(); + //获取用户语言 + int language=ri.getRequestManager().getUser().getLanguage(); + log.writeLog("language---------->"+language); + String workflowname=BaseUtil.getBaseInfoByParm("workflowname", "workflow_base", "id", workflowid, ""); + log.writeLog("---------------"+workflowname+"开始写入K3生成付款单-------------requestId:" + requestid); + //获取表名 + String tablename=BaseUtil.getBaseInfoByParm("tablename", "workflow_bill", "1", "1", " and id in (select formid from workflow_base where id="+workflowid+")");; + RecordSet rs=new RecordSet(); + try { + String mainid="";//主键ID + String sfyht="";//是否有合同 + double bcfkje=0;//本次付款金额 + String htxx="";//相关合同 + String sql="select * from "+tablename+" where requestid="+requestid; + rs.execute(sql); + while(rs.next()){ + mainid=Util.null2String(rs.getString("id")); + sfyht=Util.null2String(rs.getString("sfyht")); + bcfkje=Double.parseDouble(Util.null2o(rs.getString("bcfkje")).replaceAll(",", "")); + htxx=Util.null2String(rs.getString("htxx")); + } + //有合同才需更新合同台账 + if("0".equals(sfyht)){ + //更新至建模的批次明细中 + sql="update uf_httz_dt1 a set (yfkje,fkzt)=(select TO_CHAR(to_number(replace(nvl(a.yfkje,0),',',''))+to_number(replace(nvl(b.bcfkje,0),',','')),'FM999,999,999,999,999,999,990.00'),(case when to_number(replace(nvl(a.yfkje,0),',',''))+to_number(replace(nvl(b.bcfkje,0),',',''))=to_number(replace(nvl(a.fkje,0),',','')) then 0 else 2 end) from "+tablename+"_dt5 b where a.id=b.fkpc and b.mainid='"+mainid+"') where a.mainid='"+htxx+"'"; + log.writeLog("流程中支付金额更新至合同建模明细中的金额SQL---------->"+sql); + rs.execute(sql); + //更新至建模的主表中 + sql="update uf_httz a set yfkje=TO_CHAR(to_number(replace(nvl(a.yfkje,0),',',''))+"+bcfkje+",'FM999,999,999,999,999,999,990.00'),fkzt=(case when to_number(replace(nvl(a.yfkje,0),',',''))+"+bcfkje+"=to_number(replace(nvl(a.htzje,0),',','')) then 0 else 2 end) where id='"+htxx+"'"; + log.writeLog("流程中支付金额更新至合同建模主表中的金额SQL---------->"+sql); + rs.execute(sql); + + } + } catch (Exception e) { + e.printStackTrace(); + String error_msg="付款流程写入K3失败,错误信息为:------>"+e.toString(); + ri.getRequestManager().setMessage("111100"); + ri.getRequestManager().setMessagecontent(error_msg); + return "0"; + } + return SUCCESS; + } +} diff --git a/src/main/youhong_ai_jitu_src/com/jet/action/YyApply.java b/src/main/youhong_ai_jitu_src/com/jet/action/YyApply.java new file mode 100644 index 0000000..6d07839 --- /dev/null +++ b/src/main/youhong_ai_jitu_src/com/jet/action/YyApply.java @@ -0,0 +1,45 @@ +package com.jet.action; + +import weaver.soa.workflow.request.RequestInfo; +import weaver.workflow.action.BaseAction; +import weaver.conn.RecordSet; +import weaver.general.Util; + +import com.working.util.LogTool; +import com.working.util.WorkflowUtil; + +/** + * 02-用印申请-J&T中国 + * @author lwt + * + */ +public class YyApply extends BaseAction{ + + LogTool log = new LogTool("/log/feeChina/",false); + + @Override + public String execute(RequestInfo requestInfo) { + // TODO Auto-generated method stub + String requestid = requestInfo.getRequestid(); + RecordSet rs = new RecordSet(); + RecordSet rs1 = new RecordSet(); + String mainTable = WorkflowUtil.getMainTable(requestid); + String detail1Table = mainTable + "_dt1"; + int mainId = requestInfo.getRequestManager().getBillid();//主表数据id + rs.execute("select * from " + detail1Table + " where mainid = '" + mainId + "' order by id desc"); + String sfwjMain = "1";//主表是否外借字段 + String sfwj = "";//明细表1是否外借字段 + while (rs.next()) { + sfwj = Util.null2String(rs.getString("SFWJ")); + if (!sfwj.isEmpty()) { + if (sfwj.equals("0")) {//团队活动费 + sfwjMain = "0";//主表是否外借字段 + } + } + } + rs1.execute("update " + mainTable + " set sfwj = '" +sfwjMain+ "' where requestid = '" + requestid +"'"); + + return SUCCESS; + } + +} diff --git a/src/main/youhong_ai_jitu_src/com/jet/k3/K3Connect.java b/src/main/youhong_ai_jitu_src/com/jet/k3/K3Connect.java new file mode 100644 index 0000000..03a9c07 --- /dev/null +++ b/src/main/youhong_ai_jitu_src/com/jet/k3/K3Connect.java @@ -0,0 +1,45 @@ +package com.jet.k3; + + +import kingdee.bos.webapi.client.K3CloudApiClient; +import selfdev.util.log.LogTool; +import weaver.file.Prop; +import weaver.general.Util; + + +/** + * K3连接连接配置 + * @author + */ +public class K3Connect { + //日志类 + public static LogTool log=new LogTool("/log/selfdev", false); + //当前系统模式 + public static String mode=Util.null2String(Prop.getPropValue("DevToK3_jet", "mode")); + //获取K3 连接参数 + public static String K3CloudURL =Util.null2String(Prop.getPropValue("DevToK3_jet", mode+"_K3CloudURL")); + public static String dbId = Util.null2String(Prop.getPropValue("DevToK3_jet", mode+"_dbId")); + public static String uid = Util.null2String(Prop.getPropValue("DevToK3_jet", mode+"_uid")); + public static String pwd = Util.null2String(Prop.getPropValue("DevToK3_jet", mode+"_pwd")); + public static int lang = Integer.parseInt(Util.null2o(Prop.getPropValue("DevToK3_jet", mode+"_lang"))); + + /** + * 获取K3连接 + * @return + */ + public static K3CloudApiClient connect(){ + K3CloudApiClient client =null; + try { + client = new K3CloudApiClient(K3CloudURL); + boolean result = client.login(dbId, uid, pwd, lang); + if(!result){ + log.writeLog("连接K3失败,可能是用户名或密码错误!"); + client =null; + } + } catch (Exception e) { + log.writeLog("连接K3失败, 错误信息为: " + e.toString()); + client =null; + } + return client; + } +} diff --git a/src/main/youhong_ai_jitu_src/com/jet/schedule/syn/SynAccountBookToOA.java b/src/main/youhong_ai_jitu_src/com/jet/schedule/syn/SynAccountBookToOA.java new file mode 100644 index 0000000..2f0c1b1 --- /dev/null +++ b/src/main/youhong_ai_jitu_src/com/jet/schedule/syn/SynAccountBookToOA.java @@ -0,0 +1,115 @@ +package com.jet.schedule.syn; + +import java.util.List; +import java.util.Map; + +import com.jet.k3.K3Connect; + +import kingdee.bos.webapi.client.K3CloudApiClient; + +import selfdev.util.base.BaseUtil; +import selfdev.util.base.TimeCommonUtil; + +import selfdev.util.log.LogTool; +import weaver.conn.RecordSet; +import weaver.file.Prop; +import weaver.general.Util; +import weaver.interfaces.schedule.BaseCronJob; +import weaver.interfaces.schedule.CronJob; + + +/** + * 定时将K3中账簿数据同步至OA建模表 + * @author KangMD + * 2019-11-14 + */ +public class SynAccountBookToOA extends BaseCronJob implements CronJob { + + public static RecordSet rs=new RecordSet(); + public static LogTool log=new LogTool("/log/selfdev/syn", false); + + public void execute(){ + long startStamp=System.currentTimeMillis(); + log.writeLog("*******同步K3账簿开始start:(" + weaver.general.TimeUtil.getCurrentTimeString() + ")"); + try { + //连接K3 + K3CloudApiClient client =K3Connect.connect(); + if(client!=null){ + String sql=""; + String now=TimeCommonUtil.obtainDate(0);//获取当前系统日期yyyy-MM-dd HH:mm:ss格式 + String currDate = now.substring(0,10);//当前系统日期 + String currTime = now.substring(11);//当前系统时间 + //获取账簿key-value MAP值,主键为账簿内码ID + Map zb_map=BaseUtil.getMapKeyValueInfoByParm("uf_zb_K3","","FBookId","FNumber"); + //当前系统模式 + String mode=Util.null2String(Prop.getPropValue("DevToK3_jet", "mode")); + //账簿建模ID + String modeid_zb=Util.null2String(Prop.getPropValue("DevToK3_jet", mode+"_modeid_zb")); + + //分页查询 + for(int t=0;t<1000;t++){ + String sContent = "{\"FormId\":\"BD_ACCOUNTBOOK\"," + // 账簿formid + +"\"TopRowCount\":0," + // 最多允许查询的数量,0或者不要此属性表示不限制 + +"\"Limit\":2000," + // 分页取数每页允许获取的数据,最大不能超过2000 + +"\"StartRow\":"+(2000*t)+"," + //分页取数开始行索引,从0开始,例如每页10行数据,第2页开始是10,第3页开始是20 + //""FilterString":"FMaterialId.FNumber like 'HG_TEST%'","+// 过滤条件 + //""FilterString":"FBillNo='CGDD000008'","+// 过滤条件 + +"\"FilterString\":\"FNumber!=''\"," //过滤条件 编码不为空值 + //+"\"OrderString\":\"FGoodsNO ASC\","// 排序条件 + //获取账簿基础信息 组织ID、内码、名称、编码、科目表 + +"\"FieldKeys\":\"FUseOrgId,FBookId,FName,FNumber,FACCTTABLEID\"}"; + //获取账簿列表 + List> sResult = client.executeBillQuery(sContent); + int rows=sResult.size(); + //已经没有数据了,跳出循环 + if(rows==0){ + break; + }else{ + for(int k=0;k" + sql); + }else{ + //插入SQL + sql="insert into uf_zb_K3(formmodeid,modedatacreater,modedatacreatertype,modedatacreatedate,modedatacreatetime," + + "FUseOrgId,FBookId,FName,FAcctTableId,FNumber) values(" + + "'"+modeid_zb+"','1','0','"+currDate+"','"+currTime+"'," + + "'"+FUseOrgId+"','"+FBookId+"','"+FName+"','"+FAcctTableId+"'," + + "'"+FNumber+"')"; + log.writeLog("账簿数据插入SQL------->" + sql); + //将新增的数据加入至MAP中 + zb_map.put(FBookId, FNumber); + } + rs.execute(sql); + } + } + } + } + + } catch (Exception e) { + // TODO Auto-generated catch block + e.printStackTrace(); + log.writeLog("获取K3账簿数据错误,错误信息为------->" + e.toString()); + } + //获取同步耗时 + long hs = (System.currentTimeMillis() - startStamp)/1000; + log.writeLog("*******同步K3账簿数据完成end:(" + weaver.general.TimeUtil.getCurrentTimeString() + "),耗时:"+hs+"秒"); + } +} diff --git a/src/main/youhong_ai_jitu_src/com/jet/schedule/syn/SynAccountToOA.java b/src/main/youhong_ai_jitu_src/com/jet/schedule/syn/SynAccountToOA.java new file mode 100644 index 0000000..1e27501 --- /dev/null +++ b/src/main/youhong_ai_jitu_src/com/jet/schedule/syn/SynAccountToOA.java @@ -0,0 +1,113 @@ +package com.jet.schedule.syn; + +import java.util.List; +import java.util.Map; + +import com.jet.k3.K3Connect; + +import kingdee.bos.webapi.client.K3CloudApiClient; + +import selfdev.util.base.BaseUtil; +import selfdev.util.base.TimeCommonUtil; + +import selfdev.util.log.LogTool; +import weaver.conn.RecordSet; +import weaver.file.Prop; +import weaver.general.Util; +import weaver.interfaces.schedule.BaseCronJob; +import weaver.interfaces.schedule.CronJob; + + +/** + * 定时将K3中科目数据同步至OA建模表 + * @author KangMD + * 2019-08-28 + */ +public class SynAccountToOA extends BaseCronJob implements CronJob { + + public static RecordSet rs=new RecordSet(); + public static LogTool log=new LogTool("/log/selfdev", false); + + public void execute(){ + long startStamp=System.currentTimeMillis(); + log.writeLog("*******同步K3科目开始start:(" + weaver.general.TimeUtil.getCurrentTimeString() + ")"); + try { + //连接K3 + K3CloudApiClient client =K3Connect.connect(); + if(client!=null){ + String sql=""; + String now=TimeCommonUtil.obtainDate(0);//获取当前系统日期yyyy-MM-dd HH:mm:ss格式 + String currDate = now.substring(0,10);//当前系统日期 + String currTime = now.substring(11);//当前系统时间 + //获取科目key-value MAP值,主键为科目内码ID + Map km_map=BaseUtil.getMapKeyValueInfoByParm("uf_km_k3","","FAcctId","FNumber"); + //当前系统模式 + String mode=Util.null2String(Prop.getPropValue("DevToK3_winsun", "mode")); + //科目建模ID + String modeid_km=Util.null2String(Prop.getPropValue("DevToK3_winsun", mode+"_modeid_km")); + + //分页查询 + for(int t=0;t<1000;t++){ + String sContent = "{\"FormId\":\"BD_Account\"," + // 科目formid + +"\"TopRowCount\":0," + // 最多允许查询的数量,0或者不要此属性表示不限制 + +"\"Limit\":2000," + // 分页取数每页允许获取的数据,最大不能超过2000 + +"\"StartRow\":"+(2000*t)+"," + //分页取数开始行索引,从0开始,例如每页10行数据,第2页开始是10,第3页开始是20 + //""FilterString":"FMaterialId.FNumber like 'HG_TEST%'","+// 过滤条件 + //""FilterString":"FBillNo='CGDD000008'","+// 过滤条件 + +"\"FilterString\":\"FNumber!=''\"," //过滤条件 编码不为空值 + //+"\"OrderString\":\"FGoodsNO ASC\","// 排序条件 + //获取科目基础信息 组织ID、内码、名称、编码 + +"\"FieldKeys\":\"FCreateOrgId,FAcctId,FName,FNumber\"}"; + //获取科目列表 + List> sResult = client.executeBillQuery(sContent); + + int rows=sResult.size(); + //已经没有数据了,跳出循环 + if(rows==0){ + break; + }else{ + for(int k=0;k" + sql); + }else{ + //插入SQL + sql="insert into uf_km_k3(formmodeid,modedatacreater,modedatacreatertype,modedatacreatedate,modedatacreatetime," + + "FCreateOrgId,FAcctId,FName,FNumber) values(" + + "'"+modeid_km+"','1','0','"+currDate+"','"+currTime+"'," + + "'"+FCreateOrgId+"','"+FAcctId+"','"+FName+"','"+FNumber+"')"; + log.writeLog("科目数据插入SQL------->" + sql); + //将新增的数据加入至MAP中 + km_map.put(FAcctId, FNumber); + } + rs.execute(sql); + } + } + } + } + + } catch (Exception e) { + // TODO Auto-generated catch block + e.printStackTrace(); + log.writeLog("获取K3科目数据错误,错误信息为------->" + e.toString()); + } + //获取同步耗时 + long hs = (System.currentTimeMillis() - startStamp)/1000; + log.writeLog("*******同步K3科目数据完成end:(" + weaver.general.TimeUtil.getCurrentTimeString() + "),耗时:"+hs+"秒"); + } +} diff --git a/src/main/youhong_ai_jitu_src/com/jet/schedule/syn/SynBankToOA.java b/src/main/youhong_ai_jitu_src/com/jet/schedule/syn/SynBankToOA.java new file mode 100644 index 0000000..e585431 --- /dev/null +++ b/src/main/youhong_ai_jitu_src/com/jet/schedule/syn/SynBankToOA.java @@ -0,0 +1,110 @@ +package com.jet.schedule.syn; + +import java.util.List; +import java.util.Map; + +import kingdee.bos.webapi.client.K3CloudApiClient; +import selfdev.util.base.BaseUtil; +import selfdev.util.base.TimeCommonUtil; +import selfdev.util.log.LogTool; +import weaver.conn.RecordSet; +import weaver.file.Prop; +import weaver.general.Util; +import weaver.interfaces.schedule.BaseCronJob; +import weaver.interfaces.schedule.CronJob; + +import com.jet.k3.K3Connect; + + +/** + * 定时将K3中银行数据同步至OA建模表 + * @author KangMD + * 2019-08-28 + */ +public class SynBankToOA extends BaseCronJob implements CronJob { + + public static RecordSet rs=new RecordSet(); + public static LogTool log=new LogTool("/log/selfdev", false); + + public void execute(){ + long startStamp=System.currentTimeMillis(); + log.writeLog("*******同步K3银行开始start:(" + weaver.general.TimeUtil.getCurrentTimeString() + ")"); + try { + //连接K3 + K3CloudApiClient client =K3Connect.connect(); + if(client!=null){ + String sql=""; + String now=TimeCommonUtil.obtainDate(0);//获取当前系统日期yyyy-MM-dd HH:mm:ss格式 + String currDate = now.substring(0,10);//当前系统日期 + String currTime = now.substring(11);//当前系统时间 + //获取银行key-value MAP值,主键为银行内码ID + Map yh_map=BaseUtil.getMapKeyValueInfoByParm("uf_yh_k3","","FBankId","FNumber"); + //当前系统模式 + String mode=Util.null2String(Prop.getPropValue("DevToK3_winsun", "mode")); + //银行建模ID + String modeid_yh=Util.null2String(Prop.getPropValue("DevToK3_winsun", mode+"_modeid_yh")); + + //分页查询 + for(int t=0;t<1000;t++){ + String sContent = "{\"FormId\":\"BD_BANK\"," + // 银行formid + +"\"TopRowCount\":0," + // 最多允许查询的数量,0或者不要此属性表示不限制 + +"\"Limit\":2000," + // 分页取数每页允许获取的数据,最大不能超过2000 + +"\"StartRow\":"+(2000*t)+"," + //分页取数开始行索引,从0开始,例如每页10行数据,第2页开始是10,第3页开始是20 + //""FilterString":"FMaterialId.FNumber like 'HG_TEST%'","+// 过滤条件 + //""FilterString":"FBillNo='CGDD000008'","+// 过滤条件 + +"\"FilterString\":\"FNumber!=''\"," //过滤条件 编码不为空值 + //+"\"OrderString\":\"FGoodsNO ASC\","// 排序条件 + //获取银行基础信息 组织ID、内码、名称、编码 + +"\"FieldKeys\":\"FCreateOrgId,FBankId,FName,FNumber\"}"; + //获取银行列表 + List> sResult = client.executeBillQuery(sContent); + int rows=sResult.size(); + //已经没有数据了,跳出循环 + if(rows==0){ + break; + }else{ + for(int k=0;k" + sql); + }else{ + //插入SQL + sql="insert into uf_yh_k3(formmodeid,modedatacreater,modedatacreatertype,modedatacreatedate,modedatacreatetime," + + "FCreateOrgId,FBankId,FName,FNumber) values(" + + "'"+modeid_yh+"','1','0','"+currDate+"','"+currTime+"'," + + "'"+FCreateOrgId+"','"+FBankId+"','"+FName+"','"+FNumber+"')"; + log.writeLog("银行数据插入SQL------->" + sql); + //将新增的数据加入至MAP中 + yh_map.put(FBankId, FNumber); + } + rs.execute(sql); + } + } + } + } + + } catch (Exception e) { + // TODO Auto-generated catch block + e.printStackTrace(); + log.writeLog("获取K3银行数据错误,错误信息为------->" + e.toString()); + } + //获取同步耗时 + long hs = (System.currentTimeMillis() - startStamp)/1000; + log.writeLog("*******同步K3银行数据完成end:(" + weaver.general.TimeUtil.getCurrentTimeString() + "),耗时:"+hs+"秒"); + } +} diff --git a/src/main/youhong_ai_jitu_src/com/jet/schedule/syn/SynCustomerToOA.java b/src/main/youhong_ai_jitu_src/com/jet/schedule/syn/SynCustomerToOA.java new file mode 100644 index 0000000..ca2adb5 --- /dev/null +++ b/src/main/youhong_ai_jitu_src/com/jet/schedule/syn/SynCustomerToOA.java @@ -0,0 +1,133 @@ +package com.jet.schedule.syn; + +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +import com.jet.k3.K3Connect; + +import kingdee.bos.webapi.client.K3CloudApiClient; + +import selfdev.util.base.BaseUtil; +import selfdev.util.base.TimeCommonUtil; + +import selfdev.util.log.LogTool; +import weaver.conn.RecordSet; +import weaver.file.Prop; +import weaver.general.Util; +import weaver.interfaces.schedule.BaseCronJob; +import weaver.interfaces.schedule.CronJob; + + +/** + * 定时将K3中客户数据同步至OA建模表 + * @author KangMD + * 2019-08-28 + */ +public class SynCustomerToOA extends BaseCronJob implements CronJob { + + public static RecordSet rs=new RecordSet(); + public static LogTool log=new LogTool("/log/selfdev", false); + + public void execute(){ + long startStamp=System.currentTimeMillis(); + log.writeLog("*******同步K3客户开始start:(" + weaver.general.TimeUtil.getCurrentTimeString() + ")"); + try { + //连接K3 + K3CloudApiClient client =K3Connect.connect(); + if(client!=null){ + String sql=""; + String now=TimeCommonUtil.obtainDate(0);//获取当前系统日期yyyy-MM-dd HH:mm:ss格式 + String currDate = now.substring(0,10);//当前系统日期 + String currTime = now.substring(11);//当前系统时间 + //获取客户key-value MAP值,主键为客户内码ID + Map kh_map=BaseUtil.getMapKeyValueInfoByParm("uf_kh_k3","","FCustId","FNumber"); + //保存已同步客户key-value MAP值,主键为客户内码ID + Map ts_map=new HashMap(); + //当前系统模式 + String mode=Util.null2String(Prop.getPropValue("DevToK3_winsun", "mode")); + //客户建模ID + String modeid_kh=Util.null2String(Prop.getPropValue("DevToK3_winsun", mode+"_modeid_kh")); + + //分页查询 + for(int t=0;t<1000;t++){ + String sContent = "{\"FormId\":\"BD_Customer\"," + // 客户formid + +"\"TopRowCount\":0," + // 最多允许查询的数量,0或者不要此属性表示不限制 + +"\"Limit\":2000," + // 分页取数每页允许获取的数据,最大不能超过2000 + +"\"StartRow\":"+(2000*t)+"," + //分页取数开始行索引,从0开始,例如每页10行数据,第2页开始是10,第3页开始是20 + //""FilterString":"FMaterialId.FNumber like 'HG_TEST%'","+// 过滤条件 + //""FilterString":"FBillNo='CGDD000008'","+// 过滤条件 + +"\"FilterString\":\"FNumber!=''\"," //过滤条件 编码不为空值 + //+"\"OrderString\":\"FCustId ASC\","// 排序条件 + //获取客户基础信息 组织ID、内码、名称、编码、银行账号、开户银行、账户名称 + +"\"FieldKeys\":\"FUseOrgId,FCustId,FName,FNumber,FBankCode,FOpenBankName,FAccountName\"}"; + //获取客户列表 + List> sResult = client.executeBillQuery(sContent); + int rows=sResult.size(); + //已经没有数据了,跳出循环 + if(rows==0){ + break; + }else{ + for(int k=0;k" + FCustId); + continue; + } + + //判断当前记录是否已同步,若已同步则更新,未同步则插入 + if(kh_map.containsKey(FCustId)){ + //更新SQL + sql="update uf_kh_k3 set " + + "FUseOrgId='"+FUseOrgId+"'," +//组织ID + "FName='"+FName+"'," +//客户名称 + "FNumber='"+FNumber+"'," +//客户编码 + "FBankCode='"+FBankCode+"'," +//银行账号 + "FAccountName='"+FAccountName+"'," +//账户名称 + "FOpenBankName='"+FOpenBankName+"' " +//开户银行 + " where FCustId='"+FCustId+"'"; + log.writeLog("客户数据更新SQL------->" + sql); + }else{ + //插入SQL + sql="insert into uf_kh_k3(formmodeid,modedatacreater,modedatacreatertype,modedatacreatedate,modedatacreatetime," + + "FUseOrgId,FCustId,FName,FNumber,FBankCode,FOpenBankName,FAccountName) values(" + + "'"+modeid_kh+"','1','0','"+currDate+"','"+currTime+"'," + + "'"+FUseOrgId+"','"+FCustId+"','"+FName+"','"+FNumber+"','"+FBankCode+"','"+FOpenBankName+"','"+FAccountName+"')"; + log.writeLog("客户数据插入SQL------->" + sql); + //将新增的数据加入至MAP中 + kh_map.put(FCustId, FNumber); + } + rs.execute(sql); + ts_map.put(FCustId, FNumber); + } + } + } + } + + } catch (Exception e) { + // TODO Auto-generated catch block + e.printStackTrace(); + log.writeLog("获取K3客户数据错误,错误信息为------->" + e.toString()); + } + //获取同步耗时 + long hs = (System.currentTimeMillis() - startStamp)/1000; + log.writeLog("*******同步K3客户数据完成end:(" + weaver.general.TimeUtil.getCurrentTimeString() + "),耗时:"+hs+"秒"); + } +} diff --git a/src/main/youhong_ai_jitu_src/com/jet/schedule/syn/SynDepartmentToOA.java b/src/main/youhong_ai_jitu_src/com/jet/schedule/syn/SynDepartmentToOA.java new file mode 100644 index 0000000..791204a --- /dev/null +++ b/src/main/youhong_ai_jitu_src/com/jet/schedule/syn/SynDepartmentToOA.java @@ -0,0 +1,113 @@ +package com.jet.schedule.syn; + +import java.util.List; +import java.util.Map; + +import com.jet.k3.K3Connect; + +import kingdee.bos.webapi.client.K3CloudApiClient; + +import selfdev.util.base.BaseUtil; +import selfdev.util.base.TimeCommonUtil; + +import selfdev.util.log.LogTool; +import weaver.conn.RecordSet; +import weaver.file.Prop; +import weaver.general.Util; +import weaver.interfaces.schedule.BaseCronJob; +import weaver.interfaces.schedule.CronJob; + + +/** + * 定时将K3中部门数据同步至OA建模表 + * @author KangMD + * 2019-12-07 + */ +public class SynDepartmentToOA extends BaseCronJob implements CronJob { + + public static RecordSet rs=new RecordSet(); + public static LogTool log=new LogTool("/log/selfdev/syn", false); + + public void execute(){ + long startStamp=System.currentTimeMillis(); + log.writeLog("*******同步K3部门开始start:(" + weaver.general.TimeUtil.getCurrentTimeString() + ")"); + try { + //连接K3 + K3CloudApiClient client =K3Connect.connect(); + if(client!=null){ + String sql=""; + String now=TimeCommonUtil.obtainDate(0);//获取当前系统日期yyyy-MM-dd HH:mm:ss格式 + String currDate = now.substring(0,10);//当前系统日期 + String currTime = now.substring(11);//当前系统时间 + //获取部门key-value MAP值,主键为部门内码ID + Map bm_map=BaseUtil.getMapKeyValueInfoByParm("uf_bm_K3","","FDeptId","FNumber"); + //当前系统模式 + String mode=Util.null2String(Prop.getPropValue("DevToK3_jet", "mode")); + //部门建模ID + String modeid_bm=Util.null2String(Prop.getPropValue("DevToK3_jet", mode+"_modeid_bm")); + + //分页查询 + for(int t=0;t<1000;t++){ + String sContent = "{\"FormId\":\"BD_Department\"," + // 部门formid + +"\"TopRowCount\":0," + // 最多允许查询的数量,0或者不要此属性表示不限制 + +"\"Limit\":2000," + // 分页取数每页允许获取的数据,最大不能超过2000 + +"\"StartRow\":"+(2000*t)+"," + //分页取数开始行索引,从0开始,例如每页10行数据,第2页开始是10,第3页开始是20 + //""FilterString":"FMaterialId.FNumber like 'HG_TEST%'","+// 过滤条件 + //""FilterString":"FBillNo='CGDD000008'","+// 过滤条件 + +"\"FilterString\":\"FNumber!=''\"," //过滤条件 编码不为空值 + //+"\"OrderString\":\"FGoodsNO ASC\","// 排序条件 + //获取部门基础信息 组织ID、内码、名称、编码 + +"\"FieldKeys\":\"FUseOrgId,FDeptId,FName,FNumber\"}"; + //获取部门列表 + List> sResult = client.executeBillQuery(sContent); + int rows=sResult.size(); + //已经没有数据了,跳出循环 + if(rows==0){ + break; + }else{ + for(int k=0;k" + sql); + }else{ + //插入SQL + sql="insert into uf_bm_K3(formmodeid,modedatacreater,modedatacreatertype,modedatacreatedate,modedatacreatetime," + + "FUseOrgId,FDeptId,FName,FNumber) values(" + + "'"+modeid_bm+"','1','0','"+currDate+"','"+currTime+"'," + + "'"+FUseOrgId+"','"+FDeptId+"','"+FName+"'," + + "'"+FNumber+"')"; + log.writeLog("部门数据插入SQL------->" + sql); + //将新增的数据加入至MAP中 + bm_map.put(FDeptId, FNumber); + } + rs.execute(sql); + } + } + } + } + + } catch (Exception e) { + // TODO Auto-generated catch block + e.printStackTrace(); + log.writeLog("获取K3部门数据错误,错误信息为------->" + e.toString()); + } + //获取同步耗时 + long hs = (System.currentTimeMillis() - startStamp)/1000; + log.writeLog("*******同步K3部门数据完成end:(" + weaver.general.TimeUtil.getCurrentTimeString() + "),耗时:"+hs+"秒"); + } +} diff --git a/src/main/youhong_ai_jitu_src/com/jet/schedule/syn/SynMaterialToOA.java b/src/main/youhong_ai_jitu_src/com/jet/schedule/syn/SynMaterialToOA.java new file mode 100644 index 0000000..b47b532 --- /dev/null +++ b/src/main/youhong_ai_jitu_src/com/jet/schedule/syn/SynMaterialToOA.java @@ -0,0 +1,118 @@ +package com.jet.schedule.syn; + +import java.util.List; +import java.util.Map; + +import kingdee.bos.webapi.client.K3CloudApiClient; +import selfdev.util.base.BaseUtil; +import selfdev.util.base.TimeCommonUtil; +import selfdev.util.log.LogTool; +import weaver.conn.RecordSet; +import weaver.file.Prop; +import weaver.general.Util; +import weaver.interfaces.schedule.BaseCronJob; +import weaver.interfaces.schedule.CronJob; + +import com.jet.k3.K3Connect; + + +/** + * 定时将K3中物料数据同步至OA建模表 + * @author KangMD + * 2019-08-28 + */ +public class SynMaterialToOA extends BaseCronJob implements CronJob { + + public static RecordSet rs=new RecordSet(); + public static LogTool log=new LogTool("/log/selfdev", false); + + public void execute(){ + long startStamp=System.currentTimeMillis(); + log.writeLog("*******同步K3物料开始start:(" + weaver.general.TimeUtil.getCurrentTimeString() + ")"); + try { + //连接K3 + K3CloudApiClient client =K3Connect.connect(); + if(client!=null){ + String sql=""; + String now=TimeCommonUtil.obtainDate(0);//获取当前系统日期yyyy-MM-dd HH:mm:ss格式 + String currDate = now.substring(0,10);//当前系统日期 + String currTime = now.substring(11);//当前系统时间 + //获取物料key-value MAP值,主键为物料内码ID + Map wl_map=BaseUtil.getMapKeyValueInfoByParm("uf_wl_k3","","FNumber","FNumber"); + //当前系统模式 + String mode=Util.null2String(Prop.getPropValue("DevToK3_winsun", "mode")); + //物料建模ID + String modeid_wl=Util.null2String(Prop.getPropValue("DevToK3_winsun", mode+"_modeid_wl")); + + //分页查询 + for(int t=0;t<1000;t++){ + String sContent = "{\"FormId\":\"BD_MATERIAL\"," + // 物料formid + +"\"TopRowCount\":0," + // 最多允许查询的数量,0或者不要此属性表示不限制 + +"\"Limit\":2000," + // 分页取数每页允许获取的数据,最大不能超过2000 + +"\"StartRow\":"+(2000*t)+"," + //分页取数开始行索引,从0开始,例如每页10行数据,第2页开始是10,第3页开始是20 + //""FilterString":"FMaterialId.FNumber like 'HG_TEST%'","+// 过滤条件 + //""FilterString":"FBillNo='CGDD000008'","+// 过滤条件 + +"\"FilterString\":\"FNumber!=''\"," //过滤条件 编码不为空值 + //+"\"OrderString\":\"FGoodsNO ASC\","// 排序条件 + //获取物料基础信息 组织ID、内码、名称、编码、货号、基本单位、规格型号 + //+"\"FieldKeys\":\"FUseOrgId.FNumber,FMaterialId,FName,FNumber,FMnemonicCode,FBaseUnitId.FNumber,FSpecification\"}"; + +"\"FieldKeys\":\"FMaterialId,FName,FNumber,FMnemonicCode,FBaseUnitId.FNumber,FSpecification\"}"; + //获取物料列表 + List> sResult = client.executeBillQuery(sContent); + int rows=sResult.size(); + //已经没有数据了,跳出循环 + if(rows==0){ + break; + }else{ + for(int k=0;k" + sql); + }else{ + //插入SQL + sql="insert into uf_wl_K3(formmodeid,modedatacreater,modedatacreatertype,modedatacreatedate,modedatacreatetime," + + "FUseOrgId,FMaterialId,FName,FNumber,FMnemonicCode,FBaseUnitId,FSpecification) values(" + + "'"+modeid_wl+"','1','0','"+currDate+"','"+currTime+"'," + + "'100','"+FMaterialId+"','"+FName+"','"+FNumber+"','"+FMnemonicCode+"','"+FBaseUnitId+"','"+FSpecification+"')"; + //"'"+FUseOrgId+"','"+FMaterialId+"','"+FName+"','"+FNumber+"','"+FMnemonicCode+"','"+FBaseUnitId+"','"+FSpecification+"')"; + log.writeLog("物料数据插入SQL------->" + sql); + //将新增的数据加入至MAP中 + wl_map.put(FNumber, FNumber); + } + rs.execute(sql); + } + } + } + } + + } catch (Exception e) { + // TODO Auto-generated catch block + e.printStackTrace(); + log.writeLog("获取K3物料数据错误,错误信息为------->" + e.toString()); + } + //获取同步耗时 + long hs = (System.currentTimeMillis() - startStamp)/1000; + log.writeLog("*******同步K3物料数据完成end:(" + weaver.general.TimeUtil.getCurrentTimeString() + "),耗时:"+hs+"秒"); + } +} diff --git a/src/main/youhong_ai_jitu_src/com/jet/schedule/syn/SynOrganizationsToOA.java b/src/main/youhong_ai_jitu_src/com/jet/schedule/syn/SynOrganizationsToOA.java new file mode 100644 index 0000000..a1b8f02 --- /dev/null +++ b/src/main/youhong_ai_jitu_src/com/jet/schedule/syn/SynOrganizationsToOA.java @@ -0,0 +1,110 @@ +package com.jet.schedule.syn; + +import java.util.List; +import java.util.Map; + +import com.jet.k3.K3Connect; + +import kingdee.bos.webapi.client.K3CloudApiClient; + +import selfdev.util.base.BaseUtil; +import selfdev.util.base.TimeCommonUtil; + +import selfdev.util.log.LogTool; +import weaver.conn.RecordSet; +import weaver.file.Prop; +import weaver.general.Util; +import weaver.interfaces.schedule.BaseCronJob; +import weaver.interfaces.schedule.CronJob; + + +/** + * 定时将K3中组织机构数据同步至OA建模表 + * @author KangMD + * 2019-11-07 + */ +public class SynOrganizationsToOA extends BaseCronJob implements CronJob { + + public static RecordSet rs=new RecordSet(); + public static LogTool log=new LogTool("/log/selfdev/syn", false); + + public void execute(){ + long startStamp=System.currentTimeMillis(); + log.writeLog("*******同步K3组织机构开始start:(" + weaver.general.TimeUtil.getCurrentTimeString() + ")"); + try { + //连接K3 + K3CloudApiClient client =K3Connect.connect(); + if(client!=null){ + String sql=""; + String now=TimeCommonUtil.obtainDate(0);//获取当前系统日期yyyy-MM-dd HH:mm:ss格式 + String currDate = now.substring(0,10);//当前系统日期 + String currTime = now.substring(11);//当前系统时间 + //获取组织机构key-value MAP值,主键为组织机构内码ID + Map zz_map=BaseUtil.getMapKeyValueInfoByParm("uf_zz_k3","","Forgid","FNumber"); + //当前系统模式 + String mode=Util.null2String(Prop.getPropValue("DevToK3_jet", "mode")); + //组织机构建模ID + String modeid_zz=Util.null2String(Prop.getPropValue("DevToK3_jet", mode+"_modeid_zz")); + + //分页查询 + for(int t=0;t<1000;t++){ + String sContent = "{\"FormId\":\"ORG_Organizations\"," + // 组织机构formid + +"\"TopRowCount\":0," + // 最多允许查询的数量,0或者不要此属性表示不限制 + +"\"Limit\":2000," + // 分页取数每页允许获取的数据,最大不能超过2000 + +"\"StartRow\":"+(2000*t)+"," + //分页取数开始行索引,从0开始,例如每页10行数据,第2页开始是10,第3页开始是20 + //""FilterString":"FMaterialId.FNumber like 'HG_TEST%'","+// 过滤条件 + //""FilterString":"FBillNo='CGDD000008'","+// 过滤条件 + +"\"FilterString\":\"FNumber!=''\"," //过滤条件 编码不为空值 + //+"\"OrderString\":\"FGoodsNO ASC\","// 排序条件 + //获取组织机构基础信息 组织ID、名称、编码 + +"\"FieldKeys\":\"Forgid,FName,FNumber\"}"; + //获取组织机构列表 + List> sResult = client.executeBillQuery(sContent); + int rows=sResult.size(); + //已经没有数据了,跳出循环 + if(rows==0){ + break; + }else{ + for(int k=0;k" + sql); + }else{ + //插入SQL + sql="insert into uf_zz_k3(formmodeid,modedatacreater,modedatacreatertype,modedatacreatedate,modedatacreatetime," + + "Forgid,FName,FNumber) values(" + + "'"+modeid_zz+"','1','0','"+currDate+"','"+currTime+"'," + + "'"+Forgid+"','"+FName+"','"+FNumber+"')"; + log.writeLog("组织机构数据插入SQL------->" + sql); + //将新增的数据加入至MAP中 + zz_map.put(Forgid, FNumber); + } + rs.execute(sql); + } + } + } + } + + } catch (Exception e) { + // TODO Auto-generated catch block + e.printStackTrace(); + log.writeLog("获取K3组织机构数据错误,错误信息为------->" + e.toString()); + } + //获取同步耗时 + long hs = (System.currentTimeMillis() - startStamp)/1000; + log.writeLog("*******同步K3组织机构数据完成end:(" + weaver.general.TimeUtil.getCurrentTimeString() + "),耗时:"+hs+"秒"); + } +} diff --git a/src/main/youhong_ai_jitu_src/com/jet/schedule/syn/SynPayBankAcntToOA.java b/src/main/youhong_ai_jitu_src/com/jet/schedule/syn/SynPayBankAcntToOA.java new file mode 100644 index 0000000..717f9f3 --- /dev/null +++ b/src/main/youhong_ai_jitu_src/com/jet/schedule/syn/SynPayBankAcntToOA.java @@ -0,0 +1,114 @@ +package com.jet.schedule.syn; + +import java.util.List; +import java.util.Map; + +import kingdee.bos.webapi.client.K3CloudApiClient; +import selfdev.util.base.BaseUtil; +import selfdev.util.base.TimeCommonUtil; +import selfdev.util.log.LogTool; +import weaver.conn.RecordSet; +import weaver.file.Prop; +import weaver.general.Util; +import weaver.interfaces.schedule.BaseCronJob; +import weaver.interfaces.schedule.CronJob; + +import com.jet.k3.K3Connect; + + +/** + * 定时将K3中付款银行同步至OA建模表 + * @author KangMD + * 2019-12-04 + */ +public class SynPayBankAcntToOA extends BaseCronJob implements CronJob { + + public static RecordSet rs=new RecordSet(); + public static LogTool log=new LogTool("/log/selfdev/syn", false); + + public void execute(){ + long startStamp=System.currentTimeMillis(); + log.writeLog("*******同步K3付款银行开始start:(" + weaver.general.TimeUtil.getCurrentTimeString() + ")"); + try { + //连接K3 + K3CloudApiClient client =K3Connect.connect(); + if(client!=null){ + String sql=""; + String now=TimeCommonUtil.obtainDate(0);//获取当前系统日期yyyy-MM-dd HH:mm:ss格式 + String currDate = now.substring(0,10);//当前系统日期 + String currTime = now.substring(11);//当前系统时间 + //获取付款银行key-value MAP值,主键为付款银行内码ID + Map fkyh_map=BaseUtil.getMapKeyValueInfoByParm("uf_fkyh_k3","","FBankAcntId","FNumber"); + //当前系统模式 + String mode=Util.null2String(Prop.getPropValue("DevToK3_jet", "mode")); + //付款银行建模ID + String modeid_gys=Util.null2String(Prop.getPropValue("DevToK3_jet", mode+"_modeid_fkyh")); + + //分页查询 + for(int t=0;t<1000;t++){ + String sContent = "{\"FormId\":\"CN_BANKACNT\"," + // 付款银行formid + +"\"TopRowCount\":0," + // 最多允许查询的数量,0或者不要此属性表示不限制 + +"\"Limit\":2000," + // 分页取数每页允许获取的数据,最大不能超过2000 + +"\"StartRow\":"+(2000*t)+"," + //分页取数开始行索引,从0开始,例如每页10行数据,第2页开始是10,第3页开始是20 + //""FilterString":"FMaterialId.FNumber like 'HG_TEST%'","+// 过滤条件 + //""FilterString":"FBillNo='CGDD000008'","+// 过滤条件 + +"\"FilterString\":\"FNumber!='' \"," //过滤条件 编码不为空值 + //+"\"OrderString\":\"FGoodsNO ASC\","// 排序条件 + //获取付款银行基础信息 组织ID、内码、名称、编码、开户银行 + +"\"FieldKeys\":\"FUseOrgId,FBankAcntId,FName,FNumber,FBankId\"}"; + //获取付款银行列表 + List> sResult = client.executeBillQuery(sContent); + int rows=sResult.size(); + //已经没有数据了,跳出循环 + if(rows==0){ + break; + }else{ + for(int k=0;k" + sql); + }else{ + //插入SQL + sql="insert into uf_fkyh_k3(formmodeid,modedatacreater,modedatacreatertype,modedatacreatedate,modedatacreatetime," + + "FUseOrgId,FBankAcntId,FName,FNumber,FBankId) values(" + + "'"+modeid_gys+"','1','0','"+currDate+"','"+currTime+"'," + + "'"+FUseOrgId+"','"+FBankAcntId+"','"+FName+"','"+FNumber+"'," + + "'"+FBankId+"')"; + log.writeLog("付款银行数据插入SQL------->" + sql); + + //将新增的数据加入至MAP中 + fkyh_map.put(FBankAcntId, FNumber); + } + rs.execute(sql); + } + } + } + } + + } catch (Exception e) { + // TODO Auto-generated catch block + e.printStackTrace(); + log.writeLog("获取K3付款银行数据错误,错误信息为------->" + e.toString()); + } + //获取同步耗时 + long hs = (System.currentTimeMillis() - startStamp)/1000; + log.writeLog("*******同步K3付款银行数据完成end:(" + weaver.general.TimeUtil.getCurrentTimeString() + "),耗时:"+hs+"秒"); + } +} diff --git a/src/main/youhong_ai_jitu_src/com/jet/schedule/syn/SynSettleTypeToOA.java b/src/main/youhong_ai_jitu_src/com/jet/schedule/syn/SynSettleTypeToOA.java new file mode 100644 index 0000000..e75437d --- /dev/null +++ b/src/main/youhong_ai_jitu_src/com/jet/schedule/syn/SynSettleTypeToOA.java @@ -0,0 +1,109 @@ +package com.jet.schedule.syn; + +import java.util.List; +import java.util.Map; + +import kingdee.bos.webapi.client.K3CloudApiClient; +import selfdev.util.base.BaseUtil; +import selfdev.util.base.TimeCommonUtil; +import selfdev.util.log.LogTool; +import weaver.conn.RecordSet; +import weaver.file.Prop; +import weaver.general.Util; +import weaver.interfaces.schedule.BaseCronJob; +import weaver.interfaces.schedule.CronJob; + +import com.jet.k3.K3Connect; + + +/** + * 定时将K3中结算方式数据同步至OA建模表 + * @author KangMD + * 2019-09-04 + */ +public class SynSettleTypeToOA extends BaseCronJob implements CronJob { + + public static RecordSet rs=new RecordSet(); + public static LogTool log=new LogTool("/log/selfdev", false); + + public void execute(){ + long startStamp=System.currentTimeMillis(); + log.writeLog("*******同步K3结算方式开始start:(" + weaver.general.TimeUtil.getCurrentTimeString() + ")"); + try { + //连接K3 + K3CloudApiClient client =K3Connect.connect(); + if(client!=null){ + String sql=""; + String now=TimeCommonUtil.obtainDate(0);//获取当前系统日期yyyy-MM-dd HH:mm:ss格式 + String currDate = now.substring(0,10);//当前系统日期 + String currTime = now.substring(11);//当前系统时间 + //获取结算方式key-value MAP值,主键为结算方式内码ID + Map jsfs_map=BaseUtil.getMapKeyValueInfoByParm("uf_jsfs_K3","","FID","FNumber"); + //当前系统模式 + String mode=Util.null2String(Prop.getPropValue("DevToK3_winsun", "mode")); + //结算方式建模ID + String modeid_jsfs=Util.null2String(Prop.getPropValue("DevToK3_winsun", mode+"_modeid_jsfs")); + + //分页查询 + for(int t=0;t<1000;t++){ + String sContent = "{\"FormId\":\"BD_SETTLETYPE\"," + // 结算方式formid + +"\"TopRowCount\":0," + // 最多允许查询的数量,0或者不要此属性表示不限制 + +"\"Limit\":2000," + // 分页取数每页允许获取的数据,最大不能超过2000 + +"\"StartRow\":"+(2000*t)+"," + //分页取数开始行索引,从0开始,例如每页10行数据,第2页开始是10,第3页开始是20 + //""FilterString":"FMaterialId.FNumber like 'HG_TEST%'","+// 过滤条件 + //""FilterString":"FBillNo='CGDD000008'","+// 过滤条件 + +"\"FilterString\":\"FNumber!=''\"," //过滤条件 编码不为空值 + //+"\"OrderString\":\"FGoodsNO ASC\","// 排序条件 + //获取结算方式基础信息 内码、名称、编码 + +"\"FieldKeys\":\"FID,FName,FNumber\"}"; + //获取结算方式列表 + List> sResult = client.executeBillQuery(sContent); + int rows=sResult.size(); + //已经没有数据了,跳出循环 + if(rows==0){ + break; + }else{ + for(int k=0;k" + sql); + }else{ + //插入SQL + sql="insert into uf_jsfs_K3(formmodeid,modedatacreater,modedatacreatertype,modedatacreatedate,modedatacreatetime," + + "FID,FName,FNumber) values(" + + "'"+modeid_jsfs+"','1','0','"+currDate+"','"+currTime+"'," + + "'"+FID+"','"+FName+"'," + + "'"+FNumber+"')"; + log.writeLog("结算方式数据插入SQL------->" + sql); + //将新增的数据加入至MAP中 + jsfs_map.put(FID, FNumber); + } + rs.execute(sql); + } + } + } + } + + } catch (Exception e) { + // TODO Auto-generated catch block + e.printStackTrace(); + log.writeLog("获取K3结算方式数据错误,错误信息为------->" + e.toString()); + } + //获取同步耗时 + long hs = (System.currentTimeMillis() - startStamp)/1000; + log.writeLog("*******同步K3结算方式数据完成end:(" + weaver.general.TimeUtil.getCurrentTimeString() + "),耗时:"+hs+"秒"); + } +} diff --git a/src/main/youhong_ai_jitu_src/com/jet/schedule/syn/SynSupplierToOA.java b/src/main/youhong_ai_jitu_src/com/jet/schedule/syn/SynSupplierToOA.java new file mode 100644 index 0000000..4b056c8 --- /dev/null +++ b/src/main/youhong_ai_jitu_src/com/jet/schedule/syn/SynSupplierToOA.java @@ -0,0 +1,128 @@ +package com.jet.schedule.syn; + +import java.util.List; +import java.util.Map; + +import kingdee.bos.webapi.client.K3CloudApiClient; +import selfdev.util.base.BaseUtil; +import selfdev.util.base.TimeCommonUtil; +import selfdev.util.log.LogTool; +import weaver.conn.RecordSet; +import weaver.file.Prop; +import weaver.general.Util; +import weaver.interfaces.schedule.BaseCronJob; +import weaver.interfaces.schedule.CronJob; + +import com.jet.k3.K3Connect; + + +/** + * 定时将K3中供应商数据同步至OA建模表 + * @author KangMD + * 2019-11-08 + */ +public class SynSupplierToOA extends BaseCronJob implements CronJob { + + public static RecordSet rs=new RecordSet(); + public static LogTool log=new LogTool("/log/selfdev/syn", false); + + public void execute(){ + long startStamp=System.currentTimeMillis(); + log.writeLog("*******同步K3供应商开始start:(" + weaver.general.TimeUtil.getCurrentTimeString() + ")"); + try { + //连接K3 + K3CloudApiClient client =K3Connect.connect(); + if(client!=null){ + String sql=""; + String now=TimeCommonUtil.obtainDate(0);//获取当前系统日期yyyy-MM-dd HH:mm:ss格式 + String currDate = now.substring(0,10);//当前系统日期 + String currTime = now.substring(11);//当前系统时间 + //获取供应商key-value MAP值,主键为供应商内码ID + Map gys_map=BaseUtil.getMapKeyValueInfoByParm("uf_gys_k3","","FSupplierId","FNumber"); + //当前系统模式 + String mode=Util.null2String(Prop.getPropValue("DevToK3_jet", "mode")); + //供应商建模ID + String modeid_gys=Util.null2String(Prop.getPropValue("DevToK3_jet", mode+"_modeid_gys")); + + //分页查询 + for(int t=0;t<1000;t++){ + String sContent = "{\"FormId\":\"BD_Supplier\"," + // 供应商formid + +"\"TopRowCount\":0," + // 最多允许查询的数量,0或者不要此属性表示不限制 + +"\"Limit\":2000," + // 分页取数每页允许获取的数据,最大不能超过2000 + +"\"StartRow\":"+(2000*t)+"," + //分页取数开始行索引,从0开始,例如每页10行数据,第2页开始是10,第3页开始是20 + //""FilterString":"FMaterialId.FNumber like 'HG_TEST%'","+// 过滤条件 + //""FilterString":"FBillNo='CGDD000008'","+// 过滤条件 + +"\"FilterString\":\"FNumber!='' and FDocumentStatus='C'\"," //过滤条件 编码不为空值,FDocumentStatus='C'标识数据状态为已审核 + //+"\"OrderString\":\"FGoodsNO ASC\","// 排序条件 + //获取供应商基础信息 组织ID、内码、名称、编码、银行账号、账户名称、开户银行 + +"\"FieldKeys\":\"FUseOrgId,FSupplierId,FName,FNumber,FBankCode,FBankHolder,FOpenBankName,F_RTA_VATType.FNumber,FTaxRateId.FNumber\"}"; + //获取供应商列表 + List> sResult = client.executeBillQuery(sContent); + int rows=sResult.size(); + //已经没有数据了,跳出循环 + if(rows==0){ + break; + }else{ + for(int k=0;k" + sql); + }else{ + //插入SQL + sql="insert into uf_gys_K3(formmodeid,modedatacreater,modedatacreatertype,modedatacreatedate,modedatacreatetime," + + "FUseOrgId,FSupplierId,FName,FNumber,FBankCode,FBankHolder,F_RTA_VATType,FTaxRate,FOpenBankName) values(" + + "'"+modeid_gys+"','1','0','"+currDate+"','"+currTime+"'," + + "'"+FUseOrgId+"','"+FSupplierId+"','"+FName+"','"+FNumber+"','"+FBankCode+"'," + + "'"+FBankHolder+"','"+F_RTA_VATType+"','"+FTaxRate+"'," + + "'"+FOpenBankName+"')"; + log.writeLog("供应商数据插入SQL------->" + sql); + + //将新增的数据加入至MAP中 + gys_map.put(FSupplierId, FNumber); + } + rs.execute(sql); + } + } + } + } + + } catch (Exception e) { + // TODO Auto-generated catch block + e.printStackTrace(); + log.writeLog("获取K3供应商数据错误,错误信息为------->" + e.toString()); + } + //获取同步耗时 + long hs = (System.currentTimeMillis() - startStamp)/1000; + log.writeLog("*******同步K3供应商数据完成end:(" + weaver.general.TimeUtil.getCurrentTimeString() + "),耗时:"+hs+"秒"); + } +} diff --git a/src/main/youhong_ai_jitu_src/com/jet/test/AP_OtherPayableSaveTestK3.java b/src/main/youhong_ai_jitu_src/com/jet/test/AP_OtherPayableSaveTestK3.java new file mode 100644 index 0000000..3b6a181 --- /dev/null +++ b/src/main/youhong_ai_jitu_src/com/jet/test/AP_OtherPayableSaveTestK3.java @@ -0,0 +1,175 @@ +package com.jet.test; + + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.JSONArray; +import com.alibaba.fastjson.JSONObject; +import com.alibaba.fastjson.serializer.SerializerFeature; + +import kingdee.bos.webapi.client.K3CloudApiClient; + +/** + * 其他应付款 + * @author KangMD + * + */ +public class AP_OtherPayableSaveTestK3 { + static String K3CloudURL = "http://k3.jet.co.id:8880/K3Cloud/"; + static String dbId = "5da41554614595"; + static String uid = "lulu yang"; + static String pwd = "20190716"; + static int lang = 2052; + + + public static void main(String[] args) { + // TODO Auto-generated method stub + try { + queryBD_Expense(); + } catch (Exception e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + } + + //供应商 + public static void queryBD_Expense() throws Exception { + K3CloudApiClient client = new K3CloudApiClient(K3CloudURL); + boolean result = client.login(dbId, uid, pwd, lang); + if (result) { + Map data=new HashMap(); + + Map Model=new HashMap(); + //单据类型(必填项)--------默认为标准应付单YFD01_SYS + Map FBillTypeID=new HashMap(); + FBillTypeID.put("FNUMBER", "QTYFD01_SYS"); + Model.put("FBillTypeID", FBillTypeID); + + //Model.put("FISINIT", false);//是否期初单据 + Model.put("FDATE", "2019-11-28");//业务日期(必填项)--------默认为申请日期 + Model.put("FENDDATE_H", "2019-11-28");//到期日(必填项)-------- + Model.put("FCONTACTUNITTYPE", "BD_Empinfo");//往来单位类型,默认为员工 + //Model.put("FDOCUMENTSTATUS", "Z");//单据状态 + + //往来单位编码(即员工编码) + Map FCONTACTUNIT=new HashMap(); + FCONTACTUNIT.put("FNUMBER", "E0003"); + Model.put("FCONTACTUNIT", FCONTACTUNIT); + + //币别(必填项)-------- + Map FCURRENCYID=new HashMap(); + FCURRENCYID.put("FNUMBER", "IDR"); + Model.put("FCURRENCYID", FCURRENCYID); + + Model.put("FTOTALAMOUNTFOR_H", 10000.0);//总金额 + Model.put("FNOTSETTLEAMOUNTFOR", 10000.0);//未结算金额 + + //申请部门 + Map FDEPARTMENTID=new HashMap(); + FDEPARTMENTID.put("FNumber", "BM000002"); + Model.put("FDEPARTMENTID", FDEPARTMENTID); + + //付款组织(必填项)---- + Map FPAYORGID=new HashMap(); + FPAYORGID.put("FNUMBER", "100"); + Model.put("FPAYORGID", FPAYORGID); + //结算组织 + Model.put("FSETTLEORGID", FPAYORGID); + //采购组织 + Model.put("FPURCHASEORGID", FPAYORGID); + //采购部门 + Map FPURCHASEDEPTID=new HashMap(); + FPURCHASEDEPTID.put("FNumber", "BM000001"); + Model.put("FPURCHASEDEPTID", FPURCHASEDEPTID); + //本位币 + Model.put("FMAINBOOKSTDCURRID", FCURRENCYID); + + + //汇率类型 +// Map FEXCHANGETYPE=new HashMap(); +// FEXCHANGETYPE.put("FNUMBER", "HLTX01_SYS"); +// Model.put("FEXCHANGETYPE", FEXCHANGETYPE); + + //到期日计算日期(期望支付日期) + Model.put("FACCNTTIMEJUDGETIME", "2019-12-20"); + //作废状态 + Model.put("FCancelStatus", "A"); + + + //-----------------明细 start-----------------// + List> FEntity=new ArrayList>(); + //定义一行明细 + Map EntityDetail=new HashMap(); + //费用项目编码 + Map FCOSTID=new HashMap(); + FCOSTID.put("FNUMBER", "CI074"); + EntityDetail.put("FCOSTID", FCOSTID); + //费用归属部门 + EntityDetail.put("FCOSTDEPARTMENTID", FDEPARTMENTID); + //不含税金额 + EntityDetail.put("FNOTAXAMOUNTFOR", 10000); + //总金额 + EntityDetail.put("FTOTALAMOUNTFOR", 10000); + //未结算金额 + EntityDetail.put("FNOTSETTLEAMOUNTFOR_D", 10000); + //不含税金额本位币 + EntityDetail.put("FNOTAXAMOUNT_D", 10000); + //发票类型 + //EntityDetail.put("FINVOICETYPE", ""); + //将MAP添加至List中 + FEntity.add(EntityDetail); + //EntityDetail.clear();//清空继续循环---------- + + Model.put("FEntity", FEntity);// + + //-----------------明细 end-----------------// + + + data.put("Model", Model); + + //将MAP转JSON,fastjson默认开启引用检测将相同的对象写成引用的形式,所以必须加上SerializerFeature.DisableCircularReferenceDetect,否则转换的字符串会出现$ref + String jsonStr = JSON.toJSONString(data, SerializerFeature.DisableCircularReferenceDetect); + System.out.println(jsonStr); + //调用应付单保存接口 + String sResult = client.excuteOperation("AP_OtherPayable", "save", jsonStr); + System.out.println(sResult); + + //解析K3返回的JSO字符串 + JSONObject jsonObject = JSONObject.parseObject(sResult); + JSONObject ResponseStatus=jsonObject.getJSONObject("Result").getJSONObject("ResponseStatus"); + //是否成功写入K3 + String IsSuccess=ResponseStatus.get("IsSuccess").toString(); + System.out.println(IsSuccess); + if("true".equals(IsSuccess)){ + JSONArray SuccessJSONArray=ResponseStatus.getJSONArray("SuccessEntitys"); + String Id="";//单据ID + String Number="";//单据编号 + + for(int p=0;p"+Id+",Number------>"+Number); +// String jsonStr2="{\"CreateOrgId\":0,\"Numbers\":[],\"Ids\":\""+Id+"\",\"SelectedPostId\":0}"; +// //调用应付单提交接口(将单据状态由创建--->审核中) +// String sResult2 = client.excuteOperation("AP_Payable", "submit", jsonStr2); +// System.out.println(sResult2); + + }else{ + JSONArray ErrorsJSONArray=ResponseStatus.getJSONArray("Errors"); + String msg=""; + for(int p=0;p"+Id+",Number------>"+Number); +// String jsonStr2="{\"CreateOrgId\":0,\"Numbers\":[],\"Ids\":\""+Id+"\",\"SelectedPostId\":0}"; +// //调用应付单提交接口(将单据状态由创建--->审核中) +// String sResult2 = client.excuteOperation("AP_Payable", "submit", jsonStr2); +// System.out.println(sResult2); + + }else{ + JSONArray ErrorsJSONArray=ResponseStatus.getJSONArray("Errors"); + String msg=""; + for(int p=0;p data=new HashMap(); + Map Model=new HashMap(); + //单据类型(必填项)--------默认为采购业务付款单FKDLX01_SYS + Map FBillTypeID=new HashMap(); + FBillTypeID.put("FNUMBER", "FKDLX01_SYS"); + Model.put("FBillTypeID", FBillTypeID); + Model.put("FDATE", "2019-11-28");//业务日期(必填项)--------默认为申请日期 + //往来单位类型,默认为供应商 + Model.put("FCONTACTUNITTYPE", "BD_Supplier"); + //往来单位(必填项)-------- + Map FCONTACTUNIT=new HashMap(); + FCONTACTUNIT.put("FNUMBER", "1009"); + Model.put("FCONTACTUNIT", FCONTACTUNIT); + + //收款单位类型,默认为供应商 + Model.put("FRECTUNITTYPE", "BD_Supplier"); + //收款单位(必填项)-------- + Map FRECTUNIT=new HashMap(); + FRECTUNIT.put("FNUMBER", "1009"); + Model.put("FRECTUNIT", FRECTUNIT); + + //币别(必填项)-------- + Map FCURRENCYID=new HashMap(); + FCURRENCYID.put("FNUMBER", "IDR"); + Model.put("FCURRENCYID", FCURRENCYID); + Model.put("FEXCHANGERATE", 1.0);//汇率 + Model.put("FSETTLERATE", 1.0);//结算汇率 + //采购部门 + Map FPURCHASEDEPTID=new HashMap(); + FPURCHASEDEPTID.put("FNUMBER", "BM000001"); + Model.put("FPURCHASEDEPTID", FPURCHASEDEPTID); + //结算组织(必填项)---- + Map FSETTLEORGID=new HashMap(); + FSETTLEORGID.put("FNumber", "100"); + Model.put("FSETTLEORGID", FSETTLEORGID);//结算组织(必填项)---- + //采购组织 + Model.put("FPURCHASEORGID", FSETTLEORGID); + //备注 + Model.put("FREMARK", "备注test123"); + //期望付款日期 + Model.put("FBookingDate", "2019-12-12"); + Model.put("FDOCUMENTSTATUS", "Z");//单据状态 + Model.put("FCancelStatus", "A");//作废状态(必填项)----默认为A + //结算组织 + Model.put("FPAYORGID", FSETTLEORGID); + //结算币别 + Model.put("FSETTLECUR", FCURRENCYID); + //结算本位币 + Model.put("FSETTLEMAINBOOKID", FCURRENCYID); + + //-----------------付款单明细 start-----------------// + List> FPAYBILLENTRY=new ArrayList>(); + //定义一行明细 + Map PAYBILLENTRY=new HashMap(); + //结算方式 + Map FSETTLETYPEID=new HashMap(); + FSETTLETYPEID.put("FNUMBER", "JSFS03_SYS"); + PAYBILLENTRY.put("FSETTLETYPEID", FSETTLETYPEID); + + //付款用途 + Map FPURPOSEID=new HashMap(); + FPURPOSEID.put("FNUMBER", "SFKYT08_SYS"); + PAYBILLENTRY.put("FPURPOSEID", FPURPOSEID); + + PAYBILLENTRY.put("FPAYTOTALAMOUNTFOR", 88.0);//表体-应付金额 + PAYBILLENTRY.put("FPAYAMOUNTFOR_E", 88.0);//付款金额 + PAYBILLENTRY.put("FSETTLEPAYAMOUNTFOR", 88.0);//折后金额 + PAYBILLENTRY.put("FREALPAYAMOUNTFOR_D", 88.0);//表体-实付金额 + //我方银行账号 + Map FACCOUNTID=new HashMap(); + FACCOUNTID.put("FNUMBER", "1683066137"); + PAYBILLENTRY.put("FACCOUNTID", FACCOUNTID); + + PAYBILLENTRY.put("FPAYAMOUNT_E", 88.0);//付款金额本位币 + PAYBILLENTRY.put("FPOSTDATE", "2019-12-03");//登账日期 + PAYBILLENTRY.put("FRuZhangType", "1");//入账类型 + PAYBILLENTRY.put("FPayType", "A");//支付类型 + + + //将MAP添加至List中 + FPAYBILLENTRY.add(PAYBILLENTRY); + + Model.put("FPAYBILLENTRY", FPAYBILLENTRY);// + + //-----------------付款单明细 end-----------------// + + + //-----------------付款单源单明细 start-----------------// + List> FPAYBILLSRCENTRY=new ArrayList>(); + //定义一行明细 + Map PAYBILLSRCENTRY=new HashMap(); + //源单类型 + PAYBILLSRCENTRY.put("FSOURCETYPE", "AP_Payable"); + //源单编号 + PAYBILLSRCENTRY.put("FSRCBILLNO", "AP00000081"); + //本次付款金额 + PAYBILLSRCENTRY.put("FREALPAYAMOUNT_S", 88); + //应付金额 + PAYBILLSRCENTRY.put("FAFTTAXTOTALAMOUNT", 100); + //计划付款金额 + PAYBILLSRCENTRY.put("FPLANPAYAMOUNT", 100); + //源单币别 + PAYBILLSRCENTRY.put("FSRCCURRENCYID", FCURRENCYID); + //到期日 + PAYBILLSRCENTRY.put("FEXPIRY", "2019-12-01"); + + //将MAP添加至List中 + FPAYBILLSRCENTRY.add(PAYBILLSRCENTRY); + Model.put("FPAYBILLSRCENTRY", FPAYBILLSRCENTRY);// + + //-----------------付款单源单明细 end-----------------// + + + + data.put("Model", Model); + + //将MAP转JSON,fastjson默认开启引用检测将相同的对象写成引用的形式,所以必须加上SerializerFeature.DisableCircularReferenceDetect,否则转换的字符串会出现$ref + String jsonStr = JSON.toJSONString(data, SerializerFeature.DisableCircularReferenceDetect); + System.out.println(jsonStr); + //String str="{\"Model\":{\"FBUSINESSTYPE\":\"CG\",\"FBillTypeID\":{\"FNUMBER\":\"YFD01_SYS\"},\"FISINIT\":false,\"FDATE\":\"2019-11-28\",\"FENDDATE_H\":\"2019-11-28\",\"FDOCUMENTSTATUS\":\"Z\",\"FSUPPLIERID\":{\"FNumber\":\"1009\"},\"FCURRENCYID\":{\"FNumber\":\"IDR\"},\"FISPRICEEXCLUDETAX\":true,\"FISTAX\":true,\"FSETTLEORGID\":{\"FNumber\":\"100\"},\"FTaxType\":{\"FNumber\":\"Non-PKP\"},\"FPAYORGID\":{\"FNumber\":\"100\"},\"FSetAccountType\":\"1\",\"FISTAXINCOST\":false,\"FISHookMatch\":false,\"FCancelStatus\":\"A\",\"F_RTA_NPWPNumber\":\"000000000000000\",\"F_RTA_EntityType\":\"Company\",\"F_RTA_PPH_H\":{\"FNumber\":\"PPH23-4\"},\"FISBYIV\":false,\"FISGENHSADJ\":false,\"FISINVOICEARLIER\":false,\"F_RTA_VATType\":{\"FNUMBER\":\"000\"},\"F_RTA_InvoiceNo\":\"1574998101931\",\"F_RTA_CanDeductVAT\":false,\"F_RTA_PPHByComp\":true,\"F_RTA_BusinessType\":\"S\",\"F_RTA_CalculateFlag\":false,\"F_RTA_PPNByComp\":false,\"FsubHeadSuppiler\":{\"FORDERID\":{\"FNumber\":\"1009\"},\"FTRANSFERID\":{\"FNumber\":\"1009\"},\"FChargeId\":{\"FNumber\":\"1009\"}},\"FsubHeadFinc\":{\"FACCNTTIMEJUDGETIME\":\"2019-11-28\",\"FMAINBOOKSTDCURRID\":{\"FNumber\":\"IDR\"},\"FEXCHANGETYPE\":{\"FNumber\":\"HLTX01_SYS\"},\"FExchangeRate\":1.0,\"FNoTaxAmountFor\":11.0},\"FEntityDetail\":[{\"FMATERIALID\":{\"FNumber\":\"100013\"},\"FMaterialDesc\":\"ROYALTYFEE\",\"FPRICEUNITID\":{\"FNumber\":\"Pcs\"},\"FPrice\":11.0,\"FPriceQty\":1.0,\"FTaxPrice\":11.0,\"FPriceWithTax\":11.0,\"F_RTA_VATType_d\":{\"FNUMBER\":\"000\"},\"FNoTaxAmountFor_D\":11.0,\"FALLAMOUNTFOR_D\":11.0,\"F_RTA_PPH\":{\"FNUMBER\":\"PPH23-4\"},\"FINCLUDECOST\":false,\"FISOUTSTOCK\":false,\"F_RTA_FakturPajakNo_d\":\"6666666666\",\"FIsFree\":false,\"FStockUnitId\":{\"FNumber\":\"Pcs\"},\"FStockQty\":1.0,\"FStockBaseQty\":1.0,\"FPriceBaseDen\":1.0,\"FStockBaseNum\":1.0,\"F_RTA_SUPPLIER_D\":{\"FNUMBER\":\"1009\"}}],\"FEntityPlan\":[{\"FENDDATE\":\"2019-11-28\",\"FPAYAMOUNTFOR\":11.0,\"FPAYRATE\":100.0}]}}"; + //String str2="{\"Model\":{\"FBUSINESSTYPE\":\"CG\",\"FBillTypeID\":{\"FNUMBER\":\"YFD01_SYS\"},\"FISINIT\":false,\"FDATE\":\"2019-11-28\",\"FENDDATE_H\":\"2019-11-28\",\"FDOCUMENTSTATUS\":\"Z\",\"FSUPPLIERID\":{\"FNUMBER\":\"1009\"},\"FCURRENCYID\":{\"FNUMBER\":\"IDR\"},\"FISPRICEEXCLUDETAX\":true,\"FISTAX\":true,\"FSETTLEORGID\":{\"FNumber\":\"100\"},\"FTaxType\":{\"FNumber\":\"Non-PKP\"},\"FPAYORGID\":{\"FNUMBER\":\"100\"},\"FSetAccountType\":\"1\",\"FISTAXINCOST\":false,\"FISHookMatch\":false,\"FCancelStatus\":\"A\",\"F_RTA_NPWPNumber\":\"000000000000000\",\"F_RTA_EntityType\":\"Company\",\"F_RTA_PPH_H\":{\"FNUMBER\":\"PPH23-4\"},\"FISBYIV\":false,\"FISGENHSADJ\":false,\"FISINVOICEARLIER\":false,\"F_RTA_VATType\":{\"FNUMBER\":\"000\"},\"F_RTA_InvoiceNo\":\"4184918116892\",\"F_RTA_CanDeductVAT\":false,\"F_RTA_PPHByComp\":true,\"F_RTA_BusinessType\":\"S\",\"F_RTA_CalculateFlag\":false,\"F_RTA_PPNByComp\":false,\"FsubHeadSuppiler\":{\"FORDERID\":{\"FNUMBER\":\"1009\"},\"FTRANSFERID\":{\"FNUMBER\":\"1009\"},\"FChargeId\":{\"FNUMBER\":\"1009\"}},\"FsubHeadFinc\":{\"FACCNTTIMEJUDGETIME\":\"2019-11-28\",\"FMAINBOOKSTDCURRID\":{\"FNUMBER\":\"IDR\"},\"FEXCHANGETYPE\":{\"FNUMBER\":\"HLTX01_SYS\"},\"FExchangeRate\":1.0,\"FNoTaxAmountFor\":11.0},\"FEntityDetail\":[{\"FMATERIALID\":{\"FNUMBER\":\"100013\"},\"FMaterialDesc\":\"ROYALTYFEE\",\"FPRICEUNITID\":{\"FNUMBER\":\"Pcs\"},\"FPrice\":11.0,\"FPriceQty\":1.0,\"FTaxPrice\":11.0,\"FPriceWithTax\":11.0,\"F_RTA_VATType_d\":{\"FNUMBER\":\"000\"},\"FNoTaxAmountFor_D\":11.0,\"FALLAMOUNTFOR_D\":11.0,\"FAUXPROPID\":{},\"FBASICUNITQTY\":1,\"FBUYIVQTY\":0,\"FINCLUDECOST\":false,\"FISOUTSTOCK\":false,\"FIVALLAMOUNTFOR\":0,\"FIsFree\":false,\"FPriceBaseDen\":1,\"FStockBaseNum\":1,\"FStockBaseQty\":1,\"FStockQty\":1,\"F_RTA_PPH\":{\"FNUMBER\":\"PPH23-4\"},\"FStockUnitId\":{\"FNUMBER\":\"Pcs\"},\"FTAXAMOUNTFOR_D\":0,\"F_RTA_EntryRemarks\":\"testtest\",\"F_RTA_FakturPajakNo_d\":\"9999999999\",\"F_RTA_SUPPLIER_D\":{\"FNUMBER\":\"1009\"}}],\"FEntityPlan\":[{\"FENDDATE\":\"2019-11-27\",\"FPAYAMOUNTFOR\":11,\"FPAYRATE\":100}]}}"; + //System.out.println(str); + //调用应付单保存接口 + String sResult = client.excuteOperation("AP_PAYBILL", "save", jsonStr); + System.out.println(sResult); + + //解析K3返回的JSO字符串 + JSONObject jsonObject = JSONObject.parseObject(sResult); + JSONObject ResponseStatus=jsonObject.getJSONObject("Result").getJSONObject("ResponseStatus"); + //是否成功写入K3 + String IsSuccess=ResponseStatus.get("IsSuccess").toString(); + System.out.println(IsSuccess); + if("true".equals(IsSuccess)){ + JSONArray SuccessJSONArray=ResponseStatus.getJSONArray("SuccessEntitys"); + String Id="";//单据ID + String Number="";//单据编号 + + for(int p=0;p"+Id+",Number------>"+Number); + + }else{ + JSONArray ErrorsJSONArray=ResponseStatus.getJSONArray("Errors"); + String msg=""; + for(int p=0;p"+Id+",Number------>"+Number); + + }else{ + JSONArray ErrorsJSONArray=ResponseStatus.getJSONArray("Errors"); + String msg=""; + for(int p=0;p data=new HashMap(); + Map Model=new HashMap(); + List> FPAYBILLENTRY=new ArrayList>(); + //定义一行明细 + Map PAYBILLENTRY=new HashMap(); + //结算方式 + Map FSETTLETYPEID=new HashMap(); + FSETTLETYPEID.put("FNUMBER", "JSFS03_SYS"); + PAYBILLENTRY.put("FSETTLETYPEID", FSETTLETYPEID); + //将MAP添加至List中 + FPAYBILLENTRY.add(PAYBILLENTRY); + Model.put("FPAYBILLENTRY", FPAYBILLENTRY);// + + data.put("Model", Model); + + //将MAP转JSON,fastjson默认开启引用检测将相同的对象写成引用的形式,所以必须加上SerializerFeature.DisableCircularReferenceDetect,否则转换的字符串会出现$ref + String str = JSON.toJSONString(data, SerializerFeature.DisableCircularReferenceDetect); + System.out.println(str); + + //传入的JSON格式 + String jsonStr="{\"Ids\": \"\",\"Numbers\": \"AP00022976\",\"EntryIds\": \"\",\"RuleId\": \"AP_PayableToPayBill\",\"TargetBillTypeId\": \"\",\"TargetOrgId\": 0,\"TargetFormId\": \"\",\"IsEnableDefaultRule\": \"false\",\"IsDraftWhenSaveFail\": \"false\",\"CustomParams\": "+str+"}"; + System.out.println(jsonStr); + //调用应付单保存接口 + String sResult = client.excuteOperation("AP_Payable", "push", jsonStr); + System.out.println(sResult); + + //解析K3返回的JSO字符串 + JSONObject jsonObject = JSONObject.parseObject(sResult); + JSONObject ResponseStatus=jsonObject.getJSONObject("Result").getJSONObject("ResponseStatus"); + //是否成功写入K3 + String IsSuccess=ResponseStatus.get("IsSuccess").toString(); + System.out.println(IsSuccess); + if("true".equals(IsSuccess)){ + JSONArray SuccessJSONArray=ResponseStatus.getJSONArray("SuccessEntitys"); + String Id="";//单据ID + String Number="";//单据编号 + + + for(int p=0;p"+Id+",Number------>"+Number); +// String jsonStr2="{\"CreateOrgId\":0,\"Numbers\":[],\"Ids\":\""+Id+"\",\"SelectedPostId\":0}"; +// //调用应付单提交接口(将单据状态由创建--->审核中) +// String sResult2 = client.excuteOperation("AP_Payable", "submit", jsonStr2); +// System.out.println(sResult2); + + }else{ + JSONArray ErrorsJSONArray=ResponseStatus.getJSONArray("Errors"); + String msg=""; + for(int p=0;p data=new HashMap(); +// data.put("Creator", ""); +// data.put("NeedUpDateFields", new String[0]); +// data.put("NeedReturnFields", new String[0]); +// data.put("IsDeleteEntry", "true"); +// data.put("SubSystemId", ""); +// data.put("IsVerifyBaseDataField", "false"); +// data.put("IsEntryBatchFill", "true"); +// data.put("ValidateFlag", "true"); +// data.put("NumberSearch", "true"); +// data.put("InterationFlags", ""); +// data.put("IsAutoSubmitAndAudit", "false"); + + Map Model=new HashMap(); + //Model.put("FID", "0");//实体主键 + //单据类型(必填项)--------默认为标准应付单YFD01_SYS + Map FBillTypeID=new HashMap(); + FBillTypeID.put("FNUMBER", "YFD01_SYS"); + Model.put("FBillTypeID", FBillTypeID); + + //Model.put("FBillNo", "");//单据编号--------K3动生成 + Model.put("FISINIT", false);//是否期初单据 + Model.put("FDATE", "2019-11-28");//业务日期(必填项)--------默认为申请日期 + Model.put("FENDDATE_H", "2019-11-28");//到期日(必填项)-------- + Model.put("FDOCUMENTSTATUS", "Z");//单据状态 + + //供应商(必填项)-------- + Map FSUPPLIERID=new HashMap(); + FSUPPLIERID.put("FNUMBER", "1009"); + Model.put("FSUPPLIERID", FSUPPLIERID); + + //币别(必填项)-------- + Map FCURRENCYID=new HashMap(); + FCURRENCYID.put("FNUMBER", "IDR"); + Model.put("FCURRENCYID", FCURRENCYID); + + Model.put("FISPRICEEXCLUDETAX", true);//价外税 + Model.put("FBUSINESSTYPE", "CG");//业务类型(必填项)----默认为CG + Model.put("FISTAX", true);//按含税单价录入---- + + //结算组织(必填项)---- + Map FSETTLEORGID=new HashMap(); + FSETTLEORGID.put("FNumber", "100"); + Model.put("FSETTLEORGID", FSETTLEORGID);//结算组织(必填项)---- + + //税分类----//根据供应商自动带出 +// Map FTaxType=new HashMap(); +// FTaxType.put("FNumber", "Non-PKP"); +// Model.put("FTaxType", FTaxType); + + //付款组织(必填项)---- + Map FPAYORGID=new HashMap(); + FPAYORGID.put("FNUMBER", "100"); + Model.put("FPAYORGID", FPAYORGID); + + //Model.put("FSetAccountType", "1");//立账类型----默认为1 +// Model.put("FISTAXINCOST", false);//税额计入成本 +// Model.put("FISHookMatch", false);//参与暂估应付核销 + Model.put("FCancelStatus", "A");//作废状态(必填项)----默认为A + + //Model.put("F_RTA_NPWPNumber", "000000000000000");//NPWP Number----//根据供应商自动带出 + //Model.put("F_RTA_EntityType", "Company");//Entity Type----//根据供应商自动带出 + + //PPH---- +// Map F_RTA_PPH_H=new HashMap(); +// F_RTA_PPH_H.put("FNUMBER", "PPH23-4"); +// Model.put("F_RTA_PPH_H", F_RTA_PPH_H); + +// Model.put("FISBYIV", false);//是发票审核自动生成 +// Model.put("FISGENHSADJ", false);//是否需要成本调整 + //Model.put("FMatchMethodID", 0);//核销方式 +// Model.put("FISINVOICEARLIER", false);//先到票后入库 + +// Map F_RTA_VATType=new HashMap(); +// F_RTA_VATType.put("FNUMBER", "000"); +// Model.put("F_RTA_VATType", F_RTA_VATType);//PPN Type + + Model.put("F_RTA_InvoiceNo", System.currentTimeMillis()+"");//Invoice No(必填项)---- + //Model.put("F_RTA_CanDeductVAT", false);//可否抵扣增值税选项 + //Model.put("FBILLMATCHLOGID", 0);//开票核销记录序号 + //Model.put("F_RTA_PPHByComp", true);//PPH By Company + Model.put("F_RTA_BusinessType", "S");//business type(必填项)----默认为服务类 + //Model.put("F_RTA_CalculateFlag", false);//PPH21已计算标识 + //Model.put("F_RTA_PPNByComp", false);//PPN By Company + + + //-----------------表头供应商 start-----------------// + Map FsubHeadSuppiler=new HashMap(); + //FsubHeadSuppiler.put("FEntryId", 0);//实体主键 + FsubHeadSuppiler.put("FORDERID", FSUPPLIERID);//订货方 + FsubHeadSuppiler.put("FTRANSFERID", FSUPPLIERID);//供货方 + FsubHeadSuppiler.put("FChargeId", FSUPPLIERID);//收款方 + + Model.put("FsubHeadSuppiler", FsubHeadSuppiler);// + //-----------------表头供应商 end-----------------// + + + + //付款条件---- +// Map FPayConditon=new HashMap(); +// FPayConditon.put("FNUMBER", "FKTJ01_SYS"); +// Model.put("FPayConditon", FPayConditon); +// +// +// Model.put("FSourceBillType", "");//源单类型---- +// +// + Model.put("FAP_Remark", "test测试");//备注---- +// +// //Model.put("FACCOUNTSYSTEM", "{\"FNUMBER\":\"\"}");//会计核算体系 +// +// //采购部门---- +// Map FPURCHASEDEPTID=new HashMap(); +// FPURCHASEDEPTID.put("FNUMBER", "BM000009"); +// Model.put("FPURCHASEDEPTID", FPURCHASEDEPTID); +// +// //采购组---- +// Map FPURCHASERGROUPID=new HashMap(); +// FPURCHASERGROUPID.put("FNUMBER", ""); +// Model.put("FPURCHASERGROUPID", FPURCHASERGROUPID); +// +// //采购员---- +// Map FPURCHASERID=new HashMap(); +// FPURCHASERID.put("FNUMBER", ""); +// Model.put("FPURCHASERID", FPURCHASERID); +// +// +// Model.put("F_RTA_Isclerka", "");//Is Staff----//根据供应商自动带出 + + + + + //Model.put("FScanPoint", "{\"FNUMBER\":\"\"}");//扫描点 + //Model.put("F_RTA_DPwithPPN", "A1");//Down Payment with PPN(必填项)---- + + + + + //-----------------表头财务 start-----------------// + Map FsubHeadFinc=new HashMap(); + //FsubHeadFinc.put("FEntryId", 0);//实体主键 + FsubHeadFinc.put("FACCNTTIMEJUDGETIME", "2019-11-28");//到期日计算日期(必填项)---- + + //结算方式 + Map FSettleTypeID=new HashMap(); + FSettleTypeID.put("FNUMBER", "JSFS03_SYS"); + FsubHeadFinc.put("FSettleTypeID", FSettleTypeID); + //本位币 + FsubHeadFinc.put("FMAINBOOKSTDCURRID", FCURRENCYID); + //汇率类型 +// Map FEXCHANGETYPE=new HashMap(); +// FEXCHANGETYPE.put("FNUMBER", "HLTX01_SYS"); +// FsubHeadFinc.put("FEXCHANGETYPE", FEXCHANGETYPE);// +// FsubHeadFinc.put("FExchangeRate", 1.0);//汇率 + //FsubHeadFinc.put("FTaxAmountFor", 2276.0);//税额 + //FsubHeadFinc.put("FNoTaxAmountFor", 11.0);//不含税金额 + + Model.put("FsubHeadFinc", FsubHeadFinc);// + //-----------------表头财务 end-----------------// + + + //-----------------明细 start-----------------// + List> FEntityDetail=new ArrayList>(); + //定义一行明细 + Map EntityDetail=new HashMap(); + //EntityDetail.put("FEntryId", 0);//实体主键 + //EntityDetail.put("FCOSTID", "{\"FNUMBER\":\"\"}");//费用项目编码 + //物料编码 + Map FMATERIALID=new HashMap(); + FMATERIALID.put("FNUMBER", "100013"); + EntityDetail.put("FMATERIALID", FMATERIALID); + //EntityDetail.put("FMaterialDesc", "ROYALTY FEE");//物料说明 + + EntityDetail.put("F_RTA_EntryRemarks", "testtest");//备 注 + + //EntityDetail.put("FASSETID", "{\"FNUMBER\":\"\"}");//卡片编码 + //计价单位 + Map FPRICEUNITID=new HashMap(); + FPRICEUNITID.put("FNUMBER", "Pcs"); + EntityDetail.put("FPRICEUNITID", FPRICEUNITID); + + EntityDetail.put("FPrice", 11.0);//单价 + EntityDetail.put("FPriceQty", 1.0);//计价数量 + //EntityDetail.put("FBASICUNITQTY", 1);//计价基本数量 + EntityDetail.put("FTaxPrice", 11.0);//含税单价 + //EntityDetail.put("F_RTA_PPHAmount", 3035);//PPH Amount + EntityDetail.put("FPriceWithTax", 11);//含税净价 + + //PPN Type + Map F_RTA_VATType_d=new HashMap(); + F_RTA_VATType_d.put("FNUMBER", "000"); + EntityDetail.put("F_RTA_VATType_d", F_RTA_VATType_d); + + //EntityDetail.put("FEntryTaxRate", 0);//税率(%) + //EntityDetail.put("FTaxCombination", "{\"FNUMBER\":\"\"}");//税组合 + //EntityDetail.put("FEntryDiscountRate", 0);//折扣率(%) + //EntityDetail.put("FDISCOUNTAMOUNTFOR", 0);//折扣额 + EntityDetail.put("FNoTaxAmountFor_D", 11.0);//不含税金额 + EntityDetail.put("FTAXAMOUNTFOR_D", 0);//税额 + EntityDetail.put("FALLAMOUNTFOR_D", 11.0);//价税合计 + + //PPH------------- +// Map F_RTA_PPH=new HashMap(); +// F_RTA_PPH.put("FNUMBER", "PPH23-4"); +// EntityDetail.put("F_RTA_PPH", F_RTA_PPH); + + //EntityDetail.put("FINCLUDECOST", false);//计入成本 + //EntityDetail.put("FOUTSTOCKID", "[{\"FNUMBER\":\"\"}]");//出库单号 + //EntityDetail.put("FAUXPROPID", new HashMap());//辅助属性 + //EntityDetail.put("FBUYIVQTY", 0);//采购发票数量 + //EntityDetail.put("FIVALLAMOUNTFOR", 0);//采购发票价税合计 + //EntityDetail.put("FISOUTSTOCK", false);//是否有出库单号 + EntityDetail.put("F_RTA_FakturPajakNo_d", "-");//Faktur Pajak No + //EntityDetail.put("FIsFree", false);//是否赠品 + //EntityDetail.put("FStockUnitId", FPRICEUNITID);//库存单位 + + + //EntityDetail.put("FCOSTDEPARTMENTID", "{\"FNUMBER\":\"\"}");//费用承担部门 + //EntityDetail.put("FLot", "{\"FNUMBER\":\"\"}");//批号 +// EntityDetail.put("FMONUMBER", "");//生产订单编号 +// EntityDetail.put("FMOENTRYSEQ", 0);//生产订单行号 +// EntityDetail.put("FOPNO", "");//工序计划号 +// EntityDetail.put("FSEQNUMBER", "");//序列号 +// EntityDetail.put("FOPERNUMBER", 0);//工序号 + //EntityDetail.put("FPROCESSID", "{\"FNUMBER\":\"\"}");//作业 + //EntityDetail.put("FFPRODEPARTMENTID", "{\"FNUMBER\":\"\"}");//生产车间 +// EntityDetail.put("FWWINTYPE", "");//入库类型 + + + +// EntityDetail.put("FStockQty", 1);//库存数量 +// EntityDetail.put("FStockBaseQty", 1);//库存基本数量 +// EntityDetail.put("FPriceBaseDen", 1);//计价基本分母 +// EntityDetail.put("FStockBaseNum", 1);//库存基本分子 + //EntityDetail.put("FOrderEntryID", 0);//采购订单明细内码 + //EntityDetail.put("FORDERENTRYSEQ", 0);//采购订单行号 + //EntityDetail.put("FBUYIVINIQTY", 0);//采购发票数量期初 + //EntityDetail.put("FBUYIVINIBASICQTY", 0);//采购发票基本单位数量期初 + //EntityDetail.put("FIVINIALLAMOUNTFOR", 0);//采购发票价税合计期初 + //EntityDetail.put("FPushRedQty", 0);//已下推负数财务应付数量 + EntityDetail.put("F_RTA_SUPPLIER_D", FSUPPLIERID);//表体供应商(用于校验税票号唯一) + //EntityDetail.put("F_RTA_AccumulatedAmount", 0);//累计金额 + //EntityDetail.put("FSRCROWID", 0);//源单行内码 + //EntityDetail.put("F_RTA_AccumulatedPPH21", 0);//累计PPH21税额 + //EntityDetail.put("F_RTA_PPHAmountM", 0);//PPH Amount(本位币) + + //-----------------税务明细 start-----------------// +// List> FTaxDetailSubEntity=new ArrayList>(); +// Map FTax=new HashMap(); +// FTax.put("FDetailID", 0);//实体主键 +// //FTax.put("FTaxRateId", "{\"FNUMBER\":\"\"}");//税率名称 +// FTax.put("FTaxRate", 0);//税率(%) +// FTax.put("FTaxAmount_T", 0);//税额 +// FTax.put("FCostPercent", 0);//计入成本比例 +// FTax.put("FCostAmount", 0);//计入成本金额 +// FTax.put("FVAT", "false");//增值税 +// FTax.put("FSellerWithholding", "false");//卖方代扣代缴 +// FTax.put("FBuyerWithholding", "false");//买方代扣代缴 +// +// FTaxDetailSubEntity.add(FTax); +// EntityDetail.put("FTaxDetailSubEntity", FTaxDetailSubEntity);// + //-----------------税务明细 end-----------------// + //将MAP添加至List中 + FEntityDetail.add(EntityDetail); + //EntityDetail.clear();//清空继续循环---------- + + Model.put("FEntityDetail", FEntityDetail);// + + //-----------------明细 end-----------------// + + + //-----------------付款计划 start-----------------// + List> FEntityPlan=new ArrayList>(); + Map FPlan=new HashMap(); + //FPlan.put("FEntryID", 0);//实体主键 + FPlan.put("FENDDATE", "2019-11-27");//表头计划 - 到期日 + FPlan.put("FPAYAMOUNTFOR", 11.0);//应付金额 + //FPlan.put("FPAYAMOUNT", 11);//应付金额 + FPlan.put("FPAYRATE", 100);//应付比例(%) +// FPlan.put("FPURCHASEORDERID", 0);//采购订单ID +// FPlan.put("FPAYABLEENTRYID", 0);//采购订单明细内码 + + //物料编码 +// Map FMATERIALID_P=new HashMap(); +// FMATERIALID_P.put("FNUMBER", "2-07.01"); +// FPlan.put("FMATERIALID_P", FMATERIALID_P); +// FPlan.put("FPRICEUNITID_P", FPRICEUNITID);//计价单位 +// FPlan.put("FPRICE_P", 11);//含税单价 +// FPlan.put("FQTY_P", 1);//数量 +// FPlan.put("FPURCHASEORDERNO", "");//采购订单号 +// FPlan.put("FMATERIALSEQ", 0);//订单行号 +// FPlan.put("FRELATEHADPAYQTY", 1);//付(退)款关联数量 + FEntityPlan.add(FPlan); + //FPlan.clear(); + Model.put("FEntityPlan", FEntityPlan);// + //-----------------付款计划 end-----------------// + + data.put("Model", Model); + + //将MAP转JSON,fastjson默认开启引用检测将相同的对象写成引用的形式,所以必须加上SerializerFeature.DisableCircularReferenceDetect,否则转换的字符串会出现$ref + String jsonStr = JSON.toJSONString(data, SerializerFeature.DisableCircularReferenceDetect); + System.out.println(jsonStr); + + //MAP转JSON + //JSONObject json = new JSONObject(data); + //System.out.println(json.toJSONString()); + + String str="{\"Model\": {\"FBillTypeID\": {\"FNUMBER\": \"YFD01_SYS\"},\"FISINIT\": false,\"FDATE\": \"2020-08-26\",\"FENDDATE_H\": \"2020-08-26\",\"FDOCUMENTSTATUS\": \"Z\",\"FSUPPLIERID\": {\"FNUMBER\": \"1160\"},\"FCURRENCYID\": {\"FNUMBER\": \"IDR\"},\"FISPRICEEXCLUDETAX\": true,\"FBUSINESSTYPE\": \"CG\",\"FISTAX\": true,\"FSETTLEORGID\": {\"FNumber\": \"100\"},\"FPURCHASEDEPTID\": {\"FNUMBER\": \"BM000002\"},\"FPAYORGID\": {\"FNUMBER\": \"100\"},\"F_RTA_VATType\": {\"FNUMBER\": \"II-6\"},\"FCancelStatus\": \"A\",\"F_RTA_InvoiceNo\": \"TEST\",\"F_RTA_BusinessType\": \"S\",\"FAP_Remark\": \"TEST\",\"F_RTA_PPHByComp\": false,\"FsubHeadSuppiler\": {\"FORDERID\": {\"FNUMBER\": \"1160\"},\"FTRANSFERID\": {\"FNUMBER\": \"1160\"},\"FChargeId\": {\"FNUMBER\": \"1160\"}},\"FsubHeadFinc\": {\"FACCNTTIMEJUDGETIME\": \"2020-08-19\",\"FSettleTypeID\": {\"FNUMBER\": \"JSFS03_SYS\"},\"FMAINBOOKSTDCURRID\": {\"FNUMBER\": \"IDR\"}},\"FEntityDetail\": [{\"FMATERIALID\": {\"FNUMBER\": \"100013\"},\"F_RTA_EntryRemarks\": \"TEST\",\"FPRICEUNITID\": {\"FNUMBER\": \"Pcs\"},\"FPrice\": \"1000000.00\",\"FPriceQty\": 1.0,\"FTaxPrice\": \"1100000.00\",\"FTAXAMOUNTFOR_D\": \"100000.00\",\"FPriceWithTax\": \"1000000.00\",\"F_RTA_VATType_d\": {\"FNUMBER\": \"II-6\"},\"FNoTaxAmountFor_D\": \"1000000.00\",\"FTAXAMOUNTFOR_D\": 0,\"FALLAMOUNTFOR_D\": \"1000000.00\",\"F_RTA_FakturPajakNo_d\": \"-\",\"F_RTA_SUPPLIER_D\": {\"FNUMBER\": \"1160\"}}],\"FEntityPlan\": [{\"FENDDATE\": \"2020-08-19\",\"FPAYAMOUNTFOR\": \"1000000.00\",\"FPAYRATE\": 100}]}}"; + //String str2="{\"Model\":{\"FBUSINESSTYPE\":\"CG\",\"FBillTypeID\":{\"FNUMBER\":\"YFD01_SYS\"},\"FISINIT\":false,\"FDATE\":\"2019-11-28\",\"FENDDATE_H\":\"2019-11-28\",\"FDOCUMENTSTATUS\":\"Z\",\"FSUPPLIERID\":{\"FNUMBER\":\"1009\"},\"FCURRENCYID\":{\"FNUMBER\":\"IDR\"},\"FISPRICEEXCLUDETAX\":true,\"FISTAX\":true,\"FSETTLEORGID\":{\"FNumber\":\"100\"},\"FTaxType\":{\"FNumber\":\"Non-PKP\"},\"FPAYORGID\":{\"FNUMBER\":\"100\"},\"FSetAccountType\":\"1\",\"FISTAXINCOST\":false,\"FISHookMatch\":false,\"FCancelStatus\":\"A\",\"F_RTA_NPWPNumber\":\"000000000000000\",\"F_RTA_EntityType\":\"Company\",\"F_RTA_PPH_H\":{\"FNUMBER\":\"PPH23-4\"},\"FISBYIV\":false,\"FISGENHSADJ\":false,\"FISINVOICEARLIER\":false,\"F_RTA_VATType\":{\"FNUMBER\":\"000\"},\"F_RTA_InvoiceNo\":\"4184918116892\",\"F_RTA_CanDeductVAT\":false,\"F_RTA_PPHByComp\":true,\"F_RTA_BusinessType\":\"S\",\"F_RTA_CalculateFlag\":false,\"F_RTA_PPNByComp\":false,\"FsubHeadSuppiler\":{\"FORDERID\":{\"FNUMBER\":\"1009\"},\"FTRANSFERID\":{\"FNUMBER\":\"1009\"},\"FChargeId\":{\"FNUMBER\":\"1009\"}},\"FsubHeadFinc\":{\"FACCNTTIMEJUDGETIME\":\"2019-11-28\",\"FMAINBOOKSTDCURRID\":{\"FNUMBER\":\"IDR\"},\"FEXCHANGETYPE\":{\"FNUMBER\":\"HLTX01_SYS\"},\"FExchangeRate\":1.0,\"FNoTaxAmountFor\":11.0},\"FEntityDetail\":[{\"FMATERIALID\":{\"FNUMBER\":\"100013\"},\"FMaterialDesc\":\"ROYALTYFEE\",\"FPRICEUNITID\":{\"FNUMBER\":\"Pcs\"},\"FPrice\":11.0,\"FPriceQty\":1.0,\"FTaxPrice\":11.0,\"FPriceWithTax\":11.0,\"F_RTA_VATType_d\":{\"FNUMBER\":\"000\"},\"FNoTaxAmountFor_D\":11.0,\"FALLAMOUNTFOR_D\":11.0,\"FAUXPROPID\":{},\"FBASICUNITQTY\":1,\"FBUYIVQTY\":0,\"FINCLUDECOST\":false,\"FISOUTSTOCK\":false,\"FIVALLAMOUNTFOR\":0,\"FIsFree\":false,\"FPriceBaseDen\":1,\"FStockBaseNum\":1,\"FStockBaseQty\":1,\"FStockQty\":1,\"F_RTA_PPH\":{\"FNUMBER\":\"PPH23-4\"},\"FStockUnitId\":{\"FNUMBER\":\"Pcs\"},\"FTAXAMOUNTFOR_D\":0,\"F_RTA_EntryRemarks\":\"testtest\",\"F_RTA_FakturPajakNo_d\":\"9999999999\",\"F_RTA_SUPPLIER_D\":{\"FNUMBER\":\"1009\"}}],\"FEntityPlan\":[{\"FENDDATE\":\"2019-11-27\",\"FPAYAMOUNTFOR\":11,\"FPAYRATE\":100}]}}"; + //System.out.println(str); + //调用应付单保存接口 + String sResult = client.excuteOperation("AP_Payable", "save", str); + System.out.println(sResult); + + //解析K3返回的JSO字符串 + JSONObject jsonObject = JSONObject.parseObject(sResult); + JSONObject ResponseStatus=jsonObject.getJSONObject("Result").getJSONObject("ResponseStatus"); + //是否成功写入K3 + String IsSuccess=ResponseStatus.get("IsSuccess").toString(); + System.out.println(IsSuccess); + if("true".equals(IsSuccess)){ + JSONArray SuccessJSONArray=ResponseStatus.getJSONArray("SuccessEntitys"); + String Id="";//单据ID + String Number="";//单据编号 + + for(int p=0;p"+Id+",Number------>"+Number); +// String jsonStr2="{\"CreateOrgId\":0,\"Numbers\":[],\"Ids\":\""+Id+"\",\"SelectedPostId\":0}"; +// //调用应付单提交接口(将单据状态由创建--->审核中) +// String sResult2 = client.excuteOperation("AP_Payable", "submit", jsonStr2); +// System.out.println(sResult2); + + }else{ + JSONArray ErrorsJSONArray=ResponseStatus.getJSONArray("Errors"); + String msg=""; + for(int p=0;p> sResult = client.executeBillQuery(sContent); + int rows=sResult.size(); + for(int k=0;k"+FName+";FNumber----->"+FNumber+";FForbidStatus----->"+FForbidStatus); + } + System.out.println("F_RTA_VATType----->"+F_RTA_VATType+";FTaxRateId----->"+FTaxRateId+";FForbidStatus----->"+FForbidStatus); + + } + } + } + + +} diff --git a/src/main/youhong_ai_jitu_src/com/jet/test/CN_BankAcntTestK3.java b/src/main/youhong_ai_jitu_src/com/jet/test/CN_BankAcntTestK3.java new file mode 100644 index 0000000..d0ebaa1 --- /dev/null +++ b/src/main/youhong_ai_jitu_src/com/jet/test/CN_BankAcntTestK3.java @@ -0,0 +1,64 @@ +package com.jet.test; + + +import java.util.List; + +import weaver.general.Util; + + +import kingdee.bos.webapi.client.K3CloudApiClient; + +public class CN_BankAcntTestK3 { + static String K3CloudURL = "http://k3.jet.co.id:8880/K3Cloud/"; + static String dbId = "5da41554614595"; + static String uid = "lulu yang"; + static String pwd = "20190716"; + static int lang = 2052; + + + public static void main(String[] args) { + // TODO Auto-generated method stub + try { + queryBD_Expense(); + } catch (Exception e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + } + + //供应商 + public static void queryBD_Expense() throws Exception { + K3CloudApiClient client = new K3CloudApiClient(K3CloudURL); + boolean result = client.login(dbId, uid, pwd, lang); + if (result) { + String sContent = "{\"FormId\":\"CN_BANKACNT\"," + // 供应商formid + +"\"TopRowCount\":0," + // 最多允许查询的数量,0或者不要此属性表示不限制 + +"\"Limit\":2000," + // 分页取数每页允许获取的数据,最大不能超过2000 + +"\"StartRow\":0," + //分页取数开始行索引,从0开始,例如每页10行数据,第2页开始是10,第3页开始是20 + //""FilterString":"FMaterialId.FNumber like 'HG_TEST%'","+// 过滤条件 + //""FilterString":"FBillNo='CGDD000008'","+// 过滤条件 + +"\"FilterString\":\"FNumber!=''\"," //过滤条件 编码不为空值 + //+"\"OrderString\":\"FGoodsNO ASC\","// 排序条件 + //获取供应商基础信息 组织ID、内码、名称、编码、银行账号、账户名称、开户银行 + +"\"FieldKeys\":\"FUseOrgId,FBANKACNTID,FName,FNumber,FBANKID\"}"; + + List> sResult = client.executeBillQuery(sContent); + int rows=sResult.size(); + for(int k=0;k"+FBANKACNTID+";FName----->"+FName+";FNumber----->"+FNumber+";FBANKID----->"+FBANKID); + + } + } + } + + +} diff --git a/src/main/youhong_ai_jitu_src/com/jet/test/DBSSO_Test.java b/src/main/youhong_ai_jitu_src/com/jet/test/DBSSO_Test.java new file mode 100644 index 0000000..bd8f7f4 --- /dev/null +++ b/src/main/youhong_ai_jitu_src/com/jet/test/DBSSO_Test.java @@ -0,0 +1,15 @@ +package com.jet.test; + +import org.apache.commons.codec.digest.DigestUtils; + +import com.jet.util.JwtUtil; + +public class DBSSO_Test { + + public static void main(String[] args) { + String aa= DigestUtils.shaHex("782ZfF谢莹1603935541292"); + System.out.println("aa------->"+aa); + String token=JwtUtil.createSsoToken("00001304","TPFKAGB3QGPM2LBD","DPQY6CN2UT",36000).getToken(); + System.out.println("token------->"+token); + } +} diff --git a/src/main/youhong_ai_jitu_src/com/jet/test/Decode_Encode.java b/src/main/youhong_ai_jitu_src/com/jet/test/Decode_Encode.java new file mode 100644 index 0000000..fff8dba --- /dev/null +++ b/src/main/youhong_ai_jitu_src/com/jet/test/Decode_Encode.java @@ -0,0 +1,19 @@ +package com.jet.test; + +import java.io.UnsupportedEncodingException; +import java.net.URLDecoder; +public class Decode_Encode { + + + public static void main(String[] args) { + String pcurlsrc="/openDoc?title=Suhana%25E7%259A%2584%25E8%25AF%25B7%25E5%2581%2587%25E5%258D%2595%2528JT20191121000001%25EF%25BC%2589&templateId=1122317121229303809&workId=1197361606271516673"; + try { + String s=URLDecoder.decode(pcurlsrc,"UTF-8"); + System.out.println(s); + } catch (UnsupportedEncodingException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + + } +} diff --git a/src/main/youhong_ai_jitu_src/com/jet/test/Test.java b/src/main/youhong_ai_jitu_src/com/jet/test/Test.java new file mode 100644 index 0000000..02e2587 --- /dev/null +++ b/src/main/youhong_ai_jitu_src/com/jet/test/Test.java @@ -0,0 +1,43 @@ +package com.jet.test; + +import java.text.DecimalFormat; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +import com.alibaba.fastjson.JSONObject; + +public class Test { + + /** + * @param args + */ + public static void main(String[] args) { + double te=88888888888.00; + DecimalFormat df = new DecimalFormat( "###############0.00 ");// 16位整数位,两小数位 + String temp = df.format(te); + System.out.println(temp); + // TODO Auto-generated method stub + Map data=new HashMap(); + List> Model=new ArrayList>(); + Map map1=new HashMap(); + Map map2=new HashMap(); + + map1.put("A", "test1"); + map1.put("B", "test2"); + + map2.put("C", "test3"); + map2.put("D", "test4"); + + Model.add(map1); + Model.add(map2); + + data.put("Model", Model); + //MAP转JSON + JSONObject json = new JSONObject(data); + + System.out.println(json.toJSONString()); + } + +} diff --git a/src/main/youhong_ai_jitu_src/com/jet/util/BaseUtil.java b/src/main/youhong_ai_jitu_src/com/jet/util/BaseUtil.java new file mode 100644 index 0000000..82b86a9 --- /dev/null +++ b/src/main/youhong_ai_jitu_src/com/jet/util/BaseUtil.java @@ -0,0 +1,30 @@ +package com.jet.util; + +import weaver.conn.RecordSet; +import weaver.general.Util; + +public class BaseUtil { + public static String getFormidId(String workflowid){ + StringBuffer lSQL = new StringBuffer(); + lSQL.append(" SELECT formid FROM workflow_base WHERE id='"+workflowid+"' "); + RecordSet rs = new RecordSet(); + rs.execute(lSQL.toString()); + String formid="0"; + if(rs.next()){ + formid=Util.null2String(rs.getString("formid")); + formid=Math.abs(Integer.parseInt(formid))+""; + } + return formid; + } + public static String getWorkflowId(String requestid){ + StringBuffer lSQL = new StringBuffer(); + lSQL.append(" SELECT workflowid FROM workflow_requestbase WHERE requestid='"+requestid+"' "); + RecordSet rs = new RecordSet(); + rs.execute(lSQL.toString()); + String workflowid=""; + if(rs.next()){ + workflowid=Util.null2String(rs.getString("workflowid")); + } + return workflowid; + } +} diff --git a/src/main/youhong_ai_jitu_src/com/jet/util/InvokeHelper.java b/src/main/youhong_ai_jitu_src/com/jet/util/InvokeHelper.java new file mode 100644 index 0000000..881a8fb --- /dev/null +++ b/src/main/youhong_ai_jitu_src/com/jet/util/InvokeHelper.java @@ -0,0 +1,226 @@ +package com.jet.util; +import java.io.BufferedReader; +import java.io.DataOutputStream; +import java.io.InputStreamReader; +import java.net.HttpURLConnection; +import java.net.URL; +import java.util.Date; +import java.util.HashMap; +import java.util.Map; +import java.util.UUID; +import org.apache.log4j.Logger; +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; + +import org.json.JSONArray; +import org.json.JSONObject; + +public class InvokeHelper { + + // K3 Cloud WebSite URL Example "http://192.168.19.113/K3Cloud/" + public static String POST_K3CloudURL = "http://k3.jet.co.id:8880/k3cloud/"; + + // Cookie 值 + private static String CookieVal = null; + + private static Map map = new HashMap(); + static { + map.put("Save", + "Kingdee.BOS.WebApi.ServicesStub.DynamicFormService.Save.common.kdsvc"); + map.put("View", + "Kingdee.BOS.WebApi.ServicesStub.DynamicFormService.View.common.kdsvc"); + map.put("Submit", + "Kingdee.BOS.WebApi.ServicesStub.DynamicFormService.Submit.common.kdsvc"); + map.put("Audit", + "Kingdee.BOS.WebApi.ServicesStub.DynamicFormService.Audit.common.kdsvc"); + map.put("UnAudit", + "Kingdee.BOS.WebApi.ServicesStub.DynamicFormService.UnAudit.common.kdsvc"); + map.put("StatusConvert", + "Kingdee.BOS.WebApi.ServicesStub.DynamicFormService.StatusConvert.common.kdsvc"); + } + + // HttpURLConnection + private static HttpURLConnection initUrlConn(String url, JSONArray paras) + throws Exception { + System.out.println(POST_K3CloudURL.concat(url)); + URL postUrl = new URL(POST_K3CloudURL.concat(url)); + HttpURLConnection connection = (HttpURLConnection) postUrl + .openConnection(); + if (CookieVal != null) { + connection.setRequestProperty("Cookie", CookieVal); + } + if (!connection.getDoOutput()) { + connection.setDoOutput(true); + } + connection.setRequestMethod("POST"); + connection.setUseCaches(false); + connection.setInstanceFollowRedirects(true); + connection.setRequestProperty("Content-Type", "application/json"); + DataOutputStream out = new DataOutputStream( + connection.getOutputStream()); + + UUID uuid = UUID.randomUUID(); + int hashCode = uuid.toString().hashCode(); + + JSONObject jObj = new JSONObject(); + + jObj.put("format", 1); + jObj.put("useragent", "ApiClient"); + jObj.put("rid", hashCode); + jObj.put("parameters", chinaToUnicode(paras.toString())); + jObj.put("timestamp", new Date().toString()); + jObj.put("v", "1.0"); + + out.writeBytes(jObj.toString()); + out.flush(); + out.close(); + + return connection; + } + + // Login + public static boolean Login(String dbId, String user, String pwd, int lang) + throws Exception { + + boolean bResult = false; + + String sUrl = "Kingdee.BOS.WebApi.ServicesStub.AuthService.ValidateUser.common.kdsvc"; + + JSONArray jParas = new JSONArray(); + jParas.put(dbId);// 帐套Id + jParas.put(user);// 用户名 + jParas.put(pwd);// 密码 + jParas.put(lang);// 语言 + + HttpURLConnection connection = initUrlConn(sUrl, jParas); + // 获取Cookie + String key = null; + for (int i = 1; (key = connection.getHeaderFieldKey(i)) != null; i++) { + if (key.equalsIgnoreCase("Set-Cookie")) { + String tempCookieVal = connection.getHeaderField(i); + if (tempCookieVal.startsWith("kdservice-sessionid")) { + CookieVal = tempCookieVal; + break; + } + } + } + + BufferedReader reader = new BufferedReader(new InputStreamReader( + connection.getInputStream())); + String line; + System.out.println(" ============================= "); + System.out.println(" Contents of post request "); + System.out.println(" ============================= "); + while ((line = reader.readLine()) != null) { + String sResult = new String(line.getBytes()); + System.out.println(sResult); + bResult = line.contains("\"LoginResultType\":1"); + } + System.out.println(" ============================= "); + System.out.println(" Contents of post request ends "); + System.out.println(" ============================= "); + reader.close(); + + connection.disconnect(); + + return bResult; + } + + // Save + public static JSONObject Save(String formId, String content) throws Exception { + JSONObject JSONObject=Invoke("Save", formId, content); + return JSONObject; + } + + // View + public static void View(String formId, String content) throws Exception { + Invoke("View", formId, content); + } + + // Submit + public static void Submit(String formId, String content) throws Exception { + Invoke("Submit", formId, content); + } + + // Audit + public static void Audit(String formId, String content) throws Exception { + Invoke("Audit", formId, content); + } + + // UnAudit + public static void UnAudit(String formId, String content) throws Exception { + Invoke("UnAudit", formId, content); + } + + // StatusConvert + public static void StatusConvert(String formId, String content) + throws Exception { + Invoke("StatusConvert", formId, content); + } + + private static JSONObject Invoke(String deal, String formId, String content) + throws Exception { + Logger log = Logger.getLogger(JSONObject.class); +JSONObject json=new JSONObject(); +boolean flag=false; +BufferedReader reader =null; +HttpURLConnection connectionInvoke =null; +String sResult=""; +try{ +String sUrl = map.get(deal).toString(); +JSONArray jParas = new JSONArray(); +jParas.put(formId); +jParas.put(content); + + connectionInvoke = initUrlConn(sUrl, jParas); + + reader = new BufferedReader(new InputStreamReader( + connectionInvoke.getInputStream())); + +String line; +System.out.println(" ============================= "); +System.out.println(" Contents of post request "); +System.out.println(" ============================= "); +while ((line = reader.readLine()) != null) { + sResult = new String(line.getBytes(), "utf-8"); + System.out.println(sResult); + log.error("sResult--"+sResult); +} + +System.out.println(" ============================= "); +System.out.println(" Contents of post request ends "); +System.out.println(" ============================= "); +flag=true; +reader.close(); +connectionInvoke.disconnect(); + +}catch(Exception e){ + sResult=e.getMessage(); + reader.close(); + connectionInvoke.disconnect(); +} +json.put("flag", flag); +json.put("sResult", sResult); +return json; +} + + + /** + * 把中文转成Unicode码 + * + * @param str + * @return + */ + public static String chinaToUnicode(String str) { + String result = ""; + for (int i = 0; i < str.length(); i++) { + int chr1 = (char) str.charAt(i); + if (chr1 >= 19968 && chr1 <= 171941) {// 汉字范围 \u4e00-\u9fa5 (中文) + result += "\\u" + Integer.toHexString(chr1); + } else { + result += str.charAt(i); + } + } + return result; + } +} \ No newline at end of file diff --git a/src/main/youhong_ai_jitu_src/com/jet/util/JwtSsoTokenResult.java b/src/main/youhong_ai_jitu_src/com/jet/util/JwtSsoTokenResult.java new file mode 100644 index 0000000..95abe25 --- /dev/null +++ b/src/main/youhong_ai_jitu_src/com/jet/util/JwtSsoTokenResult.java @@ -0,0 +1,23 @@ +package com.jet.util; + +public class JwtSsoTokenResult { + + public JwtSsoTokenResult(String token){ + this.token = token; + } + + private String token; + private Long expires = 7200L; + + public String getToken(){ + return token; + } + + public Long getExpires(){ + return expires; + } + + public Boolean IsSuccess(){ + return token != null; + } +} diff --git a/src/main/youhong_ai_jitu_src/com/jet/util/JwtUtil.java b/src/main/youhong_ai_jitu_src/com/jet/util/JwtUtil.java new file mode 100644 index 0000000..7b8ba9e --- /dev/null +++ b/src/main/youhong_ai_jitu_src/com/jet/util/JwtUtil.java @@ -0,0 +1,53 @@ +package com.jet.util; + +import com.auth0.jwt.JWT; +import com.auth0.jwt.algorithms.Algorithm; +import com.auth0.jwt.exceptions.JWTCreationException; + +import java.io.UnsupportedEncodingException; +import java.util.*; + +public class JwtUtil { + + /** + * 简单Sso登录 + * + * @param account:工号 + * @param clientId:客户端ID + * @param secret:秘钥 + * @param second:有效时长 + * @return + */ + public static JwtSsoTokenResult createSsoToken(String account, String clientId, String secret, int second) { + try { + Algorithm algorithm = Algorithm.HMAC256(secret); + Map map = new HashMap(); + + map.put("alg", "HS256"); + map.put("typ", "JWT"); + Date nowDate = new Date(); + Calendar cal = new GregorianCalendar(); + cal.setTime(nowDate); + cal.add(Calendar.SECOND, second); + Date expireDate = cal.getTime(); + String token = JWT.create() + .withHeader(map) + .withClaim("uid", account) + .withClaim("clientId", clientId) + .withIssuer("DbSsoServer") + .withSubject("DbSso_AccessToken") + .withAudience("Web") + .withIssuedAt(nowDate) + .withExpiresAt(expireDate) + .sign(algorithm); + return new JwtSsoTokenResult(token); + + } catch (JWTCreationException exception) { + exception.printStackTrace(); + } catch (UnsupportedEncodingException e) { + throw new RuntimeException(e); + } + return new JwtSsoTokenResult(null); + } + +} diff --git a/src/main/youhong_ai_jitu_src/com/working/link/RequestLink.java b/src/main/youhong_ai_jitu_src/com/working/link/RequestLink.java new file mode 100644 index 0000000..0efb304 --- /dev/null +++ b/src/main/youhong_ai_jitu_src/com/working/link/RequestLink.java @@ -0,0 +1,16 @@ +package com.working.link; + +import javax.servlet.http.HttpServletRequest; + +import javax.servlet.http.HttpServletResponse; +import javax.servlet.jsp.JspWriter; + +import weaver.hrm.User; +import weaver.soa.workflow.request.RequestInfo; + +public interface RequestLink { + + public abstract Object ExecuteRequest(HttpServletRequest request,HttpServletResponse response, + User user,JspWriter out,RequestInfo requestinfo,StringBuffer sb) throws Exception; + +} diff --git a/src/main/youhong_ai_jitu_src/com/working/schedule/SynDeptOrSubCom.java b/src/main/youhong_ai_jitu_src/com/working/schedule/SynDeptOrSubCom.java new file mode 100644 index 0000000..bda1350 --- /dev/null +++ b/src/main/youhong_ai_jitu_src/com/working/schedule/SynDeptOrSubCom.java @@ -0,0 +1,159 @@ +package com.working.schedule; + +import com.working.util.LogTool; + +import weaver.conn.RecordSet; +import weaver.general.Util; +import weaver.interfaces.schedule.BaseCronJob; + +/** + * 第一次初始化是同步部门或者分部信息 + * @author lwt + * + */ +public class SynDeptOrSubCom extends BaseCronJob{ + + public void execute() { + LogTool log = new LogTool("/log/working/",false); + log.writeLog("同步部门或分部信息开始."); + RecordSet rs = new RecordSet(); + RecordSet rs1 = new RecordSet(); + RecordSet rs2 = new RecordSet(); + RecordSet rs3 = new RecordSet(); + String name = "";//组织名称 + String code = "";//组织编码 + String type = "";//组织类型 + String supId = "";//上级组织id + String supName = "";//上级组织名称 + String datasourType = rs.getDBType(); + log.writeLog("datasourType="+datasourType); + if ("oracle".equals(datasourType)) { + rs.executeQuery("select * from uf_dept_subcom order by length(code) asc"); + } else if ("sqlserver".equals(datasourType)) { + rs.executeQuery("select * from uf_dept_subcom order by len(code) asc"); + } + while (rs.next()) { + name = Util.null2String(rs.getString("NAME")); + code = Util.null2String(rs.getString("CODE")); + type = Util.null2String(rs.getString("TYPE")); + supName = Util.null2String(rs.getString("SUP_NAME")); + if ("oracle".equals(datasourType)) { + if (name.indexOf("&")!=-1) {//包含& + name = name.replaceAll("&", "'||chr(38)||'"); + } + if (supName.indexOf("&")!=-1) {//包含& + supName = supName.replaceAll("&", "'||chr(38)||'"); + } + log.writeLog("name="+name+";supName="+supName); + } + if ("0".equals(type)) {//分部 + //先查询上级分部的id + rs1.execute("select * from hrmsubcompany where subcompanyname like '%"+supName+"%'"); + log.writeLog("sql1="+"select * from hrmsubcompany where subcompanyname like '%"+supName+"%'"); + while (rs1.next()) { + supId = Util.null2String(rs1.getInt("ID")); + rs2.executeQuery("select * from hrmsubcompany where subcompanyname like '%"+name+"%' and supsubcomid = " + supId); + log.writeLog("sql2="+"select * from hrmsubcompany where subcompanyname like '%"+name+"%' and supsubcomid = " + supId); + while (rs2.next()) { + log.writeLog("sql3="+"update hrmsubcompany set subcompanycode = '"+code+"' where subcompanyname like '%" + +name+"%' and supsubcomid = "+supId); + rs3.executeQuery("update hrmsubcompany set subcompanycode = '"+code+"' where subcompanyname like '%" + +name+"%' and supsubcomid = "+supId); + } + } + } else if ("1".equals(type)) {//部门 + if (code.length()==4) {//表示是jnt-->部门 + //先查询上级分部的id + rs1.executeQuery("select * from hrmsubcompany where subcompanycode = ?", code.substring(0, 2)); + while (rs1.next()) { + supId = Util.null2String(rs1.getInt("ID")); + log.writeLog("sql2="+"select * from hrmdepartment where departmentname like '%"+name+"%' and subcompanyid1 = "+ supId); + rs2.executeQuery("select * from hrmdepartment where departmentname like '%"+name+"%' and subcompanyid1 = "+ supId); + while (rs2.next()) { + log.writeLog("sql3="+"update hrmdepartment set departmentcode = '"+code+"' where departmentname like '%" + +name+"%' and subcompanyid1 = "+supId); + rs3.executeQuery("update hrmdepartment set departmentcode = '"+code+"' where departmentname like '%" + +name+"%' and subcompanyid1 = "+supId); + } + } + } else if (code.length()==6) {//表示是分部-->部门 + //先查询上级分部的id + rs1.executeQuery("select * from hrmsubcompany where subcompanycode = ?", code.substring(0, 4)); + while (rs1.next()) { + supId = Util.null2String(rs1.getInt("ID")); + log.writeLog("sql2="+"select * from hrmdepartment where departmentname like '%"+name+"%' and subcompanyid1 = "+ supId); + rs2.executeQuery("select * from hrmdepartment where departmentname like '%"+name+"%' and subcompanyid1 = "+ supId); + while (rs2.next()) { + log.writeLog("sql3="+"update hrmdepartment set departmentcode = '"+code+"' where departmentname like '%" + +name+"%' and subcompanyid1 = "+supId); + rs3.executeQuery("update hrmdepartment set departmentcode = '"+code+"' where departmentname like '%" + +name+"%' and subcompanyid1 = "+supId); + } + } + } else if (code.length()==8) {//表示是分部-->部门-->部门 + //先查询上级部门的id + rs1.executeQuery("select * from hrmdepartment where departmentcode = ?", code.substring(0, 6)); + while (rs1.next()) { + supId = Util.null2String(rs1.getInt("ID")); + log.writeLog("sql2="+"select * from hrmdepartment where departmentname like '%"+name+"%' and supdepid = "+supId); + rs2.executeQuery("select * from hrmdepartment where departmentname like '%"+name+"%' and supdepid = "+supId); + while (rs2.next()) { + log.writeLog("sql3="+"update hrmdepartment set departmentcode = '"+code+"' where departmentname like '%" + +name+"%' and supdepid = "+supId); + rs3.executeQuery("update hrmdepartment set departmentcode = '"+code+"' where departmentname like '%" + +name+"%' and supdepid = "+supId); + } + } + } else if (code.length()==10) {//表示是分部-->分部-->部门 + //先查询上级分部的id + rs1.executeQuery("select * from hrmsubcompany where subcompanycode = ?", code.substring(0, 8)); + while (rs1.next()) { + supId = Util.null2String(rs1.getInt("ID")); + log.writeLog("sql2="+"select * from hrmdepartment where departmentname like '%"+name+"%' and subcompanyid1 = "+ supId); + rs2.executeQuery("select * from hrmdepartment where departmentname like '%"+name+"%' and subcompanyid1 = "+ supId); + while (rs2.next()) { + log.writeLog("sql3="+"update hrmdepartment set departmentcode = '"+code+"' where departmentname like '%" + +name+"%' and subcompanyid1 = "+supId); + rs3.executeQuery("update hrmdepartment set departmentcode = '"+code+"' where departmentname like '%" + +name+"%' and subcompanyid1 = "+supId); + } + } + //再查询上级部门的id + rs1.executeQuery("select * from hrmdepartment where departmentcode = ?", code.substring(0, 8)); + while (rs1.next()) { + supId = Util.null2String(rs1.getInt("ID")); + log.writeLog("sql2="+"select * from hrmdepartment where departmentname like '%"+name+"%' and supdepid = "+ supId); + rs2.executeQuery("select * from hrmdepartment where departmentname like '%"+name+"%' and supdepid = "+ supId); + while (rs2.next()) { + log.writeLog("sql3="+"update hrmdepartment set departmentcode = '"+code+"' where departmentname like '%" + +name+"%' and supdepid = "+supId); + rs3.executeQuery("update hrmdepartment set departmentcode = '"+code+"' where departmentname like '%" + +name+"%' and supdepid = "+supId); + } + } + } else if (code.length()==12) {//表示分部-->分部-->部门-->部门 + //先查询上级部门的id + rs1.executeQuery("select * from hrmdepartment where departmentcode = ?", code.substring(0, 10)); + while (rs1.next()) { + supId = Util.null2String(rs1.getInt("ID")); + log.writeLog("sql2="+"select * from hrmdepartment where departmentname like '%"+name+"%' and supdepid = "+ supId); + rs2.executeQuery("select * from hrmdepartment where departmentname like '%"+name+"%' and supdepid = "+ supId); + while (rs2.next()) { + log.writeLog("sql3="+"update hrmdepartment set departmentcode = '"+code+"' where departmentname like '%" + +name+"%' and supdepid = "+supId); + rs3.executeQuery("update hrmdepartment set departmentcode = '"+code+"' where departmentname like '%" + +name+"%' and supdepid = "+supId); + } + } + } + } + } + log.writeLog("同步部门或分部信息结束."); + } + +} + + + + + diff --git a/src/main/youhong_ai_jitu_src/com/working/schedule/SynScheduleSignDatas.java b/src/main/youhong_ai_jitu_src/com/working/schedule/SynScheduleSignDatas.java new file mode 100644 index 0000000..d08958b --- /dev/null +++ b/src/main/youhong_ai_jitu_src/com/working/schedule/SynScheduleSignDatas.java @@ -0,0 +1,193 @@ +package com.working.schedule; + +import java.io.IOException; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.Iterator; +import java.util.List; +import java.util.Map; + +import org.apache.commons.httpclient.HttpException; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.JSONObject; +import com.alibaba.fastjson.serializer.SerializerFeature; + +import weaver.file.Prop; + +import com.working.third.JwtUtil; +import com.working.util.HttpManager; +import com.working.util.LogTool; +import com.working.util.WorkflowUtil; + +import weaver.conn.RecordSet; +import weaver.general.Util; +import weaver.interfaces.schedule.BaseCronJob; + +/** + * 查询人员移动端考勤信息,并同步更新到东宝系统 + * @author lwt + * + */ +public class SynScheduleSignDatas extends BaseCronJob{ + + public void execute() { + LogTool log = new LogTool("/log/working/schedule",false); + String clientId = Prop.getPropValue("db_work","clientId"); + String secret = Prop.getPropValue("db_work","secret"); + Integer second = Integer.valueOf(Prop.getPropValue("db_work","second")); + String code = Prop.getPropValue("db_work","code"); + String moduleCode = Prop.getPropValue("db_work","moduleCode"); + String batchCardDataUrl = Prop.getPropValue("db_work","batchCardDataUrl"); + log.writeLog("同步人员移动端考勤信息更新到东宝系统开始.clientId="+clientId+";secret="+secret+";second="+second + +";code="+code+";moduleCode="+moduleCode+";batchCardDataUrl="+batchCardDataUrl); + String token = JwtUtil.createThirdToken(clientId,secret,second).getToken(); + Map dataMap = new HashMap();//保存数据id和员工编号的集合 + Map headMap = new HashMap(); + headMap.put("code",code); + headMap.put("moduleCode",moduleCode); + headMap.put("token",token); + headMap.put("clientId",clientId); + Map bodyMap2 = new HashMap(); + Map bodyMap3 = new HashMap(); + List list = new ArrayList();//存储打卡数据 + List idList = new ArrayList();//存储数据id + + RecordSet rs = new RecordSet(); + RecordSet rs1 = new RecordSet(); + String id = "";//签到id + String workCode = "";//人员编号 + String userId = "";//签到人id + String signDate = "";//签到日期 + String signTime = "";//签到时间 + String longitude = "";//经度 + String latitude = "";//纬度 + String address = "";//地址 + String remark = "";//签到备注 + //查询考勤数据 + String datasource = rs.getDBType(); + log.writeLog("datasource="+datasource); + if ("oracle".equals(datasource)) { + rs.execute("select * from hrmschedulesign where syn_flag != 2 order by signdate desc"); + } else if ("sqlserver".equals(datasource)) { + rs.execute("select * from hrmschedulesign where syn_flag != 2 order by signdate desc"); + } + //取到考勤数据,调用同步接口 + while (rs.next()) { + Map bodyMap = new HashMap(); + Map bodyMap1 = new HashMap(); + id = Util.null2String(rs.getInt("ID")); + idList.add(id); + userId = Util.null2String(rs.getString("USERID")); + workCode = Util.null2String(WorkflowUtil.getUserInfo(userId).get("workcode")); + dataMap.put(id, workCode); + signDate = Util.null2String(rs.getString("SIGNDATE")); + signTime = Util.null2String(rs.getString("SIGNTIME")); + longitude = Util.null2String(rs.getString("LONGITUDE")); + latitude = Util.null2String(rs.getString("LATITUDE")); + address = Util.null2String(rs.getString("ADDR")); + remark = Util.null2String(rs.getString("REMARK")); +// log.writeLog("id="+id+";workCode="+workCode+";userId="+userId+";signDate="+signDate+";signTime="+signTime +// +";longitude="+longitude+";latitude="+latitude+";address="+address); + bodyMap.put("cardTime", signDate + " " +signTime); + bodyMap.put("dataSource", "8"); + bodyMap.put("signPlace", address); + bodyMap.put("status", "1"); + bodyMap.put("longitude", longitude); + bodyMap.put("latitude", latitude); + bodyMap.put("describe", remark); + bodyMap.put("timeZone", "GMT+8"); + bodyMap1.put("empRule","1"); + bodyMap1.put("empKey",workCode); + bodyMap1.put("cardData",bodyMap); + //存储所有数据在集合中 + list.add(bodyMap1); + } +// bodyMap2.put("empOrders", list); + bodyMap3.put("header",headMap); + bodyMap3.put("body",bodyMap2); + try { + if (list.size()>0) { + //循环次数,每次传输1000条数据 + int num = list.size()/1000+1; + for (int i=0;i<=num;i++) { + //初始化传输的list + List listSign = new ArrayList(); + List listSignId = new ArrayList(); + for (int j=i*1000;j<(i+1)*1000;j++) { + if (j>=list.size()) {//超出list的下标,跳出循环 + break; + } + listSign.add(list.get(j)); + listSignId.add(idList.get(j)); + } + if (listSign.size() ==0) { + continue; + } else { + bodyMap2.put("empOrders", listSign); + } + String param = JSON.toJSONString(bodyMap3,SerializerFeature.DisableCircularReferenceDetect); +// log.writeLog("param="+param); + String result = HttpManager.postMap(batchCardDataUrl,headMap,param); + log.writeLog("result="+result); + //解析返回值result + JSONObject jsonObject = new JSONObject(); + //解析JOSN + jsonObject = JSONObject.parseObject(result); + String returnCode = Util.null2String(jsonObject.get("code")); + String data = Util.null2String(jsonObject.get("data")); + if ("200".equals(returnCode)) {//同步成功(可能存在部分数据失败) + //先全部更新为同步成功 + log.writeLog("sql1="+"update hrmschedulesign set syn_flag = 2 where id in ("+listSignId.toString().replace("[", "'").replace("]", "'").replace(",", "','")+")"); + rs1.execute("update hrmschedulesign set syn_flag = 2 where id in ("+listSignId.toString().replace("[", "'").replace("]", "'").replace(",", "','")+")"); + if (!data.isEmpty()) {//有更新失败的 + //解析返回值data + JSONObject dataObject = new JSONObject(); + dataObject = JSONObject.parseObject(data); + String key = "";//返回的错误的数据的员工编号 + String mapKey = "";//保存map的key + String mapValue = "";//保存map的value + Iterator dataIterator = dataObject.keySet().iterator(); + Iterator dataMapIter = dataMap.keySet().iterator(); + while (dataIterator.hasNext()) { + // 获得key + key = dataIterator.next(); + while (dataMapIter.hasNext()) { + mapKey = dataMapIter.next(); + mapValue = dataMap.get(mapKey); + if (key.equals(mapValue)) { + //更新为同步失败 + rs1.executeQuery("update hrmschedulesign set syn_flag = 1 where id = ?", mapKey); + } + } + } + } + } else {//同步异常,更新这批数据为同步失败 + rs1.executeQuery("update hrmschedulesign set syn_flag = 1 where id in (?)", listSignId.toString().replace("[", "'").replace("]", "'").replace(",", "','")); + } + } + } else { + log.writeLog("此次查询无符合数据!"); + } + } catch (HttpException e) { + // TODO Auto-generated catch block + log.writeLog("HttpException="+e.toString()); + e.printStackTrace(); + } catch (IOException e) { + // TODO Auto-generated catch block + log.writeLog("IOException="+e.toString()); + e.printStackTrace(); + } catch (Exception e) { + log.writeLog("Exception="+e.toString()); + e.printStackTrace(); + } + + log.writeLog("同步人员移动端考勤信息更新到东宝系统结束."); + } + +} + + + + + diff --git a/src/main/youhong_ai_jitu_src/com/working/schedule/SynSignDatas.java b/src/main/youhong_ai_jitu_src/com/working/schedule/SynSignDatas.java new file mode 100644 index 0000000..811b77e --- /dev/null +++ b/src/main/youhong_ai_jitu_src/com/working/schedule/SynSignDatas.java @@ -0,0 +1,193 @@ +package com.working.schedule; + +import java.io.IOException; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.Iterator; +import java.util.List; +import java.util.Map; + +import org.apache.commons.httpclient.HttpException; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.JSONObject; +import com.alibaba.fastjson.serializer.SerializerFeature; + +import weaver.file.Prop; + +import com.working.third.JwtUtil; +import com.working.util.HttpManager; +import com.working.util.LogTool; +import com.working.util.WorkflowUtil; + +import weaver.conn.RecordSet; +import weaver.general.Util; +import weaver.interfaces.schedule.BaseCronJob; + +/** + * 查询人员移动端外勤考勤信息,并同步更新到东宝系统 + * @author lwt + * + */ +public class SynSignDatas extends BaseCronJob{ + + public void execute() { + LogTool log = new LogTool("/log/working/sign",false); + String clientId = Prop.getPropValue("db_work","clientId"); + String secret = Prop.getPropValue("db_work","secret"); + Integer second = Integer.valueOf(Prop.getPropValue("db_work","second")); + String code = Prop.getPropValue("db_work","code"); + String moduleCode = Prop.getPropValue("db_work","moduleCode"); + String batchCardDataUrl = Prop.getPropValue("db_work","batchCardDataUrl"); + log.writeLog("同步人员移动端考勤信息更新到东宝系统开始.clientId="+clientId+";secret="+secret+";second="+second + +";code="+code+";moduleCode="+moduleCode+";batchCardDataUrl="+batchCardDataUrl); + String token = JwtUtil.createThirdToken(clientId,secret,second).getToken(); + Map dataMap = new HashMap();//保存数据id和员工编号的集合 + Map headMap = new HashMap(); + headMap.put("code",code); + headMap.put("moduleCode",moduleCode); + headMap.put("token",token); + headMap.put("clientId",clientId); + Map bodyMap2 = new HashMap(); + Map bodyMap3 = new HashMap(); + List list = new ArrayList();//存储打卡数据 + List idList = new ArrayList();//存储数据id + + RecordSet rs = new RecordSet(); + RecordSet rs1 = new RecordSet(); + String id = "";//移动签到id + String workCode = "";//人员编号 + String operater = "";//签到人id + String operateDate = "";//签到日期 + String operateTime = "";//签到时间 + String longitude = "";//经度 + String latitude = "";//纬度 + String address = "";//地址 + String remark = "";//签到备注 + //查询考勤数据 + String datasource = rs.getDBType(); + log.writeLog("datasource="+datasource); + if ("oracle".equals(datasource)) { + rs.execute("select * from mobile_sign where syn_flag != 2 order by operate_date desc"); + } else if ("sqlserver".equals(datasource)) { + rs.execute("select * from mobile_sign where syn_flag != 2 order by operate_date desc"); + } + //取到考勤数据,调用同步接口 + while (rs.next()) { + Map bodyMap = new HashMap(); + Map bodyMap1 = new HashMap(); + id = Util.null2String(rs.getInt("ID")); + idList.add(id); + operater = Util.null2String(rs.getString("OPERATER")); + workCode = Util.null2String(WorkflowUtil.getUserInfo(operater).get("workcode")); + dataMap.put(id, workCode); + operateDate = Util.null2String(rs.getString("OPERATE_DATE")); + operateTime = Util.null2String(rs.getString("OPERATE_TIME")); + longitude = Util.null2String(rs.getString("LONGITUDE")); + latitude = Util.null2String(rs.getString("LATITUDE")); + address = Util.null2String(rs.getString("ADDRESS")); + remark = Util.null2String(rs.getString("REMARK")); +// log.writeLog("id="+id+";workCode="+workCode+";operater="+operater+";operateDate="+operateDate+";operateTime="+operateTime +// +";longitude="+longitude+";latitude="+latitude+";address="+address+";remark="+remark); + bodyMap.put("cardTime", operateDate + " " +operateTime); + bodyMap.put("dataSource", "8"); + bodyMap.put("signPlace", address); + bodyMap.put("status", "1"); + bodyMap.put("longitude", longitude); + bodyMap.put("latitude", latitude); + bodyMap.put("describe", remark); + bodyMap.put("timeZone", "GMT+8"); + bodyMap1.put("empRule","1"); + bodyMap1.put("empKey",workCode); + bodyMap1.put("cardData",bodyMap); + //查询所有数据放入集合 + list.add(bodyMap1); + } +// bodyMap2.put("empOrders", list); + bodyMap3.put("header",headMap); + bodyMap3.put("body",bodyMap2); + try { + if (list.size()>0) { + //循环次数,每次传输1000条数据 + int num = list.size()/1000+1; + for (int i=0;i<=num;i++) { + //初始化传输的list + List listSign = new ArrayList(); + List listSignId = new ArrayList(); + for (int j=i*1000;j<(i+1)*1000;j++) { + if (j>=list.size()) {//超出list的下标,跳出循环 + break; + } + listSign.add(list.get(j)); + listSignId.add(idList.get(j)); + } + if (listSign.size() ==0) { + continue; + } else { + bodyMap2.put("empOrders", listSign); + } + String param = JSON.toJSONString(bodyMap3,SerializerFeature.DisableCircularReferenceDetect); +// log.writeLog("param="+param); + String result = HttpManager.postMap(batchCardDataUrl,headMap,param); + log.writeLog("result="+result); + //解析返回值result + JSONObject jsonObject = new JSONObject(); + //解析JOSN + jsonObject = JSONObject.parseObject(result); + String returnCode = Util.null2String(jsonObject.get("code")); + String data = Util.null2String(jsonObject.get("data")); + if ("200".equals(returnCode)) {//同步成功(可能存在部分数据失败) + //先全部更新为同步成功 + log.writeLog("sql1="+"update mobile_sign set syn_flag = 2 where id in ("+listSignId.toString().replace("[", "'").replace("]", "'").replace(",", "','")+")"); + rs1.execute("update mobile_sign set syn_flag = 2 where id in ("+listSignId.toString().replace("[", "'").replace("]", "'").replace(",", "','")+")"); + if (!data.isEmpty()) {//有更新失败的 + //解析返回值data + JSONObject dataObject = new JSONObject(); + dataObject = JSONObject.parseObject(data); + String key = "";//返回的错误的数据的员工编号 + String mapKey = "";//保存map的key + String mapValue = "";//保存map的value + Iterator dataIterator = dataObject.keySet().iterator(); + Iterator dataMapIter = dataMap.keySet().iterator(); + while (dataIterator.hasNext()) { + // 获得key + key = dataIterator.next(); + while (dataMapIter.hasNext()) { + mapKey = dataMapIter.next(); + mapValue = dataMap.get(mapKey); + if (key.equals(mapValue)) { + //更新为同步失败 + rs1.executeQuery("update mobile_sign set syn_flag = 1 where id = ?", mapKey); + } + } + } + } + } else {//同步异常,更新这批数据为同步失败 + rs1.executeQuery("update mobile_sign set syn_flag = 1 where id in (?)", listSignId.toString().replace("[", "'").replace("]", "'").replace(",", "','")); + } + } + } else { + log.writeLog("此次查询无符合数据!"); + } + } catch (HttpException e) { + // TODO Auto-generated catch block + log.writeLog("HttpException="+e.toString()); + e.printStackTrace(); + } catch (IOException e) { + // TODO Auto-generated catch block + log.writeLog("IOException="+e.toString()); + e.printStackTrace(); + } catch (Exception e) { + log.writeLog("Exception="+e.toString()); + e.printStackTrace(); + } + + log.writeLog("同步人员移动端考勤信息更新到东宝系统结束."); + } + +} + + + + + diff --git a/src/main/youhong_ai_jitu_src/com/working/schedule/WorkingTimer.java b/src/main/youhong_ai_jitu_src/com/working/schedule/WorkingTimer.java new file mode 100644 index 0000000..84a4c7a --- /dev/null +++ b/src/main/youhong_ai_jitu_src/com/working/schedule/WorkingTimer.java @@ -0,0 +1,28 @@ +package com.working.schedule; + +import com.working.util.LogTool; +import weaver.interfaces.schedule.BaseCronJob; + +/** + * 考勤同步数据总的定时器 + * @author lwt + * + */ +public class WorkingTimer extends BaseCronJob{ + + public void execute() { + LogTool log = new LogTool("/log/working",false); + log.writeLog("考勤总的同步定时开始."); + SynSignDatas ssd = new SynSignDatas(); + ssd.execute(); + SynScheduleSignDatas sssd = new SynScheduleSignDatas(); + sssd.execute(); + log.writeLog("考勤总的同步定时结束."); + } + +} + + + + + diff --git a/src/main/youhong_ai_jitu_src/com/working/test/SSLClient.java b/src/main/youhong_ai_jitu_src/com/working/test/SSLClient.java new file mode 100644 index 0000000..095dc4e --- /dev/null +++ b/src/main/youhong_ai_jitu_src/com/working/test/SSLClient.java @@ -0,0 +1,35 @@ +package com.working.test; + +import java.security.cert.CertificateException; +import java.security.cert.X509Certificate; +import javax.net.ssl.SSLContext; +import javax.net.ssl.TrustManager; +import javax.net.ssl.X509TrustManager; +import org.apache.http.conn.ClientConnectionManager; +import org.apache.http.conn.scheme.Scheme; +import org.apache.http.conn.scheme.SchemeRegistry; +import org.apache.http.conn.ssl.SSLSocketFactory; +import org.apache.http.impl.client.DefaultHttpClient; +//用于进行Https请求的HttpClient +public class SSLClient extends DefaultHttpClient{ + public SSLClient() throws Exception{ + super(); + SSLContext ctx = SSLContext.getInstance("TLS"); + X509TrustManager tm = new X509TrustManager() { + public void checkClientTrusted(X509Certificate[] chain, + String authType) throws CertificateException { + } + public void checkServerTrusted(X509Certificate[] chain, + String authType) throws CertificateException { + } + public X509Certificate[] getAcceptedIssuers() { + return null; + } + }; + ctx.init(null, new TrustManager[]{tm}, null); + SSLSocketFactory ssf = new SSLSocketFactory(ctx,SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER); + ClientConnectionManager ccm = this.getConnectionManager(); + SchemeRegistry sr = ccm.getSchemeRegistry(); + sr.register(new Scheme("https", 443, ssf)); + } +} \ No newline at end of file diff --git a/src/main/youhong_ai_jitu_src/com/working/test/Test.java b/src/main/youhong_ai_jitu_src/com/working/test/Test.java new file mode 100644 index 0000000..06e8dcc --- /dev/null +++ b/src/main/youhong_ai_jitu_src/com/working/test/Test.java @@ -0,0 +1,82 @@ +package com.working.test; + +import java.util.HashMap; +import java.util.Map; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.serializer.SerializerFeature; +import com.working.third.JwtUtil; +import com.working.util.HttpManager; + +public class Test { + + /** + * 单个接口 + * @param args + * @throws Exception + */ + public static void main(String[] args) throws Exception { + // TODO Auto-generated method stub + try { + String token = JwtUtil.createThirdToken("P3F28BIFKGFL0ANX","5UGY7G1N8O",36000).getToken(); +// System.out.println(token); + String param = + "{"+ + "\"header\":{"+ + "\"code\":\"saveCardDataToThird\","+ + "\"moduleCode\":\"attCardDataService\","+ + "\"token\":\""+token+"\","+ + "\"clientId\":\"P3F28BIFKGFL0ANX\","+ + "\"empRule\":\"1\","+ + "\"empInfo\":\"00000775\""+ + "},"+ + "\"body\":{"+ + "\"cardData\":{"+ + "\"cardTime\":\"\","+ + "\"dataSource\":\"8\","+ + "\"signPlace\":\"上海市王者村\","+ + "\"status\":\"1\","+ + "\"longitude\":\"121.45787447\","+ + "\"latitude\":\"124.54444411\","+ + "\"orderId\":\"1168801193654599682\","+ + "\"orderCode\":\"BT20190903000204\","+ + "\"describe\":\"移动签到测试\","+ + "\"timeZone\":\"\""+ + "}"+ + "}"+ + "}"; + Map headMap = new HashMap(); + headMap.put("code","saveCardDataToThird"); + headMap.put("moduleCode","attCardDataService"); + headMap.put("token",token); + headMap.put("clientId","P3F28BIFKGFL0ANX"); + headMap.put("empRule","1"); + headMap.put("empInfo","00000775"); + Map bodyMap = new HashMap(); + Map bodyMap1 = new HashMap(); + Map bodyMap2 = new HashMap(); + bodyMap.put("cardTime", ""); + bodyMap.put("dataSource", "8"); + bodyMap.put("signPlace", "上海市王者村"); + bodyMap.put("status", "1"); + bodyMap.put("longitude", "121.45787447"); + bodyMap.put("latitude", "124.54444411"); + bodyMap.put("orderId", "1168801193654599682"); + bodyMap.put("orderCode", "BT20190903000204"); + bodyMap.put("describe", "移动签到测试"); + bodyMap.put("timeZone", "GMT+8"); + bodyMap1.put("cardData",bodyMap); + bodyMap2.put("header",headMap); + bodyMap2.put("body",bodyMap1); + param = JSON.toJSONString(bodyMap2,SerializerFeature.DisableCircularReferenceDetect); + System.out.println(param); + String result = HttpManager.postMap("https://hr.jtexpress.com:9022/third/api",headMap,param); + System.out.println(result); + } catch (Exception e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + + } + +} diff --git a/src/main/youhong_ai_jitu_src/com/working/test/Test1.java b/src/main/youhong_ai_jitu_src/com/working/test/Test1.java new file mode 100644 index 0000000..f43f135 --- /dev/null +++ b/src/main/youhong_ai_jitu_src/com/working/test/Test1.java @@ -0,0 +1,63 @@ +package com.working.test; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.serializer.SerializerFeature; +import com.working.third.JwtUtil; +import com.working.util.HttpManager; + +public class Test1 { + + /** + * 批量接口 + * @param args + * @throws Exception + */ + public static void main(String[] args) throws Exception { + // TODO Auto-generated method stub + try { + String token = JwtUtil.createThirdToken("P3F28BIFKGFL0ANX","5UGY7G1N8O",36000).getToken(); +// System.out.println(token); + Map headMap = new HashMap(); + headMap.put("code","saveBatchCardDataToThird"); + headMap.put("moduleCode","attCardDataService"); + headMap.put("token",token); + headMap.put("clientId","P3F28BIFKGFL0ANX"); + Map bodyMap2 = new HashMap(); + Map bodyMap3 = new HashMap(); + List list = new ArrayList(); + for (int i=0;i<=2;i++) { + Map bodyMap = new HashMap(); + Map bodyMap1 = new HashMap(); + bodyMap.put("cardTime", "2019-07-20 13:22:13"); + bodyMap.put("dataSource", "8"); + bodyMap.put("signPlace", "上海市王者村"); + bodyMap.put("status", "1"); + bodyMap.put("longitude", "121.45787447"); + bodyMap.put("latitude", "124.54444411"); + bodyMap.put("describe", "移动签到测试"); + bodyMap.put("timeZone", "GMT+8"); + bodyMap1.put("empRule","1"); + bodyMap1.put("empKey","00000006"); + bodyMap1.put("cardData",bodyMap); + list.add(bodyMap1); + } + bodyMap2.put("empOrders", list); + bodyMap3.put("header",headMap); + bodyMap3.put("body",bodyMap2); + String param = JSON.toJSONString(bodyMap3,SerializerFeature.DisableCircularReferenceDetect); + System.out.println(param); + String result = HttpManager.postMap("https://hr.jtexpress.com:9022/third/api",headMap,param); + System.out.println(result); + } catch (Exception e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + + } + +} diff --git a/src/main/youhong_ai_jitu_src/com/working/test/Test2.java b/src/main/youhong_ai_jitu_src/com/working/test/Test2.java new file mode 100644 index 0000000..e9308ba --- /dev/null +++ b/src/main/youhong_ai_jitu_src/com/working/test/Test2.java @@ -0,0 +1,47 @@ +package com.working.test; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.JSONObject; +import com.alibaba.fastjson.serializer.SerializerFeature; +import com.working.third.JwtUtil; +import com.working.util.HttpManager; + +public class Test2 { + + public static void main(String[] args) throws Exception { + // TODO Auto-generated method stub + //解析JOSN() + Map map = new HashMap(); + map.put("deptCode", "01010101"); + map.put("bmfzr", "00000001"); + map.put("bmfgld", ""); + String json = JSON.toJSONString(map); + System.out.println(json); +// List list = new ArrayList(); +// System.out.println(list); +// JSONObject jsonObject = new JSONObject(); +// //解析JOSN +// jsonObject = JSONObject.parseObject(json); +// String bmfzr = jsonObject.getString("bmfzr"); +// System.out.println(bmfzr.isEmpty()); + +// Map comMap = new HashMap(); +// comMap.put("subComCode", "JTyn"); +// comMap.put("cwsh", "389,390"); +// comMap.put("zzcw", "412,413"); +// comMap.put("cwzj", "MSIL15,MSIL47"); +// comMap.put("ceozjl", "MSIL15,MSIL47"); +// comMap.put("cn", "389,390"); +// comMap.put("cnfh", "MSIL15,MSIL47"); +// comMap.put("zjbfzr", "412,413"); +// String comJson = JSON.toJSONString(comMap); +// System.out.println(comJson); + + } + +} diff --git a/src/main/youhong_ai_jitu_src/com/working/test/Test3.java b/src/main/youhong_ai_jitu_src/com/working/test/Test3.java new file mode 100644 index 0000000..ed2a396 --- /dev/null +++ b/src/main/youhong_ai_jitu_src/com/working/test/Test3.java @@ -0,0 +1,33 @@ +package com.working.test; + +import java.util.Iterator; + +import weaver.general.Util; + +import com.alibaba.fastjson.JSONObject; + +public class Test3 { + + public static void main(String[] args) throws Exception { +// String json = "{\"code\":200,\"data\":{\"123000007701\":\"用户信息为空\",\"12300000770\":\"用户信息为空\",\"1230000077012\":\"用户信息为空\"},\"id\":\"\",\"list\":[],\"message\":\"操作成功\",\"rows\":null}"; +// //解析返回值result +// JSONObject jsonObject = new JSONObject(); +// //解析JOSN +// jsonObject = JSONObject.parseObject(json); +// String returnCode = Util.null2String(jsonObject.getString("code")); +// String data = Util.null2String(jsonObject.getString("data")); +// JSONObject dataObject = jsonObject.parseObject(data); +// String key = ""; +// Iterator entry = dataObject.keySet().iterator(); +// while(entry.hasNext()){ +// // 获得key +// key = entry.next(); +// System.out.println(key); +// } + String code = "01091138"; + System.out.println(code.substring(0, 6)); + System.out.println(code.length()); + + } + +} diff --git a/src/main/youhong_ai_jitu_src/com/working/test/Test4.java b/src/main/youhong_ai_jitu_src/com/working/test/Test4.java new file mode 100644 index 0000000..f0510e8 --- /dev/null +++ b/src/main/youhong_ai_jitu_src/com/working/test/Test4.java @@ -0,0 +1,18 @@ +package com.working.test; + +import java.util.Iterator; + +import weaver.general.Util; + +import com.alibaba.fastjson.JSONObject; + +public class Test4 { + + public static void main(String[] args) throws Exception { + StringBuffer a = new StringBuffer(); + a.append("'").append("'"); + System.out.println(a); + System.out.println(a.toString().equals("''")); + } + +} diff --git a/src/main/youhong_ai_jitu_src/com/working/third/JwtThirdTokenResult.java b/src/main/youhong_ai_jitu_src/com/working/third/JwtThirdTokenResult.java new file mode 100644 index 0000000..100222c --- /dev/null +++ b/src/main/youhong_ai_jitu_src/com/working/third/JwtThirdTokenResult.java @@ -0,0 +1,8 @@ +package com.working.third; + +public class JwtThirdTokenResult extends JwtTokenResult{ + + public JwtThirdTokenResult(String token) { + super(token); + } +} diff --git a/src/main/youhong_ai_jitu_src/com/working/third/JwtTokenResult.java b/src/main/youhong_ai_jitu_src/com/working/third/JwtTokenResult.java new file mode 100644 index 0000000..1f851e6 --- /dev/null +++ b/src/main/youhong_ai_jitu_src/com/working/third/JwtTokenResult.java @@ -0,0 +1,23 @@ +package com.working.third; + +public class JwtTokenResult { + + public JwtTokenResult(String token){ + this.token = token; + } + + private String token; + private Long expires = 7200L; + + public String getToken(){ + return token; + } + + public Long getExpires(){ + return expires; + } + + public Boolean IsSuccess(){ + return token != null; + } +} diff --git a/src/main/youhong_ai_jitu_src/com/working/third/JwtUtil.java b/src/main/youhong_ai_jitu_src/com/working/third/JwtUtil.java new file mode 100644 index 0000000..b8fc16f --- /dev/null +++ b/src/main/youhong_ai_jitu_src/com/working/third/JwtUtil.java @@ -0,0 +1,60 @@ +package com.working.third; + +import com.auth0.jwt.JWT; +import com.auth0.jwt.JWTVerifier; +import com.auth0.jwt.algorithms.Algorithm; +import com.auth0.jwt.interfaces.Claim; +import com.auth0.jwt.interfaces.DecodedJWT; + +import java.util.Calendar; +import java.util.Date; +import java.util.GregorianCalendar; +import java.util.HashMap; +import java.util.Map; + +public class JwtUtil { + + private static final String SECRET = "5UGY7G1N8O"; + + /** + * 生成token + * @param secret + * @param second + * @return + */ + public static JwtThirdTokenResult createThirdToken(String clientId,String secret,int second){ + try { + Algorithm algorithm = Algorithm.HMAC256(secret); + Map map = new HashMap(); + + map.put("alg", "HS256"); + map.put("typ", "JWT"); + Date nowDate = new Date(); + Calendar cal = new GregorianCalendar(); + cal.setTime(nowDate); + cal.add(Calendar.SECOND, -3600); + nowDate = cal.getTime(); + + cal = new GregorianCalendar(); + cal.setTime(nowDate); + cal.add(Calendar.SECOND, second); + + Date expireDate = cal.getTime(); + String token = JWT.create() + .withHeader(map) + .withClaim("clientId", clientId) + .withIssuer("DbSsoServer") + .withSubject("DbSso_AccessToken") + .withAudience("Web") + .withIssuedAt(nowDate) + .withExpiresAt(expireDate) + .sign(algorithm); + return new JwtThirdTokenResult(token); + + } catch (Exception exception){ + exception.printStackTrace(); + } + return new JwtThirdTokenResult(null); + } + +} diff --git a/src/main/youhong_ai_jitu_src/com/working/util/ActionUtil.java b/src/main/youhong_ai_jitu_src/com/working/util/ActionUtil.java new file mode 100644 index 0000000..01fb00d --- /dev/null +++ b/src/main/youhong_ai_jitu_src/com/working/util/ActionUtil.java @@ -0,0 +1,49 @@ +package com.working.util; + +import weaver.conn.RecordSet; +import weaver.general.Util; +import weaver.soa.workflow.request.RequestInfo; + +public class ActionUtil { + + /** + * 通过请求id获得流程基本参数 + * @param requsetid + * @return + */ + public static WAction getMainTable(RequestInfo requestInfo){ + WAction action=new WAction(); + String requestid = Util.getIntValue(requestInfo.getRequestid())+""; + String workflowId = requestInfo.getWorkflowid(); + RecordSet rs0 = new RecordSet(); + rs0.execute("select formid from workflow_base where id in(select workflowid from workflow_requestbase where requestid='"+requestid+"')"); + String mainTabName=""; + String formid=""; + if(rs0.next()){ + formid=Util.null2String(rs0.getString("formid").replace("-", "")); + mainTabName="formtable_main_"+formid; + } + action.setRequestid(requestid); + action.setFormid(formid); + action.setMainTabName(mainTabName); + action.setWorkflowId(workflowId); + return action; + } + + /** + * 获得流程主表的id + * @param tableName + * @param requestid + * @return + */ + public static String getMainId(String tableName,String requestid){ + RecordSet rsRecordSet = new RecordSet(); + String sql=" select id from "+tableName+" where requestid='"+requestid+"' "; + rsRecordSet.execute(sql); + if(rsRecordSet.next()){ + return rsRecordSet.getString("id"); + } + return ""; + } + +} diff --git a/src/main/youhong_ai_jitu_src/com/working/util/HttpManager.java b/src/main/youhong_ai_jitu_src/com/working/util/HttpManager.java new file mode 100644 index 0000000..75316a0 --- /dev/null +++ b/src/main/youhong_ai_jitu_src/com/working/util/HttpManager.java @@ -0,0 +1,101 @@ +package com.working.util; + +import org.apache.commons.httpclient.HttpException; +import org.apache.http.HttpEntity; +import org.apache.http.client.methods.CloseableHttpResponse; +import org.apache.http.client.methods.HttpPost; +import org.apache.http.conn.ssl.NoopHostnameVerifier; +import org.apache.http.conn.ssl.SSLConnectionSocketFactory; +import org.apache.http.conn.ssl.TrustSelfSignedStrategy; +import org.apache.http.conn.ssl.TrustStrategy; +import org.apache.http.entity.ContentType; +import org.apache.http.entity.StringEntity; +import org.apache.http.impl.client.CloseableHttpClient; +import org.apache.http.impl.client.HttpClients; +import org.apache.http.ssl.SSLContextBuilder; +import org.apache.http.ssl.SSLContexts; +import org.apache.http.util.EntityUtils; + +import javax.net.ssl.SSLContext; +import java.io.IOException; +import java.security.KeyManagementException; +import java.security.KeyStoreException; +import java.security.NoSuchAlgorithmException; +import java.security.cert.CertificateException; +import java.security.cert.X509Certificate; +import java.util.Iterator; +import java.util.Map; +import java.util.Map.Entry; + +/** + * @author Administrator + * + */ +public class HttpManager { + /** + * 向指定 URL 发送POST方法的请求 + * @param url + * 发送请求的 URL + * @param param + * 请求参数,请求参数应该是 name1=value1&name2=value2 的形式。 + * @return 所代表远程资源的响应结果 + * @throws IOException + * @throws HttpException + * @throws Exception + */ + public static String postMap(String requestUrl,Map headerMap, String param) throws HttpException, IOException { + String result = null; + try { + CloseableHttpClient httpClient = new SSLClient(); + HttpPost postMethod = new HttpPost(requestUrl); + CloseableHttpResponse response = null; + //设置请求头Authorization + // postMethod.setRequestHeader("Authorization", "Basic " + authorization); + //设置请求头 Content-Type + postMethod.setHeader("Content-Type", "application/json"); + Iterator headerIterator = headerMap.entrySet().iterator();//循环增加header + while(headerIterator.hasNext()){ + Entry elem = (Entry) headerIterator.next(); + // System.out.println("key="+elem.getKey()+";value="+elem.getValue()); + postMethod.addHeader(elem.getKey(),elem.getValue()); + } + StringEntity stringentity = new StringEntity(param,ContentType.create("application/json", "UTF-8")); + postMethod.setEntity(stringentity); + response = httpClient.execute(postMethod);//发送请求并接收返回数据 + // System.out.println(response.getStatusLine()); + if(response != null && response.getStatusLine().getStatusCode() == 200){ + HttpEntity entity = response.getEntity();//获取response的body部分 + result = EntityUtils.toString(entity);//读取reponse的body部分并转化成字符串 + } + } catch (Exception e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + //打印返回结果 + // System.out.println(result); + return result; + } + + public static CloseableHttpClient createSSLClientDefault(){ + try { + SSLContext sslContext = new SSLContextBuilder().loadTrustMaterial(null, new TrustStrategy() { + //信任所有 + public boolean isTrusted(X509Certificate[] chain,String authType) throws CertificateException { + return true; + } + }).build(); + //SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslContext); + SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(SSLContexts.custom().loadTrustMaterial( + null, new TrustSelfSignedStrategy()).build(), NoopHostnameVerifier.INSTANCE); + return HttpClients.custom().setSSLSocketFactory(sslsf).build(); + } catch (KeyManagementException e) { + e.printStackTrace(); + } catch (NoSuchAlgorithmException e) { + e.printStackTrace(); + } catch (KeyStoreException e) { + e.printStackTrace(); + } + return HttpClients.createDefault(); + } + +} diff --git a/src/main/youhong_ai_jitu_src/com/working/util/LogTool.java b/src/main/youhong_ai_jitu_src/com/working/util/LogTool.java new file mode 100644 index 0000000..d0da778 --- /dev/null +++ b/src/main/youhong_ai_jitu_src/com/working/util/LogTool.java @@ -0,0 +1,118 @@ +package com.working.util; + +import java.io.PrintWriter; +import java.io.FileWriter; +import java.io.IOException; +import java.io.File; +import java.text.SimpleDateFormat; +import java.util.Date; + +import weaver.general.BaseBean; +import weaver.general.GCONST; + +/** + * * + * Copyright (C), 2010,9, szcport + * File name and path : szcport.weaver.formmode.data.ModeDataManager.java + * Author : KangMD, Version : 1.0, First complete date : 2018-5-14 下午05:01:55 + * Description :日志类 + * Others: + * Function List: + * History: + * 1. Date: + * Version: + * Author: + * Modification: + * + ** + */ +public class LogTool { + + private PrintWriter logPrint; + private String logFile = ""; + private String logPath = ""; + private boolean systemlog = false;//是否写系统日记 + + static SimpleDateFormat newDf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); + static SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd"); + static BaseBean log = new BaseBean(); + + public LogTool(){ + //if(logFile == null || logFile.trim().equals("") || !logFile.equals(getLogFile())){ + // newLog(); + //} + } + + public LogTool(String logPath,boolean systemlog){ + this.logPath = logPath; + this.systemlog = systemlog; + } + + private String getLogFile(){ + //获取当前系统路径 + String sysPath = GCONST.getRootPath(); + if (sysPath == null) { + sysPath = System.getProperty("user.dir"); + } + if (!"".equals(logPath)) { + if (logPath.endsWith("/")) { + sysPath += logPath+df.format(new Date())+".log"; + } else { + sysPath += logPath+"/"+df.format(new Date())+".log"; + } + } else { + sysPath += "/log/dev/"+df.format(new Date())+".log"; + } + return sysPath; + } + + private void newLog(){ + logFile = getLogFile(); + try { + logPrint = new PrintWriter(new FileWriter(logFile, true), true); + } catch(IOException e) { + try { + File file = new File(logFile); + if (!file.getParentFile().exists()) { + //如果目标文件所在的目录不存在,则创建父目录 + if (file.getParentFile().mkdirs()) { + file.createNewFile(); + } + } + logPrint = new PrintWriter(new FileWriter(logFile, true), true); + } catch(IOException ex) { + log.writeLog("Log记录出错了",ex); + } + } + } + + public void writeLog(Object msg) { + if (systemlog) { + log.writeLog(msg); + } + newLog(); + logPrint.println(newDf.format(new Date()) + ": " + msg); + logPrint.flush(); + logPrint.close(); + } + + public void writeLog(String msg,Throwable e) { + if (systemlog) { + log.writeLog(msg,e); + } + newLog(); + logPrint.println(newDf.format(new Date()) + ": " + msg); + e.printStackTrace(logPrint); + logPrint.flush(); + logPrint.close(); + } + + public static void main(String[] args) { + try { + Double.parseDouble("aaa"); + } catch (Exception e) { + new LogTool().writeLog("哈哈111哈",e); + } + } + +} \ No newline at end of file diff --git a/src/main/youhong_ai_jitu_src/com/working/util/MyDateUtil.java b/src/main/youhong_ai_jitu_src/com/working/util/MyDateUtil.java new file mode 100644 index 0000000..70dbdf9 --- /dev/null +++ b/src/main/youhong_ai_jitu_src/com/working/util/MyDateUtil.java @@ -0,0 +1,70 @@ +package com.working.util; + +import java.text.ParseException; +import java.text.SimpleDateFormat; +import java.util.Calendar; +import java.util.Date; + +public class MyDateUtil { + + /** + * 获取当前时间字符串 + * @return + */ + public static String getDateStr(){ + Date now = new Date(); + SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); + return sdf.format(now); + } + + /** + * 根据传入的日期字符串添加年,月,日等 + * @param dateStr yyyy-MM-dd + * @param addyear + * @param addmonth + * @param addday + * @return + */ + public static String addDate(String dateStr,int addyear,int addmonth,int addday){ + SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd"); + Calendar cal = Calendar.getInstance(); + String newDateStr = ""; + try { + Date date = sdf.parse(dateStr); + cal.setTime(date); + cal.add(Calendar.YEAR,addyear); + cal.add(Calendar.MONTH,addmonth); + cal.add(Calendar.DAY_OF_YEAR,addday); + newDateStr = sdf.format(cal.getTime()); + } catch (ParseException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + return newDateStr; + } + + /** + * 将日期格式字符串转化为日期 + * @param dateStr + * @return + */ + public static Date getDate(String dateStr){ + SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); + Date now = new Date(); + try { + now = sdf.parse(dateStr); + } catch (ParseException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + return now; + } + + public static void main(String[] args) { + // TODO Auto-generated method stub + System.out.println(getDateStr()); + System.out.println(addDate("2018-12-10",1,2,5)); + System.out.println(getDate("2018-12-10 09:00:00")); + } + +} diff --git a/src/main/youhong_ai_jitu_src/com/working/util/SSLClient.java b/src/main/youhong_ai_jitu_src/com/working/util/SSLClient.java new file mode 100644 index 0000000..cf15863 --- /dev/null +++ b/src/main/youhong_ai_jitu_src/com/working/util/SSLClient.java @@ -0,0 +1,35 @@ +package com.working.util; + +import java.security.cert.CertificateException; +import java.security.cert.X509Certificate; +import javax.net.ssl.SSLContext; +import javax.net.ssl.TrustManager; +import javax.net.ssl.X509TrustManager; +import org.apache.http.conn.ClientConnectionManager; +import org.apache.http.conn.scheme.Scheme; +import org.apache.http.conn.scheme.SchemeRegistry; +import org.apache.http.conn.ssl.SSLSocketFactory; +import org.apache.http.impl.client.DefaultHttpClient; +//用于进行Https请求的HttpClient +public class SSLClient extends DefaultHttpClient{ + public SSLClient() throws Exception{ + super(); + SSLContext ctx = SSLContext.getInstance("TLS"); + X509TrustManager tm = new X509TrustManager() { + public void checkClientTrusted(X509Certificate[] chain, + String authType) throws CertificateException { + } + public void checkServerTrusted(X509Certificate[] chain, + String authType) throws CertificateException { + } + public X509Certificate[] getAcceptedIssuers() { + return null; + } + }; + ctx.init(null, new TrustManager[]{tm}, null); + SSLSocketFactory ssf = new SSLSocketFactory(ctx,SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER); + ClientConnectionManager ccm = this.getConnectionManager(); + SchemeRegistry sr = ccm.getSchemeRegistry(); + sr.register(new Scheme("https", 443, ssf)); + } +} \ No newline at end of file diff --git a/src/main/youhong_ai_jitu_src/com/working/util/WAction.java b/src/main/youhong_ai_jitu_src/com/working/util/WAction.java new file mode 100644 index 0000000..7af8491 --- /dev/null +++ b/src/main/youhong_ai_jitu_src/com/working/util/WAction.java @@ -0,0 +1,42 @@ +package com.working.util; + +public class WAction { + + private String requestid; + private String workflowId; + private String formid; + private String mainTabName; + + public String getRequestid() { + return requestid; + } + + public void setRequestid(String requestid) { + this.requestid = requestid; + } + + public String getWorkflowId() { + return workflowId; + } + + public void setWorkflowId(String workflowId) { + this.workflowId = workflowId; + } + + public String getFormid() { + return formid; + } + + public void setFormid(String formid) { + this.formid = formid; + } + + public String getMainTabName() { + return mainTabName; + } + + public void setMainTabName(String mainTabName) { + this.mainTabName = mainTabName; + } + +} diff --git a/src/main/youhong_ai_jitu_src/com/working/util/WorkflowUtil.java b/src/main/youhong_ai_jitu_src/com/working/util/WorkflowUtil.java new file mode 100644 index 0000000..48a1f07 --- /dev/null +++ b/src/main/youhong_ai_jitu_src/com/working/util/WorkflowUtil.java @@ -0,0 +1,73 @@ +package com.working.util; + +import java.util.HashMap; +import java.util.Map; + +import weaver.conn.RecordSet; +import weaver.formmode.setup.ModeRightInfo; +import weaver.general.Util; + +public class WorkflowUtil { + + /** + * 根据流程id获取主表名称 + * @param requestid + * @return + */ + public static String getMainTable(String requestid){ + String tablename = ""; + RecordSet rs = new RecordSet(); + rs.executeQuery("select * from workflow_requestbase a,workflow_base b,workflow_bill c " + +"where a.requestid=? and a.workflowid = b.id and b.formid = c.id",requestid); + while(rs.next()){ + tablename = Util.null2String(rs.getString("tablename")); + } + return tablename; + } + + /** + * 获取用户部分信息 + * @param requestid + * @return + */ + public static Map getUserInfo(String userid){ + Map map = new HashMap(); + RecordSet rs = new RecordSet(); + rs.executeQuery("select * from hrmresource where id = ?",userid); + while(rs.next()){ + map.put("workcode",(Util.null2String(rs.getString("workcode")))); + map.put("startdate",(Util.null2String(rs.getString("startdate")))); + map.put("lastname",(Util.null2String(rs.getString("lastname")))); + map.put("departmentid",(Util.null2String(rs.getString("departmentid")))); + map.put("subcompanyid",(Util.null2String(rs.getString("subcompanyid1")))); + } + return map; + } + + /** + * 获取部门部分信息 + * @param requestid + * @return + */ + public static Map getDepartInfo(String departid){ + Map map = new HashMap(); + RecordSet rs = new RecordSet(); + rs.executeQuery("select * from hrmdepartment where id = ?",departid); + while(rs.next()){ + map.put("departmentname",(Util.null2String(rs.getString("departmentname")))); + map.put("subcompanyid1",(Util.null2String(rs.getString("subcompanyid1")))); + } + return map; + } + + /** + * 权限设置 + * @param id + */ + public static void modeRight(int id,int modeid){ + //给该记录设置权限(即权限重构) 第一个参数表示人员ID,第二个参数表建模模块modeid,第三个参数表示建模数据billid + ModeRightInfo mri = new ModeRightInfo(); + mri.editModeDataShare(1,modeid,id); + } + +} diff --git a/src/main/youhong_ai_jitu_src/com/working/webservices/hrmmatrix/SynDepartmentDefined.java b/src/main/youhong_ai_jitu_src/com/working/webservices/hrmmatrix/SynDepartmentDefined.java new file mode 100644 index 0000000..9aa6c5d --- /dev/null +++ b/src/main/youhong_ai_jitu_src/com/working/webservices/hrmmatrix/SynDepartmentDefined.java @@ -0,0 +1,8 @@ +package com.working.webservices.hrmmatrix; + +public interface SynDepartmentDefined { + + //同步部门矩阵表信息 + public abstract String synDeptDefined(String json); + +} diff --git a/src/main/youhong_ai_jitu_src/com/working/webservices/hrmmatrix/SynDepartmentDefinedImpl.java b/src/main/youhong_ai_jitu_src/com/working/webservices/hrmmatrix/SynDepartmentDefinedImpl.java new file mode 100644 index 0000000..f455e16 --- /dev/null +++ b/src/main/youhong_ai_jitu_src/com/working/webservices/hrmmatrix/SynDepartmentDefinedImpl.java @@ -0,0 +1,117 @@ +package com.working.webservices.hrmmatrix; + +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +import weaver.conn.RecordSet; +import weaver.general.Util; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.JSONObject; +import com.working.util.LogTool; +import com.working.webservices.util.DepartmentUtil; + +public class SynDepartmentDefinedImpl implements SynDepartmentDefined{ + + LogTool log = new LogTool("/log/matrix/", false); + + public String synDeptDefined(String json) { + log.writeLog("同步部门传入数据为="+json); + RecordSet rs = new RecordSet(); + RecordSet rs1 = new RecordSet(); + DepartmentUtil deptUtil = new DepartmentUtil(); + //保存报错信息 + Map msgMap = new HashMap(); + JSONObject jsonObject = new JSONObject(); + try{ + if (json.isEmpty()||json==null) { + log.writeLog("同步部门传入数据不能为空!"); +// System.out.println("传入数据不能为空!"); + msgMap.put("msg", "传入数据不能为空!"); + return JSON.toJSONString(msgMap); + } + //解析JOSN + jsonObject = JSONObject.parseObject(json); + //获取部门编号 + String deptCode = Util.null2String(jsonObject.getString("deptCode")); + if (deptCode.isEmpty()) { + log.writeLog("传入数据部门编号不能为空!"); +// System.out.println("传入数据部门编号不能为空!"); + msgMap.put("msg", "传入数据部门编号不能为空!"); + return JSON.toJSONString(msgMap); + } + log.writeLog("deptCode="+deptCode); + //获取部门id + String deptId = deptUtil.selectDept(deptCode); + log.writeLog("deptId="+deptId); + if (deptId.equals("-1")) {//-1表示根据编号在部门表查不到部门信息 + log.writeLog("传入数据部门编号["+deptCode+"]在OA中查不到,请联系OA管理员确认两边编号是否一致!"); +// System.out.println("传入数据部门编号["+deptCode+"]在OA中查不到,请联系OA管理员确认两边编号是否一致!"); + msgMap.put("msg", "传入数据部门编号["+deptCode+"]在OA中查不到,请联系OA管理员确认两边编号是否一致!"); + return JSON.toJSONString(msgMap); + } + rs.executeQuery("select * from hrmdepartmentdefined where deptid = ?", deptId); + //获取部门自定义表的字段英文名称 + String[] columnNames = deptUtil.getColumnName().split(","); + //得到需要转换的多人力资源字段集合 + List list = deptUtil.getHrmList(); + log.writeLog("list="+list); + //得到部门插入sql拼接字段 + StringBuffer intoSql = new StringBuffer(); + //得到部门更新sql拼接字段 + StringBuffer updateSql = new StringBuffer(); + //得到部门插入字段 + StringBuffer columnSql = new StringBuffer(); + //得到参数拼接字段 + StringBuffer params = new StringBuffer(); + //通过编号查询人员 + Map userMsgMap = new HashMap(); + String status = "";//判断查询人员返回信息的状态0=成功,1-存在查不到的人员 + for (String columnName : columnNames) { +// log.writeLog("columnName="+columnName); + //例如: ,name,loginid,age + columnSql.append(",").append(columnName); + if (list.contains(columnName)&&jsonObject.getString(columnName)!=null&&!jsonObject.getString(columnName).equals("")) {//存在需要转换的多人力资源字段 + userMsgMap = deptUtil.getUserIdByCodes(jsonObject.getString(columnName)); + status = userMsgMap.get("status"); + if (status.equals("0")) {//0表示根据工号转换人员id全部成功 + log.writeLog("0-userMap="+userMsgMap.get("msg")); + params.append("'" + userMsgMap.get("msg")).append("',"); + updateSql.append(columnName).append("='"+userMsgMap.get("msg")).append("',"); + } else if (status.equals("1")) {//1表示根据工号转换人员id存在不存在的 + log.writeLog("1-userMap="+userMsgMap.get("msg")); + msgMap.put("msg", userMsgMap.get("msg")); + return JSON.toJSONString(msgMap); + } + } else { + params.append("'").append(jsonObject.getString(columnName)==null?"":jsonObject.getString(columnName)).append("',"); + updateSql.append(columnName).append("='").append(jsonObject.getString(columnName)==null?"":jsonObject.getString(columnName)).append("',"); + } + } + String sql = "";//执行更新操作的sql语句 + if (rs.getCounts() <= 0) {//不存在,插入数据 + intoSql.append("insert into hrmdepartmentdefined(deptid").append(columnSql).append(")values(").append(deptId) + .append(","+params.substring(0,params.length()-1)).append(")"); + log.writeLog("intoSql="+intoSql); + rs1.execute(intoSql.toString()); + } else {//更新 + //去掉第一个英文逗号 + sql = "update hrmdepartmentdefined set "; + log.writeLog("updateSql="+updateSql.substring(0,updateSql.length()-1).toString()); + sql = sql + updateSql.substring(0,updateSql.length()-1).toString() + " where deptid = " + deptId; + log.writeLog("sql="+sql); + rs1.execute(sql); + } + + }catch (Exception e) { + log.writeLog("errorMsg="+e.toString()); +// System.out.println(e.toString()); + msgMap.put("msg", e.toString()); + return JSON.toJSONString(msgMap); + } + msgMap.put("msg", "部门矩阵同步成功!"); + return JSON.toJSONString(msgMap); + } + +} diff --git a/src/main/youhong_ai_jitu_src/com/working/webservices/hrmmatrix/SynSubCompanyDefined.java b/src/main/youhong_ai_jitu_src/com/working/webservices/hrmmatrix/SynSubCompanyDefined.java new file mode 100644 index 0000000..05ec022 --- /dev/null +++ b/src/main/youhong_ai_jitu_src/com/working/webservices/hrmmatrix/SynSubCompanyDefined.java @@ -0,0 +1,8 @@ +package com.working.webservices.hrmmatrix; + +public interface SynSubCompanyDefined { + + //同步分部矩阵表信息 + public abstract String synSubComDefined(String json); + +} diff --git a/src/main/youhong_ai_jitu_src/com/working/webservices/hrmmatrix/SynSubCompanyDefinedImpl.java b/src/main/youhong_ai_jitu_src/com/working/webservices/hrmmatrix/SynSubCompanyDefinedImpl.java new file mode 100644 index 0000000..f68aed9 --- /dev/null +++ b/src/main/youhong_ai_jitu_src/com/working/webservices/hrmmatrix/SynSubCompanyDefinedImpl.java @@ -0,0 +1,117 @@ +package com.working.webservices.hrmmatrix; + +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +import weaver.conn.RecordSet; +import weaver.general.Util; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.JSONObject; +import com.working.util.LogTool; +import com.working.webservices.util.DepartmentUtil; +import com.working.webservices.util.SubComUtil; + +public class SynSubCompanyDefinedImpl implements SynSubCompanyDefined{ + + LogTool log = new LogTool("/log/matrix/", false); + + public String synSubComDefined(String json) { + log.writeLog("分部传入数据为="+json); + RecordSet rs = new RecordSet(); + RecordSet rs1 = new RecordSet(); + //部门矩阵工具类 + DepartmentUtil deptUtil = new DepartmentUtil(); + //分部矩阵工具类 + SubComUtil subComUtil = new SubComUtil(); + //保存报错信息 + Map msgMap = new HashMap(); + JSONObject jsonObject = new JSONObject(); + try{ + if (json.isEmpty()||json==null) { + log.writeLog("同步分部传入数据不能为空!"); + msgMap.put("msg", "传入数据不能为空!"); + return JSON.toJSONString(msgMap); + } + //解析JOSN + jsonObject = JSONObject.parseObject(json); + //获取分部编号 + String subComCode = Util.null2String(jsonObject.getString("subComCode")); + if (subComCode.isEmpty()) { + log.writeLog("传入数据分部编号不能为空!"); + msgMap.put("msg", "传入数据分部编号不能为空!"); + return JSON.toJSONString(msgMap); + } + log.writeLog("subComCode="+subComCode); + //获取分部id + String subComId = subComUtil.selectSubCom(subComCode); + log.writeLog("subComId="+subComId); + if (subComId.equals("-1")) {//-1表示根据编号在分部表查不到分部信息 + log.writeLog("传入数据分部编号["+subComCode+"]在OA中查不到,请联系OA管理员确认两边编号是否一致!"); + msgMap.put("msg", "传入数据分部编号["+subComCode+"]在OA中查不到,请联系OA管理员确认两边编号是否一致!"); + return JSON.toJSONString(msgMap); + } + rs.executeQuery("select * from hrmsubcompanydefined where subcomid = ?", subComId); + //获取分部自定义表的字段英文名称 + String[] columnNames = subComUtil.getColumnName().split(","); + //得到需要转换的多人力资源字段集合 + List list = deptUtil.getHrmList(); + log.writeLog("list="+list); + //得到分部插入sql拼接字段 + StringBuffer intoSql = new StringBuffer(); + //得到分部更新sql拼接字段 + StringBuffer updateSql = new StringBuffer(); + //得到分部插入字段 + StringBuffer columnSql = new StringBuffer(); + //得到参数拼接字段 + StringBuffer params = new StringBuffer(); + //通过编号查询人员 + Map userMsgMap = new HashMap(); + String status = "";//判断查询人员返回信息的状态0=成功,1-存在查不到的人员 + for (String columnName : columnNames) { +// log.writeLog("columnName="+columnName); + //例如: ,name,loginid,age + columnSql.append(",").append(columnName); + if (list.contains(columnName)&&jsonObject.getString(columnName)!=null&&!jsonObject.getString(columnName).equals("")) {//存在需要转换的多人力资源字段 + userMsgMap = deptUtil.getUserIdByCodes(jsonObject.getString(columnName)); + status = userMsgMap.get("status"); + if (status.equals("0")) {//0表示根据工号转换人员id全部成功 + log.writeLog("0-userMap="+userMsgMap.get("msg")); + params.append("'" + userMsgMap.get("msg")).append("',"); + updateSql.append(columnName).append("='"+userMsgMap.get("msg")).append("',"); + } else if (status.equals("1")) {//1表示根据工号转换人员id存在不存在的 + log.writeLog("1-userMap="+userMsgMap.get("msg")); + msgMap.put("msg", userMsgMap.get("msg")); + return JSON.toJSONString(msgMap); + } + } else { + params.append("'").append(jsonObject.getString(columnName)==null?"":jsonObject.getString(columnName)).append("',"); + updateSql.append(columnName).append("='").append(jsonObject.getString(columnName)==null?"":jsonObject.getString(columnName)).append("',"); + } + } + String sql = "";//执行更新操作的sql语句 + if (rs.getCounts() <= 0) {//不存在,插入数据 + intoSql.append("insert into hrmsubcompanydefined(subcomid").append(columnSql).append(")values(").append(subComId) + .append(","+params.substring(0,params.length()-1)).append(")"); + log.writeLog("intoSql="+intoSql); + rs1.execute(intoSql.toString()); + } else {//更新 + //去掉第一个英文逗号 + sql = "update hrmsubcompanydefined set "; + log.writeLog("updateSql="+updateSql.substring(0,updateSql.length()-1).toString()); + sql = sql + updateSql.substring(0,updateSql.length()-1).toString() + " where subcomid = " + subComId; + log.writeLog("sql="+sql); + rs1.execute(sql); + } + + }catch (Exception e) { + log.writeLog("errorMsg="+e.toString()); + msgMap.put("msg", e.toString()); + return JSON.toJSONString(msgMap); + } + msgMap.put("msg", "同步成功!"); + return JSON.toJSONString(msgMap); + } + +} diff --git a/src/main/youhong_ai_jitu_src/com/working/webservices/org/GetDeptInfoService.java b/src/main/youhong_ai_jitu_src/com/working/webservices/org/GetDeptInfoService.java new file mode 100644 index 0000000..dbad823 --- /dev/null +++ b/src/main/youhong_ai_jitu_src/com/working/webservices/org/GetDeptInfoService.java @@ -0,0 +1,11 @@ +package com.working.webservices.org; + +public interface GetDeptInfoService { + + //校验部门是否存在 + public abstract String checkDeptIsExist(String json); + + //校验分部是否存在 + public abstract String checkSubIsExist(String json); + +} diff --git a/src/main/youhong_ai_jitu_src/com/working/webservices/org/GetDeptInfoServiceImpl.java b/src/main/youhong_ai_jitu_src/com/working/webservices/org/GetDeptInfoServiceImpl.java new file mode 100644 index 0000000..22d5589 --- /dev/null +++ b/src/main/youhong_ai_jitu_src/com/working/webservices/org/GetDeptInfoServiceImpl.java @@ -0,0 +1,119 @@ +package com.working.webservices.org; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +import weaver.general.Util; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.JSONArray; +import com.alibaba.fastjson.JSONObject; +import com.working.util.LogTool; +import com.working.webservices.util.DepartmentUtil; +import com.working.webservices.util.SubComUtil; + +public class GetDeptInfoServiceImpl implements GetDeptInfoService{ + + LogTool log = new LogTool("/log/checkDept/", false); + + public String checkDeptIsExist(String json) { + log.writeLog("同步部门传入数据为="+json); + DepartmentUtil deptUtil = new DepartmentUtil(); + //保存信息 + Map msgMap = new HashMap(); + //保存OA不存在的部门编码 + List codeList = new ArrayList(); + //保存OA不存在的部门编码 + Map codeMap = null; + try{ + if (json.isEmpty()||json==null) { + log.writeLog("校验部门是否存在的数据不能为空!"); + msgMap.put("isAllExist", "no"); + msgMap.put("notExistList", "传入部门的json不能为空!"); + return JSON.toJSONString(msgMap); + } + //解析JOSN + JSONArray datas = JSONArray.parseArray(json); + log.writeLog("datas="+datas); + if (datas.size()>0) { + for (int i=0;i(); + codeMap.put("deptno", deptno); + codeList.add(codeMap); + } + } + } + if (codeList.size()>0) {//大于0表示有传入的部门编码在OA没有 + msgMap.put("isAllExist", "no"); + msgMap.put("notExistList", codeList); + } else { + msgMap.put("isAllExist", "yes"); + } + + } catch (Exception e) { + log.writeLog("errorMsg="+e.toString()); + msgMap.put("isAllExist", "no"); + msgMap.put("notExistList", e.toString()); + return JSON.toJSONString(msgMap); + } + return JSON.toJSONString(msgMap); + } + + public String checkSubIsExist(String json) { + log.writeLog("同步分部传入数据为="+json); + SubComUtil subComUtil = new SubComUtil(); + //保存信息 + Map msgMap = new HashMap(); + //保存OA不存在的分部编码 + List codeList = new ArrayList(); + //保存OA不存在的分部编码 + Map codeMap = null; + try{ + if (json.isEmpty()||json==null) { + log.writeLog("校验分部是否存在的数据不能为空!"); + msgMap.put("isAllExist", "no"); + msgMap.put("notExistList", "传入分部的json不能为空!"); + return JSON.toJSONString(msgMap); + } + //解析JOSN + JSONArray datas = JSONArray.parseArray(json); + log.writeLog("datas="+datas); + if (datas.size()>0) { + for (int i=0;i(); + codeMap.put("subno", subno); + codeList.add(codeMap); + } + } + } + if (codeList.size()>0) {//大于0表示有传入的分部编码在OA没有 + msgMap.put("isAllExist", "no"); + msgMap.put("notExistList", codeList); + } else { + msgMap.put("isAllExist", "yes"); + } + + } catch (Exception e) { + log.writeLog("errorMsg="+e.toString()); + msgMap.put("isAllExist", "no"); + msgMap.put("notExistList", e.toString()); + return JSON.toJSONString(msgMap); + } + return JSON.toJSONString(msgMap); + } + +} diff --git a/src/main/youhong_ai_jitu_src/com/working/webservices/util/DepartmentUtil.java b/src/main/youhong_ai_jitu_src/com/working/webservices/util/DepartmentUtil.java new file mode 100644 index 0000000..c5253d9 --- /dev/null +++ b/src/main/youhong_ai_jitu_src/com/working/webservices/util/DepartmentUtil.java @@ -0,0 +1,81 @@ +package com.working.webservices.util; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +import com.working.util.LogTool; + +import weaver.conn.RecordSet; +import weaver.general.Util; + +public class DepartmentUtil { + + LogTool log = new LogTool("/log/matrix/", false); + + //根据部门编号查询部门是否存在,存在返回部门id + public String selectDept(String deptCode) { + String pdetId = "-1";//默认设置为-1 + RecordSet rs = new RecordSet(); + rs.executeQuery("select * from hrmdepartment where departmentcode = ?", deptCode); + while (rs.next()) { + pdetId = Util.null2String(rs.getString("ID")); + } + return pdetId; + } + + //查询部门自定义字段需要同步的字段名称 + public String getColumnName() { + String columnNames = "";//默认设置为-1 + RecordSet rs = new RecordSet(); + rs.execute("select * from uf_definded_data where type = 0"); + while (rs.next()) { + columnNames = Util.null2String(rs.getString("TRANS_STR")); + } + return columnNames; + } + + //查询需转换的多人力资源字段 + public List getHrmList(){ + List list = new ArrayList();//插入部门自定义表的自定义字段的sql语句 + RecordSet rs = new RecordSet(); + rs.execute("select * from uf_definded_data where type = 4"); + while (rs.next()) { + list.add(Util.null2String(rs.getString("TRANS_STR"))); + } + return list; + } + + /** + * 通过人员编号查询人员id,将返回信息保存到map中返回给调用函数 + * @param workCodes 员工编号集合例子 : a,b,c + * @return 查询的信息,成功或失败信息 + */ + public Map getUserIdByCodes(String workCodes){ + //保存通过人员编号查询人员信息的结果 + log.writeLog("workCodes="+workCodes); + Map map = new HashMap(); + String status = "0";//默认为0,表示根据编号查的员工全部存在 + String[] codeArr = workCodes.split(","); + StringBuffer msg = new StringBuffer(); + RecordSet rs = new RecordSet(); + for (int i=0;i" + userDefaultCompanyType); + log.writeLog("selectCompanyType------>" + selectCompanyType); + //跨组织,则说明代理区想总部借款 + if(!userDefaultCompanyType.equals(selectCompanyType)){ + if("".equals(userDefaultCompanyType)){ + //获取流程名称 + String workflowname=BaseUtil.getBaseInfoByParm("workflowname", "workflow_base", "id", workflowid, ""); + //若名称中带有“代理区”,则说明员工默认组织类型是代理区 + if(workflowname.contains("代理区")){ + userDefaultCompanyType="2"; + } + } + //查询建模维护的对应关系 + String defaultDeptNo=BaseUtil.getBaseInfoByParm("mroabmbm", "uf_kzzfkdybmsz", "sqgslx", userDefaultCompanyType, " and fkgslx='"+selectCompanyType+"'"); + log.writeLog("defaultDeptNo------>" + defaultDeptNo); + if(!"".equals(defaultDeptNo)){ + deptid=defaultDeptNo; + } + } + //截取前120位 + if(zy.length()>120){ + zy=zy.substring(0,120); + } + //标题截取前150位 + if (zyx9.length() > 150){ + zyx9 = zyx9.substring(0, 150); + } + //结算方式 + if("0".equals(jsfs)){ + jsfs = "3"; //网银 + }else{ + jsfs = "0"; //现金 + } + receiver = new ResourceComInfo().getWorkcode(xm); //收款人,与申请人一致 + jkbxr = receiver; // 借款报销人,与申请人一致 + //收款对象为员工时,则对应NCC的对私借款单 + if("0".equals(jklx)){ + paytarget="0";//0=员工,1=供应商,2=客户 + djlxbm = "263X-Cxx-DSJKD"; // 单据类型编码 + skyhzh=yxzh; + //供应商收款信息清空 + hbbm=""; + custaccount=""; + }else{//对公借款单 + djlxbm = "263X-Cxx-DGJKD"; // 单据类型编码 + paytarget="1";//0=员工,1=供应商,2=客户 + if("3".equals(jklx)){//集团关联公司 + hbbm=jtglgsbm; + szxmid="901062";//经营借款(外部借款) + custaccount=yxzhjtglgs; + }else{ + hbbm=dls; + szxmid="901061";//经营借款(内部借款) + custaccount=yxzhdlgs; + } + //员工收款信息清空 + receiver=""; + skyhzh=""; + } + + //获取UUID + String uuid=UUID.randomUUID().toString().replace("-", "").toUpperCase(); + operator = loginid;//当前节点操作者 + + borrowOrder.setUuid(uuid); + borrowOrder.setPk_org(pk_org); + borrowOrder.setTotal(total); + borrowOrder.setDeptid(deptid); + borrowOrder.setDjlxbm(djlxbm); + borrowOrder.setDjrq(djrq); + borrowOrder.setPayflag(payflag); + borrowOrder.setPaytarget(paytarget); + borrowOrder.setHbbm(hbbm); + borrowOrder.setReceiver(receiver); + borrowOrder.setJkbxr(jkbxr); + borrowOrder.setOperator(operator); + borrowOrder.setJsfs(jsfs); + borrowOrder.setFkyhzh(fkyhzh); + borrowOrder.setSkyhzh(skyhzh); + borrowOrder.setCustaccount(custaccount); + borrowOrder.setZy(zy); + borrowOrder.setDjzt(djzt); + borrowOrder.setKjqj(kjqj); + borrowOrder.setKjnd(kjnd); + borrowOrder.setZyx1(zyx1); + borrowOrder.setZyx2(zyx2); + borrowOrder.setZyx3(zyx3); + borrowOrder.setZyx5(zyx5); + borrowOrder.setZyx8(zyx8); + borrowOrder.setZyx9(zyx9); + log.writeLog("【header数据准备完毕...】"); + + List borrowOrderBodyList = new ArrayList(); + String tablecode = ""; // jk_busitem + String rowno = ""; // 10 + String defitem50 = ""; // 发票类型 + String defitem49 = ""; // 发票号码 + String defitem42 = ""; // OA明细ID + String defitem43 = ""; // 车牌号 + String defitem44 = ""; // 仓库 + String defitem45 = ""; // 国家 + + String defitem48 = deptid; // SD3300301" //分摊部门 + BorrowOrderBody body = new BorrowOrderBody(); + tablecode = "jk_busitem"; + rowno = "10"; + + body.setAmount(total); + body.setTablecode(tablecode); + body.setRowno(rowno); + body.setSzxmid(szxmid); + body.setDefitem50(defitem50); + body.setDefitem49(defitem49); + body.setDefitem42(defitem42); + body.setDefitem43(defitem43); + body.setDefitem44(defitem44); + body.setDefitem45(defitem45); + body.setDefitem46(defitem46); + body.setDefitem48(defitem48); + borrowOrderBodyList.add(body); + borrowOrder.setJk_busitem(borrowOrderBodyList); + + String parm=JSONObject.toJSONString(borrowOrder, SerializerFeature.DisableCircularReferenceDetect); + log.writeLog("借款单准备传入数据中台的数据为------>" + parm); + + //获取TOKEN + String token = HttpClientToDC.getToken(); + log.writeLog("获取数据中台的token------>" + token); + if ("".equals(Util.null2String(token))) { + String tokenMsg="流程提交失败,未获取到数据中台接口TOKEN,请联系管理员处理!"; + //将NCC返回结果回写至OA流程表单 + rs.execute(" update " + mainTable + " set sfcgscnccfkd = 1 ,nccfhxx='" + tokenMsg.replace("'", "''") + "' where requestid = " + requestId); + //是否需要显示报错信息 + if("yes".equals(isShowErrorMsg)){ + requestInfo.getRequestManager().setMessagecontent(tokenMsg); + return Action.FAILURE_AND_CONTINUE; + }else{ + return SUCCESS; + } + } + + + //调用NCC接口,将数据传给NCC + String returndata = HttpClientToDC.sendPostApi(url,token, parm); + log.writeLog("【调用数据中台借款接口返回结果result:】" + returndata); + if (!"".equals(returndata) && returndata != null) { + JSONObject jsonObject = JSONObject.parseObject(returndata); + String success = Util.null2String(jsonObject.get("succ")); + log.writeLog("--------发送请求返回的success值为:" + success); + if ("true".equals(success)) { + JSONObject data = jsonObject.getJSONObject("data"); + String billno = Util.null2String(data.get("billno"));//NCC单号 + log.writeLog("--------发送请求返回的billno值为:" + billno); + //将NCC返回结果回写至OA流程表单 + rs.execute(" update " + mainTable + " set sfcgscnccfkd = 0 , nccfkdh = '" + billno + "',nccfhxx='' where requestid = " + requestId); + } else { + String message = Util.null2String(jsonObject.get("msg")); + String message2=message.replace("'", "''"); + //超出1333个字符,则只截取前面这部分 + if(message2.length()>1334){ + message2=message2.substring(0,1333); + } + //将NCC返回结果回写至OA流程表单 + rs.execute(" update " + mainTable + " set sfcgscnccfkd = 1 ,nccfhxx='" + message2 + "' where requestid = " + requestId); + //是否需要显示报错信息 + if("yes".equals(isShowErrorMsg)){ + requestInfo.getRequestManager().setMessagecontent("流程数据写入NCC借款单失败,失败信息:
"+message); + return Action.FAILURE_AND_CONTINUE; + }else{ + return SUCCESS; + } + } + } else { + String ermsg="流程数据写入NCC借款单失败,未获取到接口返回结果,请联系系统管理员处理!"; + //将NCC返回结果回写至OA流程表单 + rs.execute(" update " + mainTable + " set sfcgscnccfkd = 1 ,nccfhxx='" + ermsg.replace("'", "''") + "' where requestid = " + requestId); + //是否需要显示报错信息 + if("yes".equals(isShowErrorMsg)){ + requestInfo.getRequestManager().setMessagecontent(ermsg); + return Action.FAILURE_AND_CONTINUE; + }else{ + return SUCCESS; + } + } + } catch (Exception e) { + String ermsg="流程数据生成中台借款单失败,失败信息:
" + e.toString(); + //将NCC返回结果回写至OA流程表单 + rs.execute(" update " + mainTable + " set sfcgscnccfkd = 1 ,nccfhxx='" + ermsg.replace("'", "''") + "' where requestid = " + requestId); + //是否需要显示报错信息 + if("yes".equals(isShowErrorMsg)){ + requestInfo.getRequestManager().setMessagecontent(ermsg); + return Action.FAILURE_AND_CONTINUE; + }else{ + return SUCCESS; + } + } + log.writeLog("--------借款单数据传入中台完毕----requestId值为:" + requestId); + return Action.SUCCESS; + } + +} \ No newline at end of file diff --git a/src/main/youhong_ai_jitu_src/jntchina/action/BorrowOrderActionYY.java b/src/main/youhong_ai_jitu_src/jntchina/action/BorrowOrderActionYY.java new file mode 100644 index 0000000..60267e7 --- /dev/null +++ b/src/main/youhong_ai_jitu_src/jntchina/action/BorrowOrderActionYY.java @@ -0,0 +1,324 @@ +package jntchina.action; + +import java.util.ArrayList; +import java.util.List; +import java.util.UUID; + + +import com.alibaba.fastjson.JSONObject; +import com.alibaba.fastjson.serializer.SerializerFeature; +import com.working.util.WorkflowUtil; + +import jntchina.entity.BorrowOrder; +import jntchina.entity.BorrowOrderBody; +import jntchina.util.HttpClientToDC; +import selfdev.util.base.BaseUtil; +import selfdev.util.base.TimeCommonUtil; +import selfdev.util.log.LogTool; +import weaver.conn.RecordSet; +import weaver.file.Prop; +import weaver.general.Util; +import weaver.hrm.resource.ResourceComInfo; +import weaver.interfaces.workflow.action.Action; +import weaver.interfaces.workflow.action.BaseAction; +import weaver.soa.workflow.request.RequestInfo; + +/** + * @Author Administrator + * @Description 借款申请单数据传入NCC生成单据 + * @Date 2021/1/8 12:14 + */ +public class BorrowOrderActionYY extends BaseAction { + + @Override + public String execute(RequestInfo requestInfo) { + String src = requestInfo.getRequestManager().getSrc();//获取操作方式 + if (!"submit".equals(src)) { // 只有submit才执行接口 + return SUCCESS; + } + LogTool log = new LogTool("/log/selfdev/action", false); + String requestId = requestInfo.getRequestid(); // 获取requestid + String workflowid=requestInfo.getWorkflowid(); + log.writeLog("--------借款申请单数据传入中台开始----requestId值为:" + requestId); + + //获取当前用户的登录账号(即工号) + String loginid=requestInfo.getRequestManager().getUser().getLoginid(); + //获取配置文件中的参数 + String mode = Prop.getPropValue("DevToDC_jntchina","mode"); + // 服务器ip:port + String baseUrl = Prop.getPropValue("DevToDC_jntchina", mode+"_baseUrl"); + String url = baseUrl+"/dcnccapi/billLoan/receiveData"; + BorrowOrder borrowOrder = new BorrowOrder(); + + String mainTable = WorkflowUtil.getMainTable(requestId); + String pk_org = ""; // JTSDCN0001 //借款单位编码 + String isShowErrorMsg = "";//写入NCC失败时是否显示报错信息 + String total = ""; // 1000.00 //合计金额 + String deptid = ""; // SD3300101 //借款人部门 + String djlxbm = ""; // 263X-Cxx-DSJKD", //交易类型编码 263X-Cxx-DSJKD:对私借款单 263X-Cxx-DGJKD:对公预付/借款单 + String djrq = TimeCommonUtil.obtainDate(0); // 2021-03-05 10:17:10", //单据日期 + String payflag = "1"; //1", //支付状态 + String paytarget = ""; // 0" //收款对象(0=员工,1=供应商) + //String bzbm = "CNY"; // 币种编码,默认为人民币 + String yxzh = ""; //银行账号(员工) + String yxzhjtglgs = ""; //银行账号_集团关联公司 + String yxzhdlgs = ""; //银行账号_代理公司 + String receiver = ""; // yonyou88", //收款人(员工) + String skyhzh = ""; //收款人银行账号(员工) + String custaccount = ""; //收款人银行账号(供应商) + String jkbxr = ""; // yonyou88 //借款报销人 + String operator = ""; // yonyou88 //录入人 + String jsfs = ""; //结算方式 0现金 3网银 + String fkyhzh = ""; //单位银行账户 + String zy = ""; //借款测试", //事由 + String djzt = "1"; // 1", //单据状态 1 保存 + String kjqj = ""; // 03", //会计期间 + String kjnd = ""; // 2021", //会计年度 + String zyx1 = ""; // CSBX21020501", //OA单据号 + String zyx2 = ""; // 提交人 + String zyx3 = ""; // OA核销单号 + String zyx5 = ""; // CSBX21020501", // OARequestID + String zyx8="";//银行付款备注 +// String zyx9=requestInfo.getRequestManager().getRequestname();//标题 + String zyx9=requestInfo.getRequestManager().getRequestname().length()>140?requestInfo.getRequestManager().getRequestname().substring(0,140):requestInfo.getRequestManager().getRequestname();//标题 + + String defitem46 = ""; // 网点(成本中心) + String xm="";//申请人 + String bm="";//申请部门 + String dls="";//代理公司编码 + String jtglgsbm="";//集团关联公司编码 + String jklx="";//借款类型 + String hbbm="";//供应商编码 + String szxmid = "901038"; // 收支项目 默认为员工借款 + + RecordSet rs = new RecordSet(); + try { + String sql = " select * from " + mainTable + " where requestid='" + requestId + "'"; + rs.execute(sql); + while (rs.next()) { + isShowErrorMsg = Util.null2String(rs.getString("xrnccsbcsfts")); + pk_org = Util.null2String(rs.getString("gsmc")); // 付款公司名称 + total = Util.null2String(rs.getString("jkje")); // 借款金额 金额由表体相应字段汇总得出 +// djrq = Util.null2String(rs.getString("cjrq")); // 单据日期 yyyy-mm-dd hh:mm:ss + jklx = Util.null2String(rs.getString("jklx")); // 收款对象 + xm = Util.null2String(rs.getString("xm")); // 姓名 + yxzh = Util.null2String(rs.getString("yxzh")).replace(" ", ""); //收款人银行账号 + dls = Util.null2String(rs.getString("dls")); // 代理公司编码 + jtglgsbm = Util.null2String(rs.getString("jtglgsbm")); // 集团关联公司编码 + yxzhdlgs = Util.null2String(rs.getString("yxzhdlgs")); // 银行账号_代理公司 + yxzhjtglgs = Util.null2String(rs.getString("yxzhjtglgs")); // 银行账号_集团关联公司 + bm = Util.null2String(rs.getString("bm")); //申请部门 + jsfs = Util.null2String(rs.getString("zffs")); //结算方式 传输编码 + fkyhzh = Util.null2String(rs.getString("")); // 付款银行账户 传输编码 + zy = Util.null2String(rs.getString("jkyy")); //借款原因 + zyx8 = Util.null2String(rs.getString("yxfkbz")); //银行付款备注 + zyx1 = Util.null2String(rs.getString("lcbh")); // OA单据号 OA传过来,用于联查单据 + zyx2 = new ResourceComInfo().getLastname(xm); //提交人姓名 + zyx3 = Util.null2String(rs.getString("")); // OA核销单号 + zyx5 = requestId; // OARequestID + defitem46 = Util.null2String(rs.getString("cbzx")); // 网点(成本中心) + } + kjqj = djrq.substring(5,7); // 会计期间 + kjnd = djrq.substring(0,4); // 会计年度 + //根据申请部门ID转换查询部门编码 + deptid=BaseUtil.getBaseInfoByParm("departmentcode", "hrmdepartment", "id", bm, ""); + //获取员工默认的组织对应的类型 + String userDefaultCompanyType=BaseUtil.getBaseInfoByParm("company_type", "v_oa_user_org_nsrsbh", "userid", xm, ""); + //获取付款单选择的组织对应的类型 + String selectCompanyType=BaseUtil.getBaseInfoByParm("company_type", "uf_businessunit", "code", pk_org, ""); + log.writeLog("userDefaultCompanyType------>" + userDefaultCompanyType); + log.writeLog("selectCompanyType------>" + selectCompanyType); + //跨组织,则说明代理区想总部借款 + if(!userDefaultCompanyType.equals(selectCompanyType)){ + if("".equals(userDefaultCompanyType)){ + //获取流程名称 + String workflowname=BaseUtil.getBaseInfoByParm("workflowname", "workflow_base", "id", workflowid, ""); + //若名称中带有“代理区”,则说明员工默认组织类型是代理区 + if(workflowname.contains("代理区")){ + userDefaultCompanyType="2"; + } + } + //查询建模维护的对应关系 + String defaultDeptNo=BaseUtil.getBaseInfoByParm("mroabmbm", "uf_kzzfkdybmsz", "sqgslx", userDefaultCompanyType, " and fkgslx='"+selectCompanyType+"'"); + log.writeLog("defaultDeptNo------>" + defaultDeptNo); + if(!"".equals(defaultDeptNo)){ + deptid=defaultDeptNo; + } + } + //截取前120位 + if(zy.length()>120){ + zy=zy.substring(0,120); + } + //结算方式 + if("0".equals(jsfs)){ + jsfs = "3"; //网银 + }else{ + jsfs = "0"; //现金 + } + receiver = new ResourceComInfo().getWorkcode(xm); //收款人,与申请人一致 + jkbxr = receiver; // 借款报销人,与申请人一致 + //收款对象为员工时,则对应NCC的对私借款单 + if("0".equals(jklx)){ + paytarget="0";//0=员工,1=供应商,2=客户 + djlxbm = "263X-Cxx-DSJKD"; // 单据类型编码 + skyhzh=yxzh; + //供应商收款信息清空 + hbbm=""; + custaccount=""; + }else{//对公借款单 + djlxbm = "263X-Cxx-DGJKD"; // 单据类型编码 + paytarget="1";//0=员工,1=供应商,2=客户 + if("3".equals(jklx)){//集团关联公司 + hbbm=jtglgsbm; + szxmid="901062";//经营借款(外部借款) + custaccount=yxzhjtglgs; + }else{ + hbbm=dls; + szxmid="901061";//经营借款(内部借款) + custaccount=yxzhdlgs; + } + //员工收款信息清空 + receiver=""; + skyhzh=""; + } + + //获取UUID + String uuid=UUID.randomUUID().toString().replace("-", "").toUpperCase(); + operator = loginid;//当前节点操作者 + + borrowOrder.setUuid(uuid); + borrowOrder.setPk_org(pk_org); + borrowOrder.setTotal(total); + borrowOrder.setDeptid(deptid); + borrowOrder.setDjlxbm(djlxbm); + borrowOrder.setDjrq(djrq); + borrowOrder.setPayflag(payflag); + borrowOrder.setPaytarget(paytarget); + borrowOrder.setHbbm(hbbm); + borrowOrder.setReceiver(receiver); + borrowOrder.setJkbxr(jkbxr); + borrowOrder.setOperator(operator); + borrowOrder.setJsfs(jsfs); + borrowOrder.setFkyhzh(fkyhzh); + borrowOrder.setSkyhzh(skyhzh); + borrowOrder.setCustaccount(custaccount); + borrowOrder.setZy(zy); + borrowOrder.setDjzt(djzt); + borrowOrder.setKjqj(kjqj); + borrowOrder.setKjnd(kjnd); + borrowOrder.setZyx1(zyx1); + borrowOrder.setZyx2(zyx2); + borrowOrder.setZyx3(zyx3); + borrowOrder.setZyx5(zyx5); + borrowOrder.setZyx8(zyx8); + borrowOrder.setZyx9(zyx9); + log.writeLog("【header数据准备完毕...】"); + + List borrowOrderBodyList = new ArrayList(); + String tablecode = ""; // jk_busitem + String rowno = ""; // 10 + String defitem50 = ""; // 发票类型 + String defitem49 = ""; // 发票号码 + String defitem42 = ""; // OA明细ID + String defitem43 = ""; // 车牌号 + String defitem44 = ""; // 仓库 + String defitem45 = ""; // 国家 + + String defitem48 = deptid; // SD3300301" //分摊部门 + BorrowOrderBody body = new BorrowOrderBody(); + tablecode = "jk_busitem"; + rowno = "10"; + + body.setAmount(total); + body.setTablecode(tablecode); + body.setRowno(rowno); + body.setSzxmid(szxmid); + body.setDefitem50(defitem50); + body.setDefitem49(defitem49); + body.setDefitem42(defitem42); + body.setDefitem43(defitem43); + body.setDefitem44(defitem44); + body.setDefitem45(defitem45); + body.setDefitem46(defitem46); + body.setDefitem48(defitem48); + borrowOrderBodyList.add(body); + borrowOrder.setJk_busitem(borrowOrderBodyList); + + String parm=JSONObject.toJSONString(borrowOrder, SerializerFeature.DisableCircularReferenceDetect); + log.writeLog("借款单准备传入数据中台的数据为------>" + parm); + + //获取TOKEN + String token = HttpClientToDC.getToken(); + log.writeLog("获取数据中台的token------>" + token); + if ("".equals(Util.null2String(token))) { + String tokenMsg="流程提交失败,未获取到数据中台接口TOKEN,请联系管理员处理!"; + //将NCC返回结果回写至OA流程表单 + rs.execute(" update " + mainTable + " set sfcgscnccfkd = 1 ,nccfhxx='" + tokenMsg.replace("'", "''") + "' where requestid = " + requestId); + //是否需要显示报错信息 + if("yes".equals(isShowErrorMsg)){ + requestInfo.getRequestManager().setMessagecontent(tokenMsg); + return Action.FAILURE_AND_CONTINUE; + }else{ + return SUCCESS; + } + } + + + //调用NCC接口,将数据传给NCC + String returndata = HttpClientToDC.sendPostApi(url,token, parm); + log.writeLog("【调用数据中台借款接口返回结果result:】" + returndata); + if (!"".equals(returndata) && returndata != null) { + JSONObject jsonObject = JSONObject.parseObject(returndata); + String success = Util.null2String(jsonObject.get("succ")); + log.writeLog("--------发送请求返回的success值为:" + success); + if ("true".equals(success)) { + JSONObject data = jsonObject.getJSONObject("data"); + String billno = Util.null2String(data.get("billno"));//NCC单号 + log.writeLog("--------发送请求返回的billno值为:" + billno); + //将NCC返回结果回写至OA流程表单 + rs.execute(" update " + mainTable + " set sfcgscnccfkd = 0 , nccfkdh = '" + billno + "',nccfhxx='' where requestid = " + requestId); + } else { + String message = Util.null2String(jsonObject.get("msg")); + String message2=message.replace("'", "''"); + //超出1333个字符,则只截取前面这部分 + if(message2.length()>1334){ + message2=message2.substring(0,1333); + } + //将NCC返回结果回写至OA流程表单 + rs.execute(" update " + mainTable + " set sfcgscnccfkd = 1 ,nccfhxx='" + message2 + "' where requestid = " + requestId); + //是否需要显示报错信息 + if("yes".equals(isShowErrorMsg)){ + requestInfo.getRequestManager().setMessagecontent("流程数据写入NCC借款单失败,失败信息:
"+message); + return Action.FAILURE_AND_CONTINUE; + }else{ + return SUCCESS; + } + } + } else { + String ermsg="流程数据写入NCC借款单失败,未获取到接口返回结果,请联系系统管理员处理!"; + //将NCC返回结果回写至OA流程表单 + rs.execute(" update " + mainTable + " set sfcgscnccfkd = 1 ,nccfhxx='" + ermsg.replace("'", "''") + "' where requestid = " + requestId); + //是否需要显示报错信息 + if("yes".equals(isShowErrorMsg)){ + requestInfo.getRequestManager().setMessagecontent(ermsg); + return Action.FAILURE_AND_CONTINUE; + }else{ + return SUCCESS; + } + } + } catch (Exception e) { + String ermsg="流程数据生成中台借款单失败,失败信息:
" + e.toString(); + //将NCC返回结果回写至OA流程表单 + rs.execute(" update " + mainTable + " set sfcgscnccfkd = 1 ,nccfhxx='" + ermsg.replace("'", "''") + "' where requestid = " + requestId); + //是否需要显示报错信息 + if("yes".equals(isShowErrorMsg)){ + requestInfo.getRequestManager().setMessagecontent(ermsg); + return Action.FAILURE_AND_CONTINUE; + }else{ + return SUCCESS; + } + } + log.writeLog("--------借款单数据传入中台完毕----requestId值为:" + requestId); + return Action.SUCCESS; + } +} \ No newline at end of file diff --git a/src/main/youhong_ai_jitu_src/jntchina/action/BusinessTripChangeAction.java b/src/main/youhong_ai_jitu_src/jntchina/action/BusinessTripChangeAction.java new file mode 100644 index 0000000..2090d8f --- /dev/null +++ b/src/main/youhong_ai_jitu_src/jntchina/action/BusinessTripChangeAction.java @@ -0,0 +1,60 @@ +package jntchina.action; + +import com.working.util.WorkflowUtil; + +import selfdev.util.base.TimeUtil; +import selfdev.util.log.LogTool; +import weaver.conn.RecordSet; +import weaver.general.Util; +import weaver.soa.workflow.request.RequestInfo; +import weaver.workflow.action.BaseAction; + +/** + * 出差申请变更时更新流程表单数据 + * @author KangMD + * 2021-08-09 + */ +public class BusinessTripChangeAction extends BaseAction { + + @Override + public String execute(RequestInfo requestInfo) { + LogTool log = new LogTool("/log/selfdev/action", false); + log.writeLog("-----------------------开始OA出差申请变更时,删除明细行-----------------------"); + String requestId = requestInfo.getRequestid(); //获取requestid + log.writeLog("------------requestId值为:" + requestId); + String mainTable = WorkflowUtil.getMainTable(requestId); + String mainid = ""; // + RecordSet rs = new RecordSet(); + String sql = " select * from " + mainTable + " where requestid='" + requestId + "'"; + rs.execute(sql); + while (rs.next()) { + mainid=Util.null2String(rs.getString("id")); + } + //获取获取系统当前时间 + String nowDate=TimeUtil.obtainDate(0).substring(0,10); + //将数据插入历史记录表 + + //插入机票明细至历史记录表 + rs.execute("insert into "+mainTable+"_dt5(MAINID,BGCZRQ,CCRY,CFD,DDD,HBLX,CFRQ,FCRQ,BZ) " + + "select MAINID,'"+nowDate+"',CCRY,CFD,DDD,HBLX,CFRQ,FCRQ,BZ from "+mainTable+"_dt1 where mainid="+mainid); + //插入酒店明细至历史记录表 + rs.execute("insert into "+mainTable+"_dt6(MAINID,BGCZRQ,ccry,rzrq,ldrq,rzcs,BZ) " + + "select MAINID,'"+nowDate+"',ccry,rzrq,ldrq,rzcs,BZ from "+mainTable+"_dt2 where mainid="+mainid); + //插入火车明细至历史记录表 + rs.execute("insert into "+mainTable+"_dt7(MAINID,BGCZRQ,ccry,cfrq,cfcs,ddcs,BZ) " + + "select MAINID,'"+nowDate+"',ccry,cfksrq,cfcs,ddcs,BZ from "+mainTable+"_dt3 where mainid="+mainid); + //插入用车明细至历史记录表 + rs.execute("insert into "+mainTable+"_dt8(MAINID,BGCZRQ,ycry,ksrq,jsrq,yccs,BZ) " + + "select MAINID,'"+nowDate+"',ycry,ksrq,jsrq,yccs,BZ from "+mainTable+"_dt4 where mainid="+mainid); + + //删除已填写的历史明细 +// rs.execute("delete from "+mainTable+"_dt1 where mainid="+mainid); +// rs.execute("delete from "+mainTable+"_dt2 where mainid="+mainid); +// rs.execute("delete from "+mainTable+"_dt3 where mainid="+mainid); +// rs.execute("delete from "+mainTable+"_dt4 where mainid="+mainid); + //将“行程是否已修改过”更新为是 + rs.execute("update "+mainTable+" set xcsfyxgg=0,xczt=null where requestid="+requestId); + + return SUCCESS; + } +} \ No newline at end of file diff --git a/src/main/youhong_ai_jitu_src/jntchina/action/BusinessTripIntoHRAction.java b/src/main/youhong_ai_jitu_src/jntchina/action/BusinessTripIntoHRAction.java new file mode 100644 index 0000000..baf87b0 --- /dev/null +++ b/src/main/youhong_ai_jitu_src/jntchina/action/BusinessTripIntoHRAction.java @@ -0,0 +1,211 @@ +package jntchina.action; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.JSONObject; +import com.alibaba.fastjson.serializer.SerializerFeature; +import com.working.third.JwtUtil; +import com.working.util.HttpManager; +import com.working.util.WorkflowUtil; +import selfdev.util.log.LogTool; +import weaver.conn.RecordSet; +import weaver.file.Prop; +import weaver.general.Util; +import weaver.soa.workflow.request.RequestInfo; +import weaver.workflow.action.BaseAction; + +import java.io.IOException; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +/** + * @Author Administrator + * @Description OA出差申请数据写入东宝HR系统 + * @Date 2020/10/20 16:26 + *

+ * 这两个值后需要写在配置文件中 + * 正式环境 + * https://hr.jtexpress.com.cn + * clientId:TPFKAGB3QGPM2LBD + * 测试环境 + * http://121.36.223.187:8093 + * clientId: P3F28BIFKGFL0ANX + */ +public class BusinessTripIntoHRAction extends BaseAction { + + @Override + public String execute(RequestInfo requestInfo) { + LogTool log = new LogTool("/log/selfdev/action", false); + log.writeLog("-----------------------开始OA出差申请数据写入东宝HR系统-----------------------"); + String requestId = requestInfo.getRequestid(); //获取requestid + log.writeLog("------------requestId值为:" + requestId); + + //获取配置文件中的参数 + String mode = Prop.getPropValue("db_work_china","mode"); + + String mainTable = WorkflowUtil.getMainTable(requestId); + + String clientId = Prop.getPropValue("db_work_china", mode+"_clientId"); +// String clientId = "P3F28BIFKGFL0ANX"; + String secret = Prop.getPropValue("db_work_china", mode+"_secret"); + int second = Integer.parseInt(Prop.getPropValue("db_work_china", mode+"_second")); + + String batchCardDataUrl = Prop.getPropValue("db_work_china", mode+"_batchCardDataUrl"); +// String batchCardDataUrl = "http://121.36.223.187:8093/third/api"; + + String code = Prop.getPropValue("db_work_china", mode+"_code"); + String moduleCode = Prop.getPropValue("db_work_china", mode+"_moduleCode"); +// String code = "saveBusinessTripOrderToThirdNew"; +// String moduleCode = "attBusinessTripOrderService"; + String token = JwtUtil.createThirdToken(clientId, secret, second).getToken(); + + HashMap headMap = new HashMap(); // 存放head的值 + headMap.put("code", code); + headMap.put("moduleCode", moduleCode); + headMap.put("token", token); + headMap.put("clientId", clientId); + + HashMap bodyMap = new HashMap(); // 存放body的值 + + String userId = ""; // 申请人id + String workCode = ""; //人员编号 + + String trip_category = "2"; // 出差类型(1-外出,2-出差) + String trip_area = ""; // 出差区域(1-市内,2-省内,3-国内,4-海外) 暂时只分3和4 + String trip_way = "4"; // 出差方式(1-整天,2-上半天,3-下半天,4-连续时间段,5-每天固定时间) + + String begin_date = ""; // 开始日期 + String end_date = ""; // 结束日期 + String begin_time = ""; // 开始时间 + String end_time = ""; // 结束时间 + String reason = ""; // 出差事由 + String origin = ""; // 出发地 + String destination = ""; // 目的地 + + String is_overtime = "1"; // 是否出差计加班(默认传入1) + String audit_status = "5"; // 提交状态 0-保存 1-提交 5-无需审核 + + RecordSet rs = new RecordSet(); + String sql = " select * from " + mainTable + " where requestid='" + requestId + "'"; + rs.execute(sql); + while (rs.next()) { + HashMap empOrderMap = new HashMap(); // 存放empOrder的值 + HashMap businessTripOrderMap = new HashMap(); // 存放businessTripOrder的值 + + userId = Util.null2String(rs.getString("sqr"));// 人员转换唯一标识 + workCode = Util.null2String(WorkflowUtil.getUserInfo(userId).get("workcode")); + log.writeLog("------------人员转换唯一标识值为:" + workCode); + + String trip_area1 = Util.null2String(rs.getString("cclb")); // 出差类别 + if ("0".equals(trip_area1)) { + trip_area = "3"; // 国内 + } + if ("1".equals(trip_area1)) { + trip_area = "4"; // 国外 + } + + + begin_date = Util.null2String(rs.getString("ksrq")); // 开始日期 + end_date = Util.null2String(rs.getString("jsrq1")); // 结束日期 + begin_time = Util.null2String(rs.getString("kssj")); // 开始时间 + end_time = Util.null2String(rs.getString("jssj")); // 结束时间 + + reason = Util.null2String(rs.getString("ccsy")); // 出差事由 + origin = Util.null2String(rs.getString("cfd")); // 出发地 + destination = Util.null2String(rs.getString("mdd")); // 目的地 + +// String[] s = begin_date.split(" "); +// begin_time = s[1]; +// String[] s1 = end_date.split(" "); +// end_time = s1[1]; + + List> scheduleList = new ArrayList>(); // 出差行程记录 + Map scheduleMap1 = new HashMap(); + scheduleMap1.put("name", "出发地"); + scheduleMap1.put("place", origin); + scheduleMap1.put("longitude", ""); + scheduleMap1.put("latitude", ""); + scheduleMap1.put("id", ""); + + Map scheduleMap2 = new HashMap(); + scheduleMap2.put("name", "目的地"); + scheduleMap2.put("place", destination); + scheduleMap2.put("longitude", ""); + scheduleMap2.put("latitude", ""); + scheduleMap2.put("id", ""); + scheduleList.add(scheduleMap1); + scheduleList.add(scheduleMap2); + + log.writeLog("------------出差类型值为:" + trip_category); + log.writeLog("------------出差区域值为:" + trip_area); + log.writeLog("------------出差方式值为:" + trip_way); + log.writeLog("------------开始日期值为:" + begin_date); + log.writeLog("------------结束日期值为:" + end_date); + log.writeLog("------------开始时间值为:" + begin_time); + log.writeLog("------------结束时间值为:" + end_time); + log.writeLog("------------出差事由值为:" + reason); + log.writeLog("------------出发地值为:" + origin); + log.writeLog("------------目的地值为:" + destination); + + empOrderMap.put("empKey", workCode); + empOrderMap.put("empRule", "1"); // 人员转换规则(0-无,1-工号,2-身份证,3邮箱,4-手机号码) + + businessTripOrderMap.put("trip_category", trip_category); + businessTripOrderMap.put("trip_area", trip_area); + businessTripOrderMap.put("trip_way", trip_way); + businessTripOrderMap.put("begin_date", begin_date); + businessTripOrderMap.put("end_date", end_date); + businessTripOrderMap.put("begin_time", begin_time); + businessTripOrderMap.put("end_time", end_time); + businessTripOrderMap.put("reason", reason); + + businessTripOrderMap.put("is_overtime", is_overtime); + businessTripOrderMap.put("audit_status", audit_status); + businessTripOrderMap.put("isChangeTripOrder", false); // 是否变更出差单(默认传入false) + + businessTripOrderMap.put("scheduleList", scheduleList); + + empOrderMap.put("businessTripOrder", businessTripOrderMap); + bodyMap.put("empOrder", empOrderMap); + } + + HashMap paramMap = new HashMap(); + paramMap.put("header", headMap); + paramMap.put("body", bodyMap); + + try { + String param = JSON.toJSONString(paramMap, SerializerFeature.DisableCircularReferenceDetect); + log.writeLog("---------------paramMap的值为:" + param); + String result = HttpManager.postMap(batchCardDataUrl, headMap, param); + log.writeLog("-----------发送请求返回的结果值为:" + result); + + JSONObject jsonObject = JSONObject.parseObject(result); + String returnCode = Util.null2String(jsonObject.get("code")); + String data = Util.null2String(jsonObject.get("data")); + String message = Util.null2String(jsonObject.get("message")); + String id = Util.null2String(jsonObject.get("id")); + + log.writeLog("--------发送请求返回的code值为:" + returnCode); + log.writeLog("--------发送请求返回的数据值为:" + data); + log.writeLog("--------发送请求返回的信息为:" + message); + log.writeLog("--------发送请求返回的id值为:" + id); + + if (!"".equals(result) && result != null) { + if ("200".equals(returnCode)) { + return SUCCESS; + } else { + requestInfo.getRequestManager().setMessagecontent("写入HR系统失败,失败信息为:" + message); + return "0"; + } + } else { + requestInfo.getRequestManager().setMessagecontent("写入HR系统失败,发送请求返回的结果值为" + result); + return "0"; + } + + } catch (IOException ioException) { + requestInfo.getRequestManager().setMessagecontent("发生异常了,写入HR系统失败"); + return "0"; + } + } +} \ No newline at end of file diff --git a/src/main/youhong_ai_jitu_src/jntchina/action/CarApplicationAction.java b/src/main/youhong_ai_jitu_src/jntchina/action/CarApplicationAction.java new file mode 100644 index 0000000..4efda47 --- /dev/null +++ b/src/main/youhong_ai_jitu_src/jntchina/action/CarApplicationAction.java @@ -0,0 +1,341 @@ +package jntchina.action; + +import com.alibaba.fastjson.JSONObject; +import com.working.util.WorkflowUtil; + +import jntchina.entity.BorrowOrder; +import jntchina.entity.BorrowOrderBody; +import jntchina.entity.ReimbursementOrder; +import jntchina.entity.ReimbursementOrderBody; +import jntchina.util.HttpClientToDC; +import selfdev.util.base.BaseUtil; +import selfdev.util.log.LogTool; +import weaver.conn.RecordSet; +import weaver.file.Prop; +import weaver.general.Util; +import weaver.interfaces.workflow.action.Action; +import weaver.soa.workflow.request.RequestInfo; +import weaver.workflow.action.BaseAction; + +import java.util.ArrayList; +import java.util.List; +import java.util.UUID; + +import org.apache.commons.lang3.StringEscapeUtils; + +/** + * @Author Administrator + * @Description 汽运承运商付款申请写入中台生成NCC对公报销单或者对公借款单 + * @Date 2021/3/2 11:50 + */ +public class CarApplicationAction extends BaseAction { + @Override + public String execute(RequestInfo requestInfo) { + String src = requestInfo.getRequestManager().getSrc();//获取操作方式 + if (!"submit".equals(src)) { // 只有submit才执行接口 + return SUCCESS; + } + LogTool log = new LogTool("/log/selfdev/action", false); + String requestId = requestInfo.getRequestid(); // 获取requestid + log.writeLog("--------汽运承运商付款申请数据传入NCC开始----requestId值为:" + requestId); + //获取当前用户的登录账号(即工号) + String loginid=requestInfo.getRequestManager().getUser().getLoginid(); + //获取配置文件中的参数 + String mode = Prop.getPropValue("DevToDC_jntchina","mode"); + // 服务器ip:port + String baseUrl = Prop.getPropValue("DevToDC_jntchina", mode+"_baseUrl"); + //String url = baseUrl+ "/dcoaapi/claimForm/receiveData"; + String url = baseUrl+ "/dcnccapi/claimForm/receiveData"; +// List reimbursementList=new ArrayList(); + ReimbursementOrder reimbursementOrder = new ReimbursementOrder(); + +// List borrowList=new ArrayList(); + BorrowOrder borrowOrder = new BorrowOrder(); + + String mainTable = WorkflowUtil.getMainTable(requestId); + String mainId = ""; + String fygsbm = ""; // 申请部门 + String pk_org = ""; // 报销单位 JTSDCN0001 + String total = ""; // 报销金额 金额由表体相应字段汇总得出 + String deptid = ""; // 部门 传输编码 + String djlxbm = "264X-Cxx-DGBXD"; // 单据类型编码 默认 对公报销单:264X-Cxx-DGBXD + String djlxmc = "对公报销单"; // 单据类型名称 默认 对公报销单 + String djrq = ""; // 单据日期 yyyy-mm-dd hh:mm:ss + String payflag = ""; // 支付状态 + String paytarget = "1"; // 受款对象 0=员工,1=供应商,2=客户 + String hbbm = ""; //供应商编码 + String sfyfp = ""; // 是否有发票 + String receiver = ""; // 收款人 + String skyhzh = ""; // 收款人银行账号(员工) + String custaccount = ""; // 收款人银行账号(供应商) + String jkbxr = ""; // 借款报销人 传输编码 + String operator = ""; // 录入人 + String jsfs = "3"; // 结算方式 3 网银 + String fkyhzh = ""; // 单位银行账户 传输编码 + String jobid = ""; // 项目 + String zy = ""; // 报销事由 + String kjqj = ""; // 会计期间 + String kjnd = ""; // 会计年度 + String fjzs = ""; // 附件张数 需业务人员在OA上传附件同时填写附件张数后传数据到NCC + String zyx1 = ""; // OA单据号 OA传过来,用于联查单据 + String zyx2 = ""; // 提交人 提交人姓名 + String zyx3 = ""; // OA核销单号 + String zyx5 = ""; // OARequestID + String zyx8 = ""; // 银行付款备注 + String zyx9=requestInfo.getRequestManager().getRequestname();//标题 + + RecordSet rs = new RecordSet(); + RecordSet rsFna = new RecordSet(); + try { + String sql = " select * from " + mainTable + " where requestid='" + requestId + "'"; + rs.execute(sql); + while (rs.next()) { + mainId = Util.null2String(rs.getString("id")); + fygsbm = Util.null2String(rs.getString("fygsbm"));//申请部门 + pk_org = Util.null2String(rs.getString("gsmc")); // 报销单位 + total = Util.null2String(rs.getString("fkje")); // 金额 金额由表体相应字段汇总得出 + custaccount = Util.null2String(rs.getString("yxhm")).replace(" ", ""); //收款银行账号 + sfyfp = Util.null2String(rs.getString("sfyfp")); //是否有发票 + djrq = Util.null2String(rs.getString("cjrq")); // 单据日期 yyyy-mm-dd hh:mm:ss + zy = Util.null2String(rs.getString("fksm")); // 付款说明 + hbbm = Util.null2String(rs.getString("gysmc")); // 供应商名称 + kjqj = djrq.substring(5,7); // 会计期间 + kjnd = djrq.substring(0,4); // 会计年度 + fjzs = Util.null2String(rs.getString("fjzs")); // 附件张数 需业务人员在OA上传附件同时填写附件张数后传数据到NCC + zyx1 = Util.null2String(rs.getString("lcbh")); // OA单据号 OA传过来,用于联查单据 + zyx2 = Util.null2String(rs.getString("xm")); // 提交人 提交人姓名 + zyx5 = requestId; // OARequestID + zyx8 = Util.null2String(rs.getString("yxfkbz")); //银行付款备注 + } + //获取UUID + String uuid=UUID.randomUUID().toString().replace("-", "").toUpperCase(); + //根据部门ID查询部门编码 + deptid=BaseUtil.getBaseInfoByParm("departmentcode", "hrmdepartment", "id", fygsbm, ""); + operator = loginid;//当前节点操作者 + //没有发票时,则对应NCC的对公借款单 + if("1".equals(sfyfp)){ + djlxmc = "对公借款单"; + djlxbm = "263X-Cxx-DGJKD"; // 单据类型编码 + //url = baseUrl+"/dcoaapi/billLoan/receiveData"; + url = baseUrl+"/dcnccapi/billLoan/receiveData"; + borrowOrder.setUuid(uuid); + borrowOrder.setPk_org(pk_org); + borrowOrder.setTotal(total); + borrowOrder.setDeptid(deptid); + borrowOrder.setDjlxbm(djlxbm); + borrowOrder.setDjrq(djrq); + borrowOrder.setPayflag(payflag); + borrowOrder.setPaytarget(paytarget); + borrowOrder.setHbbm(hbbm); + borrowOrder.setReceiver(receiver); + //borrowOrder.setCustaccount(custaccount); + //borrowOrder.setSkyhzh(skyhzh); + borrowOrder.setJkbxr(jkbxr); + borrowOrder.setOperator(operator); + borrowOrder.setJsfs(jsfs); + borrowOrder.setFkyhzh(fkyhzh); + borrowOrder.setZy(zy); + borrowOrder.setDjzt("1"); + borrowOrder.setKjqj(kjqj); + borrowOrder.setKjnd(kjnd); + borrowOrder.setZyx1(zyx1); + borrowOrder.setZyx2(zyx2); + borrowOrder.setZyx3(zyx3); + borrowOrder.setZyx5(zyx5); + borrowOrder.setZyx8(zyx8); + borrowOrder.setZyx9(zyx9); + + }else{ + reimbursementOrder.setUuid(uuid); + reimbursementOrder.setPk_org(pk_org); + reimbursementOrder.setTotal(total); + reimbursementOrder.setDeptid(deptid); + reimbursementOrder.setDjlxbm(djlxbm); + reimbursementOrder.setDjrq(djrq); + reimbursementOrder.setPayflag(payflag); + reimbursementOrder.setPaytarget(paytarget); + reimbursementOrder.setReceiver(receiver); + reimbursementOrder.setHbbm(hbbm); + reimbursementOrder.setJkbxr(jkbxr); + reimbursementOrder.setOperator(operator); + reimbursementOrder.setJsfs(jsfs); +// reimbursementOrder.setCustaccount(custaccount); +// reimbursementOrder.setSkyhzh(skyhzh); + reimbursementOrder.setFkyhzh(fkyhzh); + reimbursementOrder.setJobid(jobid); + reimbursementOrder.setZy(zy); + reimbursementOrder.setKjqj(kjqj); + reimbursementOrder.setKjnd(kjnd); + reimbursementOrder.setFjzs(fjzs); + reimbursementOrder.setZyx1(zyx1); + reimbursementOrder.setZyx2(zyx2); + reimbursementOrder.setZyx3(zyx3); + reimbursementOrder.setZyx5(zyx5); + reimbursementOrder.setZyx8(zyx8); + reimbursementOrder.setZyx9(zyx9); + } + + log.writeLog("【header数据准备完毕...】"); + int rowno = 0; + //对公报销 + List reimbursementOrderBodyList = new ArrayList(); + //对公借款 + List borrowOrderBodyList = new ArrayList(); + rs.execute(" select * from " + mainTable + "_dt1 where mainid = " + mainId); + while (rs.next()) { + String fpdm = ""; //发票代码 + String fphm = ""; //发票号码 + String deptid1 = ""; // 费用承担部门  + String fycdbm = Util.null2String(rs.getString("fycdbm")); //费用承担部门 + String jobid1 = Util.null2String(rs.getString("")); // 项目 + String amount = Util.null2String(rs.getString("yfkje")); // 付款金额 + String defitem36 = Util.null2o(rs.getString("fpje")); // 发票金额 + String tax_rate = Util.null2String(rs.getString("sl")); // 税率 3% + String tax_amount = Util.null2String(rs.getString("se")); // 税额 + String tni_amount = Util.null2String(rs.getString("bhsje")); // 无税金额 + String tablecode = "arap_bxbusitem"; + String szxmid = Util.null2String(rs.getString("fylx")); // 收支项目 + String defitem46 = Util.null2String(rs.getString("wd")); // 网点(成本中心) + String defitem45 = Util.null2String(rs.getString("gj")); // 国家 + String defitem44 = Util.null2String(rs.getString("ck")); // 仓库 + String defitem43 = Util.null2String(rs.getString("cph")); //车牌号 + String defitem42 = Util.null2String(rs.getString("id")); // OA明细行ID + + // 得到浏览按钮中发票号码的id,再去数据库中把发票号码和发票代码查出来 + String fphmId = Util.null2String(rs.getString("fphm")); // 发票号码 + if(!"".equals(fphmId)){ + // 得到浏览按钮中发票号码的id,再去数据库中把发票号码和发票代码查出来 + rsFna.execute(" select * from fnainvoiceledger where id = " + fphmId); + while (rsFna.next()) { + fpdm = Util.null2String(rsFna.getString("INVOICECODE")); // 发票代码 + fphm = Util.null2String(rsFna.getString("INVOICENUMBER")); // 发票号码 + } + } + //发票金额为空时,默认等于付款金额 + if(Double.parseDouble(defitem36)==0){ + defitem36=amount; + } + //若收支项目为空时,则费用类型默认为物流运输费用 + if("".equals(szxmid)){ + szxmid="901052"; + } + //根据部门ID查询部门编码 + String defitem48=BaseUtil.getBaseInfoByParm("departmentcode", "hrmdepartment", "id", fycdbm, ""); + deptid1=defitem48; + rowno++; + + + log.writeLog("----deptid1:" + deptid1); + log.writeLog("----amount:" + amount); + log.writeLog("----tax_rate:" + tax_rate); + log.writeLog("----tax_amount:" + tax_amount); + log.writeLog("----tni_amount:" + tni_amount); + log.writeLog("----defitem48:" + defitem48); + + //没有发票时,则对应NCC的对公借款单 + if("1".equals(sfyfp)){ + BorrowOrderBody body = new BorrowOrderBody(); + body.setAmount(total); + body.setTablecode(tablecode); + body.setRowno(rowno+""); + body.setSzxmid(szxmid); + body.setDefitem50(""); + body.setDefitem49(""); + body.setDefitem42(defitem42); + body.setDefitem43(defitem43); + body.setDefitem44(defitem44); + body.setDefitem45(defitem45); + body.setDefitem46(defitem46); + body.setDefitem48(defitem48); + borrowOrderBodyList.add(body); + }else{ + ReimbursementOrderBody body = new ReimbursementOrderBody(); + body.setJobid(jobid1); + body.setDeptid(deptid1); + body.setAmount(amount); + body.setTax_rate(tax_rate); + body.setTax_amount(tax_amount); + body.setTni_amount(tni_amount); + body.setTablecode(tablecode); + body.setRowno(rowno+""); + body.setSzxmid(szxmid); + body.setFpdm(fpdm); + body.setFphm(fphm); + body.setDefitem36(defitem36); + body.setDefitem46(defitem46); + body.setDefitem45(defitem45); + body.setDefitem44(defitem44); + body.setDefitem43(defitem43); + body.setDefitem42(defitem42); + body.setDefitem48(defitem48); + reimbursementOrderBodyList.add(body); + } + + } + + String parm=""; + //没有发票时,则对应NCC的对公借款单 + if("1".equals(sfyfp)){ + borrowOrder.setJk_busitem(borrowOrderBodyList); +// borrowList.add(borrowOrder); + parm=JSONObject.toJSONString(borrowOrder); + log.writeLog(djlxmc+"准备传入中台的数据为------>" + parm); + }else{ + reimbursementOrder.setEr_busitem(reimbursementOrderBodyList); +// reimbursementList.add(reimbursementOrder); + parm=JSONObject.toJSONString(reimbursementOrder); + log.writeLog(djlxmc+"准备传入中台的数据为------>" + parm); + } + + //获取TOKEN + String token = HttpClientToDC.getToken(); + log.writeLog("获取数据中台的token------>" + token); + if ("".equals(Util.null2String(token))) { + requestInfo.getRequestManager().setMessagecontent("流程提交失败,未获取到数据中台接口TOKEN,请联系管理员处理!"); + return Action.FAILURE_AND_CONTINUE; + } + + //调用NCC接口,将数据传给NCC + String returndata = HttpClientToDC.sendPostApi(url,token, parm); + log.writeLog("【调用数据中台"+djlxmc+"接口返回结果result:】" + returndata); + if (!"".equals(returndata) && returndata != null) { +// //过滤前面的双引号 +// if(returndata.startsWith("\"")){ +// returndata=returndata.substring(1); +// } +// //过滤后面的双引号 +// if(returndata.endsWith("\"")){ +// returndata=returndata.substring(0,returndata.length()-1); +// } +// //转义\" +// returndata=StringEscapeUtils.unescapeJava(returndata); +// log.writeLog("【借款接口返回转译处理后的结果result:】" + returndata); + JSONObject jsonObject = JSONObject.parseObject(returndata); + String success = Util.null2String(jsonObject.get("succ")); + log.writeLog("--------发送请求返回的success值为:" + success); + if ("true".equals(success)) { + JSONObject data = jsonObject.getJSONObject("data"); + String billno = Util.null2String(data.get("billno"));//NCC单号 + log.writeLog("--------发送请求返回的billno值为:" + billno); + //将NCC返回结果回写至OA流程表单 + rs.execute(" update " + mainTable + " set sfcgscnccfkd = 0 , nccfkdh = '" + billno + "',nccfhxx='' where requestid = " + requestId); + } else { + String message = Util.null2String(jsonObject.get("msg")); + //将NCC返回结果回写至OA流程表单 + rs.execute(" update " + mainTable + " set sfcgscnccfkd = 1 ,nccfhxx='" + message.replace("'", "''") + "' where requestid = " + requestId); + requestInfo.getRequestManager().setMessagecontent("流程数据写入NCC借款单失败,失败信息:
"+message); + return Action.FAILURE_AND_CONTINUE; + } + } else { + requestInfo.getRequestManager().setMessagecontent("流程数据写入中台"+djlxmc+"失败,未获取到接口返回结果,请联系系统管理员处理!"); + return Action.FAILURE_AND_CONTINUE; + } + + } catch (Exception e) { + requestInfo.getRequestManager().setMessagecontent("流程数据生成中台对公报销单/对公借款单失败!" + e.toString()); + return Action.FAILURE_AND_CONTINUE; + } + log.writeLog("--------承运商付款单数据传入中台完毕----requestId值为:" + requestId); + return Action.SUCCESS; + } +} \ No newline at end of file diff --git a/src/main/youhong_ai_jitu_src/jntchina/action/ChargeCardAction.java b/src/main/youhong_ai_jitu_src/jntchina/action/ChargeCardAction.java new file mode 100644 index 0000000..143fd8a --- /dev/null +++ b/src/main/youhong_ai_jitu_src/jntchina/action/ChargeCardAction.java @@ -0,0 +1,152 @@ +package jntchina.action; + +import com.alibaba.fastjson.JSONObject; +import jntchina.util.HttpClientToDC; +import selfdev.util.base.BaseUtil; +import selfdev.util.log.LogTool; +import weaver.conn.RecordSet; +import weaver.file.Prop; +import weaver.general.Util; +import weaver.interfaces.workflow.action.BaseAction; +import weaver.soa.workflow.request.RequestInfo; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +/** + * @description: 签卡申请单 + * @author: dzs + * @date: 2021/7/29 + **/ +public class ChargeCardAction extends BaseAction { + + @Override + public String execute(RequestInfo requestInfo) { + LogTool log = new LogTool("/log/selfdev/action/hrm", true); + String requestId = requestInfo.getRequestid(); // 获取requestid + String workflowid = requestInfo.getWorkflowid(); // 获取workflowid + + //获取工作流名称 + String workflowname = BaseUtil.getBaseInfoByParm("workflowname", "workflow_base", "id", workflowid, ""); + log.writeLog("---------------工作流名称---------·--workflowname为:" + workflowname); + log.writeLog("--------签卡申请单数据传入中台开始----requestId值为:" + requestId); + + //获取配置文件中的参数,到时候URL路径 + String mode = Prop.getPropValue("DevToDC_jntchina", "mode"); + //服务器ip:port + String baseUrl = Prop.getPropValue("DevToDC_jntchina", mode + "_baseUrl"); + //访问路径拼接 + String url = baseUrl + "/dcoaapi/hr/signCard"; + + //根据流程id获取主表名称 + String mainTable = RegularizationApplyForAction.getMainTable(requestId); + log.writeLog("-------------获取到的表名为-------------:" + mainTable); + + String mainid = ""; + //申请单号 + String C_OA_NUM = ""; + //员工编码 + String EMPLID = ""; + + //签卡数据 + List> list = new ArrayList>(); + //签卡日期 + String C_CARD_DT = ""; + //签卡时间 + String C_CARD_TM = ""; + //签卡类型 + String C_APP_CARD_TYPE = "10"; + String qklx = "";//OA签卡类型 + //签卡原因 + String C_CARD_REASON = ""; + //签卡时段 + String detail_signtype = ""; + + RecordSet rs = new RecordSet(); + try { + String sql = "select a.* from " + mainTable + " a where a.requestid = '" + requestId + "'"; + rs.execute(sql); + log.writeLog("查询主表数据sql语句---------------->" + sql); + while (rs.next()) { + mainid = Util.null2String(rs.getString("id"));//主表主键ID + C_OA_NUM = Util.null2String(rs.getString("lcbh"));//申请单号 + EMPLID = Util.null2String(rs.getString("tjrgh"));//员工编号 + qklx = Util.null2String(rs.getString("qklx"));//签卡类型 + C_CARD_REASON = Util.null2String(rs.getString("qkyy"));//签卡原因 + } + log.writeLog("qklx---------------->" + qklx); + + //历史选项,因公或者因私 + if ("".equals(qklx) || "0".equals(qklx) || "1".equals(qklx)) { + C_APP_CARD_TYPE = "10"; + } else { + //根据下拉框的值获取对应的描述 + C_APP_CARD_TYPE = BaseUtil.getBaseInfoByParm("selectname", "workflow_selectitem", "selectvalue", qklx, + " and fieldid in (select id from workflow_billfield where billid in (select formid from workflow_base where id=" + workflowid + ") and fieldname='qklx' and viewtype=0)"); + //过滤多语言,截取"-"前面的编码 + C_APP_CARD_TYPE = Util.formatMultiLang(C_APP_CARD_TYPE, "7").split("-")[0]; + } + log.writeLog("C_APP_CARD_TYPE---------------->" + C_APP_CARD_TYPE); + //查询明细数据 + sql = "select * from " + mainTable + "_dt1 a where a.mainid = '" + mainid + "'"; + rs.execute(sql); + log.writeLog("查询sql语句---------------->" + sql); + while (rs.next()) { + C_CARD_DT = Util.null2String(rs.getString("detail_signdate"));//签卡日期 + C_CARD_TM = Util.null2String(rs.getString("detail_signtime"));//签卡时间 + detail_signtype = Util.null2String(rs.getString("detail_signtype"));//签卡时段 + //将签卡数据进行包装 + Map maps = new HashMap(); + maps.put("EMPLID", EMPLID); + maps.put("C_CARD_DT", C_CARD_DT); + maps.put("C_CARD_TM", C_CARD_TM); + maps.put("C_APP_CARD_TYPE", C_APP_CARD_TYPE); + maps.put("C_CARD_REASON", C_CARD_REASON); + maps.put("detail_signtype", detail_signtype); + list.add(maps); + } + log.writeLog("----------------->签卡数据明细数据:" + list.toString()); + + //最后再将数据全部打包 + Map map = new HashMap(); + map.put("C_OA_NUM", C_OA_NUM); + map.put("EMPLID", EMPLID); + map.put("LINES", list); + String strParm = JSONObject.toJSONString(map); + log.writeLog("---------------打印的Map数据为:-----------------:" + strParm); + + //获取Token + String token = HttpClientToDC.getToken(); + log.writeLog("签卡申请单token------>" + token); + log.writeLog("签卡申请单url------>" + url); + + //调用NCC接口,将数据传给NCC + String returndata = HttpClientToDC.sendPostApi(url, token, strParm); + log.writeLog("【调用数据中台签卡申请单接口返回结果result:】" + returndata); + if (!"".equals(returndata) && returndata != null) { + JSONObject jsonObject = JSONObject.parseObject(returndata); + String code = Util.null2String(jsonObject.get("code")); + log.writeLog("--------发送请求返回的code值为:" + code); + if (code.equals("1")) { + return SUCCESS; + } else { + String msg = Util.null2String(jsonObject.get("msg")); + requestInfo.getRequestManager().setMessageid("111100"); + requestInfo.getRequestManager().setMessagecontent(msg); + return "0"; + } + } else { + String ermsg = "流程数据写入NCC调动申请单失败,未获取到接口返回结果,请联系系统管理员处理!"; + requestInfo.getRequestManager().setMessageid("111100"); + requestInfo.getRequestManager().setMessagecontent(ermsg); + return "0"; + } + } catch (Exception e) { + //返回0,调用失败 + log.writeLog("------------------------捕获到的异常是:" + e.toString()); + return "0"; + } + } +} diff --git a/src/main/youhong_ai_jitu_src/jntchina/action/ChuchaiCheckAction.java b/src/main/youhong_ai_jitu_src/jntchina/action/ChuchaiCheckAction.java new file mode 100644 index 0000000..2897e43 --- /dev/null +++ b/src/main/youhong_ai_jitu_src/jntchina/action/ChuchaiCheckAction.java @@ -0,0 +1,86 @@ +package jntchina.action; + +import weaver.conn.RecordSet; +import weaver.general.Util; +import weaver.interfaces.workflow.action.BaseAction; +import weaver.soa.workflow.request.RequestInfo; + +import selfdev.util.log.LogTool; +import selfdev.util.base.BaseUtil; +/** + * @description: 出差校验 + * @author: daizhishun + * @date: 2021/9/6 + **/ +public class ChuchaiCheckAction extends BaseAction{ + public static LogTool log=new LogTool("/log/selfdev/action/hrm", true); + public String execute(RequestInfo ri){ + String requestid=ri.getRequestid(); + log.writeLog("---------------出差流程提交时数据逻辑校验开始-------------requestId:" + requestid); + //获取workflowid + String workflowid=ri.getWorkflowid(); + try { + //获取表名 + String tablename=BaseUtil.getBaseInfoByParm("tablename", "workflow_bill", "1", "1", " and id in (select formid from workflow_base where id="+workflowid+")"); + RecordSet rs=new RecordSet(); + + String sql="select * from "+tablename+" where requestid="+requestid; + + String lastname="";//申请人 + String workcode = ""; + String fromDate="";//开始日期 + String fromTime="";//开始时间 + String toDate="";//结束日期 + String toTime="";//结束时间 + + rs.execute(sql); + while(rs.next()){ + workcode = Util.null2String(rs.getString("tjrgh"));//主键ID + lastname=Util.null2String(rs.getString("resourceId"));//BaseUtil.getBaseInfoByParm("lastname", "HrmResource", "id", rs.getString("resourceId"), "");//申请人 + fromDate=Util.null2String(rs.getString("fromDate"));//开始日期 + fromTime=Util.null2String(rs.getString("fromTime"));//开始时间 + toDate=Util.null2String(rs.getString("toDate"));//结束日期 + toTime=Util.null2String(rs.getString("toTime"));//结束时间 + } + + //开始 + String ks=(fromDate+" "+fromTime).substring(0,16); + //结束 + String js=(toDate+" "+toTime).substring(0,16); + String msg=""; + + //检查当前员工在此期间是否有出差记录 + RecordSet rs1=new RecordSet(); + sql="select * from FORMTABLE_MAIN_1723 b where"+ + "((b.fromdate||' '||b.fromtime)>'"+ks+"' and (b.fromdate||' '||b.fromtime)<'"+js+"')"+ + "or ((b.toDate||' '||b.toTime)>'"+ks+"' and (b.toDate||' '||b.toTime)<'"+js+"')"+ + "or ((b.fromdate||' '||b.fromtime)<='"+ks+"' and (b.fromdate||' '||b.fromtime)>='"+js+"')"+ + "and b.resourceId="+lastname+" and b.requestid != "+requestid+""; + log.writeLog("检查当前员工在此期间是否有出差记录sql--------->"+sql); + rs1.execute(sql); + if(rs1.getCounts()>0){ + log.writeLog("进入判断,查询的数据大于0,说明有数据存在,存在:"+rs.getCounts()); + String temp=""; + while(rs1.next()){ + temp+="【requestid="+requestid+""; + } + temp=temp.substring(0,temp.length()-1); + msg+=lastname+"【"+workcode+"】出差时间段"+ks+"~"+js+"之前的流程"+temp+"已提交过出差申请,请重新选择出差时间
"; + } + if(!"".equals(msg)){ + ri.getRequestManager().setMessage("111100"); + ri.getRequestManager().setMessagecontent(msg); + return "0"; + } + } catch (Exception e) { + e.printStackTrace(); + log.writeLog("出差流程提交时数据逻辑校验失败,错误信息为:------>"+e.toString()); + ri.getRequestManager().setMessageid("111100"); + ri.getRequestManager().setMessagecontent("出差流程提交时数据逻辑校验失败,错误信息为:------>"+e.toString()); + return "0"; + } + log.writeLog("---------------出差流程提交时数据逻辑校验结束-------------requestId:" + requestid); + return SUCCESS; + } +} + diff --git a/src/main/youhong_ai_jitu_src/jntchina/action/ChuchaiForceDrawBackAction.java b/src/main/youhong_ai_jitu_src/jntchina/action/ChuchaiForceDrawBackAction.java new file mode 100644 index 0000000..e8e7b08 --- /dev/null +++ b/src/main/youhong_ai_jitu_src/jntchina/action/ChuchaiForceDrawBackAction.java @@ -0,0 +1,37 @@ +package jntchina.action; + +import selfdev.util.base.BaseUtil; +import selfdev.util.log.LogTool; +import weaver.interfaces.workflow.action.BaseAction; +import weaver.soa.workflow.request.RequestInfo; + +/** + * @description: 出差强制收回时的节点附加操作 + * @author: KangMD + * @date: 2021-12-19 + **/ +public class ChuchaiForceDrawBackAction extends BaseAction { + + public static LogTool log=new LogTool("/log/selfdev/action/hrm", false); + public String execute(RequestInfo requestInfo){ + String requestId = requestInfo.getRequestid(); // 获取requestid + String workflowid = requestInfo.getWorkflowid(); // 获取workflowid + //获取工作流名称 + String workflowname = BaseUtil.getBaseInfoByParm("workflowname", "workflow_base", "id", workflowid, ""); + log.writeLog("--------【"+workflowname+"】强制收回时的节点附加操作----requestId值为:" + requestId); + try{ + ChuchaiForceDrawBackThread forceDrawBackThread=new ChuchaiForceDrawBackThread(); + //设置参数 + forceDrawBackThread.setRequestInfo(requestInfo); + Thread thread = new Thread(forceDrawBackThread); + //启动线程 + thread.start(); + log.writeLog("--------【"+workflowname+"】强制收回时启用线程--------"); + }catch (Exception e){ + //返回0,调用失败 + log.writeLog("------------------------捕获到的异常是:" + e.toString()); + return "0"; + } + return SUCCESS; + } +} diff --git a/src/main/youhong_ai_jitu_src/jntchina/action/ChuchaiForceDrawBackAction2.java b/src/main/youhong_ai_jitu_src/jntchina/action/ChuchaiForceDrawBackAction2.java new file mode 100644 index 0000000..d01a70b --- /dev/null +++ b/src/main/youhong_ai_jitu_src/jntchina/action/ChuchaiForceDrawBackAction2.java @@ -0,0 +1,37 @@ +package jntchina.action; + +import selfdev.util.base.BaseUtil; +import selfdev.util.log.LogTool; +import weaver.interfaces.workflow.action.BaseAction; +import weaver.soa.workflow.request.RequestInfo; + +/** + * @description: 携程集成出差强制收回时的节点附加操作 + * @author: KangMD + * @date: 2021-12-19 + **/ +public class ChuchaiForceDrawBackAction2 extends BaseAction { + + public static LogTool log=new LogTool("/log/selfdev/action/hrm", false); + public String execute(RequestInfo requestInfo){ + String requestId = requestInfo.getRequestid(); // 获取requestid + String workflowid = requestInfo.getWorkflowid(); // 获取workflowid + //获取工作流名称 + String workflowname = BaseUtil.getBaseInfoByParm("workflowname", "workflow_base", "id", workflowid, ""); + log.writeLog("--------【"+workflowname+"】强制收回时的节点附加操作----requestId值为:" + requestId); + try{ + ChuchaiForceDrawBackThread2 forceDrawBackThread=new ChuchaiForceDrawBackThread2(); + //设置参数 + forceDrawBackThread.setRequestInfo(requestInfo); + Thread thread = new Thread(forceDrawBackThread); + //启动线程 + thread.start(); + log.writeLog("--------【"+workflowname+"】强制收回时启用线程--------"); + }catch (Exception e){ + //返回0,调用失败 + log.writeLog("------------------------捕获到的异常是:" + e.toString()); + return "0"; + } + return SUCCESS; + } +} diff --git a/src/main/youhong_ai_jitu_src/jntchina/action/ChuchaiForceDrawBackThread.java b/src/main/youhong_ai_jitu_src/jntchina/action/ChuchaiForceDrawBackThread.java new file mode 100644 index 0000000..91c61e3 --- /dev/null +++ b/src/main/youhong_ai_jitu_src/jntchina/action/ChuchaiForceDrawBackThread.java @@ -0,0 +1,124 @@ +package jntchina.action; + +import com.alibaba.fastjson.JSONObject; +import jntchina.util.HttpClientToDC; +import selfdev.util.base.BaseUtil; +import selfdev.util.log.LogTool; +import weaver.conn.RecordSet; +import weaver.file.Prop; +import weaver.general.Util; +import weaver.soa.workflow.request.RequestInfo; + +import java.util.HashMap; +import java.util.Map; + +/** + * @description: 出差流程强制收回时执行接口 + * @author: KangMD + * @date: 2021-12-19 + **/ +public class ChuchaiForceDrawBackThread implements Runnable { + public static LogTool log=new LogTool("/log/selfdev/action/hrm", true); + public RequestInfo requestInfo; + + public RequestInfo getRequestInfo() { + return requestInfo; + } + + public void setRequestInfo(RequestInfo requestInfo) { + this.requestInfo = requestInfo; + } + + public void run(){ + String requestId = requestInfo.getRequestid(); // 获取requestid + try { + log.writeLog("----------1.5秒后再启动【requestId:" + requestId+"】-------------"); + Thread.sleep(1500);//延迟执行 + } catch (InterruptedException e1) { + // TODO Auto-generated catch block + e1.printStackTrace(); + } + log.writeLog("----------1.5秒结束,开启执行代码【requestId:" +requestId+"】-------------"); + + String workflowid = requestInfo.getWorkflowid(); // 获取workflowid + //获取工作流名称 + String workflowname = BaseUtil.getBaseInfoByParm("workflowname", "workflow_base", "id", workflowid, ""); + log.writeLog("--------【"+workflowname+"】数据传入中台开始----requestId值为:" + requestId); + + try{ + //流程当前状态 + String currentnodetype=""; + RecordSet rs = new RecordSet(); + String sql = "select * from workflow_requestbase where requestid = "+requestId+""; + rs.execute(sql); + while (rs.next()) { + currentnodetype = Util.null2String(rs.getString("currentnodetype"));//当前流程状态 + } + log.writeLog("currentnodetype---------------->"+currentnodetype); + //流程当前处于申请节点,才需要调用HR接口 + if(!"0".equals(currentnodetype)){ + log.writeLog("*************流程不是强制收回到申请节点,不需要调用HR接口*************"); + return; + } + //获取配置文件中的参数,到时候URL路径 + String mode = Prop.getPropValue("DevToDC_jntchina", "mode"); + // 服务器ip:port + String baseUrl = Prop.getPropValue("DevToDC_jntchina", mode + "_baseUrl"); + //访问路径拼接 + String url = baseUrl + "/dcoaapi/hr/attendance"; + + //根据流程id获取主表名称 + String mainTable = RegularizationApplyForAction.getMainTable(requestId); + log.writeLog("--------获取到的表名为----:" + mainTable); + //申请单号 + String C_OA_NUM = ""; + //单据来源:默认OA + String C_APPLY_SOURCE = "OA"; + //流程名称:出差流程为30 + String C_WORKFLOW = "30"; + //审批状态:已通过:3 驳回:5 + String C_STATUS = "5"; + + sql = "select lcbh1 from "+mainTable+" where requestid = "+requestId+""; + rs.execute(sql); + log.writeLog("----------------》打印sql语句"+sql); + while (rs.next()) { + C_OA_NUM = Util.null2String(rs.getString("lcbh1"));//申请单号 + } + + + Map map = new HashMap(); + map.put("C_OA_NUM",C_OA_NUM); + map.put("C_APPLY_SOURCE",C_APPLY_SOURCE); + map.put("C_WORKFLOW",C_WORKFLOW); + map.put("C_STATUS",C_STATUS); + String strParm = JSONObject.toJSONString(map); + log.writeLog("---------------打印的Map数据为:-----------------:"+strParm); + + //获取Token + String token = HttpClientToDC.getToken(); + log.writeLog("出差申请单token------>" + token); + log.writeLog("出差申请单url------>" + url); + + //调用NCC接口,将数据传给NCC + String returndata = HttpClientToDC.sendPostApi(url,token,strParm); + log.writeLog("【调用数据中台出差申请单接口返回结果:】" + returndata); + if (!"".equals(returndata) && returndata != null) { + JSONObject jsonObject = JSONObject.parseObject(returndata); + String code = Util.null2String(jsonObject.get("code")); + log.writeLog("--------发送请求返回的code值为:" + code); + if ("1".equals(code)) { + + } else { + String msg = Util.null2String(jsonObject.get("msg")); + log.writeLog("调用HR接口返回错误信息----->" + msg); + } + }else { + log.writeLog("调用HR接口返回为空----->"); + } + }catch (Exception e){ + //返回0,调用失败 + log.writeLog("------------------------捕获到的异常是:" + e.toString()); + } + } +} diff --git a/src/main/youhong_ai_jitu_src/jntchina/action/ChuchaiForceDrawBackThread2.java b/src/main/youhong_ai_jitu_src/jntchina/action/ChuchaiForceDrawBackThread2.java new file mode 100644 index 0000000..fc5a63d --- /dev/null +++ b/src/main/youhong_ai_jitu_src/jntchina/action/ChuchaiForceDrawBackThread2.java @@ -0,0 +1,123 @@ +package jntchina.action; + +import com.alibaba.fastjson.JSONObject; +import jntchina.util.HttpClientToDC; +import selfdev.util.base.BaseUtil; +import selfdev.util.log.LogTool; +import weaver.conn.RecordSet; +import weaver.file.Prop; +import weaver.general.Util; +import weaver.soa.workflow.request.RequestInfo; + +import java.util.HashMap; +import java.util.Map; + +/** + * @description: 携程出差退回至申请人回传状态至OracleHR + * @author: KangMD + * @date: 2021-12-13 + **/ +public class ChuchaiForceDrawBackThread2 implements Runnable { + public static LogTool log=new LogTool("/log/selfdev/action/hrm", true); + public RequestInfo requestInfo; + + public RequestInfo getRequestInfo() { + return requestInfo; + } + + public void setRequestInfo(RequestInfo requestInfo) { + this.requestInfo = requestInfo; + } + + public void run(){ + String requestId = requestInfo.getRequestid(); // 获取requestid + try { + log.writeLog("----------1.5秒后再启动【requestId:" + requestId+"】-------------"); + Thread.sleep(1500);//延迟执行 + } catch (InterruptedException e1) { + // TODO Auto-generated catch block + e1.printStackTrace(); + } + log.writeLog("----------1.5秒结束,开启执行代码【requestId:" +requestId+"】-------------"); + String workflowid = requestInfo.getWorkflowid(); // 获取workflowid + //获取工作流名称 + String workflowname = BaseUtil.getBaseInfoByParm("workflowname", "workflow_base", "id", workflowid, ""); + log.writeLog("--------【"+workflowname+"】状态传入中台开始----requestId值为:" + requestId); + + try{ + //流程当前状态 + String currentnodetype=""; + RecordSet rs = new RecordSet(); + String sql = "select * from workflow_requestbase where requestid = "+requestId+""; + rs.execute(sql); + while (rs.next()) { + currentnodetype = Util.null2String(rs.getString("currentnodetype"));//当前流程状态 + } + log.writeLog("currentnodetype---------------->"+currentnodetype); + //流程当前处于申请节点,才需要调用HR接口 + if(!"0".equals(currentnodetype)){ + log.writeLog("*************流程不是强制收回到申请节点,不需要调用HR接口*************"); + return; + } + //获取配置文件中的参数,到时候URL路径 + String mode = Prop.getPropValue("DevToDC_jntchina", "mode"); + // 服务器ip:port + String baseUrl = Prop.getPropValue("DevToDC_jntchina", mode + "_baseUrl"); + //访问路径拼接 + String url = baseUrl + "/dcoaapi/hr/attendance"; + + //根据流程id获取主表名称 + String mainTable = RegularizationApplyForAction.getMainTable(requestId); + log.writeLog("--------获取到的表名为----:" + mainTable); + //申请单号 + String C_OA_NUM = ""; + //单据来源:默认OA + String C_APPLY_SOURCE = "OA"; + //流程名称:出差流程为30 + String C_WORKFLOW = "30"; + //审批状态:已通过:3, 驳回:5 + String C_STATUS = "5"; + + sql = "select lcbh from "+mainTable+" where requestid = "+requestId+""; + rs.execute(sql); + log.writeLog("----------------》打印sql语句"+sql); + while (rs.next()) { + C_OA_NUM = Util.null2String(rs.getString("lcbh"));//申请单号 + } + + + Map map = new HashMap(); + map.put("C_OA_NUM",C_OA_NUM); + map.put("C_APPLY_SOURCE",C_APPLY_SOURCE); + map.put("C_WORKFLOW",C_WORKFLOW); + map.put("C_STATUS",C_STATUS); + String strParm = JSONObject.toJSONString(map); + log.writeLog("---------------打印的Map数据为:-----------------:"+strParm); + + //获取Token + String token = HttpClientToDC.getToken(); + log.writeLog("出差申请单token------>" + token); + log.writeLog("出差申请单url------>" + url); + + //调用NCC接口,将数据传给NCC + String returndata = HttpClientToDC.sendPostApi(url,token,strParm); + log.writeLog("【调用数据中台出差退回状态回传接口返回结果:】" + returndata); + if (!"".equals(returndata) && returndata != null) { + JSONObject jsonObject = JSONObject.parseObject(returndata); + String code = Util.null2String(jsonObject.get("code")); + log.writeLog("--------发送请求返回的code值为:" + code); + if ("1".equals(code)) { + + } else { + String msg = Util.null2String(jsonObject.get("msg")); + log.writeLog("调用HR接口返回错误信息----->" + msg); + } + }else { + log.writeLog("调用HR接口返回为空----->"); + } + }catch (Exception e){ + //返回0,调用失败 + log.writeLog("------------------------捕获到的异常是:" + e.toString()); + } + } +} diff --git a/src/main/youhong_ai_jitu_src/jntchina/action/ChuchaiHuiChuanReturnAction.java b/src/main/youhong_ai_jitu_src/jntchina/action/ChuchaiHuiChuanReturnAction.java new file mode 100644 index 0000000..6e18bb6 --- /dev/null +++ b/src/main/youhong_ai_jitu_src/jntchina/action/ChuchaiHuiChuanReturnAction.java @@ -0,0 +1,100 @@ +package jntchina.action; + +import com.alibaba.fastjson.JSONObject; +import jntchina.util.HttpClientToDC; +import selfdev.util.base.BaseUtil; +import selfdev.util.log.LogTool; +import weaver.conn.RecordSet; +import weaver.file.Prop; +import weaver.general.Util; +import weaver.interfaces.workflow.action.BaseAction; +import weaver.soa.workflow.request.RequestInfo; + +import java.util.HashMap; +import java.util.Map; + +/** + * @description: 出差结果回传-退回至发起人 + * @author: daizhishun + * @date: 2021/9/10 + **/ +public class ChuchaiHuiChuanReturnAction extends BaseAction { + public static LogTool log=new LogTool("/log/selfdev/action/hrm", true); + public String execute(RequestInfo requestInfo){ + String requestId = requestInfo.getRequestid(); // 获取requestid + String workflowid = requestInfo.getWorkflowid(); // 获取workflowid + + //获取工作流名称 + String workflowname = BaseUtil.getBaseInfoByParm("workflowname", "workflow_base", "id", workflowid, ""); + log.writeLog("--------【"+workflowname+"】退回到申请节点时数据传入中台开始----requestId值为:" + requestId); + + try{ + //获取配置文件中的参数,到时候URL路径 + String mode = Prop.getPropValue("DevToDC_jntchina", "mode"); + // 服务器ip:port + String baseUrl = Prop.getPropValue("DevToDC_jntchina", mode + "_baseUrl"); + //访问路径拼接 + String url = baseUrl + "/dcoaapi/hr/attendance"; + + //根据流程id获取主表名称 + String mainTable = RegularizationApplyForAction.getMainTable(requestId); + log.writeLog("--------获取到的表名为----:" + mainTable); + //申请单号 + String C_OA_NUM = ""; + //单据来源:默认OA + String C_APPLY_SOURCE = "OA"; + //流程名称:出差流程为30 + String C_WORKFLOW = "30"; + //审批状态:已通过:3,驳回:5 + String C_STATUS = "5"; + + RecordSet rs = new RecordSet(); + String sql = "select lcbh1 from "+mainTable+" where requestid = "+requestId+""; + rs.execute(sql); + log.writeLog("----------------》打印sql语句"+sql); + while (rs.next()) { + C_OA_NUM = Util.null2String(rs.getString("lcbh1"));//申请单号 + } + + + Map map = new HashMap(); + map.put("C_OA_NUM",C_OA_NUM); + map.put("C_APPLY_SOURCE",C_APPLY_SOURCE); + map.put("C_WORKFLOW",C_WORKFLOW); + map.put("C_STATUS",C_STATUS); + String strParm = JSONObject.toJSONString(map); + log.writeLog("---------------打印的Map数据为:-----------------:"+strParm); + + //获取Token + String token = HttpClientToDC.getToken(); + log.writeLog("出差申请单token------>" + token); + log.writeLog("出差申请单url------>" + url); + + //调用NCC接口,将数据传给NCC + String returndata = HttpClientToDC.sendPostApi(url,token,strParm); + log.writeLog("【调用数据中台出差申请单接口返回结果:】" + returndata); + if (!"".equals(returndata) && returndata != null) { + JSONObject jsonObject = JSONObject.parseObject(returndata); + String code = Util.null2String(jsonObject.get("code")); + log.writeLog("--------发送请求返回的code值为:" + code); + if ("1".equals(code)) { + return SUCCESS; + } else { + String msg = Util.null2String(jsonObject.get("msg")); + requestInfo.getRequestManager().setMessageid("111100"); + requestInfo.getRequestManager().setMessagecontent(msg); + return "0"; + } + }else { + String ermsg = "流程数据已审批状态提交至中台失败,请联系系统管理员处理!"; + requestInfo.getRequestManager().setMessageid("111100"); + requestInfo.getRequestManager().setMessagecontent(ermsg); + return "0"; + } + }catch (Exception e){ + //返回0,调用失败 + log.writeLog("------------------------捕获到的异常是:" + e.toString()); + return "0"; + } + } +} diff --git a/src/main/youhong_ai_jitu_src/jntchina/action/ChuchaiHuiChuanReturnAction2.java b/src/main/youhong_ai_jitu_src/jntchina/action/ChuchaiHuiChuanReturnAction2.java new file mode 100644 index 0000000..36432a1 --- /dev/null +++ b/src/main/youhong_ai_jitu_src/jntchina/action/ChuchaiHuiChuanReturnAction2.java @@ -0,0 +1,100 @@ +package jntchina.action; + +import com.alibaba.fastjson.JSONObject; +import jntchina.util.HttpClientToDC; +import selfdev.util.base.BaseUtil; +import selfdev.util.log.LogTool; +import weaver.conn.RecordSet; +import weaver.file.Prop; +import weaver.general.Util; +import weaver.interfaces.workflow.action.BaseAction; +import weaver.soa.workflow.request.RequestInfo; + +import java.util.HashMap; +import java.util.Map; + +/** + * @description: 携程出差退回至申请人回传状态至OracleHR + * @author: KangMD + * @date: 2021-12-13 + **/ +public class ChuchaiHuiChuanReturnAction2 extends BaseAction { + public static LogTool log=new LogTool("/log/selfdev/action/hrm", true); + public String execute(RequestInfo requestInfo){ + String requestId = requestInfo.getRequestid(); // 获取requestid + String workflowid = requestInfo.getWorkflowid(); // 获取workflowid + + //获取工作流名称 + String workflowname = BaseUtil.getBaseInfoByParm("workflowname", "workflow_base", "id", workflowid, ""); + log.writeLog("--------【"+workflowname+"】退回到申请节点时状态传入中台开始----requestId值为:" + requestId); + + try{ + //获取配置文件中的参数,到时候URL路径 + String mode = Prop.getPropValue("DevToDC_jntchina", "mode"); + // 服务器ip:port + String baseUrl = Prop.getPropValue("DevToDC_jntchina", mode + "_baseUrl"); + //访问路径拼接 + String url = baseUrl + "/dcoaapi/hr/attendance"; + + //根据流程id获取主表名称 + String mainTable = RegularizationApplyForAction.getMainTable(requestId); + log.writeLog("--------获取到的表名为----:" + mainTable); + //申请单号 + String C_OA_NUM = ""; + //单据来源:默认OA + String C_APPLY_SOURCE = "OA"; + //流程名称:出差流程为30 + String C_WORKFLOW = "30"; + //审批状态:已通过:3,驳回:5 + String C_STATUS = "5"; + + RecordSet rs = new RecordSet(); + String sql = "select lcbh from "+mainTable+" where requestid = "+requestId+""; + rs.execute(sql); + log.writeLog("----------------》打印sql语句"+sql); + while (rs.next()) { + C_OA_NUM = Util.null2String(rs.getString("lcbh"));//申请单号 + } + + + Map map = new HashMap(); + map.put("C_OA_NUM",C_OA_NUM); + map.put("C_APPLY_SOURCE",C_APPLY_SOURCE); + map.put("C_WORKFLOW",C_WORKFLOW); + map.put("C_STATUS",C_STATUS); + String strParm = JSONObject.toJSONString(map); + log.writeLog("---------------打印的Map数据为:-----------------:"+strParm); + + //获取Token + String token = HttpClientToDC.getToken(); + log.writeLog("出差申请单token------>" + token); + log.writeLog("出差申请单url------>" + url); + + //调用NCC接口,将数据传给NCC + String returndata = HttpClientToDC.sendPostApi(url,token,strParm); + log.writeLog("【调用数据中台出差退回状态回传接口返回结果:】" + returndata); + if (!"".equals(returndata) && returndata != null) { + JSONObject jsonObject = JSONObject.parseObject(returndata); + String code = Util.null2String(jsonObject.get("code")); + log.writeLog("--------发送请求返回的code值为:" + code); + if ("1".equals(code)) { + return SUCCESS; + } else { + String msg = Util.null2String(jsonObject.get("msg")); + requestInfo.getRequestManager().setMessageid("111100"); + requestInfo.getRequestManager().setMessagecontent(msg); + return "0"; + } + }else { + String ermsg = "流程数据退回状态提交至中台失败,请联系系统管理员处理!"; + requestInfo.getRequestManager().setMessageid("111100"); + requestInfo.getRequestManager().setMessagecontent(ermsg); + return "0"; + } + }catch (Exception e){ + //返回0,调用失败 + log.writeLog("------------------------捕获到的异常是:" + e.toString()); + return "0"; + } + } +} diff --git a/src/main/youhong_ai_jitu_src/jntchina/action/ChuchaiHuiChuanSuccessAction.java b/src/main/youhong_ai_jitu_src/jntchina/action/ChuchaiHuiChuanSuccessAction.java new file mode 100644 index 0000000..6b6bb7e --- /dev/null +++ b/src/main/youhong_ai_jitu_src/jntchina/action/ChuchaiHuiChuanSuccessAction.java @@ -0,0 +1,102 @@ +package jntchina.action; + +import com.alibaba.fastjson.JSONObject; +import jntchina.util.HttpClientToDC; +import selfdev.util.base.BaseUtil; +import selfdev.util.log.LogTool; +import weaver.conn.RecordSet; +import weaver.file.Prop; +import weaver.general.Util; +import weaver.interfaces.workflow.action.BaseAction; +import weaver.soa.workflow.request.RequestInfo; + +import java.util.HashMap; +import java.util.Map; + +/** + * @description: 出差结果回传-成功-放归档节点前操作 + * @author: daizhishun + * @date: 2021/9/10 + **/ +public class ChuchaiHuiChuanSuccessAction extends BaseAction { + + public static LogTool log=new LogTool("/log/selfdev/action/hrm", true); + public String execute(RequestInfo requestInfo){ + String requestId = requestInfo.getRequestid(); // 获取requestid + String workflowid = requestInfo.getWorkflowid(); // 获取workflowid + + //获取工作流名称 + String workflowname = BaseUtil.getBaseInfoByParm("workflowname", "workflow_base", "id", workflowid, ""); + log.writeLog("--------【"+workflowname+"】数据传入中台开始----requestId值为:" + requestId); + + try{ + //获取配置文件中的参数,到时候URL路径 + String mode = Prop.getPropValue("DevToDC_jntchina", "mode"); + // 服务器ip:port + String baseUrl = Prop.getPropValue("DevToDC_jntchina", mode + "_baseUrl"); + //访问路径拼接 + String url = baseUrl + "/dcoaapi/hr/attendance"; + + //根据流程id获取主表名称 + String mainTable = RegularizationApplyForAction.getMainTable(requestId); + log.writeLog("--------获取到的表名为----:" + mainTable); + //申请单号 + String C_OA_NUM = ""; + //单据来源:默认OA + String C_APPLY_SOURCE = "OA"; + //流程名称:出差流程为30 + String C_WORKFLOW = "30"; + //审批状态:已通过:3,驳回:5 + String C_STATUS = "3"; + + RecordSet rs = new RecordSet(); + String sql = "select lcbh1 from "+mainTable+" where requestid = "+requestId+""; + rs.execute(sql); + log.writeLog("----------------》打印sql语句"+sql); + while (rs.next()) { + C_OA_NUM = Util.null2String(rs.getString("lcbh1"));//申请单号 + } + + + Map map = new HashMap(); + map.put("C_OA_NUM",C_OA_NUM); + map.put("C_APPLY_SOURCE",C_APPLY_SOURCE); + map.put("C_WORKFLOW",C_WORKFLOW); + map.put("C_STATUS",C_STATUS); + String strParm = JSONObject.toJSONString(map); + log.writeLog("---------------打印的Map数据为:-----------------:"+strParm); + + //获取Token + String token = HttpClientToDC.getToken(); + log.writeLog("出差申请单token------>" + token); + log.writeLog("出差申请单url------>" + url); + + //调用NCC接口,将数据传给NCC + String returndata = HttpClientToDC.sendPostApi(url,token,strParm); + log.writeLog("【调用数据中台出差申请单接口返回结果:】" + returndata); + if (!"".equals(returndata) && returndata != null) { + JSONObject jsonObject = JSONObject.parseObject(returndata); + String code = Util.null2String(jsonObject.get("code")); + log.writeLog("--------发送请求返回的code值为:" + code); + if ("1".equals(code)) { + return SUCCESS; + } else { + String msg = Util.null2String(jsonObject.get("msg")); + requestInfo.getRequestManager().setMessageid("111100"); + requestInfo.getRequestManager().setMessagecontent(msg); + return "0"; + } + }else { + String ermsg = "流程数据已审批状态提交至中台失败,请联系系统管理员处理!"; + requestInfo.getRequestManager().setMessageid("111100"); + requestInfo.getRequestManager().setMessagecontent(ermsg); + return "0"; + } + }catch (Exception e){ + //返回0,调用失败 + log.writeLog("------------------------捕获到的异常是:" + e.toString()); + return "0"; + } + } + +} diff --git a/src/main/youhong_ai_jitu_src/jntchina/action/ChuchaiHuiChuanSuccessAction2.java b/src/main/youhong_ai_jitu_src/jntchina/action/ChuchaiHuiChuanSuccessAction2.java new file mode 100644 index 0000000..e69ca57 --- /dev/null +++ b/src/main/youhong_ai_jitu_src/jntchina/action/ChuchaiHuiChuanSuccessAction2.java @@ -0,0 +1,101 @@ +package jntchina.action; + +import com.alibaba.fastjson.JSONObject; +import jntchina.util.HttpClientToDC; +import selfdev.util.base.BaseUtil; +import selfdev.util.log.LogTool; +import weaver.conn.RecordSet; +import weaver.file.Prop; +import weaver.general.Util; +import weaver.interfaces.workflow.action.BaseAction; +import weaver.soa.workflow.request.RequestInfo; + +import java.util.HashMap; +import java.util.Map; + +/** + * @description: 携程出差审批完成状态回传OracleHR + * @author: KangMD + * @date: 2021-12-13 + **/ +public class ChuchaiHuiChuanSuccessAction2 extends BaseAction { + + public static LogTool log=new LogTool("/log/selfdev/action/hrm", true); + public String execute(RequestInfo requestInfo){ + String requestId = requestInfo.getRequestid(); // 获取requestid + String workflowid = requestInfo.getWorkflowid(); // 获取workflowid + + //获取工作流名称 + String workflowname = BaseUtil.getBaseInfoByParm("workflowname", "workflow_base", "id", workflowid, ""); + log.writeLog("--------【"+workflowname+"】数据传入中台开始----requestId值为:" + requestId); + + try{ + //获取配置文件中的参数,到时候URL路径 + String mode = Prop.getPropValue("DevToDC_jntchina", "mode"); + // 服务器ip:port + String baseUrl = Prop.getPropValue("DevToDC_jntchina", mode + "_baseUrl"); + //访问路径拼接 + String url = baseUrl + "/dcoaapi/hr/attendance"; + + //根据流程id获取主表名称 + String mainTable = RegularizationApplyForAction.getMainTable(requestId); + log.writeLog("--------获取到的表名为----:" + mainTable); + //申请单号 + String C_OA_NUM = ""; + //单据来源:默认OA + String C_APPLY_SOURCE = "OA"; + //流程名称:出差流程为30 + String C_WORKFLOW = "30"; + //审批状态:已通过:3,驳回:5 + String C_STATUS = "3"; + + RecordSet rs = new RecordSet(); + String sql = "select lcbh from "+mainTable+" where requestid = "+requestId+""; + rs.execute(sql); + log.writeLog("---------------->打印sql语句"+sql); + while (rs.next()) { + C_OA_NUM = Util.null2String(rs.getString("lcbh"));//申请单号 + } + + Map map = new HashMap(); + map.put("C_OA_NUM",C_OA_NUM); + map.put("C_APPLY_SOURCE",C_APPLY_SOURCE); + map.put("C_WORKFLOW",C_WORKFLOW); + map.put("C_STATUS",C_STATUS); + String strParm = JSONObject.toJSONString(map); + log.writeLog("---------------传入参数Map数据-----------------:"+strParm); + + //获取Token + String token = HttpClientToDC.getToken(); + log.writeLog("出差申请单token------>" + token); + log.writeLog("出差申请单url------>" + url); + + //调用NCC接口,将数据传给NCC + String returndata = HttpClientToDC.sendPostApi(url,token,strParm); + log.writeLog("【调用数据中台出差申请单审批完成状态回传接口返回结果:】" + returndata); + if (!"".equals(returndata) && returndata != null) { + JSONObject jsonObject = JSONObject.parseObject(returndata); + String code = Util.null2String(jsonObject.get("code")); + log.writeLog("--------发送请求返回的code值为:" + code); + if ("1".equals(code)) { + return SUCCESS; + } else { + String msg = Util.null2String(jsonObject.get("msg")); + requestInfo.getRequestManager().setMessageid("111100"); + requestInfo.getRequestManager().setMessagecontent(msg); + return "0"; + } + }else { + String ermsg = "流程数据已审批状态提交至中台失败,请联系系统管理员处理!"; + requestInfo.getRequestManager().setMessageid("111100"); + requestInfo.getRequestManager().setMessagecontent(ermsg); + return "0"; + } + }catch (Exception e){ + //返回0,调用失败 + log.writeLog("------------------------捕获到的异常是:" + e.toString()); + return "0"; + } + } + +} diff --git a/src/main/youhong_ai_jitu_src/jntchina/action/EHRHolidayInterface.java b/src/main/youhong_ai_jitu_src/jntchina/action/EHRHolidayInterface.java new file mode 100644 index 0000000..7f18647 --- /dev/null +++ b/src/main/youhong_ai_jitu_src/jntchina/action/EHRHolidayInterface.java @@ -0,0 +1,131 @@ +package jntchina.action; + + + + +import com.alibaba.fastjson.JSONObject; +import jntchina.util.HttpClientToDC; +import weaver.file.Prop; +import weaver.general.Util; + +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +/** + * @description: 调用假期余额查询接口 + * @author: daizhishun + * @date: 2021/8/6 + **/ +public class EHRHolidayInterface { + + /** + * 调用假期余额查询接口 + * @param EMPLID 员工编码 + * @return + */ + public Map VacationBalanceSrvh(String EMPLID) { + //前端传进来的键值对字符串,类型转换为Map + Map map1 = (Map)JSONObject.parseObject(EMPLID); + //用来返回数据 + Map map = new HashMap(); + //非空校验 + if ("".equals(map1.get("EMPLID")) || map1.get("EMPLID")==null){ + map.put("zero",0.0); + return map; + } + + //用来传递数据 + String strParm = JSONObject.toJSONString(map1); + + //假期余额查询接口路径,EHR路径 + //String url = "http://121.37.156.206:21005/PSIGW/RESTListeningConnector/PSFT_HR/C_VACATION_BALANCE_SRCH.v1/"; + + String mode = Prop.getPropValue("DevToDC_jntchina", "mode"); + // 服务器ip:port + String baseUrl = Prop.getPropValue("DevToDC_jntchina", mode + "_baseUrl"); + //访问路径拼接 + String url = baseUrl + "/dcoaapi/hr/vacation"; + + //获取Token + String token = HttpClientToDC.getToken(); + + //携带参数调用 + String returndata = HttpClientToDC.sendPostApi(url,token,strParm); + if (!"".equals(returndata) && returndata != null) { + JSONObject jsonObject = JSONObject.parseObject(returndata); + String code = Util.null2String(jsonObject.get("code")); + if("1".equals(code)){ + List list = (List) jsonObject.get("DATA"); + String result = list.get(0).get("C_NJ_BAL").toString(); + String result2 = list.get(0).get("C_TX_BAL").toString(); + double re1 = Double.parseDouble(result); + double re2 = Double.parseDouble(result2); + //本年剩余年休假 + map.put("year_low",re1); + //本年剩余调休假 + map.put("rest_low",re2); + return map; + } + } + map.put("zero",0.0); + return map; + } + + + /** + * 获取员工请假天数接口 + * 员工编号 请假类型 开始日期 开始时间 结束日期 结束时间 + * @return + */ + public Map StaffLeaveByDay(String EMPLID,String C_VACATION_TYPE, + String C_START_DT,String C_START_DTM, + String C_END_DT,String C_END_DTM) { + //用来返回数据 + Map map = new HashMap(); + //非空校验 + if ("".equals(EMPLID) || "".equals(C_VACATION_TYPE) + || "".equals(C_START_DT) ||"".equals(C_START_DTM) + ||"".equals(C_END_DT) ||"".equals(C_END_DTM)){ + map.put("zero",0.0); + return map; + } + + //NCC路径地址 + String mode = Prop.getPropValue("DevToDC_jntchina", "mode"); + // 服务器ip:port + String baseUrl = Prop.getPropValue("DevToDC_jntchina", mode + "_baseUrl"); + //访问路径拼接 + String url = baseUrl + "/dcoaapi/hr/leaveDay"; + + //数据封装 + Map map1 = new HashMap(); + map1.put("EMPLID",EMPLID);//员工编号 + map1.put("C_VACATION_TYPE",C_VACATION_TYPE);//请假类型 + map1.put("C_START_DT",C_START_DT);//开始日期 + map1.put("C_START_DTM",C_START_DTM);//开始时间 + map1.put("C_END_DT",C_END_DT);//结束日期 + map1.put("C_END_DTM",C_END_DTM);//结束时间 + String strParm = JSONObject.toJSONString(map1); + + //获取Token + String token = HttpClientToDC.getToken(); + + //携带参数调用 + String returndata = HttpClientToDC.sendPostApi(url,token,strParm); + if (!"".equals(returndata) && returndata != null) { + JSONObject jsonObject = JSONObject.parseObject(returndata); + String code = Util.null2String(jsonObject.get("code")); + if("1".equals(code)) { + List list = (List) jsonObject.get("DATA"); + String result = list.get(0).get("LEAVE_DAY").toString(); + //转换为double类型 + double result2 = Double.parseDouble(result); + map.put("leavedays",result2); + return map; + } + } + map.put("zero",0.0); + return map; + } +} diff --git a/src/main/youhong_ai_jitu_src/jntchina/action/EmploymentPatternChangeAction.java b/src/main/youhong_ai_jitu_src/jntchina/action/EmploymentPatternChangeAction.java new file mode 100644 index 0000000..c396fbf --- /dev/null +++ b/src/main/youhong_ai_jitu_src/jntchina/action/EmploymentPatternChangeAction.java @@ -0,0 +1,261 @@ +package jntchina.action; + +import com.alibaba.fastjson.JSONObject; +import jntchina.util.HttpClientToDC; +import selfdev.util.base.BaseUtil; +import selfdev.util.log.LogTool; +import weaver.conn.RecordSet; +import weaver.file.Prop; +import weaver.general.Util; +import weaver.interfaces.workflow.action.BaseAction; +import weaver.soa.workflow.request.RequestInfo; + +import java.util.HashMap; +import java.util.Map; + +/** + * @description: 用工模式变更申请单 + * @author: dzs + * @date: 2021/7/26 + **/ +public class EmploymentPatternChangeAction extends BaseAction { + + @Override + public String execute(RequestInfo requestInfo) { + LogTool log = new LogTool("/log/selfdev/action/hrm", true); + String requestId = requestInfo.getRequestid(); // 获取requestid + String workflowid=requestInfo.getWorkflowid(); // 获取workflowid + //获取工作流名称 + String workflowname= BaseUtil.getBaseInfoByParm("workflowname", "workflow_base", "id", workflowid, ""); + log.writeLog("---------------工作流名称-----------workflowname为:" + workflowname); + log.writeLog("--------用工模式变更申请单数据传入中台开始----requestId值为:" + requestId); + + //获取配置文件中的参数 + String mode = Prop.getPropValue("DevToDC_jntchina","mode"); + // 服务器ip:port + String baseUrl = Prop.getPropValue("DevToDC_jntchina", mode+"_baseUrl"); + //访问路径拼接 + String url = baseUrl+"/dcoaapi/hr/factoryChange"; + + //根据流程id获取主表名称 + String mainTable = EmploymentPatternChangeAction.getMainTable(requestId); + log.writeLog("--------获取到的表名为----:" + mainTable); + + //申请单号 + String C_APP_SEQ = ""; + //审批状态 + String C_APPLI_RS ="3"; //3:已通过(默认) + //申请日期 + String C_APP_DT = ""; + //申请人ID + String EMPLID = ""; + //变更员工ID + String EMPLID2 =""; + //变更日期 + String ACTION_DT =""; + //变更员工类型 + String C_EMPL_CLASS2 ="";//默认写:10全日制 + //变更岗位 + String POSITION_NBR2="";//取岗位表里的outkey值 + //变更职级--->测试环境已维护,字段改为:变更职级(更新后) + String C_POSN_GRDE_ID1 =""; + //变更薪资组 + String GP_PAYGROUP2 ="";//默认写:NOPAY + //变更社保缴纳地 + String C_SB_LOC_ID1 =""; + //变更直接上级 + String SUPERVISOR_ID2 =""; + //社保缴纳公司 + String C_SB_LOC_COMPANY =""; + //社保缴纳规则 + String C_SB_LOC_RULE =""; + //个人缴费基数及比例 + String C_ENDO_INSU =""; + //单位缴费基数及比例 + String C_ENDO_INSU1 =""; + //公积金缴费规则 + String C_GJJ_RULE_ID =""; + //个人公积金基数 + String C_HOUS_FUND =""; + //公司公积金基数 + String C_HOUS_FUND1 =""; + //社保公积金生效日期 + String C_SB_EFFDT =""; + //是否涉及社保公积金变更 + String sfsjsbgjjbg =""; + + RecordSet rs = new RecordSet(); + + try { + //转换值接口的数据为10全日制,后续需要更改****** + String sql = "select C_APP_SEQ,C_APP_DT,EMPLID,EMPLID2,sfsjsbgjjbg," + + "ACTION_DT,C_EMPL_CLASS2,POSITION_NBR2," + + "C_POSN_GRDE_ID111,GP_PAYGROUP2,C_SB_LOC_ID1," + + "SUPERVISOR_ID2," + + "C_SB_LOC_COMPANY," + + "C_SB_LOC_RULE," + + "C_ENDO_INSU," + + "C_ENDO_INSU1," + + "C_GJJ_RULE_ID," + + "C_HOUS_FUND," + + "C_HOUS_FUND1," + + "C_SB_EFFDT " + + " from " + mainTable + " where requestid='" + requestId + "'"; + rs.execute(sql); + log.writeLog("----------------》打印sql语句"+sql); + while (rs.next()) { + C_APP_SEQ = Util.null2String(rs.getString("C_APP_SEQ")); + C_APP_DT = Util.null2String(rs.getString("C_APP_DT")); + EMPLID = Util.null2String(rs.getString("EMPLID")); + EMPLID2 =Util.null2String(rs.getString("EMPLID2")); + ACTION_DT =Util.null2String(rs.getString("ACTION_DT")); + C_EMPL_CLASS2 =Util.null2String(rs.getString("C_EMPL_CLASS2")); + //根据岗位的ID查询对应的岗位编码 + POSITION_NBR2 = EmploymentPatternChangeAction.selectPOSITION_NBR2(Util.null2String(rs.getString("POSITION_NBR2"))); + log.writeLog("--------------->打印表单变更岗位字段的id:"+Util.null2String(rs.getString("POSITION_NBR2"))+"执行查询方法后取到的outkey:"+POSITION_NBR2); + C_POSN_GRDE_ID1 =Util.null2String(rs.getString("C_POSN_GRDE_ID111")); + GP_PAYGROUP2 =Util.null2String(rs.getString("GP_PAYGROUP2")); + C_SB_LOC_ID1 =Util.null2String(rs.getString("C_SB_LOC_ID1")); + SUPERVISOR_ID2 =Util.null2String(rs.getString("SUPERVISOR_ID2")); + + C_SB_LOC_COMPANY =Util.null2String(rs.getString("C_SB_LOC_COMPANY")); + C_SB_LOC_RULE =Util.null2String(rs.getString("C_SB_LOC_RULE")); + C_ENDO_INSU =Util.null2String(rs.getString("C_ENDO_INSU")); + C_ENDO_INSU1 =Util.null2String(rs.getString("C_ENDO_INSU1")); + C_GJJ_RULE_ID =Util.null2String(rs.getString("C_GJJ_RULE_ID")); + C_HOUS_FUND =Util.null2String(rs.getString("C_HOUS_FUND")); + C_HOUS_FUND1 =Util.null2String(rs.getString("C_HOUS_FUND1")); + C_SB_EFFDT =Util.null2String(rs.getString("C_SB_EFFDT")); + sfsjsbgjjbg =Util.null2String(rs.getString("sfsjsbgjjbg")); + + } + //使用Map封装数据 + Map map = new HashMap(); + map.put("C_APP_SEQ",C_APP_SEQ);//申请单号 + map.put("C_APPLI_RS",C_APPLI_RS);//审批状态:默认放为3 + map.put("C_APP_DT",C_APP_DT);//申请日期 + map.put("EMPLID",EMPLID);//申请人ID + map.put("EMPLID2",EMPLID2);//变更员工ID + map.put("ACTION_DT",ACTION_DT);//变更日期 + //变更员工类型,下拉框显示值 + String c_empl_class2 = ResignationFormWriteBackAction.getItemName2("C_EMPL_CLASS2", C_EMPL_CLASS2.toString(), workflowid); + map.put("C_EMPL_CLASS2",c_empl_class2.split("-")[0]);//变更员工类型,获取下拉框显示值"-"前面部分的编码 + map.put("POSITION_NBR2",POSITION_NBR2);//变更岗位 + + + if (C_POSN_GRDE_ID1.equals("")){//存在历史问题 所以加判断 变更职级 + map.put("C_POSN_GRDE_ID1","101");//变更职级 + }else{ + map.put("C_POSN_GRDE_ID1",C_POSN_GRDE_ID1);//变更职级 + } + + if (GP_PAYGROUP2.equals("")){//存在历史问题 所以加判断 + map.put("GP_PAYGROUP2","100");//变更薪资组 默认100 G0 + }else{ + map.put("GP_PAYGROUP2",GP_PAYGROUP2);//变更薪资组 + } + + //根据上级ID获取上级编码 + String ucode = ResignationFormWriteBackAction.getWorkcodeByUid(SUPERVISOR_ID2); + map.put("SUPERVISOR_ID2",ucode);//变更直接上级 + + if("0".equals(sfsjsbgjjbg)){ + map.put("C_SB_LOC_COMPANY",C_SB_LOC_COMPANY);//社保缴纳公司 + map.put("C_SB_LOC_ID1",C_SB_LOC_ID1);//变更社保缴纳地 + map.put("C_SB_LOC_RULE",C_SB_LOC_RULE);//社保缴纳规则 + map.put("C_ENDO_INSU",C_ENDO_INSU);//个人缴费基数及比例 + map.put("C_ENDO_INSU1",C_ENDO_INSU1);//单位缴费基数及比例 + map.put("C_GJJ_RULE_ID",C_GJJ_RULE_ID);//公积金缴费规则 + map.put("C_HOUS_FUND",C_HOUS_FUND);//个人公积金基数 + map.put("C_HOUS_FUND1",C_HOUS_FUND1);//公司公积金基数 + map.put("C_SB_EFFDT",C_SB_EFFDT);//社保公积金生效日期 + }else{ + map.put("C_SB_LOC_COMPANY","");//社保缴纳公司 + map.put("C_SB_LOC_ID1","");//变更社保缴纳地 + map.put("C_SB_LOC_RULE","");//社保缴纳规则 + map.put("C_ENDO_INSU","");//个人缴费基数及比例 + map.put("C_ENDO_INSU1","");//单位缴费基数及比例 + map.put("C_GJJ_RULE_ID","");//公积金缴费规则 + map.put("C_HOUS_FUND","");//个人公积金基数 + map.put("C_HOUS_FUND1","");//公司公积金基数 + map.put("C_SB_EFFDT","");//社保公积金生效日期 + } + + + String strParm = JSONObject.toJSONString(map); + log.writeLog("---------------打印的Map数据为:-----------------:"+strParm); + + //获取Token + String token = HttpClientToDC.getToken(); + log.writeLog("用工模式变更申请单token------>" + token); + log.writeLog("用工模式变更申请单url------>" + url); + + //调用NCC接口,将数据传给NCC + String returndata = HttpClientToDC.sendPostApi(url,token,strParm); + log.writeLog("【调用数据中台用工模式变更申请单接口返回结果result:】" + returndata); + if (!"".equals(returndata) && returndata != null) { + JSONObject jsonObject = JSONObject.parseObject(returndata); + String code = Util.null2String(jsonObject.get("code")); + log.writeLog("--------发送请求返回的code值为:" + code); + if("1".equals(code)){ + return SUCCESS; + }else{ + String msg = Util.null2String(jsonObject.get("msg")); + requestInfo.getRequestManager().setMessageid("111100"); + requestInfo.getRequestManager().setMessagecontent(msg); + return "0"; + } + }else{ + String ermsg="流程数据写入NCC用工模式变更失败,未获取到接口返回结果,请联系系统管理员处理!"; + requestInfo.getRequestManager().setMessageid("111100"); + requestInfo.getRequestManager().setMessagecontent(ermsg); + return "0"; + } + }catch (Exception e){ + //返回0,调用失败 + log.writeLog("------------------------捕获到的异常是:" + e.toString()); + return "0"; + } + } + + + + /** + * 使用requestid获取数据库表名 + * @param requestid + * @return + */ + public static String getMainTable(String requestid){ + String tablename = ""; + RecordSet rs = new RecordSet(); + rs.executeQuery("select * from workflow_requestbase a,workflow_base b,workflow_bill c " + +"where a.requestid=? and a.workflowid = b.id and b.formid = c.id",requestid); + while(rs.next()){ + tablename = Util.null2String(rs.getString("tablename")); + } + return tablename; + } + + + /** + * 使用岗位的id查询对应的Outkey + * @param str:入参岗位ID + * @return + */ + public static String selectPOSITION_NBR2(String str){ + //查询变更岗位取outkey + RecordSet rs = new RecordSet(); + String result = ""; + if(!"".equals(str) || str!=""){ + String sqls = "select OUTKEY from HRMJOBTITLES where id ="+str+""; + rs.executeQuery(sqls); + while (rs.next()) { + result = Util.null2String(rs.getString("OUTKEY")); + } + return result; + }else { + return result; + } + } + +} diff --git a/src/main/youhong_ai_jitu_src/jntchina/action/EvectionApplicationAction.java b/src/main/youhong_ai_jitu_src/jntchina/action/EvectionApplicationAction.java new file mode 100644 index 0000000..4611851 --- /dev/null +++ b/src/main/youhong_ai_jitu_src/jntchina/action/EvectionApplicationAction.java @@ -0,0 +1,144 @@ +package jntchina.action; + +import com.alibaba.fastjson.JSONObject; +import jntchina.util.HttpClientToDC; +import selfdev.util.base.BaseUtil; +import selfdev.util.log.LogTool; +import weaver.conn.RecordSet; +import weaver.file.Prop; +import weaver.general.Util; +import weaver.interfaces.workflow.action.BaseAction; +import weaver.soa.workflow.request.RequestInfo; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +/** + * @description: 出差申请单 + * @author: daizhishun + * @date: 2021/7/30 + **/ +public class EvectionApplicationAction extends BaseAction { + @Override + public String execute(RequestInfo requestInfo) { + LogTool log = new LogTool("/log/selfdev/action/hrm", true); + String requestId = requestInfo.getRequestid(); // 获取requestid + String workflowid = requestInfo.getWorkflowid(); // 获取workflowid + + //获取工作流名称 + String workflowname = BaseUtil.getBaseInfoByParm("workflowname", "workflow_base", "id", workflowid, ""); + log.writeLog("---------------工作流名称-----------workflowname为:" + workflowname); + log.writeLog("--------出差申请单数据传入中台开始----requestId值为:" + requestId); + + //获取配置文件中的参数,到时候URL路径 + String mode = Prop.getPropValue("DevToDC_jntchina", "mode"); + // 服务器ip:port + String baseUrl = Prop.getPropValue("DevToDC_jntchina", mode + "_baseUrl"); + //访问路径拼接 + String url = baseUrl + "/dcoaapi/hr/trip"; + + //对接EHR系统路径 + //String url = "http://121.37.156.206:21005/PSIGW/RESTListeningConnector/PSFT_HR/C_TRIP_APPLY.v1/"; + + + //根据流程id获取主表名称 + String mainTable = RegularizationApplyForAction.getMainTable(requestId); + log.writeLog("-------------获取到的表名为-------------:" + mainTable); + //申请编号 + String C_OA_NUM = ""; + //单据来源 + String C_APPLY_SOURCE = "OA"; + //提单人,申请人 + String EMPLID = ""; + + //{ + //出差数据 + List> list = new ArrayList>(); + //出差开始日期 + String C_START_DT = ""; + //出差开始时间 + String C_START_DTM = ""; + //出差结束日期 + String C_END_DT = ""; + //出差结束时间 + String C_END_DTM = ""; + //出差原因 + String C_REASON = ""; + //出差天数 + // String C_TRIP_DAYS = ""; + //出差地点 + String ccdd = ""; + + RecordSet rs = new RecordSet(); + try { + String sql = "select * from " + mainTable + " where requestid = '" + requestId + "'"; + rs.executeQuery(sql); + log.writeLog("查询sql语句---------------->" + sql); + while (rs.next()) { + C_OA_NUM = Util.null2String(rs.getString("lcbh1"));//申请单号 + EMPLID = Util.null2String(rs.getString("gh"));//申请人 + C_START_DT = Util.null2String(rs.getString("fromDate"));//开始日期 + C_START_DTM = Util.null2String(rs.getString("fromTime"));//开始时间 + C_END_DT = Util.null2String(rs.getString("toDate"));//结束日期 + C_END_DTM = Util.null2String(rs.getString("toTime"));//结束时间 + C_REASON = Util.null2String(rs.getString("ccsy"));//出差事由 + //C_TRIP_DAYS = Util.null2o(rs.getString("duration"));//出差天数 + ccdd = Util.null2String(rs.getString("ccdd"));//出差地点 + } + //将出差数据进行包装 + Map maps = new HashMap(); + maps.put("EMPLID", EMPLID); + maps.put("C_START_DT", C_START_DT); + maps.put("C_START_DTM", C_START_DTM); + maps.put("C_END_DT", C_END_DT); + maps.put("C_END_DTM", C_END_DTM); + maps.put("C_REASON", C_REASON); + maps.put("ccdd",ccdd); + maps.put("C_TRIP_DAYS", "1");//20220429 by KangMD 不需要传出差天数,HR系统自动计算,默认传固定值1 + list.add(maps); + log.writeLog("----------------->出差数据明细数据:" + list.toString()); + + //最后再将数据全部打包 + Map map = new HashMap(); + map.put("C_OA_NUM", C_OA_NUM); + map.put("C_APPLY_SOURCE", C_APPLY_SOURCE); + map.put("EMPLID", EMPLID); + map.put("LINES", list); + String strParm = JSONObject.toJSONString(map); + log.writeLog("---------------打印的Map数据为:-----------------:" + strParm); + + //获取Token + String token = HttpClientToDC.getToken(); + log.writeLog("出差申请单token------>" + token); + log.writeLog("出差申请单url------>" + url); + + //调用NCC接口,将数据传给NCC + String returndata = HttpClientToDC.sendPostApi(url, token, strParm); + log.writeLog("【调用数据中台出差申请单接口返回结果result:】" + returndata); + if (!"".equals(returndata) && returndata != null) { + JSONObject jsonObject = JSONObject.parseObject(returndata); + String code = Util.null2String(jsonObject.get("code")); + log.writeLog("--------发送请求返回的code值为:" + code); + if (code.equals("1")) { + return SUCCESS; + } else { + String msg = Util.null2String(jsonObject.get("msg")); + requestInfo.getRequestManager().setMessageid("111100"); + requestInfo.getRequestManager().setMessagecontent(msg); + return "0"; + } + } else { + String ermsg = "流程数据写入NCC出差申请单失败,未获取到接口返回结果,请联系系统管理员处理!"; + requestInfo.getRequestManager().setMessageid("111100"); + requestInfo.getRequestManager().setMessagecontent(ermsg); + return "0"; + } + } catch (Exception e) { + //返回0,调用失败 + log.writeLog("------------------------捕获到的异常是:" + e.toString()); + return "0"; + } + } +} diff --git a/src/main/youhong_ai_jitu_src/jntchina/action/EvectionApplicationAction2.java b/src/main/youhong_ai_jitu_src/jntchina/action/EvectionApplicationAction2.java new file mode 100644 index 0000000..1f10a64 --- /dev/null +++ b/src/main/youhong_ai_jitu_src/jntchina/action/EvectionApplicationAction2.java @@ -0,0 +1,147 @@ +package jntchina.action; + +import com.alibaba.fastjson.JSONObject; +import jntchina.util.HttpClientToDC; +import selfdev.util.base.BaseUtil; +import selfdev.util.log.LogTool; +import weaver.conn.RecordSet; +import weaver.file.Prop; +import weaver.general.Util; +import weaver.interfaces.workflow.action.BaseAction; +import weaver.soa.workflow.request.RequestInfo; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +/** + * @description: 出差申请单-对接hr + * @author: daizhishun + * @date: 2021/7/30 + **/ +public class EvectionApplicationAction2 extends BaseAction { + @Override + public String execute(RequestInfo requestInfo) { + LogTool log = new LogTool("/log/selfdev/action/hrm", true); + String requestId = requestInfo.getRequestid(); // 获取requestid + String workflowid = requestInfo.getWorkflowid(); // 获取workflowid + + //获取工作流名称 + String workflowname = BaseUtil.getBaseInfoByParm("workflowname", "workflow_base", "id", workflowid, ""); + log.writeLog("---------------工作流名称-----------workflowname为:" + workflowname); + log.writeLog("--------出差申请单数据传入中台开始----requestId值为:" + requestId); + + //获取配置文件中的参数,到时候URL路径 + String mode = Prop.getPropValue("DevToDC_jntchina", "mode"); + // 服务器ip:port + String baseUrl = Prop.getPropValue("DevToDC_jntchina", mode + "_baseUrl"); + //访问路径拼接 + String url = baseUrl + "/dcoaapi/hr/trip"; + + //对接EHR系统路径 + //String url = "http://121.37.156.206:21005/PSIGW/RESTListeningConnector/PSFT_HR/C_TRIP_APPLY.v1/"; + + + //根据流程id获取主表名称 + String mainTable = RegularizationApplyForAction.getMainTable(requestId); + log.writeLog("-------------获取到的表名为-------------:" + mainTable); + //申请编号 + String C_OA_NUM = ""; + //单据来源 + String C_APPLY_SOURCE = "OA"; + //提单人,申请人 + String EMPLID = ""; + + //{ + //出差数据 + List> list = new ArrayList<>(); + //出差开始日期 + String C_START_DT = ""; + //出差开始时间 + String C_START_DTM = ""; + //出差结束日期 + String C_END_DT = ""; + //出差结束时间 + String C_END_DTM = ""; + //出差原因 + String C_REASON = ""; + //出差天数( HR页面显示的出差天数不再通过OA传过来了,HR会自己计算对应的出差时长和天数。原本传入出差天数的字段改成出差类型,通过这个字段来区分是国内出差还是外出) + String C_TRIP_DAYS = "0"; + //出差类别 + String cclb = ""; + + RecordSet rs = new RecordSet(); + try { + String sql = "select * from "+mainTable+" where requestid = '" + requestId + "'"; + rs.executeQuery(sql); + log.writeLog("查询sql语句---------------->"+sql); + while (rs.next()){ + C_OA_NUM = Util.null2String(rs.getString("lcbh"));//编号 + EMPLID = Util.null2String(rs.getString("gh"));//申请人 + C_START_DT = Util.null2String(rs.getString("ksrq"));//开始日期 + C_START_DTM = Util.null2String(rs.getString("kssj"));//开始时间 + C_END_DT = Util.null2String(rs.getString("jsrq1"));//结束日期 + C_END_DTM = Util.null2String(rs.getString("jssj"));//结束时间 + C_REASON = Util.null2String(rs.getString("ccsy"));//出差事由 + cclb = Util.null2String(rs.getString("cclb"));//出差类别 +// C_TRIP_DAYS = Util.null2o(rs.getString("ccts"));//出差天数 + } + log.writeLog("cclb---------------->"+cclb); + if("0".equals(cclb)){//20220429 by KangMD 国内出差,则传到HR的值为1;市内外出或者夜间用车,则传到HR的值为0 + C_TRIP_DAYS = "1"; + } + //将出差数据进行包装 + Map maps= new HashMap<>(); + maps.put("EMPLID",EMPLID); + maps.put("C_START_DT",C_START_DT); + maps.put("C_START_DTM",C_START_DTM); + maps.put("C_END_DT",C_END_DT); + maps.put("C_END_DTM",C_END_DTM); + maps.put("C_REASON",C_REASON); + maps.put("C_TRIP_DAYS",C_TRIP_DAYS); + list.add(maps); + log.writeLog("----------------->出差数据明细数据:" + list.toString()); + + //最后再将数据全部打包 + Map map = new HashMap<>(); + map.put("C_OA_NUM",C_OA_NUM); + map.put("C_APPLY_SOURCE",C_APPLY_SOURCE); + map.put("EMPLID",EMPLID); + map.put("LINES",list); + String strParm = JSONObject.toJSONString(map); + log.writeLog("---------------打印的Map数据为:-----------------:"+strParm); + + //获取Token + String token = HttpClientToDC.getToken(); + log.writeLog("出差申请单token------>" + token); + log.writeLog("出差申请单url------>" + url); + + //调用NCC接口,将数据传给NCC + String returndata = HttpClientToDC.sendPostApi(url,token, strParm); + log.writeLog("【调用数据中台出差申请单接口返回结果result:】" + returndata); + if (!"".equals(returndata) && returndata != null) { + JSONObject jsonObject = JSONObject.parseObject(returndata); + String code = Util.null2String(jsonObject.get("code")); + log.writeLog("--------发送请求返回的code值为:" + code); + if (code.equals("1")){ + return SUCCESS; + }else{ + String msg = Util.null2String(jsonObject.get("msg")); + requestInfo.getRequestManager().setMessageid("111100"); + requestInfo.getRequestManager().setMessagecontent(msg); + return "0"; + } + }else{ + String ermsg="流程数据写入NCC出差申请单失败,未获取到接口返回结果,请联系系统管理员处理!"; + requestInfo.getRequestManager().setMessageid("111100"); + requestInfo.getRequestManager().setMessagecontent(ermsg); + return "0"; + } + }catch (Exception e){ + //返回0,调用失败 + log.writeLog("------------------------捕获到的异常是:" + e.toString()); + return "0"; + } + } +} diff --git a/src/main/youhong_ai_jitu_src/jntchina/action/HolidayAction.java b/src/main/youhong_ai_jitu_src/jntchina/action/HolidayAction.java new file mode 100644 index 0000000..c376540 --- /dev/null +++ b/src/main/youhong_ai_jitu_src/jntchina/action/HolidayAction.java @@ -0,0 +1,163 @@ +package jntchina.action; + +import com.alibaba.fastjson.JSONObject; +import jntchina.util.HttpClientToDC; +import selfdev.util.base.BaseUtil; +import selfdev.util.log.LogTool; +import weaver.conn.RecordSet; +import weaver.file.Prop; +import weaver.general.Util; +import weaver.interfaces.workflow.action.BaseAction; +import weaver.soa.workflow.request.RequestInfo; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +/** + * @description: 请假申请单(调用假期余额查询接口, 以及获取员工请假天数接口) + * @author: daizhishun + * @date: 2021/8/3 + **/ +public class HolidayAction extends BaseAction { + + @Override + public String execute(RequestInfo requestInfo) { + LogTool log = new LogTool("/log/selfdev/action/hrm", true); + String requestId = requestInfo.getRequestid(); // 获取requestid + String workflowid = requestInfo.getWorkflowid(); // 获取workflowid + //获取工作流名称 + String workflowname = BaseUtil.getBaseInfoByParm("workflowname", "workflow_base", "id", workflowid, ""); + log.writeLog("---------------工作流名称-----------workflowname为:" + workflowname); + log.writeLog("--------请假申请单数据传入中台开始----requestId值为:" + requestId); + + //获取配置文件中的参数,到时候URL路径 + String mode = Prop.getPropValue("DevToDC_jntchina", "mode"); + // 服务器ip:port + String baseUrl = Prop.getPropValue("DevToDC_jntchina", mode + "_baseUrl"); + //访问路径拼接 + String url = baseUrl + "/dcoaapi/hr/vacation"; + //String url = "http://121.37.156.206:21005/PSIGW/RESTListeningConnector/PSFT_HR/C_LEAVE_APPLY.v1/"; + + //根据流程id获取主表名称 + String mainTable = RegularizationApplyForAction.getMainTable(requestId); + log.writeLog("--------获取到的表名为----:" + mainTable); + //申请单号 + String C_OA_NUM = ""; + //假期类型 + String C_VACATION_TYPE = ""; + //员工编码 + String EMPLID = ""; + + //{ + //请假数据 + List> list = new ArrayList>(); + //请假开始日期 + String C_START_DT = ""; + //请假开始时间 + String C_START_DTM = ""; + //请假结束日期 + String C_END_DT = ""; + //请假结束时间 + String C_END_DTM = ""; + //请假原因 + String C_REASON = ""; + //OA请假类型 + String newLeaveType = ""; + //} + + //新加的 4个String + // oa请假时长 + String duration = ""; + //oa是否通宵补休 + String sftxbx = ""; + //oa补休加班流程 + String bxjblx = ""; + //oa是否为抵扣考勤异常数据 + String sfwdkkqycsq = ""; + + RecordSet rs = new RecordSet(); + try { + String sql = "select * from " + mainTable + " where requestId = '" + requestId + "'"; + rs.execute(sql); + log.writeLog("查询sql语句---------------->" + sql); + while (rs.next()) { + C_OA_NUM = Util.null2String(rs.getString("lcbh"));//申请单号 + newLeaveType = Util.null2String(rs.getString("newLeaveType"));//OA请假类型 + EMPLID = Util.null2String(rs.getString("gh"));//员工编码 + C_START_DT = Util.null2String(rs.getString("fromDate"));//开始日期 + C_START_DTM = Util.null2String(rs.getString("fromTime"));//开始时间 + C_END_DT = Util.null2String(rs.getString("toDate"));//结束日期 + C_END_DTM = Util.null2String(rs.getString("toTime"));//结束时间 + C_REASON = Util.null2String(rs.getString("qjyy"));//请假原因 + duration = Util.null2String(rs.getString("duration"));//请假时长 + sftxbx = Util.null2String(rs.getString("sftxbx"));//是否通宵补休 + bxjblx = Util.null2String(rs.getString("bxjblx"));//补休加班流程 + sfwdkkqycsq = Util.null2String(rs.getString("sfwdkkqycsq"));//oa是否为抵扣考勤异常数据 + } + + log.writeLog("newLeaveType------>" + newLeaveType); + //获取HR对应的请假类型编码 + C_VACATION_TYPE = BaseUtil.getBaseInfoByParm("hrqjlxbm", "uf_oaqjlx_hrqjlx", "oaqjlx", newLeaveType, ""); + log.writeLog("C_VACATION_TYPE------>" + C_VACATION_TYPE); + + //将请假数据进行包装 + Map maps = new HashMap(); + maps.put("EMPLID", EMPLID); + maps.put("C_START_DT", C_START_DT); + maps.put("C_START_DTM", C_START_DTM); + maps.put("C_END_DT", C_END_DT); + maps.put("C_END_DTM", C_END_DTM); + maps.put("C_REASON", C_REASON); + + maps.put("duration",duration); + maps.put("sftxbx",sftxbx); + maps.put("bxjblx",bxjblx); + maps.put("sfwdkkqycsq",sfwdkkqycsq); + + list.add(maps); + log.writeLog("----------------->出差数据明细数据:" + list.toString()); + + //最后再将数据全部打包 + Map map = new HashMap(); + map.put("C_OA_NUM", C_OA_NUM); + map.put("C_VACATION_TYPE", C_VACATION_TYPE); + map.put("EMPLID", EMPLID); + map.put("LINES", list); + String strParm = JSONObject.toJSONString(map); + log.writeLog("---------------打印的Map数据为:-----------------:" + strParm); + + //获取Token + String token = HttpClientToDC.getToken(); + log.writeLog("请假申请单token------>" + token); + log.writeLog("请假申请单url------>" + url); + + //调用NCC接口,将数据传给NCC + String returndata = HttpClientToDC.sendPostApi(url, token, strParm); + log.writeLog("【调用数据中台请假申请单接口返回结果:】" + returndata); + if (!"".equals(returndata) && returndata != null) { + JSONObject jsonObject = JSONObject.parseObject(returndata); + String code = Util.null2String(jsonObject.get("code")); + log.writeLog("--------发送请求返回的code值为:" + code); + if ("1".equals(code)) { + return SUCCESS; + } else { + String msg = Util.null2String(jsonObject.get("msg")); + requestInfo.getRequestManager().setMessageid("111100"); + requestInfo.getRequestManager().setMessagecontent(msg); + return "0"; + } + } else { + String ermsg = "流程数据写入NCC请假申请单失败,未获取到接口返回结果,请联系系统管理员处理!"; + requestInfo.getRequestManager().setMessageid("111100"); + requestInfo.getRequestManager().setMessagecontent(ermsg); + return "0"; + } + } catch (Exception e) { + //返回0,调用失败 + log.writeLog("------------------------捕获到的异常是:" + e.toString()); + return "0"; + } + } +} diff --git a/src/main/youhong_ai_jitu_src/jntchina/action/InvestmentApplicationAction.java b/src/main/youhong_ai_jitu_src/jntchina/action/InvestmentApplicationAction.java new file mode 100644 index 0000000..e6f2ae5 --- /dev/null +++ b/src/main/youhong_ai_jitu_src/jntchina/action/InvestmentApplicationAction.java @@ -0,0 +1,225 @@ +package jntchina.action; + +import com.alibaba.fastjson.JSONObject; +import com.working.util.WorkflowUtil; +import jntchina.entity.BorrowOrder; +import jntchina.entity.BorrowOrderBody; +import jntchina.util.HttpClientToDC; +import selfdev.util.base.BaseUtil; +import selfdev.util.log.LogTool; +import weaver.conn.RecordSet; +import weaver.file.Prop; +import weaver.general.Util; +import weaver.interfaces.workflow.action.Action; +import weaver.interfaces.workflow.action.BaseAction; +import weaver.soa.workflow.request.RequestInfo; + +import java.util.ArrayList; +import java.util.List; +import java.util.UUID; + +import org.apache.commons.lang3.StringEscapeUtils; + +/** + * @Author Administrator + * @Description 投资申请单数据写入中台生成NCC对公借款单 + * @Date 2021/1/8 12:14 + */ +public class InvestmentApplicationAction extends BaseAction { + @Override + public String execute(RequestInfo requestInfo) { + String src = requestInfo.getRequestManager().getSrc();//获取操作方式 + if (!"submit".equals(src)) { // 只有submit才执行接口 + return SUCCESS; + } + LogTool log = new LogTool("/log/selfdev/action", false); + String requestId = requestInfo.getRequestid(); // 获取requestid + log.writeLog("--------投资申请单数据传入NCC开始----requestId值为:" + requestId); + + //获取当前用户的登录账号(即工号) + String loginid=requestInfo.getRequestManager().getUser().getLoginid(); + //获取配置文件中的参数 + String mode = Prop.getPropValue("DevToDC_jntchina","mode"); + // 服务器ip:port + String baseUrl = Prop.getPropValue("DevToDC_jntchina", mode+"_baseUrl"); + //String url = baseUrl+"/dcoaapi/billLoan/receiveData"; + String url = baseUrl+"/dcnccapi/billLoan/receiveData"; +// List borrowList=new ArrayList(); + BorrowOrder borrowOrder = new BorrowOrder(); + + String mainTable = WorkflowUtil.getMainTable(requestId); + String mainId = ""; + String pk_org = ""; // JTSDCN0001 //借款单位编码 + String total = ""; // 1000.00 //合计金额 + String bm = ""; // 申请人部门 + String deptid = ""; // SD3300101 //借款人部门 + String djlxbm = "263X-Cxx-DGJKD"; // 263X-Cxx-DSJKD", //交易类型编码 263X-Cxx-DSJKD:对私借款单 263X-Cxx-DGJKD:对公预付/借款单 + String djrq = ""; // 2021-03-05 10:17:10", //单据日期 + String payflag = ""; //1", //支付状态 + String paytarget = "1"; // 0" //收款对象(0=员工,1=供应商) + String receiver = ""; // yonyou88", //收款人(员工) + String hbbm = ""; // yonyou88", //收款人(供应商) + String skyhzh = ""; // 收款人银行账号(员工) + String custaccount; //收款银行账户(供应商) + String jkbxr = ""; // yonyou88 //借款报销人 + String operator = ""; // yonyou88 //录入人 + String jsfs = "3"; // 3 //结算方式 3 网银 。。。 + String fkyhzh = ""; //单位银行账户 + String jobid = ""; //项目 + String zy = ""; //借款测试", //事由 + String djzt = "1"; // 1", //单据状态 1 保存 + String kjqj = ""; // 03", //会计期间 + String kjnd = ""; // 2021", //会计年度 + String zyx1 = ""; // CSBX21020501", //OA单据号 + String zyx2 = ""; // 提交人 + String zyx3 = ""; // OA核销单号 + String zyx5 = ""; // CSBX21020501", // OARequestID + String zyx8 = ""; // 银行付款备注 + String zyx9=requestInfo.getRequestManager().getRequestname();//标题 + String defitem46 = ""; // 网点(成本中心) + + RecordSet rs = new RecordSet(); + try { + String sql = " select * from " + mainTable + " where requestid='" + requestId + "'"; + rs.execute(sql); + while (rs.next()) { + mainId = Util.null2String(rs.getString("id")); + bm = Util.null2String(rs.getString("bm"));// 申请部门 + pk_org = Util.null2String(rs.getString("gsmc")); // 公司名称 + skyhzh = Util.null2String(rs.getString("yxzh")); // 收款银行账号 + total = Util.null2String(rs.getString("fkje")); // 申请金额 金额由表体相应字段汇总得出 + djrq = Util.null2String(rs.getString("cjrq")); // 单据日期 yyyy-mm-dd hh:mm:ss + hbbm = Util.null2String(rs.getString("btzgsmc")); // 收款人(被投资公司名称) + zy = Util.null2String(rs.getString("jkyy")); // 备注 + kjqj = djrq.substring(5,7); // 会计期间 + kjnd = djrq.substring(0,4); // 会计年度 + zyx1 = Util.null2String(rs.getString("lcbh")); // OA单据号 OA传过来,用于联查单据 + zyx2 = Util.null2String(rs.getString("xm")); // 提交人 提交人姓名 + zyx5 = requestId; // OARequestID + defitem46 = Util.null2String(rs.getString("cbzx")); // 网点(成本中心) + zyx8 = Util.null2String(rs.getString("yxfkbz")); //银行付款备注 + log.writeLog("----mainId:" + mainId); + } + //获取UUID + String uuid=UUID.randomUUID().toString().replace("-", "").toUpperCase(); + //根据部门ID查询部门编码 + deptid=BaseUtil.getBaseInfoByParm("departmentcode", "hrmdepartment", "id", bm, ""); + operator = loginid;//当前节点操作者 + + borrowOrder.setUuid(uuid); + borrowOrder.setPk_org(pk_org); + borrowOrder.setTotal(total); + borrowOrder.setDeptid(deptid); + borrowOrder.setDjlxbm(djlxbm); + borrowOrder.setDjrq(djrq); + borrowOrder.setPayflag(payflag); + borrowOrder.setPaytarget(paytarget); + borrowOrder.setReceiver(receiver); + borrowOrder.setHbbm(hbbm); + //borrowOrder.setSkyhzh(skyhzh); + //borrowOrder.setCustaccount(custaccount); + borrowOrder.setJkbxr(jkbxr); + borrowOrder.setOperator(operator); + borrowOrder.setJsfs(jsfs); + borrowOrder.setFkyhzh(fkyhzh); + borrowOrder.setJobid(jobid); + borrowOrder.setZy(zy); + borrowOrder.setDjzt(djzt); + borrowOrder.setKjqj(kjqj); + borrowOrder.setKjnd(kjnd); + borrowOrder.setZyx1(zyx1); + borrowOrder.setZyx2(zyx2); + borrowOrder.setZyx3(zyx3); + borrowOrder.setZyx5(zyx5); + borrowOrder.setZyx8(zyx8); + borrowOrder.setZyx9(zyx9); + log.writeLog("【header数据准备完毕...】"); + + List borrowOrderBodyList = new ArrayList(); + String tablecode = ""; // jk_busitem + String rowno = "1"; // 10 + String szxmid = "901038"; // 收支项目 默认为员工借款**********8 + String defitem50 = ""; // 发票类型 + String defitem49 = ""; // 发票号码 + String defitem42 = ""; // OA明细ID + String defitem43 = ""; // 车牌号 + String defitem44 = ""; // 仓库 + String defitem45 = ""; // 国家 + + String defitem48 = ""; // SD3300301" //分摊部门 + BorrowOrderBody body = new BorrowOrderBody(); + tablecode = "jk_busitem"; + //根据部门ID查询部门编码 + defitem48= BaseUtil.getBaseInfoByParm("departmentcode", "hrmdepartment", "id", bm, ""); + + body.setAmount(total); + body.setTablecode(tablecode); + body.setRowno(rowno); + body.setSzxmid(szxmid); + body.setDefitem50(defitem50); + body.setDefitem49(defitem49); + body.setDefitem42(defitem42); + body.setDefitem43(defitem43); + body.setDefitem44(defitem44); + body.setDefitem45(defitem45); + body.setDefitem46(defitem46); + body.setDefitem48(defitem48); + borrowOrderBodyList.add(body); + borrowOrder.setJk_busitem(borrowOrderBodyList); + +// borrowList.add(borrowOrder); + String parm=JSONObject.toJSONString(borrowOrder); + log.writeLog("借款单准备传入数据中台的数据为------>" + parm); + + //获取TOKEN + String token = HttpClientToDC.getToken(); + log.writeLog("获取数据中台的token------>" + token); + if ("".equals(Util.null2String(token))) { + requestInfo.getRequestManager().setMessagecontent("流程提交失败,未获取到数据中台接口TOKEN,请联系管理员处理!"); + return Action.FAILURE_AND_CONTINUE; + } + + //调用NCC接口,将数据传给NCC + String returndata = HttpClientToDC.sendPostApi(url,token, parm); + log.writeLog("【调用数据中台借款接口返回结果result:】" + returndata); + if (!"".equals(returndata) && returndata != null) { +// //过滤前面的双引号 +// if(returndata.startsWith("\"")){ +// returndata=returndata.substring(1); +// } +// //过滤后面的双引号 +// if(returndata.endsWith("\"")){ +// returndata=returndata.substring(0,returndata.length()-1); +// } +// //转义\" +// returndata=StringEscapeUtils.unescapeJava(returndata); +// log.writeLog("【借款接口返回转译处理后的结果result:】" + returndata); + JSONObject jsonObject = JSONObject.parseObject(returndata); + String success = Util.null2String(jsonObject.get("succ")); + log.writeLog("--------发送请求返回的success值为:" + success); + if ("true".equals(success)) { + JSONObject data = jsonObject.getJSONObject("data"); + String billno = Util.null2String(data.get("billno"));//NCC单号 + log.writeLog("--------发送请求返回的billno值为:" + billno); + //将NCC返回结果回写至OA流程表单 + rs.execute(" update " + mainTable + " set sfcgscnccfkd = 0 , nccfkdh = '" + billno + "',nccfhxx='' where requestid = " + requestId); + } else { + String message = Util.null2String(jsonObject.get("msg")); + //将NCC返回结果回写至OA流程表单 + rs.execute(" update " + mainTable + " set sfcgscnccfkd = 1 ,nccfhxx='" + message.replace("'", "''") + "' where requestid = " + requestId); + requestInfo.getRequestManager().setMessagecontent("流程数据写入NCC借款单失败,失败信息:
"+message); + return Action.FAILURE_AND_CONTINUE; + } + } else { + requestInfo.getRequestManager().setMessagecontent("流程数据写入中台借款单失败,未获取到接口返回结果,请联系系统管理员处理!"); + return Action.FAILURE_AND_CONTINUE; + } + + } catch (Exception e) { + requestInfo.getRequestManager().setMessagecontent("流程数据生成中台对公借款单失败,失败信息:
" + e.toString()); + return Action.FAILURE_AND_CONTINUE; + } + log.writeLog("--------对公借款单数据传入中台完毕----requestId值为:" + requestId); + return Action.SUCCESS; + } +} \ No newline at end of file diff --git a/src/main/youhong_ai_jitu_src/jntchina/action/InvoiceToTaxCloudBx.java b/src/main/youhong_ai_jitu_src/jntchina/action/InvoiceToTaxCloudBx.java new file mode 100644 index 0000000..dc28c4f --- /dev/null +++ b/src/main/youhong_ai_jitu_src/jntchina/action/InvoiceToTaxCloudBx.java @@ -0,0 +1,114 @@ +package jntchina.action; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.serializer.SerializerFeature; +import com.working.util.WorkflowUtil; + +import jntchina.util.HttpClientUtil; +import jntchina.util.URLConfigEnum; +import selfdev.util.base.BaseUtil; +import selfdev.util.log.LogTool; +import weaver.conn.RecordSet; +import weaver.general.Util; +import weaver.hrm.resource.ResourceComInfo; +import weaver.interfaces.workflow.action.Action; +import weaver.interfaces.workflow.action.BaseAction; +import weaver.soa.workflow.request.RequestInfo; + +/** + * 报销单数据传入税务云报销状态变为已报销 + */ +public class InvoiceToTaxCloudBx extends BaseAction { + + @Override + public String execute(RequestInfo requestInfo) { + String src = requestInfo.getRequestManager().getSrc();//获取操作方式 + if (!"submit".equals(src)) { // 只有submit才执行接口 + return SUCCESS; + } + LogTool log = new LogTool("/log/selfdev/action", false); + String requestId = requestInfo.getRequestid(); // 获取requestid + log.writeLog("--------报销单数据传入税务云开始----requestId值为:" + requestId); + String mainTable = WorkflowUtil.getMainTable(requestId); + String mainId = ""; + String nsrsbh = ""; //纳税人识别号tax_number + String lcbh = ""; //流程编号 + String gsmc = ""; //公司名称(组织编码) + String xm = ""; //申请人 + String fpdm = ""; //发票代码 + String fphm = ""; //发票号码 + + RecordSet rs = new RecordSet(); + RecordSet rs2 = new RecordSet(); + try { + Map data = new HashMap(); + List datas = new ArrayList(); + String sql = " select * from " + mainTable + " where requestid='" + requestId + "'"; + rs.execute(sql); + while (rs.next()) { + mainId = Util.null2String(rs.getString("id")); + xm = new ResourceComInfo().getLastname(Util.null2String(rs.getString("xm"))); //申请人 + gsmc = Util.null2String(rs.getString("gsmc")); // 公司名称(组织编码) + lcbh = Util.null2String(rs.getString("lcbh")); // OA单据号 OA传过来,用于联查单据 + } + //获取OA-NCC发票映射关系表 + Map map_oafplx_nccfplcx=BaseUtil.getMapKeyValueInfoByParm("uf_oafplx_nccfplx", "", "oafplxid", "nccfplxbm"); + //查询明细 + sql=" select distinct c.INVOICECODE,c.INVOICENUMBER,c.invoicetype from " + mainTable + "_dt8 a " + + "left join uf_fylx b on to_char(a.bxlx)=to_char(b.id) " + + "left join fnainvoiceledger c on a.fphm=c.id " + + "where a.mainid = " + mainId; + log.writeLog("查询付款明细sql------>" + sql); + rs.execute(sql); + while (rs.next()) { + fpdm = Util.null2String(rs.getString("INVOICECODE")); // 发票代码 + fphm = Util.null2String(rs.getString("INVOICENUMBER")); // 发票号码 + String invoicetype = Util.null2String(rs.getString("invoicetype")); // OA发票类型 + //NCC发票类型 + String fplxpk=Util.null2String(map_oafplx_nccfplcx.get(invoicetype)); + if (fplxpk.startsWith("invoice")){ + fplxpk="invoice"; + } + //发票代码 + data.put("invoiceCode",fpdm); + //发票号码 + data.put("invoiceNum",fphm); + //发票类型 + data.put("billType",fplxpk); + //记账人 + data.put("reimburseUser",xm); +// //记账人备注 +// data.put("accountNote",lcbh); + datas.add(data); + log.writeLog("发票代码------>" + fpdm); + log.writeLog("发票号码------>" + fphm); + log.writeLog("发票类型------>" + fplxpk); + log.writeLog("datas-----"+datas); + } + //根据组织编码查询纳税人识别号 + rs2.execute("select * from uf_businessunit"+" where code = '"+gsmc+"'"); + while (rs2.next()) { + nsrsbh = Util.null2String(rs2.getString("tax_number")); + } + Map paramsMap = new HashMap(); + paramsMap.put("nsrsbh", nsrsbh); + paramsMap.put("orgcode", gsmc); + paramsMap.put("bills",datas); + log.writeLog("调用税务云接口传入参数----->"+JSON.toJSONString(paramsMap, SerializerFeature.DisableCircularReferenceDetect)); + String result=HttpClientUtil.jsonPost(URLConfigEnum.REIMBURSED.getUrl(), paramsMap); + log.writeLog("调用税务云接口将发票状态更新为已报销返回结果------>"+result); + + } catch (Exception e) { + log.writeLog("流程数据生成税务云发票记账失败!错误信息------>" + e.toString()); + requestInfo.getRequestManager().setMessagecontent("流程数据生成税务云发票记账失败!错误信息------>" + e.toString()); + return Action.FAILURE_AND_CONTINUE; + } + return Action.SUCCESS; + } + +} diff --git a/src/main/youhong_ai_jitu_src/jntchina/action/InvoiceToTaxCloudFk.java b/src/main/youhong_ai_jitu_src/jntchina/action/InvoiceToTaxCloudFk.java new file mode 100644 index 0000000..735ce8f --- /dev/null +++ b/src/main/youhong_ai_jitu_src/jntchina/action/InvoiceToTaxCloudFk.java @@ -0,0 +1,110 @@ +package jntchina.action; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.serializer.SerializerFeature; +import com.working.util.WorkflowUtil; +import jntchina.util.HttpClientUtil; +import jntchina.util.URLConfigEnum; +import selfdev.util.base.BaseUtil; +import selfdev.util.log.LogTool; +import weaver.conn.RecordSet; +import weaver.general.Util; +import weaver.hrm.resource.ResourceComInfo; +import weaver.interfaces.workflow.action.Action; +import weaver.interfaces.workflow.action.BaseAction; +import weaver.soa.workflow.request.RequestInfo; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +/** + * 付款单数据传入税务云报销状态变为已报销 + */ +public class InvoiceToTaxCloudFk extends BaseAction { + + @Override + public String execute(RequestInfo requestInfo) { + String src = requestInfo.getRequestManager().getSrc();//获取操作方式 + if (!"submit".equals(src)) { // 只有submit才执行接口 + return SUCCESS; + } + LogTool log = new LogTool("/log/selfdev/action", false); + String requestId = requestInfo.getRequestid(); // 获取requestid + log.writeLog("--------报销单数据传入税务云开始----requestId值为:" + requestId); + String mainTable = WorkflowUtil.getMainTable(requestId); + String mainId = ""; + String nsrsbh = ""; //纳税人识别号tax_number + String gsmc = ""; + String xm = ""; //申请人 + String fpdm = ""; //发票代码 + String fphm = ""; //发票号码 + String lcbh = ""; + + RecordSet rs = new RecordSet(); + RecordSet rs2 = new RecordSet(); + try { + Map data = new HashMap(); + List datas = new ArrayList(); + String sql = " select * from " + mainTable + " where requestid='" + requestId + "'"; + rs.execute(sql); + while (rs.next()) { + mainId = Util.null2String(rs.getString("id")); + xm = new ResourceComInfo().getLastname(Util.null2String(rs.getString("xm"))); //申请人 + gsmc = Util.null2String(rs.getString("gsmc")); // 公司名称 + lcbh = Util.null2String(rs.getString("lcbh")); // 流程编号 + + } + //获取OA-NCC发票映射关系表 + Map map_oafplx_nccfplcx=BaseUtil.getMapKeyValueInfoByParm("uf_oafplx_nccfplx", "", "oafplxid", "nccfplxbm"); + //查询明细 + sql=" select distinct c.INVOICECODE,c.INVOICENUMBER,c.invoicetype from " + mainTable + "_dt2 a " + + "left join uf_fylx b on to_char(a.fylx)=to_char(b.id) " + + "left join fnainvoiceledger c on a.fphm=c.id " + + "where a.mainid = " + mainId; + log.writeLog("查询报销明细sql------>" + sql); + rs.execute(sql); + + while (rs.next()) { + fpdm = Util.null2String(rs.getString("INVOICECODE")); // 发票代码 + fphm = Util.null2String(rs.getString("INVOICENUMBER")); // 发票号码 + String invoicetype = Util.null2String(rs.getString("invoicetype")); // OA发票类型 + //NCC发票类型 + String fplxpk=Util.null2String(map_oafplx_nccfplcx.get(invoicetype)); + if (fplxpk.startsWith("invoice")){ + fplxpk="invoice"; + } + //发票代码 + data.put("invoiceCode",fpdm); + //发票号码 + data.put("invoiceNum",fphm); + //发票类型 + data.put("billType",fplxpk); + //记账人 + data.put("reimburseUser",xm); +// //记账人备注 +// data.put("accountNote",lcbh); + datas.add(data); + } + //根据组织编码查询纳税人识别号 + rs2.execute("select * from uf_businessunit"+" where code = '"+gsmc+"'"); + while (rs2.next()) { + nsrsbh = Util.null2String(rs2.getString("tax_number")); + } + Map paramsMap = new HashMap(); + paramsMap.put("nsrsbh", nsrsbh); + paramsMap.put("orgcode", gsmc); + paramsMap.put("bills",datas); + log.writeLog("调用税务云接口传入参数----->"+JSON.toJSONString(paramsMap, SerializerFeature.DisableCircularReferenceDetect)); + String result=HttpClientUtil.jsonPost(URLConfigEnum.REIMBURSED.getUrl(), paramsMap); + log.writeLog("调用税务云接口将发票状态更新为已报销返回结果------>"+result); + + } catch (Exception e) { + log.writeLog("流程数据生成税务云报记账失败!错误信息------>" + e.toString()); + requestInfo.getRequestManager().setMessagecontent("流程数据生成税务云报记账失败!错误信息------>" + e.toString()); + return Action.FAILURE_AND_CONTINUE; + } + return Action.SUCCESS; + } + +} diff --git a/src/main/youhong_ai_jitu_src/jntchina/action/JiabanCheckAction.java b/src/main/youhong_ai_jitu_src/jntchina/action/JiabanCheckAction.java new file mode 100644 index 0000000..7b81893 --- /dev/null +++ b/src/main/youhong_ai_jitu_src/jntchina/action/JiabanCheckAction.java @@ -0,0 +1,87 @@ +package jntchina.action; + +import selfdev.util.log.LogTool; +import selfdev.util.base.BaseUtil; + +import weaver.conn.RecordSet; +import weaver.general.Util; +import weaver.interfaces.workflow.action.BaseAction; +import weaver.soa.workflow.request.RequestInfo; + +/** + * @description: 加班校验 + * @author: daizhishun + * @date: 2021/9/8 + **/ +public class JiabanCheckAction extends BaseAction { + public static LogTool log=new LogTool("/log/selfdev/action/hrm", true); + public String execute(RequestInfo ri){ + String requestid=ri.getRequestid(); + log.writeLog("---------------加班流程提交时数据逻辑校验开始-------------requestId:" + requestid); + try { + String workflowid=ri.getWorkflowid(); + //获取表名 + String tablename=BaseUtil.getBaseInfoByParm("tablename", "workflow_bill", "1", "1", " and id in (select formid from workflow_base where id="+workflowid+")"); + RecordSet rs=new RecordSet(); + RecordSet rs1=new RecordSet(); + String sql="select * from "+tablename+" where requestid="+requestid; + String lastname = ""; + String workcode = ""; + String fromDate = ""; + String fromTime = ""; + String toDate = ""; + String toTime = ""; + rs.execute(sql); + while(rs.next()){ + workcode = Util.null2String(rs.getString("tjrgh"));//主键ID + lastname = Util.null2String(rs.getString("resourceId"));//主键ID + fromDate = Util.null2String(rs.getString("fromDate"));//主键ID + fromTime = Util.null2String(rs.getString("fromTime"));//主键ID + toDate = Util.null2String(rs.getString("toDate"));//主键ID + toTime = Util.null2String(rs.getString("toTime"));//主键ID + } + //开始 + String ks=(fromDate+" "+fromTime).substring(0,16); + //结束 + String js=(toDate+" "+toTime).substring(0,16); + String msg = ""; + //判断加班时间必须以00或者30结尾 + if(!ks.substring(14,16).endsWith("00")&&!ks.substring(14,16).endsWith("30")){ + msg+="加班开始时间"+ks+"中的分钟必须是以00或者30这种半小时整为单位;
";//返回信息 + } + if(!js.substring(14,16).endsWith("00")&&!js.substring(14,16).endsWith("30")){ + msg+="加班结束时间"+js+"中的分钟必须是以00或者30这种半小时整为单位;
";//返回信息 + } + + //检查当前员工在此期间是否有加班记录 + sql="select b.* from FORMTABLE_MAIN_1424 b,workflow_requestbase c where"+ + "((b.fromdate||' '||b.fromtime)>'"+ks+"' and (b.fromdate||' '||b.fromtime)<'"+js+"')"+ + "or ((b.toDate||' '||b.toTime)>'"+ks+"' and (b.toDate||' '||b.toTime)<'"+js+"')"+ + "or ((b.fromdate||' '||b.fromtime)<'"+ks+"' and (b.fromdate||' '||b.fromtime)>'"+js+"')"+ + "and b.requestid!= "+requestid+" and c.currentnodetype!=0 and c.createdate>='2021-05-27' and b.requestid=c.requestid and b.resourceId="+lastname+""; + log.writeLog("检查当前员工在此期间是否有加班记录sql--------->"+sql); + rs1.execute(sql); + if(rs1.getCounts()>0){ + String temp=""; + while(rs1.next()){ + temp+="【requestid="+rs1.getString("requestid")+""; + } + temp=temp.substring(0,temp.length()-1); + msg+=lastname+"【"+workcode+"】加班时间段"+ks+"~"+js+"之前的流程"+temp+"已提交过加班申请,请重新选择加班时间
"; + } + if(!"".equals(msg)){ + ri.getRequestManager().setMessageid("111100"); + ri.getRequestManager().setMessagecontent(msg); + return "0"; + } + }catch (Exception e){ + e.printStackTrace(); + log.writeLog("加班流程提交时数据逻辑校验失败,错误信息为:------>"+e.toString()); + ri.getRequestManager().setMessageid("111100"); + ri.getRequestManager().setMessagecontent("加班流程提交时数据逻辑校验失败,错误信息为:------>"+e.toString()); + return "0"; + } + log.writeLog("---------------加班流程提交时数据逻辑校验结束-------------requestId:" + requestid); + return SUCCESS; + } +} diff --git a/src/main/youhong_ai_jitu_src/jntchina/action/JiabanForceDrawBackAction.java b/src/main/youhong_ai_jitu_src/jntchina/action/JiabanForceDrawBackAction.java new file mode 100644 index 0000000..6a84002 --- /dev/null +++ b/src/main/youhong_ai_jitu_src/jntchina/action/JiabanForceDrawBackAction.java @@ -0,0 +1,38 @@ +package jntchina.action; + +import selfdev.util.base.BaseUtil; +import selfdev.util.log.LogTool; +import weaver.interfaces.workflow.action.BaseAction; +import weaver.soa.workflow.request.RequestInfo; + +/** + * @description: 加班流程强制收回时的节点附加操作 + * @author: KangMD + * @date: 2021-12-19 + **/ +public class JiabanForceDrawBackAction extends BaseAction { + + public static LogTool log=new LogTool("/log/selfdev/action/hrm", false); + public String execute(RequestInfo requestInfo){ + String requestId = requestInfo.getRequestid(); // 获取requestid + String workflowid = requestInfo.getWorkflowid(); // 获取workflowid + + //获取工作流名称 + String workflowname = BaseUtil.getBaseInfoByParm("workflowname", "workflow_base", "id", workflowid, ""); + log.writeLog("--------【"+workflowname+"】强制收回时的节点附加操作----requestId值为:" + requestId); + try{ + JiabanForceDrawBackThread forceDrawBackThread=new JiabanForceDrawBackThread(); + //设置参数 + forceDrawBackThread.setRequestInfo(requestInfo); + Thread thread = new Thread(forceDrawBackThread); + //启动线程 + thread.start(); + log.writeLog("--------【"+workflowname+"】强制收回时启用线程--------"); + }catch (Exception e){ + //返回0,调用失败 + log.writeLog("------------------------捕获到的异常是:" + e.toString()); + return "0"; + } + return SUCCESS; + } +} diff --git a/src/main/youhong_ai_jitu_src/jntchina/action/JiabanForceDrawBackThread.java b/src/main/youhong_ai_jitu_src/jntchina/action/JiabanForceDrawBackThread.java new file mode 100644 index 0000000..693a449 --- /dev/null +++ b/src/main/youhong_ai_jitu_src/jntchina/action/JiabanForceDrawBackThread.java @@ -0,0 +1,124 @@ +package jntchina.action; + +import com.alibaba.fastjson.JSONObject; +import jntchina.util.HttpClientToDC; +import selfdev.util.base.BaseUtil; +import selfdev.util.log.LogTool; +import weaver.conn.RecordSet; +import weaver.file.Prop; +import weaver.general.Util; +import weaver.soa.workflow.request.RequestInfo; + +import java.util.HashMap; +import java.util.Map; + +/** + * @description: 加班强制收回时调用HR接口 + * @author: KangMD + * @date: 2021-12-19 + **/ +public class JiabanForceDrawBackThread implements Runnable { + public static LogTool log=new LogTool("/log/selfdev/action/hrm", true); + public RequestInfo requestInfo; + + public RequestInfo getRequestInfo() { + return requestInfo; + } + + public void setRequestInfo(RequestInfo requestInfo) { + this.requestInfo = requestInfo; + } + + public void run(){ + String requestId = requestInfo.getRequestid(); // 获取requestid + try { + log.writeLog("----------1.5秒后再启动【requestId:" + requestId+"】-------------"); + Thread.sleep(1500);//延迟执行 + } catch (InterruptedException e1) { + // TODO Auto-generated catch block + e1.printStackTrace(); + } + log.writeLog("----------1.5秒结束,开启执行代码【requestId:" +requestId+"】-------------"); + + String workflowid = requestInfo.getWorkflowid(); // 获取workflowid + //获取工作流名称 + String workflowname = BaseUtil.getBaseInfoByParm("workflowname", "workflow_base", "id", workflowid, ""); + log.writeLog("--------【"+workflowname+"】数据传入中台开始----requestId值为:" + requestId); + + try{ + //流程当前状态 + String currentnodetype=""; + RecordSet rs = new RecordSet(); + String sql = "select * from workflow_requestbase where requestid = "+requestId+""; + rs.execute(sql); + while (rs.next()) { + currentnodetype = Util.null2String(rs.getString("currentnodetype"));//当前流程状态 + } + log.writeLog("currentnodetype---------------->"+currentnodetype); + //流程当前处于申请节点,才需要调用HR接口 + if(!"0".equals(currentnodetype)){ + log.writeLog("*************流程不是强制收回到申请节点,不需要调用HR接口*************"); + return; + } + //获取配置文件中的参数,到时候URL路径 + String mode = Prop.getPropValue("DevToDC_jntchina", "mode"); + // 服务器ip:port + String baseUrl = Prop.getPropValue("DevToDC_jntchina", mode + "_baseUrl"); + //访问路径拼接 + String url = baseUrl + "/dcoaapi/hr/attendance"; + + //根据流程id获取主表名称 + String mainTable = RegularizationApplyForAction.getMainTable(requestId); + log.writeLog("--------获取到的表名为----:" + mainTable); + //申请单号 + String C_OA_NUM = ""; + //单据来源:默认OA + String C_APPLY_SOURCE = "OA"; + //流程名称:加班流程为:40 + String C_WORKFLOW = "40"; + //审批状态:已通过:3,驳回:5 + String C_STATUS = "5"; + + sql = "select lcbh from "+mainTable+" where requestid = "+requestId+""; + rs.execute(sql); + log.writeLog("----------------》打印sql语句"+sql); + while (rs.next()) { + C_OA_NUM = Util.null2String(rs.getString("lcbh"));//申请单号 + } + + + Map map = new HashMap(); + map.put("C_OA_NUM",C_OA_NUM); + map.put("C_APPLY_SOURCE",C_APPLY_SOURCE); + map.put("C_WORKFLOW",C_WORKFLOW); + map.put("C_STATUS",C_STATUS); + String strParm = JSONObject.toJSONString(map); + log.writeLog("---------------打印的Map数据为:-----------------:"+strParm); + + //获取Token + String token = HttpClientToDC.getToken(); + log.writeLog("加班申请单token------>" + token); + log.writeLog("加班申请单url------>" + url); + + //调用NCC接口,将数据传给NCC + String returndata = HttpClientToDC.sendPostApi(url,token,strParm); + log.writeLog("【调用数据中台加班申请单接口返回结果:】" + returndata); + if (!"".equals(returndata) && returndata != null) { + JSONObject jsonObject = JSONObject.parseObject(returndata); + String code = Util.null2String(jsonObject.get("code")); + log.writeLog("--------发送请求返回的code值为:" + code); + if ("1".equals(code)) { + + } else { + String msg = Util.null2String(jsonObject.get("msg")); + log.writeLog("调用HR接口返回错误信息----->" + msg); + } + }else { + log.writeLog("调用HR接口返回为空----->"); + } + }catch (Exception e){ + //返回0,调用失败 + log.writeLog("------------------------捕获到的异常是:" + e.toString()); + } + } +} diff --git a/src/main/youhong_ai_jitu_src/jntchina/action/JiabanHuichuanReturnAction.java b/src/main/youhong_ai_jitu_src/jntchina/action/JiabanHuichuanReturnAction.java new file mode 100644 index 0000000..5ad07e3 --- /dev/null +++ b/src/main/youhong_ai_jitu_src/jntchina/action/JiabanHuichuanReturnAction.java @@ -0,0 +1,100 @@ +package jntchina.action; + +import com.alibaba.fastjson.JSONObject; +import jntchina.util.HttpClientToDC; +import selfdev.util.base.BaseUtil; +import selfdev.util.log.LogTool; +import weaver.conn.RecordSet; +import weaver.file.Prop; +import weaver.general.Util; +import weaver.interfaces.workflow.action.BaseAction; +import weaver.soa.workflow.request.RequestInfo; + +import java.util.HashMap; +import java.util.Map; + +/** + * @description: 加班结果回传-退回至发起人 + * @author: daizhishun + * @date: 2021/9/10 + **/ +public class JiabanHuichuanReturnAction extends BaseAction { + public static LogTool log=new LogTool("/log/selfdev/action/hrm", true); + public String execute(RequestInfo requestInfo){ + String requestId = requestInfo.getRequestid(); // 获取requestid + String workflowid = requestInfo.getWorkflowid(); // 获取workflowid + + //获取工作流名称 + String workflowname = BaseUtil.getBaseInfoByParm("workflowname", "workflow_base", "id", workflowid, ""); + log.writeLog("--------【"+workflowname+"】退回到申请节点时数据传入中台开始----requestId值为:" + requestId); + + try{ + //获取配置文件中的参数,到时候URL路径 + String mode = Prop.getPropValue("DevToDC_jntchina", "mode"); + // 服务器ip:port + String baseUrl = Prop.getPropValue("DevToDC_jntchina", mode + "_baseUrl"); + //访问路径拼接 + String url = baseUrl + "/dcoaapi/hr/attendance"; + + //根据流程id获取主表名称 + String mainTable = RegularizationApplyForAction.getMainTable(requestId); + log.writeLog("--------获取到的表名为----:" + mainTable); + //申请单号 + String C_OA_NUM = ""; + //单据来源:默认OA + String C_APPLY_SOURCE = "OA"; + //流程名称:加班流程为:40 + String C_WORKFLOW = "40"; + //审批状态:已通过:3,驳回:5 + String C_STATUS = "5"; + + RecordSet rs = new RecordSet(); + String sql = "select lcbh from "+mainTable+" where requestid = "+requestId+""; + rs.execute(sql); + log.writeLog("----------------》打印sql语句"+sql); + while (rs.next()) { + C_OA_NUM = Util.null2String(rs.getString("lcbh"));//申请单号 + } + + + Map map = new HashMap(); + map.put("C_OA_NUM",C_OA_NUM); + map.put("C_APPLY_SOURCE",C_APPLY_SOURCE); + map.put("C_WORKFLOW",C_WORKFLOW); + map.put("C_STATUS",C_STATUS); + String strParm = JSONObject.toJSONString(map); + log.writeLog("---------------打印的Map数据为:-----------------:"+strParm); + + //获取Token + String token = HttpClientToDC.getToken(); + log.writeLog("加班申请单token------>" + token); + log.writeLog("加班申请单url------>" + url); + + //调用NCC接口,将数据传给NCC + String returndata = HttpClientToDC.sendPostApi(url,token,strParm); + log.writeLog("【调用数据中台加班申请单接口返回结果:】" + returndata); + if (!"".equals(returndata) && returndata != null) { + JSONObject jsonObject = JSONObject.parseObject(returndata); + String code = Util.null2String(jsonObject.get("code")); + log.writeLog("--------发送请求返回的code值为:" + code); + if ("1".equals(code)) { + return SUCCESS; + } else { + String msg = Util.null2String(jsonObject.get("msg")); + requestInfo.getRequestManager().setMessageid("111100"); + requestInfo.getRequestManager().setMessagecontent(msg); + return "0"; + } + }else { + String ermsg = "流程数据已审批状态提交至中台失败,请联系系统管理员处理!"; + requestInfo.getRequestManager().setMessageid("111100"); + requestInfo.getRequestManager().setMessagecontent(ermsg); + return "0"; + } + }catch (Exception e){ + //返回0,调用失败 + log.writeLog("------------------------捕获到的异常是:" + e.toString()); + return "0"; + } + } +} diff --git a/src/main/youhong_ai_jitu_src/jntchina/action/JiabanHuichuanSuccessAction.java b/src/main/youhong_ai_jitu_src/jntchina/action/JiabanHuichuanSuccessAction.java new file mode 100644 index 0000000..0cb6c6d --- /dev/null +++ b/src/main/youhong_ai_jitu_src/jntchina/action/JiabanHuichuanSuccessAction.java @@ -0,0 +1,101 @@ +package jntchina.action; + +import com.alibaba.fastjson.JSONObject; +import jntchina.util.HttpClientToDC; +import selfdev.util.base.BaseUtil; +import selfdev.util.log.LogTool; +import weaver.conn.RecordSet; +import weaver.file.Prop; +import weaver.general.Util; +import weaver.interfaces.workflow.action.BaseAction; +import weaver.soa.workflow.request.RequestInfo; + +import java.util.HashMap; +import java.util.Map; + +/** + * @description: 加班结果回传-成功-放归档节点前操作 + * @author: daizhishun + * @date: 2021/9/10 + **/ +public class JiabanHuichuanSuccessAction extends BaseAction { + + public static LogTool log=new LogTool("/log/selfdev/action/hrm", true); + public String execute(RequestInfo requestInfo){ + String requestId = requestInfo.getRequestid(); // 获取requestid + String workflowid = requestInfo.getWorkflowid(); // 获取workflowid + + //获取工作流名称 + String workflowname = BaseUtil.getBaseInfoByParm("workflowname", "workflow_base", "id", workflowid, ""); + log.writeLog("--------【"+workflowname+"】数据传入中台开始----requestId值为:" + requestId); + + try{ + //获取配置文件中的参数,到时候URL路径 + String mode = Prop.getPropValue("DevToDC_jntchina", "mode"); + // 服务器ip:port + String baseUrl = Prop.getPropValue("DevToDC_jntchina", mode + "_baseUrl"); + //访问路径拼接 + String url = baseUrl + "/dcoaapi/hr/attendance"; + + //根据流程id获取主表名称 + String mainTable = RegularizationApplyForAction.getMainTable(requestId); + log.writeLog("--------获取到的表名为----:" + mainTable); + //申请单号 + String C_OA_NUM = ""; + //单据来源:默认OA + String C_APPLY_SOURCE = "OA"; + //流程名称:加班流程为:40 + String C_WORKFLOW = "40"; + //审批状态:已通过:3,驳回:5 + String C_STATUS = "3"; + + RecordSet rs = new RecordSet(); + String sql = "select lcbh from "+mainTable+" where requestid = "+requestId+""; + rs.execute(sql); + log.writeLog("----------------》打印sql语句"+sql); + while (rs.next()) { + C_OA_NUM = Util.null2String(rs.getString("lcbh"));//申请单号 + } + + + Map map = new HashMap(); + map.put("C_OA_NUM",C_OA_NUM); + map.put("C_APPLY_SOURCE",C_APPLY_SOURCE); + map.put("C_WORKFLOW",C_WORKFLOW); + map.put("C_STATUS",C_STATUS); + String strParm = JSONObject.toJSONString(map); + log.writeLog("---------------打印的Map数据为:-----------------:"+strParm); + + //获取Token + String token = HttpClientToDC.getToken(); + log.writeLog("加班申请单token------>" + token); + log.writeLog("加班申请单url------>" + url); + + //调用NCC接口,将数据传给NCC + String returndata = HttpClientToDC.sendPostApi(url,token,strParm); + log.writeLog("【调用数据中台加班申请单接口返回结果:】" + returndata); + if (!"".equals(returndata) && returndata != null) { + JSONObject jsonObject = JSONObject.parseObject(returndata); + String code = Util.null2String(jsonObject.get("code")); + log.writeLog("--------发送请求返回的code值为:" + code); + if ("1".equals(code)) { + return SUCCESS; + } else { + String msg = Util.null2String(jsonObject.get("msg")); + requestInfo.getRequestManager().setMessageid("111100"); + requestInfo.getRequestManager().setMessagecontent(msg); + return "0"; + } + }else { + String ermsg = "流程数据已审批状态提交至中台失败,请联系系统管理员处理!"; + requestInfo.getRequestManager().setMessageid("111100"); + requestInfo.getRequestManager().setMessagecontent(ermsg); + return "0"; + } + }catch (Exception e){ + //返回0,调用失败 + log.writeLog("------------------------捕获到的异常是:" + e.toString()); + return "0"; + } + } +} diff --git a/src/main/youhong_ai_jitu_src/jntchina/action/JwtParamBuilder.java b/src/main/youhong_ai_jitu_src/jntchina/action/JwtParamBuilder.java new file mode 100644 index 0000000..3e58631 --- /dev/null +++ b/src/main/youhong_ai_jitu_src/jntchina/action/JwtParamBuilder.java @@ -0,0 +1,110 @@ +package jntchina.action; + +import java.util.HashMap; +import java.util.Map; +import java.util.UUID; + +/** + * @program: yesfp-demo + * @description: + * @author: kw + * @create: 2020/04/30 12:37 + */ +public class JwtParamBuilder { + + /** JWT {@code Issuer} claims parameter name: "iss" */ + public static final String ISSUER = "iss"; + + /** JWT {@code Subject} claims parameter name: "sub" */ + public static final String SUBJECT = "sub"; + + /** JWT {@code Audience} claims parameter name: "aud" */ + public static final String AUDIENCE = "aud"; + + /** JWT {@code Expiration} claims parameter name: "exp" */ + public static final String EXPIRATION = "exp"; + + /** JWT {@code Not Before} claims parameter name: "nbf" */ + public static final String NOT_BEFORE = "nbf"; + + /** JWT {@code Issued At} claims parameter name: "iat" */ + public static final String ISSUED_AT = "iat"; + + /** JWT {@code JWT ID} claims parameter name: "jti" */ + public static final String ID = "jti"; + + private Map claims; + + private final long now; + + private JwtParamBuilder() { + claims = new HashMap<>(); + now = System.currentTimeMillis() / 1000l; + } + + public static JwtParamBuilder build() { + return new JwtParamBuilder(); + } + + public JwtParamBuilder addIssuedAt() { + claims.put(ISSUED_AT, now); + return this; + } + + public JwtParamBuilder setExpirySeconds(final Integer expirySeconds) { + claims.put(EXPIRATION, now + expirySeconds); + return this; + } + + public JwtParamBuilder setNotBeforeSeconds(final Integer beforeSeconds) { + claims.put(NOT_BEFORE, now - beforeSeconds); + return this; + } + + public JwtParamBuilder setSubject(String sub) { + addOneClaim(SUBJECT, sub); + return this; + } + + public JwtParamBuilder setIssuer(String iss) { + addOneClaim(ISSUER, iss); + return this; + } + + public JwtParamBuilder setAudience(String aud) { + addOneClaim(AUDIENCE, aud); + return this; + } + + public JwtParamBuilder addJwtId() { + return setJwtId(UUID.randomUUID().toString()); + } + + public JwtParamBuilder setJwtId(String jwtid) { + addOneClaim(ID, UUID.randomUUID().toString()); + return this; + } + + public JwtParamBuilder claim(String name, Object value) { + if (value == null) { + this.claims.remove(name); + } else { + this.claims.put(name, value); + } + return this; + } + + private void addOneClaim(String key, String value) { + if (value != null && value.length() > 0) { + claims.put(key, value); + } + } + + + /** + * @return the claims + */ + public Map getClaims() { + return claims; + } +} diff --git a/src/main/youhong_ai_jitu_src/jntchina/action/OverTimeApplicantAction.java b/src/main/youhong_ai_jitu_src/jntchina/action/OverTimeApplicantAction.java new file mode 100644 index 0000000..09dbe29 --- /dev/null +++ b/src/main/youhong_ai_jitu_src/jntchina/action/OverTimeApplicantAction.java @@ -0,0 +1,136 @@ +package jntchina.action; + + +import com.alibaba.fastjson.JSONObject; +import jntchina.util.HttpClientToDC; +import selfdev.util.base.BaseUtil; +import selfdev.util.log.LogTool; +import weaver.conn.RecordSet; +import weaver.file.Prop; +import weaver.general.Util; +import weaver.interfaces.workflow.action.BaseAction; +import weaver.soa.workflow.request.RequestInfo; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +/** + * @description: 加班申请单 + * @author: dzs + * @date: 2021/7/29 + **/ +public class OverTimeApplicantAction extends BaseAction { + + @Override + public String execute(RequestInfo requestInfo) { + LogTool log = new LogTool("/log/selfdev/action/hrm", true); + String requestId = requestInfo.getRequestid(); // 获取requestid + String workflowid = requestInfo.getWorkflowid(); // 获取workflowid + //获取工作流名称 + String workflowname = BaseUtil.getBaseInfoByParm("workflowname", "workflow_base", "id", workflowid, ""); + log.writeLog("---------------工作流名称-----------workflowname为:" + workflowname); + log.writeLog("--------加班申请单数据传入中台开始----requestId值为:" + requestId); + + //获取配置文件中的参数,到时候URL路径 + String mode = Prop.getPropValue("DevToDC_jntchina", "mode"); + // 服务器ip:port + String baseUrl = Prop.getPropValue("DevToDC_jntchina", mode + "_baseUrl"); + //访问路径拼接 + String url = baseUrl + "/dcoaapi/hr/work"; + //String url = "http://121.37.156.206:21005/PSIGW/RESTListeningConnector/PSFT_HR/C_WORK_APPLY.v1/"; + + + //根据流程id获取主表名称 + String mainTable = RegularizationApplyForAction.getMainTable(requestId); + log.writeLog("--------获取到的表名为----:" + mainTable); + //申请单号 OA单据号码 + String C_OA_NUM = ""; + //员工编码 OA提单人工号,加班人工号 + String EMPLID = ""; + //加班原因 自由文本 + String C_REASON = ""; + + //{ + //加班数据 + List> list = new ArrayList>(); + //加班开始日期 + String C_START_DT=""; + //加班开始时间 + String C_START_DTM=""; + //加班结束日期 + String C_END_DT=""; + //加班结束时间 + String C_END_DTM=""; + //} + + + RecordSet rs = new RecordSet(); + try { + String sql = "select * from " + mainTable + " where requestid='" + requestId + "'"; + rs.execute(sql); + log.writeLog("查询sql语句---------------->"+sql); + while (rs.next()) { + C_OA_NUM = Util.null2String(rs.getString("lcbh"));//申请单号 + EMPLID = Util.null2String(rs.getString("tjrgh"));//员工编码 + C_REASON = Util.null2String(rs.getString("qjyy"));//加班原因 + C_START_DT = Util.null2String(rs.getString("fromDate"));//加班开始日期 + C_START_DTM = Util.null2String(rs.getString("fromTime"));//加班开始时间 + C_END_DT = Util.null2String(rs.getString("toDate"));//加班结束日期 + C_END_DTM = Util.null2String(rs.getString("toTime"));//加班结束时间 + } + + //将加班数据进行包装 + Map maps= new HashMap(); + maps.put("EMPLID",EMPLID); + maps.put("C_START_DT",C_START_DT); + maps.put("C_START_DTM",C_START_DTM); + maps.put("C_END_DT",C_END_DT); + maps.put("C_END_DTM",C_END_DTM); + list.add(maps); + log.writeLog("----------------->加班数据明细数据:" + list.toString()); + + //最后再将数据全部打包 + Map map = new HashMap(); + map.put("C_OA_NUM",C_OA_NUM); + map.put("EMPLID",EMPLID); + map.put("C_REASON",C_REASON); + map.put("LINES",list); + String strParm = JSONObject.toJSONString(map); + log.writeLog("---------------加班打印的Map数据为:-----------------:"+strParm); + + //获取Token + String token = HttpClientToDC.getToken(); + log.writeLog("加班申请单token------>" + token); + log.writeLog("加班申请单url------>" + url); + + + //调用NCC接口,将数据传给NCC + String returndata = HttpClientToDC.sendPostApi(url,token, strParm); + log.writeLog("【调用数据中台出差申请单接口返回结果result:】" + returndata); + if (!"".equals(returndata) && returndata != null) { + JSONObject jsonObject = JSONObject.parseObject(returndata); + String code = Util.null2String(jsonObject.get("code")); + log.writeLog("--------发送请求返回的code值为:" + code); + if (code.equals("1")){ + return SUCCESS; + }else{ + String msg = Util.null2String(jsonObject.get("msg")); + requestInfo.getRequestManager().setMessageid("111100"); + requestInfo.getRequestManager().setMessagecontent(msg); + return "0"; + } + }else{ + String ermsg="流程数据写入NCC调动申请单失败,未获取到接口返回结果,请联系系统管理员处理!"; + requestInfo.getRequestManager().setMessageid("111100"); + requestInfo.getRequestManager().setMessagecontent(ermsg); + return "0"; + } + }catch (Exception e){ + //返回0,调用失败 + log.writeLog("------------------------捕获到的异常是:" + e.toString()); + return "0"; + } + } +} diff --git a/src/main/youhong_ai_jitu_src/jntchina/action/OverTimeApplicantActionNew.java b/src/main/youhong_ai_jitu_src/jntchina/action/OverTimeApplicantActionNew.java new file mode 100644 index 0000000..1b00600 --- /dev/null +++ b/src/main/youhong_ai_jitu_src/jntchina/action/OverTimeApplicantActionNew.java @@ -0,0 +1,120 @@ +package jntchina.action; + + +import com.alibaba.fastjson.JSONObject; +import jntchina.util.HttpClientToDC; +import selfdev.util.base.BaseUtil; +import selfdev.util.log.LogTool; +import weaver.conn.RecordSet; +import weaver.file.Prop; +import weaver.general.Util; +import weaver.interfaces.workflow.action.BaseAction; +import weaver.soa.workflow.request.RequestInfo; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +/** + * @description: 加班申请单 + * @author: ycf + * @date: 2021/01/07 + **/ +public class OverTimeApplicantActionNew extends BaseAction { + + @Override + public String execute(RequestInfo requestInfo) { + LogTool log = new LogTool("/log/selfdev/action/hrm", true); + String requestId = requestInfo.getRequestid(); // 获取requestid + String workflowid = requestInfo.getWorkflowid(); // 获取workflowid + //获取工作流名称 + String workflowname = BaseUtil.getBaseInfoByParm("workflowname", "workflow_base", "id", workflowid, ""); + log.writeLog("---------------工作流名称-----------workflowname为:" + workflowname); + log.writeLog("--------加班申请单数据传入中台开始----requestId值为:" + requestId); + + //获取配置文件中的参数,到时候URL路径 + String mode = Prop.getPropValue("DevToDC_jntchina", "mode"); + // 服务器ip:port + String baseUrl = Prop.getPropValue("DevToDC_jntchina", mode + "_baseUrl"); + //访问路径拼接 + String url = baseUrl + "/dcoaapi/hr/work"; + //String url = "http://121.37.156.206:21005/PSIGW/RESTListeningConnector/PSFT_HR/C_WORK_APPLY.v1/"; + + //根据流程id获取主表名称 + String mainTable = RegularizationApplyForAction.getMainTable(requestId); + log.writeLog("--------获取到的表名为----:" + mainTable); + + //{ + //加班数据 + List> list = new ArrayList>(); + + RecordSet rs = new RecordSet(); + try { + String sql = "select * from " + mainTable + " where requestid='" + requestId + "'"; + rs.execute(sql); + log.writeLog("查询sql语句---------------->" + sql); + Map map = new HashMap(); + String id = ""; + while (rs.next()) { + id = rs.getString("ID"); + map.put("C_REASON", Util.null2String(rs.getString("QJYY")));//原因 + map.put("EMPLID", Util.null2String(rs.getString("TJRGH")));//申请人 + map.put("C_OA_NUM", Util.null2String(rs.getString("LCBH")));//申请单号 + map.put("overtime_type", Util.null2String(rs.getString("overtime_type")));//加班补偿类型 + } + sql = "select b.*, (select workcode from hrmresource a where a.id = b.xm) code from " + mainTable + "_dt1 b where mainid = " + id; + log.writeLog("查找加班明细:" + sql); + rs.execute(sql); + while (rs.next()) { + HashMap map2 = new HashMap(); + map2.put("EMPLID", Util.null2String(rs.getString("code"))); + //加班开始日期 + map2.put("C_START_DT", Util.null2String(rs.getString("jbksrq"))); + //加班开始时间 + map2.put("C_START_DTM", Util.null2String(rs.getString("jbkssj"))); + //加班结束时间 + map2.put("C_END_DTM", Util.null2String(rs.getString("jbjssj"))); + //加班结束日期 + map2.put("jbjsrq", Util.null2String(rs.getString("jbjsrq"))); + list.add(map2); + } + map.put("LINES", list); + + String strParm = JSONObject.toJSONString(map); + log.writeLog("---------------加班打印的Map数据为:-----------------:" + strParm); + + //获取Token + String token = HttpClientToDC.getToken(); + log.writeLog("加班申请单token------>" + token); + log.writeLog("加班申请单url------>" + url); + + + //调用NCC接口,将数据传给NCC + String returndata = HttpClientToDC.sendPostApi(url, token, strParm); + log.writeLog("【调用数据中台出差申请单接口返回结果result:】" + returndata); + if (!"".equals(returndata) && returndata != null) { + JSONObject jsonObject = JSONObject.parseObject(returndata); + String code = Util.null2String(jsonObject.getString("code")); + log.writeLog("--------发送请求返回的code值为:" + code); + if (code.equals("1")) { + return SUCCESS; + } else { + String msg = Util.null2String(jsonObject.getString("msg")); + requestInfo.getRequestManager().setMessageid("111100"); + requestInfo.getRequestManager().setMessagecontent(msg); + return "0"; + } + } else { + String ermsg = "流程数据写入NCC调动申请单失败,未获取到接口返回结果,请联系系统管理员处理!"; + requestInfo.getRequestManager().setMessageid("111100"); + requestInfo.getRequestManager().setMessagecontent(ermsg); + return "0"; + } + } catch (Exception e) { + //返回0,调用失败 + log.writeLog("------------------------捕获到的异常是:" + e.toString()); + return "0"; + } + } +} diff --git a/src/main/youhong_ai_jitu_src/jntchina/action/PayApplicationAction.java b/src/main/youhong_ai_jitu_src/jntchina/action/PayApplicationAction.java new file mode 100644 index 0000000..6de9c9e --- /dev/null +++ b/src/main/youhong_ai_jitu_src/jntchina/action/PayApplicationAction.java @@ -0,0 +1,422 @@ +package jntchina.action; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.JSONObject; +import com.alibaba.fastjson.serializer.SerializerFeature; +import com.api.lh.port.AddJournal; +import com.working.util.WorkflowUtil; + +import jntchina.entity.*; +import jntchina.util.HttpClientToDC; +import selfdev.util.base.BaseUtil; +import selfdev.util.base.TimeCommonUtil; +import selfdev.util.log.LogTool; +import weaver.conn.RecordSet; +import weaver.file.Prop; +import weaver.general.Util; +import weaver.hrm.resource.ResourceComInfo; +import weaver.interfaces.workflow.action.Action; +import weaver.soa.workflow.request.RequestInfo; +import weaver.workflow.action.BaseAction; + +import java.util.ArrayList; +import java.util.List; +import java.util.Map; +import java.util.UUID; + + +/** + * @Author Administrator + * @Description 付款申请数据写入中台生成NCC对公报销单或者对公借款单 + * @Date 2021/3/2 11:50 + */ +public class PayApplicationAction extends BaseAction { + @Override + public String execute(RequestInfo requestInfo) { + String src = requestInfo.getRequestManager().getSrc();//获取操作方式 + if (!"submit".equals(src)) { // 只有submit才执行接口 + return SUCCESS; + } + LogTool log = new LogTool("/log/selfdev/action", false); + String requestId = requestInfo.getRequestid(); // 获取requestid + log.writeLog("--------付款申请单数据传入数据中台开始----requestId值为:" + requestId); + //获取当前用户的登录账号(即工号) + String loginid=requestInfo.getRequestManager().getUser().getLoginid(); + log.writeLog("loginid-------->"+loginid); + //获取配置文件中的参数 + String mode = Prop.getPropValue("DevToDC_jntchina","mode"); + // 服务器ip:port + String baseUrl = Prop.getPropValue("DevToDC_jntchina", mode+"_baseUrl"); + String url = baseUrl+"/dcnccapi/claimForm/receiveData"; + ReimbursementOrder reimbursementOrder = new ReimbursementOrder(); + BorrowOrder borrowOrder = new BorrowOrder(); + String mainTable = WorkflowUtil.getMainTable(requestId); + String mainId = ""; + String isShowErrorMsg = "";//写入NCC失败时是否显示报错信息 + String pk_org = ""; // 报销单位 JTSDCN0001 + String fygsbm = ""; // 申请部门 + String total = ""; // 报销金额 金额由表体相应字段汇总得出 + String deptid = ""; // 部门 传输编码 + String djlxbm = "264X-Cxx-DGBXD"; // 单据类型编码 对私报销单:264X-Cxx-DSBXD 对公报销单:264X-Cxx-DGBXD + String djlxmc = "对公报销单"; // 单据类型名称 默认 对公报销单 + String djrq = TimeCommonUtil.obtainDate(0); // 单据日期 yyyy-mm-dd hh:mm:ss + String payflag = ""; // 支付状态 + String paytarget = "1"; // 收款对象 0=员工,1=供应商,2=客户,默认为供应商 + String receiver = ""; // 收款人 + String skyhzh = ""; // 收款人银行账号 + String hbbm = ""; // yonyou88", //收款人(供应商) + String custaccount= ""; //收款银行账户(供应商) + String sfyfp = ""; // 是否有发票 + String jkbxr = ""; // 借款报销人 传输编码 + String operator = ""; // 录入人 + String xm= ""; // 申请人 + String jsfs = "3"; // 结算方式 3 网银 + String fkfs = ""; // 付款方式 + String fkyhzh = ""; // 单位银行账户 传输编码 + String jobid = ""; // 项目 + String zy = ""; // 报销事由 + String kjqj = ""; // 会计期间 + String kjnd = ""; // 会计年度 + String fjzs = ""; // 附件张数 需业务人员在OA上传附件同时填写附件张数后传数据到NCC + String zyx1 = ""; // OA单据号 OA传过来,用于联查单据 + String zyx2 = ""; // 提交人 提交人姓名 + String zyx3 = ""; // OA核销单号 + String zyx5 = ""; // OARequestID + String zyx8="";//银行付款备注 + String zyx9=requestInfo.getRequestManager().getRequestname();//标题 + String tablecode = "arap_bxbusitem"; + + RecordSet rs = new RecordSet(); + try { + String sql = " select * from " + mainTable + " where requestid='" + requestId + "'"; + rs.execute(sql); + while (rs.next()) { + mainId = Util.null2String(rs.getString("id")); + isShowErrorMsg = Util.null2String(rs.getString("xrnccsbcsfts")); + xm = Util.null2String(rs.getString("xm")); // 借款报销人(取流程申请人) + sfyfp = Util.null2String(rs.getString("sfyfp")); // 是否有发票 + pk_org = Util.null2String(rs.getString("gsmc")); // 公司名称 + total = Util.null2String(rs.getString("jshjje")); // 报销金额 金额由表体相应字段汇总得出 + fygsbm = Util.null2String(rs.getString("fygsbm")); // 申请部门 +// djrq = Util.null2String(rs.getString("cjrq")); // 单据日期 yyyy-mm-dd hh:mm:ss + fkfs = Util.null2String(rs.getString("fkfs")); // 付款方式 + hbbm = Util.null2String(rs.getString("gysmc")); // 收款人,供应商编码 + custaccount = Util.null2String(rs.getString("yxhm")); // 收款人银行账号 + zyx8 = Util.null2String(rs.getString("yxfkbz")); //银行付款备注 + fkyhzh = Util.null2String(rs.getString("")); // 付款银行账户 传输编码 + zy = Util.null2String(rs.getString("fksm")); // 付款说明 + + fjzs = Util.null2String(rs.getString("fjzs")); // 附件张数 需业务人员在OA上传附件同时填写附件张数后传数据到NCC + zyx1 = Util.null2String(rs.getString("lcbh")); // OA单据号 OA传过来,用于联查单据 + zyx2 = Util.null2String(rs.getString("xm")); // 提交人 提交人姓名 + zyx3 = Util.null2String(rs.getString("")); // OA核销单号 + zyx5 = requestId; // OARequestID + + } + kjqj = djrq.substring(5,7); // 会计期间 + kjnd = djrq.substring(0,4); // 会计年度 + //根据部门ID查询部门编码 + deptid=BaseUtil.getBaseInfoByParm("departmentcode", "hrmdepartment", "id", fygsbm, ""); + //获取员工默认的组织对应的类型 + String userDefaultCompanyType=BaseUtil.getBaseInfoByParm("company_type", "v_oa_user_org_nsrsbh", "userid", xm, ""); + //获取付款单选择的组织对应的类型 + String selectCompanyType=BaseUtil.getBaseInfoByParm("company_type", "uf_businessunit", "code", pk_org, ""); + log.writeLog("userDefaultCompanyType------>" + userDefaultCompanyType); + log.writeLog("selectCompanyType------>" + selectCompanyType); + //跨组织,则说明代理区向总部申请付款 + if(!userDefaultCompanyType.equals(selectCompanyType)){ + //查询建模维护的对应关系 + String defaultDeptNo=BaseUtil.getBaseInfoByParm("mroabmbm", "uf_kzzfkdybmsz", "sqgslx", userDefaultCompanyType, " and fkgslx='"+selectCompanyType+"'"); + log.writeLog("defaultDeptNo------>" + defaultDeptNo); + if(!"".equals(defaultDeptNo)){ + deptid=defaultDeptNo; + } + } + //截取前120位 + if(zy.length()>120){ + zy=zy.substring(0,120); + } + + if("1".equals(fkfs)){ + jsfs = "0"; //现金 + } + jkbxr = new ResourceComInfo().getWorkcode(xm); //借款报销人工号(即申请人工号) + operator = loginid;//当前节点操作者 + //获取UUID + String uuid=UUID.randomUUID().toString().replace("-", "").toUpperCase(); + log.writeLog("receiver------>"+receiver); + + //查询抵扣明细 + sql = " select * from " + mainTable + "_dt1 where mainid='" + mainId + "'"; + rs.execute(sql); + while (rs.next()) { + zyx3+=Util.null2String(rs.getString("yflcbh"))+","; + } + //将预付流程编号赋值到zyx3字段中 + if(!"".equals(zyx3)){ + zyx3=zyx3.substring(0,zyx3.length()-1); + } + + //没有发票时,则对应NCC的对公借款单 + if("1".equals(sfyfp)){ + djlxbm = "263X-Cxx-DGJKD"; // 单据类型编码 + djlxmc = "对公借款单"; + tablecode = "jk_busitem"; + //url = baseUrl+"/dcoaapi/billLoan/receiveData"; + url = baseUrl+"/dcnccapi/billLoan/receiveData"; + borrowOrder.setUuid(uuid); + borrowOrder.setPk_org(pk_org); + borrowOrder.setTotal(total); + borrowOrder.setDeptid(deptid); + borrowOrder.setDjlxbm(djlxbm); + borrowOrder.setDjrq(djrq); + borrowOrder.setPayflag(payflag); + borrowOrder.setPaytarget(paytarget); + borrowOrder.setHbbm(deptid); + borrowOrder.setReceiver(receiver); + borrowOrder.setHbbm(hbbm); + borrowOrder.setSkyhzh(skyhzh); + borrowOrder.setCustaccount(custaccount); + borrowOrder.setJkbxr(jkbxr); + borrowOrder.setOperator(operator); + borrowOrder.setJsfs(jsfs); + borrowOrder.setFkyhzh(fkyhzh); + + borrowOrder.setZy(zy); + borrowOrder.setDjzt("1"); + borrowOrder.setKjqj(kjqj); + borrowOrder.setKjnd(kjnd); + borrowOrder.setZyx1(zyx1); + borrowOrder.setZyx2(zyx2); + borrowOrder.setZyx3(zyx3); + borrowOrder.setZyx5(zyx5); + borrowOrder.setZyx8(zyx8); + borrowOrder.setZyx9(zyx9); + }else{ + reimbursementOrder.setUuid(uuid); + reimbursementOrder.setPk_org(pk_org); + reimbursementOrder.setTotal(total); + reimbursementOrder.setDeptid(deptid); + reimbursementOrder.setDjlxbm(djlxbm); + reimbursementOrder.setDjrq(djrq); + reimbursementOrder.setPayflag(payflag); + reimbursementOrder.setPaytarget(paytarget); + reimbursementOrder.setReceiver(receiver); + reimbursementOrder.setHbbm(hbbm); + reimbursementOrder.setSkyhzh(skyhzh); + reimbursementOrder.setCustaccount(custaccount); + reimbursementOrder.setJkbxr(jkbxr); + reimbursementOrder.setOperator(operator); + reimbursementOrder.setJsfs(jsfs); + reimbursementOrder.setFkyhzh(fkyhzh); + reimbursementOrder.setJobid(jobid); + reimbursementOrder.setZy(zy); + reimbursementOrder.setKjqj(kjqj); + reimbursementOrder.setKjnd(kjnd); + reimbursementOrder.setFjzs(fjzs); + reimbursementOrder.setZyx1(zyx1); + reimbursementOrder.setZyx2(zyx2); + reimbursementOrder.setZyx3(zyx3); + reimbursementOrder.setZyx5(zyx5); + reimbursementOrder.setZyx8(zyx8); + reimbursementOrder.setZyx9(zyx9); + } + log.writeLog("【header数据准备完毕...】"); + + //获取OA-NCC发票映射关系表 + Map map_oafplx_nccfplcx=BaseUtil.getMapKeyValueInfoByParm("uf_oafplx_nccfplx", "", "oafplxid", "nccfplxbm"); + + //对公报销 + List reimbursementOrderBodyList = new ArrayList(); + //对公借款 + List borrowOrderBodyList = new ArrayList(); + + int rowno = 0; + rs.execute(" select b.bm as szxmid,c.INVOICECODE,c.INVOICENUMBER,c.invoicetype,a.* from " + mainTable + "_dt2 a " + + "left join uf_fylx b on to_char(a.fylx)=to_char(b.id) " + + "left join fnainvoiceledger c on a.fphm=c.id " + + "where a.mainid = " + mainId); + while (rs.next()) { + + String jobid1 = ""; // 项目 + String fycdbm = Util.null2String(rs.getString("fycdbm")); //费用承担部门 + String amount = Util.null2String(rs.getString("je")); // 付款 + String defitem36 = Util.null2o(rs.getString("fpje")); // 发票金额 + String tax_rate = Util.null2String(rs.getString("sl")); // 税率 3% + String tax_amount = Util.null2String(rs.getString("se")); // 税额 + String tni_amount = Util.null2String(rs.getString("bhsje")); // 无税金额 + String szxmid = Util.null2String(rs.getString("szxmid")); // 收支项目 0101 汽车费用 + String fpdm = Util.null2String(rs.getString("INVOICECODE")); // 发票代码 + String fphm = Util.null2String(rs.getString("INVOICENUMBER")); // 发票号码 + String invoicetype = Util.null2String(rs.getString("invoicetype")); // OA发票类型 + //NCC发票类型 + String fplxpk=Util.null2String(map_oafplx_nccfplcx.get(invoicetype)); + +// String fphmId = Util.null2String(rs.getString("fphm")); // 发票号码 +// if(!"".equals(fphmId)){ +// // 得到浏览按钮中发票号码的id,再去数据库中把发票号码和发票代码查出来 +// rsFna.execute(" select * from fnainvoiceledger where id = " + fphmId); +// while (rsFna.next()) { +// fpdm = Util.null2String(rsFna.getString("INVOICECODE")); // 发票代码 +// fphm = Util.null2String(rsFna.getString("INVOICENUMBER")); // 发票号码 +// fplxpk = Util.null2String(map_oafplx_nccfplcx.get(Util.null2String(rsFna.getString("invoicetype")))); // OA发票类型 +// } +// } + //发票金额为空时,默认等于付款金额 + if(Double.parseDouble(defitem36)==0){ + defitem36=amount; + } + + String defitem46 = Util.null2String(rs.getString("wd")); // 网点(成本中心) + String defitem45 = Util.null2String(rs.getString("gj")); // 国家 + String defitem44 = Util.null2String(rs.getString("ck")); // 仓库 + String defitem43 = Util.null2String(rs.getString("cph")); //车牌号 + String defitem42 = Util.null2String(rs.getString("id")); // OA明细行ID + //根据部门ID查询部门编码(传NCC) + String fycdbm_NCC=BaseUtil.getBaseInfoByParm("departmentcode", "hrmdepartment", "id", fycdbm, ""); + + rowno++; + + log.writeLog("----fycdbm_NCC:" + fycdbm_NCC); + log.writeLog("----amount:" + amount); + log.writeLog("----tax_rate:" + tax_rate); + log.writeLog("----tax_amount:" + tax_amount); + log.writeLog("----tni_amount:" + tni_amount); +// log.writeLog("----defitem48:" + defitem48); + + //没有发票时,则对应NCC的对公借款单 + if("1".equals(sfyfp)){ + BorrowOrderBody body = new BorrowOrderBody(); + body.setAmount(amount); + body.setTablecode(tablecode); + body.setRowno(rowno+""); + body.setSzxmid(szxmid); + body.setDefitem50(""); + body.setDefitem49(""); + body.setDefitem42(defitem42); + body.setDefitem43(defitem43); + body.setDefitem44(defitem44); + body.setDefitem45(defitem45); + body.setDefitem46(defitem46); + body.setDefitem48(fycdbm_NCC); + borrowOrderBodyList.add(body); + }else{ + ReimbursementOrderBody body = new ReimbursementOrderBody(); + body.setJobid(jobid1); + body.setDeptid(fycdbm_NCC); + body.setAmount(amount); + body.setTax_rate(tax_rate); + body.setTax_amount(tax_amount); + body.setTni_amount(tni_amount); + body.setTablecode(tablecode); + body.setRowno(rowno+""); + body.setSzxmid(szxmid); + body.setFpdm(fpdm); + body.setFphm(fphm); + body.setFplxpk(fplxpk); + body.setDefitem36(defitem36); + body.setDefitem46(defitem46); + body.setDefitem45(defitem45); + body.setDefitem44(defitem44); + body.setDefitem43(defitem43); + body.setDefitem42(defitem42); + //body.setDefitem48(fycdbm_NCC); + reimbursementOrderBodyList.add(body); + } + } + + String parm=""; + //没有发票时,则对应NCC的对公借款单 + if("1".equals(sfyfp)){ + borrowOrder.setJk_busitem(borrowOrderBodyList); +// borrowList.add(borrowOrder); + parm=JSONObject.toJSONString(borrowOrder, SerializerFeature.DisableCircularReferenceDetect); + log.writeLog(djlxmc+"准备传入中台的数据为------>" + parm); + }else{ + reimbursementOrder.setEr_busitem(reimbursementOrderBodyList); +// reimbursementList.add(reimbursementOrder); + parm=JSONObject.toJSONString(reimbursementOrder, SerializerFeature.DisableCircularReferenceDetect); + log.writeLog(djlxmc+"准备传入中台的数据为------>" + parm); + } + + + //获取TOKEN + String token = HttpClientToDC.getToken(); + log.writeLog("获取数据中台的token------>" + token); + if ("".equals(Util.null2String(token))) { + String tokenMsg="流程提交失败,未获取到数据中台接口TOKEN,请联系管理员处理!"; + //将NCC返回结果回写至OA流程表单 + rs.execute(" update " + mainTable + " set sfcgscnccfkd = 1 ,nccfhxx='" + tokenMsg.replace("'", "''") + "' where requestid = " + requestId); + AddJournal.addInfo("费用报销接口", JSON.parseObject(parm), tokenMsg, "1", requestId); + //是否需要显示报错信息 + if("yes".equals(isShowErrorMsg)){ + requestInfo.getRequestManager().setMessagecontent(tokenMsg); + return Action.FAILURE_AND_CONTINUE; + }else{ + return SUCCESS; + } + } + + //调用NCC接口,将数据传给NCC + String returndata = HttpClientToDC.sendPostApi(url,token, parm); + log.writeLog("【调用数据中台报销接口返回结果result:】" + returndata); + if (!"".equals(returndata) && returndata != null) { + JSONObject jsonObject = JSONObject.parseObject(returndata); + String success = Util.null2String(jsonObject.get("succ")); + log.writeLog("--------发送请求返回的success值为:" + success); + if ("true".equals(success)) { + JSONObject data = jsonObject.getJSONObject("data"); + String billno = Util.null2String(data.get("billno"));//NCC单号 + log.writeLog("--------发送请求返回的billno值为:" + billno); + //将NCC返回结果回写至OA流程表单 + rs.execute(" update " + mainTable + " set sfcgscnccfkd = 0 , nccfkdh = '" + billno + "',nccfhxx='' where requestid = " + requestId); + AddJournal.addInfo("费用报销接口", JSON.parseObject(parm), returndata, "0", requestId); + } else { + String message = Util.null2String(jsonObject.get("msg")); + String message2=message.replace("'", "''"); + //超出1333个字符,则只截取前面这部分 + if(message2.length()>1334){ + message2=message2.substring(0,1333); + } + //将NCC返回结果回写至OA流程表单 + rs.execute(" update " + mainTable + " set sfcgscnccfkd = 1 ,nccfhxx='" + message2 + "' where requestid = " + requestId); + AddJournal.addInfo("费用报销接口", JSON.parseObject(parm), returndata, "1", requestId); + //是否需要显示报错信息 + if("yes".equals(isShowErrorMsg)){ + requestInfo.getRequestManager().setMessagecontent("流程数据写入NCC生成"+djlxmc+"失败,失败信息:
"+message); + return Action.FAILURE_AND_CONTINUE; + }else{ + return SUCCESS; + } + } + } else { + String ermsg="流程数据写入NCC生成"+djlxmc+"失败,未获取到接口返回结果,请联系系统管理员处理!"; + AddJournal.addInfo("费用报销接口", JSON.parseObject(parm), ermsg, "1", requestId); + //将NCC返回结果回写至OA流程表单 + rs.execute(" update " + mainTable + " set sfcgscnccfkd = 1 ,nccfhxx='" + ermsg.replace("'", "''") + "' where requestid = " + requestId); + //是否需要显示报错信息 + if("yes".equals(isShowErrorMsg)){ + requestInfo.getRequestManager().setMessagecontent(ermsg); + return Action.FAILURE_AND_CONTINUE; + }else{ + return SUCCESS; + } + } + + } catch (Exception e) { + String ermsg="流程数据生成中台对公报销单/对公借款单失败!" + e.toString(); + //将NCC返回结果回写至OA流程表单 + AddJournal.addInfo("费用报销接口", new JSONObject(), ermsg, "1", requestId); + rs.execute(" update " + mainTable + " set sfcgscnccfkd = 1 ,nccfhxx='" + ermsg.replace("'", "''") + "' where requestid = " + requestId); + //是否需要显示报错信息 + if("yes".equals(isShowErrorMsg)){ + requestInfo.getRequestManager().setMessagecontent(ermsg); + return Action.FAILURE_AND_CONTINUE; + }else{ + return SUCCESS; + } + } + log.writeLog("--------付款单数据传入中台完毕----requestId值为:" + requestId); + return Action.SUCCESS; + } +} \ No newline at end of file diff --git a/src/main/youhong_ai_jitu_src/jntchina/action/PayApplicationActionNew.java b/src/main/youhong_ai_jitu_src/jntchina/action/PayApplicationActionNew.java new file mode 100644 index 0000000..275c016 --- /dev/null +++ b/src/main/youhong_ai_jitu_src/jntchina/action/PayApplicationActionNew.java @@ -0,0 +1,447 @@ +package jntchina.action; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.JSONObject; +import com.alibaba.fastjson.serializer.SerializerFeature; +import com.api.lh.port.AddJournal; +import com.working.util.WorkflowUtil; +import jntchina.entity.*; +import jntchina.util.DataBaseUtils; +import jntchina.util.HttpClientToDC; +import selfdev.util.base.BaseUtil; +import selfdev.util.base.TimeCommonUtil; +import selfdev.util.log.LogTool; +import weaver.conn.RecordSet; +import weaver.file.Prop; +import weaver.general.Util; +import weaver.hrm.resource.ResourceComInfo; +import weaver.interfaces.workflow.action.Action; +import weaver.soa.workflow.request.RequestInfo; +import weaver.workflow.action.BaseAction; + +import java.util.ArrayList; +import java.util.List; +import java.util.Map; +import java.util.UUID; + + +/** + * @Author louh + * @Description 付款申请数据写入中台生成NCC对公报销单或者对公借款单, 添加抵扣明细数据 + * @Date 2022/5/9 16:00 + * @Version 1.0 + */ +public class PayApplicationActionNew extends BaseAction { + @Override + public String execute(RequestInfo requestInfo) { + String src = requestInfo.getRequestManager().getSrc();//获取操作方式 + if (!"submit".equals(src)) { // 只有submit才执行接口 + return SUCCESS; + } + LogTool log = new LogTool("/log/selfdev/action", false); + String requestId = requestInfo.getRequestid(); // 获取requestid + log.writeLog("--------付款申请单数据传入数据中台开始----requestId值为:" + requestId); + //获取当前用户的登录账号(即工号) + String loginid=requestInfo.getRequestManager().getUser().getLoginid(); + log.writeLog("loginid-------->"+loginid); + //获取配置文件中的参数 + String mode = Prop.getPropValue("DevToDC_jntchina","mode"); + // 服务器ip:port + String baseUrl = Prop.getPropValue("DevToDC_jntchina", mode+"_baseUrl"); + String url = baseUrl+"/dcnccapi/claimForm/receiveData"; + ReimbursementOrder reimbursementOrder = new ReimbursementOrder(); + BorrowOrder borrowOrder = new BorrowOrder(); + String mainTable = WorkflowUtil.getMainTable(requestId); + String mainId = ""; + String isShowErrorMsg = "";//写入NCC失败时是否显示报错信息 + String pk_org = ""; // 报销单位 JTSDCN0001 + String fygsbm = ""; // 申请部门 + String total = ""; // 报销金额 金额由表体相应字段汇总得出 + String deptid = ""; // 部门 传输编码 + String djlxbm = "264X-Cxx-DGBXD"; // 单据类型编码 对私报销单:264X-Cxx-DSBXD 对公报销单:264X-Cxx-DGBXD + String djlxmc = "对公报销单"; // 单据类型名称 默认 对公报销单 + String djrq = TimeCommonUtil.obtainDate(0); // 单据日期 yyyy-mm-dd hh:mm:ss + String payflag = ""; // 支付状态 + String paytarget = "1"; // 收款对象 0=员工,1=供应商,2=客户,默认为供应商 + String receiver = ""; // 收款人 + String skyhzh = ""; // 收款人银行账号 + String hbbm = ""; // yonyou88", //收款人(供应商) + String custaccount= ""; //收款银行账户(供应商) + String sfyfp = ""; // 是否有发票 + String jkbxr = ""; // 借款报销人 传输编码 + String operator = ""; // 录入人 + String xm= ""; // 申请人 + String jsfs = "3"; // 结算方式 3 网银 + String fkfs = ""; // 付款方式 + String fkyhzh = ""; // 单位银行账户 传输编码 + String jobid = ""; // 项目 + String zy = ""; // 报销事由 + String kjqj = ""; // 会计期间 + String kjnd = ""; // 会计年度 + String fjzs = ""; // 附件张数 需业务人员在OA上传附件同时填写附件张数后传数据到NCC + String zyx1 = ""; // OA单据号 OA传过来,用于联查单据 + String zyx2 = ""; // 提交人 提交人姓名 + String zyx3 = ""; // OA核销单号 + String zyx5 = ""; // OARequestID + String zyx8="";//银行付款备注 + String zyx9=requestInfo.getRequestManager().getRequestname();//标题 + String tablecode = "arap_bxbusitem"; + + RecordSet rs = new RecordSet(); + try { + String sql = " select * from " + mainTable + " where requestid='" + requestId + "'"; + rs.execute(sql); + while (rs.next()) { + mainId = Util.null2String(rs.getString("id")); + isShowErrorMsg = Util.null2String(rs.getString("xrnccsbcsfts")); + xm = Util.null2String(rs.getString("xm")); // 借款报销人(取流程申请人) + sfyfp = Util.null2String(rs.getString("sfyfp")); // 是否有发票 + pk_org = Util.null2String(rs.getString("gsmc")); // 公司名称 + total = Util.null2String(rs.getString("jshjje")); // 报销金额 金额由表体相应字段汇总得出 + fygsbm = Util.null2String(rs.getString("fygsbm")); // 申请部门 +// djrq = Util.null2String(rs.getString("cjrq")); // 单据日期 yyyy-mm-dd hh:mm:ss + fkfs = Util.null2String(rs.getString("fkfs")); // 付款方式 + hbbm = Util.null2String(rs.getString("gysmc")); // 收款人,供应商编码 + custaccount = Util.null2String(rs.getString("yxhm")); // 收款人银行账号 + zyx8 = Util.null2String(rs.getString("yxfkbz")); //银行付款备注 + fkyhzh = Util.null2String(rs.getString("")); // 付款银行账户 传输编码 + zy = Util.null2String(rs.getString("fksm")); // 付款说明 + + fjzs = Util.null2String(rs.getString("fjzs")); // 附件张数 需业务人员在OA上传附件同时填写附件张数后传数据到NCC + zyx1 = Util.null2String(rs.getString("lcbh")); // OA单据号 OA传过来,用于联查单据 + zyx2 = Util.null2String(rs.getString("xm")); // 提交人 提交人姓名 + zyx3 = Util.null2String(rs.getString("")); // OA核销单号 + zyx5 = requestId; // OARequestID + + } + kjqj = djrq.substring(5,7); // 会计期间 + kjnd = djrq.substring(0,4); // 会计年度 + //根据部门ID查询部门编码 + deptid=BaseUtil.getBaseInfoByParm("departmentcode", "hrmdepartment", "id", fygsbm, ""); + //获取员工默认的组织对应的类型 + String userDefaultCompanyType=BaseUtil.getBaseInfoByParm("company_type", "v_oa_user_org_nsrsbh", "userid", xm, ""); + //获取付款单选择的组织对应的类型 + String selectCompanyType=BaseUtil.getBaseInfoByParm("company_type", "uf_businessunit", "code", pk_org, ""); + log.writeLog("userDefaultCompanyType------>" + userDefaultCompanyType); + log.writeLog("selectCompanyType------>" + selectCompanyType); + //跨组织,则说明代理区向总部申请付款 + if(!userDefaultCompanyType.equals(selectCompanyType)){ + //查询建模维护的对应关系 + String defaultDeptNo=BaseUtil.getBaseInfoByParm("mroabmbm", "uf_kzzfkdybmsz", "sqgslx", userDefaultCompanyType, " and fkgslx='"+selectCompanyType+"'"); + log.writeLog("defaultDeptNo------>" + defaultDeptNo); + if(!"".equals(defaultDeptNo)){ + deptid=defaultDeptNo; + } + } + //截取前120位 + if(zy.length()>120){ + zy=zy.substring(0,120); + } + //标题截取前150位 + if (zyx9.length() > 150){ + zyx9 = zyx9.substring(0, 150); + } + if("1".equals(fkfs)){ + jsfs = "0"; //现金 + } + jkbxr = new ResourceComInfo().getWorkcode(xm); //借款报销人工号(即申请人工号) + operator = loginid;//当前节点操作者 + //获取UUID + String uuid=UUID.randomUUID().toString().replace("-", "").toUpperCase(); + log.writeLog("receiver------>"+receiver); + + //查询抵扣明细 + sql = " select * from " + mainTable + "_dt1 where mainid='" + mainId + "'"; + rs.execute(sql); + while (rs.next()) { + zyx3+=Util.null2String(rs.getString("yflcbh"))+","; + } + //将预付流程编号赋值到zyx3字段中 + if(!"".equals(zyx3)){ + zyx3=zyx3.substring(0,zyx3.length()-1); + } + + //没有发票时,则对应NCC的对公借款单 + if("1".equals(sfyfp)){ + djlxbm = "263X-Cxx-DGJKD"; // 单据类型编码 + djlxmc = "对公借款单"; + tablecode = "jk_busitem"; + //url = baseUrl+"/dcoaapi/billLoan/receiveData"; + url = baseUrl+"/dcnccapi/billLoan/receiveData"; + borrowOrder.setUuid(uuid); + borrowOrder.setPk_org(pk_org); + borrowOrder.setTotal(total); + borrowOrder.setDeptid(deptid); + borrowOrder.setDjlxbm(djlxbm); + borrowOrder.setDjrq(djrq); + borrowOrder.setPayflag(payflag); + borrowOrder.setPaytarget(paytarget); + borrowOrder.setHbbm(deptid); + borrowOrder.setReceiver(receiver); + borrowOrder.setHbbm(hbbm); + borrowOrder.setSkyhzh(skyhzh); + borrowOrder.setCustaccount(custaccount); + borrowOrder.setJkbxr(jkbxr); + borrowOrder.setOperator(operator); + borrowOrder.setJsfs(jsfs); + borrowOrder.setFkyhzh(fkyhzh); + + borrowOrder.setZy(zy); + borrowOrder.setDjzt("1"); + borrowOrder.setKjqj(kjqj); + borrowOrder.setKjnd(kjnd); + borrowOrder.setZyx1(zyx1); + borrowOrder.setZyx2(zyx2); + borrowOrder.setZyx3(zyx3); + borrowOrder.setZyx5(zyx5); + borrowOrder.setZyx8(zyx8); + borrowOrder.setZyx9(zyx9); + }else{ + reimbursementOrder.setUuid(uuid); + reimbursementOrder.setPk_org(pk_org); + reimbursementOrder.setTotal(total); + reimbursementOrder.setDeptid(deptid); + reimbursementOrder.setDjlxbm(djlxbm); + reimbursementOrder.setDjrq(djrq); + reimbursementOrder.setPayflag(payflag); + reimbursementOrder.setPaytarget(paytarget); + reimbursementOrder.setReceiver(receiver); + reimbursementOrder.setHbbm(hbbm); + reimbursementOrder.setSkyhzh(skyhzh); + reimbursementOrder.setCustaccount(custaccount); + reimbursementOrder.setJkbxr(jkbxr); + reimbursementOrder.setOperator(operator); + reimbursementOrder.setJsfs(jsfs); + reimbursementOrder.setFkyhzh(fkyhzh); + reimbursementOrder.setJobid(jobid); + reimbursementOrder.setZy(zy); + reimbursementOrder.setKjqj(kjqj); + reimbursementOrder.setKjnd(kjnd); + reimbursementOrder.setFjzs(fjzs); + reimbursementOrder.setZyx1(zyx1); + reimbursementOrder.setZyx2(zyx2); + reimbursementOrder.setZyx3(zyx3); + reimbursementOrder.setZyx5(zyx5); + reimbursementOrder.setZyx8(zyx8); + reimbursementOrder.setZyx9(zyx9); + } + log.writeLog("【header数据准备完毕...】"); + + //获取OA-NCC发票映射关系表 + Map map_oafplx_nccfplcx=BaseUtil.getMapKeyValueInfoByParm("uf_oafplx_nccfplx", "", "oafplxid", "nccfplxbm"); + + //对公报销 + List reimbursementOrderBodyList = new ArrayList(); + List erBxcontrasts = new ArrayList<>(); + //对公借款 + List borrowOrderBodyList = new ArrayList(); + + int rowno = 0; + rs.execute(" select b.bm as szxmid,c.INVOICECODE,c.INVOICENUMBER,c.invoicetype,a.* from " + mainTable + "_dt2 a " + + "left join uf_fylx b on to_char(a.fylx)=to_char(b.id) " + + "left join fnainvoiceledger c on a.fphm=c.id " + + "where a.mainid = " + mainId); + while (rs.next()) { + + String jobid1 = ""; // 项目 + String fycdbm = Util.null2String(rs.getString("fycdbm")); //费用承担部门 + String amount = Util.null2String(rs.getString("je")); // 付款 + String defitem36 = Util.null2o(rs.getString("fpje")); // 发票金额 + String tax_rate = Util.null2String(rs.getString("sl")); // 税率 3% + String tax_amount = Util.null2String(rs.getString("se")); // 税额 + String tni_amount = Util.null2String(rs.getString("bhsje")); // 无税金额 + String szxmid = Util.null2String(rs.getString("szxmid")); // 收支项目 0101 汽车费用 + String fpdm = Util.null2String(rs.getString("INVOICECODE")); // 发票代码 + String fphm = Util.null2String(rs.getString("INVOICENUMBER")); // 发票号码 + String invoicetype = Util.null2String(rs.getString("invoicetype")); // OA发票类型 + //NCC发票类型 + String fplxpk=Util.null2String(map_oafplx_nccfplcx.get(invoicetype)); + +// String fphmId = Util.null2String(rs.getString("fphm")); // 发票号码 +// if(!"".equals(fphmId)){ +// // 得到浏览按钮中发票号码的id,再去数据库中把发票号码和发票代码查出来 +// rsFna.execute(" select * from fnainvoiceledger where id = " + fphmId); +// while (rsFna.next()) { +// fpdm = Util.null2String(rsFna.getString("INVOICECODE")); // 发票代码 +// fphm = Util.null2String(rsFna.getString("INVOICENUMBER")); // 发票号码 +// fplxpk = Util.null2String(map_oafplx_nccfplcx.get(Util.null2String(rsFna.getString("invoicetype")))); // OA发票类型 +// } +// } + //发票金额为空时,默认等于付款金额 + if(Double.parseDouble(defitem36)==0){ + defitem36=amount; + } + + String defitem46 = Util.null2String(rs.getString("wd")); // 网点(成本中心) + String defitem45 = Util.null2String(rs.getString("gj")); // 国家 + String defitem44 = Util.null2String(rs.getString("ck")); // 仓库 + String defitem43 = Util.null2String(rs.getString("cph")); //车牌号 + String defitem42 = Util.null2String(rs.getString("id")); // OA明细行ID + //根据部门ID查询部门编码(传NCC) + String fycdbm_NCC=BaseUtil.getBaseInfoByParm("departmentcode", "hrmdepartment", "id", fycdbm, ""); + + rowno++; + + log.writeLog("----fycdbm_NCC:" + fycdbm_NCC); + log.writeLog("----amount:" + amount); + log.writeLog("----tax_rate:" + tax_rate); + log.writeLog("----tax_amount:" + tax_amount); + log.writeLog("----tni_amount:" + tni_amount); +// log.writeLog("----defitem48:" + defitem48); + + //没有发票时,则对应NCC的对公借款单 + if("1".equals(sfyfp)){ + BorrowOrderBody body = new BorrowOrderBody(); + body.setAmount(amount); + body.setTablecode(tablecode); + body.setRowno(rowno+""); + body.setSzxmid(szxmid); + body.setDefitem50(""); + body.setDefitem49(""); + body.setDefitem42(defitem42); + body.setDefitem43(defitem43); + body.setDefitem44(defitem44); + body.setDefitem45(defitem45); + body.setDefitem46(defitem46); + body.setDefitem48(fycdbm_NCC); + borrowOrderBodyList.add(body); + }else{ + ReimbursementOrderBody body = new ReimbursementOrderBody(); + body.setJobid(jobid1); + body.setDeptid(fycdbm_NCC); + body.setAmount(amount); + body.setTax_rate(tax_rate); + body.setTax_amount(tax_amount); + body.setTni_amount(tni_amount); + body.setTablecode(tablecode); + body.setRowno(rowno+""); + body.setSzxmid(szxmid); + body.setFpdm(fpdm); + body.setFphm(fphm); + body.setFplxpk(fplxpk); + body.setDefitem36(defitem36); + body.setDefitem46(defitem46); + body.setDefitem45(defitem45); + body.setDefitem44(defitem44); + body.setDefitem43(defitem43); + body.setDefitem42(defitem42); + //body.setDefitem48(fycdbm_NCC); + reimbursementOrderBodyList.add(body); + } + } + + String parm=""; + //没有发票时,则对应NCC的对公借款单 + if("1".equals(sfyfp)){ + borrowOrder.setJk_busitem(borrowOrderBodyList); +// borrowList.add(borrowOrder); + parm=JSONObject.toJSONString(borrowOrder, SerializerFeature.DisableCircularReferenceDetect); + log.writeLog(djlxmc+"准备传入中台的数据为------>" + parm); + }else{ + RecordSet rs4 = new RecordSet(); + String sql1 = "select * from " + mainTable + "_dt1 where mainid = " + mainId; + log.writeLog("查询当前单据是否有抵扣信息sql-----> " + sql1); + rs.execute(sql1); + while(rs.next()){ + String yfkqptzmxid = Util.null2String(rs.getString("yfkqptzmxid")); //预付欠票台账id + String yfklcmxid = Util.null2String(rs.getString("yfklcmxid")); //预付款流程明细id + String sql2 = "select fylx from uf_fksqyfb_dt1 where id = " + yfkqptzmxid; + String fylx = ""; + rs4.execute(sql2); + if(rs4.next()){ + fylx = Util.null2String(rs4.getString("fylx")); + } + fylx = DataBaseUtils.getFirstValue("select BM from uf_fylx where id = " + fylx); + String nccdh = Util.null2String(rs.getString("nccdh"));//ncc单号 + String bcdjje = Util.null2o(rs.getString("bcdjje")); //本次抵扣金额 + ErBxcontrast erBxcontrast = new ErBxcontrast(nccdh, fylx, bcdjje, yfklcmxid, yfkqptzmxid); + erBxcontrasts.add(erBxcontrast); + } + reimbursementOrder.setEr_busitem(reimbursementOrderBodyList); + reimbursementOrder.setEr_bxcontrast(erBxcontrasts); +// reimbursementList.add(reimbursementOrder); + parm=JSONObject.toJSONString(reimbursementOrder, SerializerFeature.DisableCircularReferenceDetect); + log.writeLog(djlxmc+"准备传入中台的数据为------>" + parm); + } + + + //获取TOKEN + String token = HttpClientToDC.getToken(); + log.writeLog("获取数据中台的token------>" + token); + if ("".equals(Util.null2String(token))) { + String tokenMsg="流程提交失败,未获取到数据中台接口TOKEN,请联系管理员处理!"; + //将NCC返回结果回写至OA流程表单 + rs.execute(" update " + mainTable + " set sfcgscnccfkd = 1 ,nccfhxx='" + tokenMsg.replace("'", "''") + "' where requestid = " + requestId); + AddJournal.addInfo("费用报销接口", JSON.parseObject(parm), tokenMsg, "1", requestId); + //是否需要显示报错信息 + if("yes".equals(isShowErrorMsg)){ + requestInfo.getRequestManager().setMessagecontent(tokenMsg); + return Action.FAILURE_AND_CONTINUE; + }else{ + return SUCCESS; + } + } + + //调用NCC接口,将数据传给NCC + String returndata = HttpClientToDC.sendPostApi(url,token, parm); + log.writeLog("【调用数据中台报销接口返回结果result:】" + returndata); + if (!"".equals(returndata) && returndata != null) { + JSONObject jsonObject = JSONObject.parseObject(returndata); + String success = Util.null2String(jsonObject.get("succ")); + log.writeLog("--------发送请求返回的success值为:" + success); + if ("true".equals(success)) { + JSONObject data = jsonObject.getJSONObject("data"); + String billno = Util.null2String(data.get("billno"));//NCC单号 + log.writeLog("--------发送请求返回的billno值为:" + billno); + //将NCC返回结果回写至OA流程表单 + rs.execute(" update " + mainTable + " set sfcgscnccfkd = 0 , nccfkdh = '" + billno + "',nccfhxx='' where requestid = " + requestId); + AddJournal.addInfo("费用报销接口", JSON.parseObject(parm), returndata, "0", requestId); + } else { + String message = Util.null2String(jsonObject.get("msg")); + String message2=message.replace("'", "''"); + //超出1333个字符,则只截取前面这部分 + if(message2.length()>1334){ + message2=message2.substring(0,1333); + } + //将NCC返回结果回写至OA流程表单 + rs.execute(" update " + mainTable + " set sfcgscnccfkd = 1 ,nccfhxx='" + message2 + "' where requestid = " + requestId); + AddJournal.addInfo("费用报销接口", JSON.parseObject(parm), returndata, "1", requestId); + //是否需要显示报错信息 + if("yes".equals(isShowErrorMsg)){ + requestInfo.getRequestManager().setMessagecontent("流程数据写入NCC生成"+djlxmc+"失败,失败信息:
"+message); + return Action.FAILURE_AND_CONTINUE; + }else{ + return SUCCESS; + } + } + } else { + String ermsg="流程数据写入NCC生成"+djlxmc+"失败,未获取到接口返回结果,请联系系统管理员处理!"; + AddJournal.addInfo("费用报销接口", JSON.parseObject(parm), ermsg, "1", requestId); + //将NCC返回结果回写至OA流程表单 + rs.execute(" update " + mainTable + " set sfcgscnccfkd = 1 ,nccfhxx='" + ermsg.replace("'", "''") + "' where requestid = " + requestId); + //是否需要显示报错信息 + if("yes".equals(isShowErrorMsg)){ + requestInfo.getRequestManager().setMessagecontent(ermsg); + return Action.FAILURE_AND_CONTINUE; + }else{ + return SUCCESS; + } + } + + } catch (Exception e) { + String ermsg="流程数据生成中台对公报销单/对公借款单失败!" + e.toString(); + //将NCC返回结果回写至OA流程表单 + AddJournal.addInfo("费用报销接口", new JSONObject(), ermsg, "1", requestId); + rs.execute(" update " + mainTable + " set sfcgscnccfkd = 1 ,nccfhxx='" + ermsg.replace("'", "''") + "' where requestid = " + requestId); + //是否需要显示报错信息 + if("yes".equals(isShowErrorMsg)){ + requestInfo.getRequestManager().setMessagecontent(ermsg); + return Action.FAILURE_AND_CONTINUE; + }else{ + return SUCCESS; + } + } + log.writeLog("--------付款单数据传入中台完毕----requestId值为:" + requestId); + return Action.SUCCESS; + } +} \ No newline at end of file diff --git a/src/main/youhong_ai_jitu_src/jntchina/action/PayApplicationActionYY.java b/src/main/youhong_ai_jitu_src/jntchina/action/PayApplicationActionYY.java new file mode 100644 index 0000000..11d9d64 --- /dev/null +++ b/src/main/youhong_ai_jitu_src/jntchina/action/PayApplicationActionYY.java @@ -0,0 +1,431 @@ +package jntchina.action; + +import com.alibaba.fastjson.JSONObject; +import com.alibaba.fastjson.serializer.SerializerFeature; +import com.working.util.WorkflowUtil; +import jntchina.entity.BorrowOrderYY; +import jntchina.entity.BorrowOrderBodyYY; +import jntchina.entity.ReimbursementOrderYY; +import jntchina.entity.ReimbursementOrderBodyYY; +import jntchina.util.HttpClientToDC; +import selfdev.util.base.BaseUtil; +import selfdev.util.base.TimeCommonUtil; +import selfdev.util.log.LogTool; +import weaver.conn.RecordSet; +import weaver.file.Prop; +import weaver.general.Util; +import weaver.hrm.resource.ResourceComInfo; +import weaver.interfaces.workflow.action.Action; +import weaver.soa.workflow.request.RequestInfo; +import weaver.workflow.action.BaseAction; + +import java.util.ArrayList; +import java.util.List; +import java.util.Map; +import java.util.UUID; + + +/** + * @Author Administrator + * @Description 付款申请数据写入中台生成NCC对公报销单或者对公借款单(紜毅)1 + * @Date 2021/3/2 11:50 + */ +public class PayApplicationActionYY extends BaseAction { + @Override + public String execute(RequestInfo requestInfo) { + String src = requestInfo.getRequestManager().getSrc();//获取操作方式 + if (!"submit".equals(src)) { // 只有submit才执行接口 + return SUCCESS; + } + LogTool log = new LogTool("/log/selfdev/action", false); + String requestId = requestInfo.getRequestid(); // 获取requestid + log.writeLog("--------付款申请单数据传入数据中台开始----requestId值为:" + requestId); + //获取当前用户的登录账号(即工号) + String loginid=requestInfo.getRequestManager().getUser().getLoginid(); + log.writeLog("loginid-------->"+loginid); + //获取配置文件中的参数 + String mode = Prop.getPropValue("DevToDC_jntchina","mode"); + // 服务器ip:port + String baseUrl = Prop.getPropValue("DevToDC_jntchina", mode+"_baseUrl"); + String url = baseUrl+"/dcnccapi/claimForm/receiveData"; + ReimbursementOrderYY reimbursementOrder = new ReimbursementOrderYY(); + BorrowOrderYY borrowOrder = new BorrowOrderYY(); + String mainTable = WorkflowUtil.getMainTable(requestId); + String mainId = ""; + String isShowErrorMsg = "";//写入NCC失败时是否显示报错信息 + String pk_org = ""; // 报销单位 JTSDCN0001 + String fygsbm = ""; // 申请部门 + String total = ""; // 报销金额 金额由表体相应字段汇总得出 + String deptid = ""; // 部门 传输编码 + String djlxbm = "264X-Cxx-DGBXD"; // 单据类型编码 对私报销单:264X-Cxx-DSBXD 对公报销单:264X-Cxx-DGBXD + String djlxmc = "对公报销单"; // 单据类型名称 默认 对公报销单 + String djrq = TimeCommonUtil.obtainDate(0); // 单据日期 yyyy-mm-dd hh:mm:ss + String payflag = ""; // 支付状态 + String paytarget = "1"; // 收款对象 0=员工,1=供应商,2=客户,默认为供应商 + String receiver = ""; // 收款人 + String skyhzh = ""; // 收款人银行账号 + String hbbm = ""; // yonyou88", //收款人(供应商) + String custaccount= ""; //收款银行账户(供应商) + String sfyfp = ""; // 是否有发票 + String jkbxr = ""; // 借款报销人 传输编码 + String operator = ""; // 录入人 + String xm= ""; // 申请人 + String jsfs = "3"; // 结算方式 3 网银 + String fkfs = ""; // 付款方式 + String fkyhzh = ""; // 单位银行账户 传输编码 + String jobid = ""; // 项目 + String zy = ""; // 报销事由 + String kjqj = ""; // 会计期间 + String kjnd = ""; // 会计年度 + String fjzs = ""; // 附件张数 需业务人员在OA上传附件同时填写附件张数后传数据到NCC + String zyx1 = ""; // OA单据号 OA传过来,用于联查单据 + String zyx2 = ""; // 提交人 提交人姓名 + String zyx3 = ""; // OA核销单号 + String zyx5 = ""; // OARequestID + String zyx8="";//银行付款备注 +// String zyx9=requestInfo.getRequestManager().getRequestname();//标题 + String zyx9=requestInfo.getRequestManager().getRequestname().length()>140?requestInfo.getRequestManager().getRequestname().substring(0,140):requestInfo.getRequestManager().getRequestname();//标题 + + String tablecode = "arap_bxbusitem"; + + RecordSet rs = new RecordSet(); + try { + String sql = " select * from " + mainTable + " where requestid='" + requestId + "'"; + rs.execute(sql); + while (rs.next()) { + mainId = Util.null2String(rs.getString("id")); + isShowErrorMsg = Util.null2String(rs.getString("xrnccsbcsfts")); + xm = Util.null2String(rs.getString("xm")); // 借款报销人(取流程申请人) + sfyfp = Util.null2String(rs.getString("sfyfp")); // 是否有发票 + pk_org = Util.null2String(rs.getString("gsmc")); // 公司名称 + total = Util.null2String(rs.getString("jshjje")); // 报销金额 金额由表体相应字段汇总得出 + fygsbm = Util.null2String(rs.getString("sqrbm")); // 申请部门 +// djrq = Util.null2String(rs.getString("cjrq")); // 单据日期 yyyy-mm-dd hh:mm:ss + fkfs = Util.null2String(rs.getString("fkfs")); // 付款方式 + hbbm = Util.null2String(rs.getString("gysmc")); // 收款人,供应商编码 + custaccount = Util.null2String(rs.getString("yxhm")); // 收款人银行账号 + zyx8 = Util.null2String(rs.getString("yxfkbz")); //银行付款备注 + fkyhzh = Util.null2String(rs.getString("")); // 付款银行账户 传输编码 + zy = Util.null2String(rs.getString("fksm")); // 付款说明 + + fjzs = Util.null2String(rs.getString("fjzs")); // 附件张数 需业务人员在OA上传附件同时填写附件张数后传数据到NCC + zyx1 = Util.null2String(rs.getString("lcbh")); // OA单据号 OA传过来,用于联查单据 + zyx2 = Util.null2String(rs.getString("xm")); // 提交人 提交人姓名 + zyx3 = Util.null2String(rs.getString("")); // OA核销单号 + zyx5 = requestId; // OARequestID + + } + kjqj = djrq.substring(5,7); // 会计期间 + kjnd = djrq.substring(0,4); // 会计年度 + //根据部门ID查询部门编码 +// deptid=BaseUtil.getBaseInfoByParm("BM", "uf_dept_ncc", "id", fygsbm, ""); + deptid=BaseUtil.getBaseInfoByParm("departmentcode", "hrmdepartment", "id", fygsbm, ""); + //获取员工默认的组织对应的类型 + String userDefaultCompanyType=BaseUtil.getBaseInfoByParm("company_type", "v_oa_user_org_nsrsbh", "userid", xm, ""); + //获取付款单选择的组织对应的类型 + String selectCompanyType=BaseUtil.getBaseInfoByParm("company_type", "uf_businessunit", "code", pk_org, ""); + log.writeLog("userDefaultCompanyType------>" + userDefaultCompanyType); + log.writeLog("selectCompanyType------>" + selectCompanyType); + //跨组织,则说明代理区向总部申请付款 + if(!userDefaultCompanyType.equals(selectCompanyType)){ + //查询建模维护的对应关系 + String defaultDeptNo=BaseUtil.getBaseInfoByParm("mroabmbm", "uf_kzzfkdybmsz", "sqgslx", userDefaultCompanyType, " and fkgslx='"+selectCompanyType+"'"); + log.writeLog("defaultDeptNo------>" + defaultDeptNo); + if(!"".equals(defaultDeptNo)){ + deptid=defaultDeptNo; + } + } + //截取前120位 + if(zy.length()>120){ + zy=zy.substring(0,120); + } + + if("1".equals(fkfs)){ + jsfs = "0"; //现金 + } + jkbxr = new ResourceComInfo().getWorkcode(xm); //借款报销人工号(即申请人工号) + operator = loginid;//当前节点操作者 + //获取UUID + String uuid=UUID.randomUUID().toString().replace("-", "").toUpperCase(); + log.writeLog("receiver------>"+receiver); + + //查询抵扣明细 + sql = " select * from " + mainTable + "_dt1 where mainid='" + mainId + "'"; + rs.execute(sql); + while (rs.next()) { + zyx3+=Util.null2String(rs.getString("yflcbh"))+","; + } + //将预付流程编号赋值到zyx3字段中 + if(!"".equals(zyx3)){ + zyx3=zyx3.substring(0,zyx3.length()-1); + } + + //没有发票时,则对应NCC的对公借款单 + if("1".equals(sfyfp)){ + djlxbm = "263X-Cxx-DGJKD"; // 单据类型编码 + djlxmc = "对公借款单"; + tablecode = "jk_busitem"; + //url = baseUrl+"/dcoaapi/billLoan/receiveData"; + url = baseUrl+"/dcnccapi/billLoan/receiveData"; + borrowOrder.setUuid(uuid); + borrowOrder.setPk_org(pk_org); + borrowOrder.setTotal(total); + borrowOrder.setDeptid(deptid); + borrowOrder.setDjlxbm(djlxbm); + borrowOrder.setDjrq(djrq); + borrowOrder.setPayflag(payflag); + borrowOrder.setPaytarget(paytarget); + borrowOrder.setHbbm(deptid); + borrowOrder.setReceiver(receiver); + borrowOrder.setHbbm(hbbm); + borrowOrder.setSkyhzh(skyhzh); + borrowOrder.setCustaccount(custaccount); + borrowOrder.setJkbxr(jkbxr); + borrowOrder.setOperator(operator); + borrowOrder.setJsfs(jsfs); + borrowOrder.setFkyhzh(fkyhzh); + + borrowOrder.setZy(zy); + borrowOrder.setDjzt("1"); + borrowOrder.setKjqj(kjqj); + borrowOrder.setKjnd(kjnd); + borrowOrder.setZyx1(zyx1); + borrowOrder.setZyx2(zyx2); + borrowOrder.setZyx3(zyx3); + borrowOrder.setZyx5(zyx5); + borrowOrder.setZyx8(zyx8); + borrowOrder.setZyx9(zyx9); +// borrowOrder.setDeptidIsNeedConvert("no"); + }else{ + reimbursementOrder.setUuid(uuid); + reimbursementOrder.setPk_org(pk_org); + reimbursementOrder.setTotal(total); + reimbursementOrder.setDeptid(deptid); + reimbursementOrder.setDjlxbm(djlxbm); + reimbursementOrder.setDjrq(djrq); + reimbursementOrder.setPayflag(payflag); + reimbursementOrder.setPaytarget(paytarget); + reimbursementOrder.setReceiver(receiver); + reimbursementOrder.setHbbm(hbbm); + reimbursementOrder.setSkyhzh(skyhzh); + reimbursementOrder.setCustaccount(custaccount); + reimbursementOrder.setJkbxr(jkbxr); + reimbursementOrder.setOperator(operator); + reimbursementOrder.setJsfs(jsfs); + reimbursementOrder.setFkyhzh(fkyhzh); + reimbursementOrder.setJobid(jobid); + reimbursementOrder.setZy(zy); + reimbursementOrder.setKjqj(kjqj); + reimbursementOrder.setKjnd(kjnd); + reimbursementOrder.setFjzs(fjzs); + reimbursementOrder.setZyx1(zyx1); + reimbursementOrder.setZyx2(zyx2); + reimbursementOrder.setZyx3(zyx3); + reimbursementOrder.setZyx5(zyx5); + reimbursementOrder.setZyx8(zyx8); + reimbursementOrder.setZyx9(zyx9); +// reimbursementOrder.setDeptidIsNeedConvert("no"); + } + log.writeLog("【header数据准备完毕...】"); + + //获取OA-NCC发票映射关系表 + Map map_oafplx_nccfplcx=BaseUtil.getMapKeyValueInfoByParm("uf_oafplx_nccfplx", "", "oafplxid", "nccfplxbm"); + + //对公报销 + List reimbursementOrderBodyList = new ArrayList(); + //对公借款 + List borrowOrderBodyList = new ArrayList(); + int rowno = 0; + rs.execute(" select b.bm as szxmid,c.INVOICECODE,c.INVOICENUMBER,c.invoicetype,a.* from " + mainTable + "_dt2 a " + + "left join uf_fylx b on to_char(a.fylx)=to_char(b.id) " + + "left join fnainvoiceledger c on a.fphm=c.id " + + "where a.mainid = " + mainId); + while (rs.next()) { + + String jobid1 = ""; // 项目 + String fycdbm = Util.null2String(rs.getString("fycdbm")); //费用承担部门 + String amount = Util.null2String(rs.getString("je")); // 付款 + String defitem36 = Util.null2o(rs.getString("fpje")); // 发票金额 + String tax_rate = Util.null2String(rs.getString("sl")); // 税率 3% + String tax_amount = Util.null2String(rs.getString("se")); // 税额 + String tni_amount = Util.null2String(rs.getString("bhsje")); // 无税金额 + String szxmid = Util.null2String(rs.getString("szxmid")); // 收支项目 0101 汽车费用 + String fpdm = Util.null2String(rs.getString("INVOICECODE")); // 发票代码 + String fphm = Util.null2String(rs.getString("INVOICENUMBER")); // 发票号码 + String invoicetype = Util.null2String(rs.getString("invoicetype")); // OA发票类型 + //NCC发票类型 + String fplxpk=Util.null2String(map_oafplx_nccfplcx.get(invoicetype)); + +// String fphmId = Util.null2String(rs.getString("fphm")); // 发票号码 +// if(!"".equals(fphmId)){ +// // 得到浏览按钮中发票号码的id,再去数据库中把发票号码和发票代码查出来 +// rsFna.execute(" select * from fnainvoiceledger where id = " + fphmId); +// while (rsFna.next()) { +// fpdm = Util.null2String(rsFna.getString("INVOICECODE")); // 发票代码 +// fphm = Util.null2String(rsFna.getString("INVOICENUMBER")); // 发票号码 +// fplxpk = Util.null2String(map_oafplx_nccfplcx.get(Util.null2String(rsFna.getString("invoicetype")))); // OA发票类型 +// } +// } + //发票金额为空时,默认等于付款金额 + if(Double.parseDouble(defitem36)==0){ + defitem36=amount; + } + + String defitem46 = Util.null2String(rs.getString("wd")); // 网点(成本中心) + String defitem45 = Util.null2String(rs.getString("gj")); // 国家 + String defitem44 = Util.null2String(rs.getString("ck")); // 仓库 + String defitem43 = Util.null2String(rs.getString("cph")); //车牌号 + String defitem42 = Util.null2String(rs.getString("id")); // OA明细行ID + //根据部门ID查询部门编码(传NCC) +// String fycdbm_NCC=BaseUtil.getBaseInfoByParm("bm", "uf_dept_ncc", "id", fycdbm, ""); + String fycdbm_NCC=fycdbm; + + rowno++; + + log.writeLog("----fycdbm_NCC:" + fycdbm_NCC); + log.writeLog("----amount:" + amount); + log.writeLog("----tax_rate:" + tax_rate); + log.writeLog("----tax_amount:" + tax_amount); + log.writeLog("----tni_amount:" + tni_amount); +// log.writeLog("----defitem48:" + defitem48); + + //没有发票时,则对应NCC的对公借款单 + if("1".equals(sfyfp)){ + BorrowOrderBodyYY body = new BorrowOrderBodyYY(); + body.setAmount(amount); + body.setTablecode(tablecode); + body.setRowno(rowno+""); + body.setSzxmid(szxmid); + body.setDefitem50(""); + body.setDefitem49(""); + body.setDefitem42(defitem42); + body.setDefitem43(defitem43); + body.setDefitem44(defitem44); + body.setDefitem45(defitem45); + body.setDefitem46(defitem46); + body.setDefitem48(fycdbm_NCC); + body.setDefitem48IsNeedConvert("no"); + borrowOrderBodyList.add(body); + }else{ + ReimbursementOrderBodyYY body = new ReimbursementOrderBodyYY(); + body.setJobid(jobid1); + body.setDeptid(fycdbm_NCC); + body.setAmount(amount); + body.setTax_rate(tax_rate); + body.setTax_amount(tax_amount); + body.setTni_amount(tni_amount); + body.setTablecode(tablecode); + body.setRowno(rowno+""); + body.setSzxmid(szxmid); + body.setFpdm(fpdm); + body.setFphm(fphm); + body.setFplxpk(fplxpk); + body.setDefitem36(defitem36); + body.setDefitem46(defitem46); + body.setDefitem45(defitem45); + body.setDefitem44(defitem44); + body.setDefitem43(defitem43); + body.setDeptidIsNeedConvert("no"); + body.setDefitem42(defitem42); + //body.setDefitem48(fycdbm_NCC); + reimbursementOrderBodyList.add(body); + } + } + + String parm=""; + //没有发票时,则对应NCC的对公借款单 + if("1".equals(sfyfp)){ + borrowOrder.setJk_busitem(borrowOrderBodyList); +// borrowList.add(borrowOrder); + parm=JSONObject.toJSONString(borrowOrder, SerializerFeature.DisableCircularReferenceDetect); + log.writeLog(djlxmc+"准备传入中台的数据为------>" + parm); + }else{ + reimbursementOrder.setEr_busitem(reimbursementOrderBodyList); +// reimbursementList.add(reimbursementOrder); + parm=JSONObject.toJSONString(reimbursementOrder, SerializerFeature.DisableCircularReferenceDetect); + log.writeLog(djlxmc+"准备传入中台的数据为------>" + parm); + } + +// JSONObject jsonObject1 = JSONObject.parseObject(parm); +// jsonObject1.put("deptidIsNeedConvert", "no"); +// parm = jsonObject1.toJSONString(); + + //获取TOKEN + String token = HttpClientToDC.getToken(); + log.writeLog("获取数据中台的token------>" + token); + if ("".equals(Util.null2String(token))) { + String tokenMsg="流程提交失败,未获取到数据中台接口TOKEN,请联系管理员处理!"; + //将NCC返回结果回写至OA流程表单 + rs.execute(" update " + mainTable + " set sfcgscnccfkd = 1 ,nccfhxx='" + tokenMsg.replace("'", "''") + "' where requestid = " + requestId); + //是否需要显示报错信息 + if("yes".equals(isShowErrorMsg)){ + requestInfo.getRequestManager().setMessagecontent(tokenMsg); + return Action.FAILURE_AND_CONTINUE; + }else{ + return SUCCESS; + } + } + + log.writeLog("url:"+url); + log.writeLog("token:"+token); + log.writeLog("param:"+parm); + + //调用NCC接口,将数据传给NCC + String returndata = HttpClientToDC.sendPostApi(url,token, parm); + log.writeLog("【调用数据中台报销接口返回结果result:】" + returndata); + if (!"".equals(returndata) && returndata != null) { + JSONObject jsonObject = JSONObject.parseObject(returndata); + String success = Util.null2String(jsonObject.get("succ")); + log.writeLog("--------发送请求返回的success值为:" + success); + if ("true".equals(success)) { + JSONObject data = jsonObject.getJSONObject("data"); + String billno = Util.null2String(data.get("billno"));//NCC单号 + log.writeLog("--------发送请求返回的billno值为:" + billno); + //将NCC返回结果回写至OA流程表单 + rs.execute(" update " + mainTable + " set sfcgscnccfkd = 0 , nccfkdh = '" + billno + "',nccfhxx='' where requestid = " + requestId); + } else { + String message = Util.null2String(jsonObject.get("msg")); + String message2=message.replace("'", "''"); + //超出1333个字符,则只截取前面这部分 + if(message2.length()>1334){ + message2=message2.substring(0,1333); + } + //将NCC返回结果回写至OA流程表单 + rs.execute(" update " + mainTable + " set sfcgscnccfkd = 1 ,nccfhxx='" + message2 + "' where requestid = " + requestId); + //是否需要显示报错信息 + if("yes".equals(isShowErrorMsg)){ + requestInfo.getRequestManager().setMessagecontent("流程数据写入NCC生成"+djlxmc+"失败,失败信息:
"+message); + return Action.FAILURE_AND_CONTINUE; + }else{ + return SUCCESS; + } + } + } else { + String ermsg="流程数据写入NCC生成"+djlxmc+"失败,未获取到接口返回结果,请联系系统管理员处理!"; + //将NCC返回结果回写至OA流程表单 + rs.execute(" update " + mainTable + " set sfcgscnccfkd = 1 ,nccfhxx='" + ermsg.replace("'", "''") + "' where requestid = " + requestId); + //是否需要显示报错信息 + if("yes".equals(isShowErrorMsg)){ + requestInfo.getRequestManager().setMessagecontent(ermsg); + return Action.FAILURE_AND_CONTINUE; + }else{ + return SUCCESS; + } + } + + } catch (Exception e) { + String ermsg="流程数据生成中台对公报销单/对公借款单失败!" + e.toString(); + //将NCC返回结果回写至OA流程表单 + rs.execute(" update " + mainTable + " set sfcgscnccfkd = 1 ,nccfhxx='" + ermsg.replace("'", "''") + "' where requestid = " + requestId); + //是否需要显示报错信息 + if("yes".equals(isShowErrorMsg)){ + requestInfo.getRequestManager().setMessagecontent(ermsg); + return Action.FAILURE_AND_CONTINUE; + }else{ + return SUCCESS; + } + } + log.writeLog("--------付款单数据传入中台完毕----requestId值为:" + requestId); + return Action.SUCCESS; + } +} \ No newline at end of file diff --git a/src/main/youhong_ai_jitu_src/jntchina/action/PayApplicationActionYYGYS.java b/src/main/youhong_ai_jitu_src/jntchina/action/PayApplicationActionYYGYS.java new file mode 100644 index 0000000..679aff5 --- /dev/null +++ b/src/main/youhong_ai_jitu_src/jntchina/action/PayApplicationActionYYGYS.java @@ -0,0 +1,461 @@ +package jntchina.action; + +import com.alibaba.fastjson.JSONObject; +import com.alibaba.fastjson.serializer.SerializerFeature; +import com.working.util.WorkflowUtil; +import jntchina.entity.*; +import jntchina.util.DataBaseUtils; +import jntchina.util.HttpClientToDC; +import selfdev.util.base.BaseUtil; +import selfdev.util.base.TimeCommonUtil; +import selfdev.util.log.LogTool; +import weaver.conn.RecordSet; +import weaver.file.Prop; +import weaver.general.Util; +import weaver.hrm.resource.ResourceComInfo; +import weaver.interfaces.workflow.action.Action; +import weaver.soa.workflow.request.RequestInfo; +import weaver.workflow.action.BaseAction; + +import java.util.ArrayList; +import java.util.List; +import java.util.Map; +import java.util.UUID; + + +/** + * @Author Administrator + * @Description 付款申请数据写入中台生成NCC对公报销单或者对公借款单(紜毅)1 + * @Date 2021/3/2 11:50 + */ +public class PayApplicationActionYYGYS extends BaseAction { + @Override + public String execute(RequestInfo requestInfo) { + String src = requestInfo.getRequestManager().getSrc();//获取操作方式 + if (!"submit".equals(src)) { // 只有submit才执行接口 + return SUCCESS; + } + LogTool log = new LogTool("/log/selfdev/action", false); + String requestId = requestInfo.getRequestid(); // 获取requestid + log.writeLog("--------付款申请单数据传入数据中台开始----requestId值为:" + requestId); + //获取当前用户的登录账号(即工号) + String loginid=requestInfo.getRequestManager().getUser().getLoginid(); + log.writeLog("loginid-------->"+loginid); + //获取配置文件中的参数 + String mode = Prop.getPropValue("DevToDC_jntchina","mode"); + // 服务器ip:port + String baseUrl = Prop.getPropValue("DevToDC_jntchina", mode+"_baseUrl"); + String url = baseUrl+"/dcnccapi/claimForm/receiveData"; + ReimbursementOrderYY reimbursementOrder = new ReimbursementOrderYY(); + BorrowOrderYY borrowOrder = new BorrowOrderYY(); + String mainTable = WorkflowUtil.getMainTable(requestId); + String mainId = ""; + String isShowErrorMsg = "";//写入NCC失败时是否显示报错信息 + String pk_org = ""; // 报销单位 JTSDCN0001 + String fygsbm = ""; // 申请部门 + String total = ""; // 报销金额 金额由表体相应字段汇总得出 + String deptid = ""; // 部门 传输编码 + String djlxbm = "264X-Cxx-DGBXD"; // 单据类型编码 对私报销单:264X-Cxx-DSBXD 对公报销单:264X-Cxx-DGBXD + String djlxmc = "对公报销单"; // 单据类型名称 默认 对公报销单 + String djrq = TimeCommonUtil.obtainDate(0); // 单据日期 yyyy-mm-dd hh:mm:ss + String payflag = ""; // 支付状态 + String paytarget = "1"; // 收款对象 0=员工,1=供应商,2=客户,默认为供应商 + String receiver = ""; // 收款人 + String skyhzh = ""; // 收款人银行账号 + String hbbm = ""; // yonyou88", //收款人(供应商) + String custaccount= ""; //收款银行账户(供应商) + String sfyfp = ""; // 是否有发票 + String jkbxr = ""; // 借款报销人 传输编码 + String operator = ""; // 录入人 + String xm= ""; // 申请人 + String jsfs = "3"; // 结算方式 3 网银 + String fkfs = ""; // 付款方式 + String fkyhzh = ""; // 单位银行账户 传输编码 + String jobid = ""; // 项目 + String zy = ""; // 报销事由 + String kjqj = ""; // 会计期间 + String kjnd = ""; // 会计年度 + String fjzs = ""; // 附件张数 需业务人员在OA上传附件同时填写附件张数后传数据到NCC + String zyx1 = ""; // OA单据号 OA传过来,用于联查单据 + String zyx2 = ""; // 提交人 提交人姓名 + String zyx3 = ""; // OA核销单号 + String zyx5 = ""; // OARequestID + String zyx8="";//银行付款备注 +// String zyx9=requestInfo.getRequestManager().getRequestname();//标题 + String zyx9=requestInfo.getRequestManager().getRequestname().length()>140?requestInfo.getRequestManager().getRequestname().substring(0,140):requestInfo.getRequestManager().getRequestname();//标题 + + String tablecode = "arap_bxbusitem"; + + RecordSet rs = new RecordSet(); + try { + String sql = " select * from " + mainTable + " where requestid='" + requestId + "'"; + rs.execute(sql); + while (rs.next()) { + mainId = Util.null2String(rs.getString("id")); + isShowErrorMsg = Util.null2String(rs.getString("xrnccsbcsfts")); + xm = Util.null2String(rs.getString("xm")); // 借款报销人(取流程申请人) + sfyfp = Util.null2String(rs.getString("sfyfp")); // 是否有发票 + pk_org = Util.null2String(rs.getString("gsmc")); // 公司名称 + total = Util.null2String(rs.getString("jshjje")); // 报销金额 金额由表体相应字段汇总得出 + fygsbm = Util.null2String(rs.getString("sqrbm")); // 申请部门 +// djrq = Util.null2String(rs.getString("cjrq")); // 单据日期 yyyy-mm-dd hh:mm:ss + fkfs = Util.null2String(rs.getString("fkfs")); // 付款方式 + hbbm = Util.null2String(rs.getString("gysmc")); // 收款人,供应商编码 + custaccount = Util.null2String(rs.getString("yxhm")); // 收款人银行账号 + zyx8 = Util.null2String(rs.getString("yxfkbz")); //银行付款备注 + fkyhzh = Util.null2String(rs.getString("")); // 付款银行账户 传输编码 + zy = Util.null2String(rs.getString("fksm")); // 付款说明 + + fjzs = Util.null2String(rs.getString("fjzs")); // 附件张数 需业务人员在OA上传附件同时填写附件张数后传数据到NCC + zyx1 = Util.null2String(rs.getString("lcbh")); // OA单据号 OA传过来,用于联查单据 + zyx2 = Util.null2String(rs.getString("xm")); // 提交人 提交人姓名 + zyx3 = Util.null2String(rs.getString("")); // OA核销单号 + zyx5 = requestId; // OARequestID + + } + kjqj = djrq.substring(5,7); // 会计期间 + kjnd = djrq.substring(0,4); // 会计年度 + //根据部门ID查询部门编码 +// deptid=BaseUtil.getBaseInfoByParm("BM", "uf_dept_ncc", "id", fygsbm, ""); + deptid=BaseUtil.getBaseInfoByParm("departmentcode", "hrmdepartment", "id", fygsbm, ""); + //获取员工默认的组织对应的类型 + String userDefaultCompanyType=BaseUtil.getBaseInfoByParm("company_type", "v_oa_user_org_nsrsbh", "userid", xm, ""); + //获取付款单选择的组织对应的类型 + String selectCompanyType=BaseUtil.getBaseInfoByParm("company_type", "uf_businessunit", "code", pk_org, ""); + log.writeLog("userDefaultCompanyType------>" + userDefaultCompanyType); + log.writeLog("selectCompanyType------>" + selectCompanyType); + //跨组织,则说明代理区向总部申请付款 + if(!userDefaultCompanyType.equals(selectCompanyType)){ + //查询建模维护的对应关系 + String defaultDeptNo=BaseUtil.getBaseInfoByParm("mroabmbm", "uf_kzzfkdybmsz", "sqgslx", userDefaultCompanyType, " and fkgslx='"+selectCompanyType+"'"); + log.writeLog("defaultDeptNo------>" + defaultDeptNo); + if(!"".equals(defaultDeptNo)){ + deptid=defaultDeptNo; + } + } + //截取前120位 + if(zy.length()>120){ + zy=zy.substring(0,120); + } + + if("1".equals(fkfs)){ + jsfs = "0"; //现金 + } + jkbxr = new ResourceComInfo().getWorkcode(xm); //借款报销人工号(即申请人工号) + operator = loginid;//当前节点操作者 + //获取UUID + String uuid=UUID.randomUUID().toString().replace("-", "").toUpperCase(); + log.writeLog("receiver------>"+receiver); + + //查询抵扣明细 + sql = " select * from " + mainTable + "_dt1 where mainid='" + mainId + "'"; + rs.execute(sql); + while (rs.next()) { + zyx3+=Util.null2String(rs.getString("yflcbh"))+","; + } + //将预付流程编号赋值到zyx3字段中 + if(!"".equals(zyx3)){ + zyx3=zyx3.substring(0,zyx3.length()-1); + } + + //没有发票时,则对应NCC的对公借款单 + if("1".equals(sfyfp)){ + djlxbm = "263X-Cxx-DGJKD"; // 单据类型编码 + djlxmc = "对公借款单"; + tablecode = "jk_busitem"; + //url = baseUrl+"/dcoaapi/billLoan/receiveData"; + url = baseUrl+"/dcnccapi/billLoan/receiveData"; + borrowOrder.setUuid(uuid); + borrowOrder.setPk_org(pk_org); + borrowOrder.setTotal(total); + borrowOrder.setDeptid(deptid); + borrowOrder.setDjlxbm(djlxbm); + borrowOrder.setDjrq(djrq); + borrowOrder.setPayflag(payflag); + borrowOrder.setPaytarget(paytarget); + borrowOrder.setHbbm(deptid); + borrowOrder.setReceiver(receiver); + borrowOrder.setHbbm(hbbm); + borrowOrder.setSkyhzh(skyhzh); + borrowOrder.setCustaccount(custaccount); + borrowOrder.setJkbxr(jkbxr); + borrowOrder.setOperator(operator); + borrowOrder.setJsfs(jsfs); + borrowOrder.setFkyhzh(fkyhzh); + + borrowOrder.setZy(zy); + borrowOrder.setDjzt("1"); + borrowOrder.setKjqj(kjqj); + borrowOrder.setKjnd(kjnd); + borrowOrder.setZyx1(zyx1); + borrowOrder.setZyx2(zyx2); + borrowOrder.setZyx3(zyx3); + borrowOrder.setZyx5(zyx5); + borrowOrder.setZyx8(zyx8); + borrowOrder.setZyx9(zyx9); +// borrowOrder.setDeptidIsNeedConvert("no"); + }else{ + reimbursementOrder.setUuid(uuid); + reimbursementOrder.setPk_org(pk_org); + reimbursementOrder.setTotal(total); + reimbursementOrder.setDeptid(deptid); + reimbursementOrder.setDjlxbm(djlxbm); + reimbursementOrder.setDjrq(djrq); + reimbursementOrder.setPayflag(payflag); + reimbursementOrder.setPaytarget(paytarget); + reimbursementOrder.setReceiver(receiver); + reimbursementOrder.setHbbm(hbbm); + reimbursementOrder.setSkyhzh(skyhzh); + reimbursementOrder.setCustaccount(custaccount); + reimbursementOrder.setJkbxr(jkbxr); + reimbursementOrder.setOperator(operator); + reimbursementOrder.setJsfs(jsfs); + reimbursementOrder.setFkyhzh(fkyhzh); + reimbursementOrder.setJobid(jobid); + reimbursementOrder.setZy(zy); + reimbursementOrder.setKjqj(kjqj); + reimbursementOrder.setKjnd(kjnd); + reimbursementOrder.setFjzs(fjzs); + reimbursementOrder.setZyx1(zyx1); + reimbursementOrder.setZyx2(zyx2); + reimbursementOrder.setZyx3(zyx3); + reimbursementOrder.setZyx5(zyx5); + reimbursementOrder.setZyx8(zyx8); + reimbursementOrder.setZyx9(zyx9); +// reimbursementOrder.setDeptidIsNeedConvert("no"); + } + log.writeLog("【header数据准备完毕...】"); + + //获取OA-NCC发票映射关系表 + Map map_oafplx_nccfplcx=BaseUtil.getMapKeyValueInfoByParm("uf_oafplx_nccfplx", "", "oafplxid", "nccfplxbm"); + + //对公报销 + List reimbursementOrderBodyList = new ArrayList(); + //对公借款 + List borrowOrderBodyList = new ArrayList(); + int rowno = 0; + rs.execute(" select b.bm as szxmid,c.INVOICECODE,c.INVOICENUMBER,c.invoicetype,a.* from " + mainTable + "_dt2 a " + + "left join uf_fylx b on to_char(a.fylx)=to_char(b.id) " + + "left join fnainvoiceledger c on a.fphm=c.id " + + "where a.mainid = " + mainId); + while (rs.next()) { + + String jobid1 = ""; // 项目 + String fycdbm = Util.null2String(rs.getString("fycdbm")); //费用承担部门 + String amount = Util.null2String(rs.getString("je")); // 付款 + String defitem36 = Util.null2o(rs.getString("fpje")); // 发票金额 + String tax_rate = Util.null2String(rs.getString("sl")); // 税率 3% + String tax_amount = Util.null2String(rs.getString("se")); // 税额 + String tni_amount = Util.null2String(rs.getString("bhsje")); // 无税金额 + String szxmid = Util.null2String(rs.getString("szxmid")); // 收支项目 0101 汽车费用 + String fpdm = Util.null2String(rs.getString("INVOICECODE")); // 发票代码 + String fphm = Util.null2String(rs.getString("INVOICENUMBER")); // 发票号码 + String invoicetype = Util.null2String(rs.getString("invoicetype")); // OA发票类型 + //NCC发票类型 + String fplxpk=Util.null2String(map_oafplx_nccfplcx.get(invoicetype)); + +// String fphmId = Util.null2String(rs.getString("fphm")); // 发票号码 +// if(!"".equals(fphmId)){ +// // 得到浏览按钮中发票号码的id,再去数据库中把发票号码和发票代码查出来 +// rsFna.execute(" select * from fnainvoiceledger where id = " + fphmId); +// while (rsFna.next()) { +// fpdm = Util.null2String(rsFna.getString("INVOICECODE")); // 发票代码 +// fphm = Util.null2String(rsFna.getString("INVOICENUMBER")); // 发票号码 +// fplxpk = Util.null2String(map_oafplx_nccfplcx.get(Util.null2String(rsFna.getString("invoicetype")))); // OA发票类型 +// } +// } + //发票金额为空时,默认等于付款金额 + if(Double.parseDouble(defitem36)==0){ + defitem36=amount; + } + + String defitem46 = Util.null2String(rs.getString("wd")); // 网点(成本中心) + String defitem45 = Util.null2String(rs.getString("gj")); // 国家 + String defitem44 = Util.null2String(rs.getString("ck")); // 仓库 + String defitem43 = Util.null2String(rs.getString("cph")); //车牌号 + String defitem42 = Util.null2String(rs.getString("id")); // OA明细行ID + //根据部门ID查询部门编码(传NCC) +// String fycdbm_NCC=BaseUtil.getBaseInfoByParm("bm", "uf_dept_ncc", "id", fycdbm, ""); + String fycdbm_NCC=fycdbm; + + rowno++; + + log.writeLog("----fycdbm_NCC:" + fycdbm_NCC); + log.writeLog("----amount:" + amount); + log.writeLog("----tax_rate:" + tax_rate); + log.writeLog("----tax_amount:" + tax_amount); + log.writeLog("----tni_amount:" + tni_amount); +// log.writeLog("----defitem48:" + defitem48); + + //没有发票时,则对应NCC的对公借款单 + if("1".equals(sfyfp)){ + BorrowOrderBodyYY body = new BorrowOrderBodyYY(); + body.setAmount(amount); + body.setTablecode(tablecode); + body.setRowno(rowno+""); + body.setSzxmid(szxmid); + body.setDefitem50(""); + body.setDefitem49(""); + body.setDefitem42(defitem42); + body.setDefitem43(defitem43); + body.setDefitem44(defitem44); + body.setDefitem45(defitem45); + body.setDefitem46(defitem46); + body.setDefitem48(fycdbm_NCC); + body.setDefitem48IsNeedConvert("no"); + borrowOrderBodyList.add(body); + }else{ + ReimbursementOrderBodyYY body = new ReimbursementOrderBodyYY(); + body.setJobid(jobid1); + body.setDeptid(fycdbm_NCC); + body.setAmount(amount); + body.setTax_rate(tax_rate); + body.setTax_amount(tax_amount); + body.setTni_amount(tni_amount); + body.setTablecode(tablecode); + body.setRowno(rowno+""); + body.setSzxmid(szxmid); + body.setFpdm(fpdm); + body.setFphm(fphm); + body.setFplxpk(fplxpk); + body.setDefitem36(defitem36); + body.setDefitem46(defitem46); + body.setDefitem45(defitem45); + body.setDefitem44(defitem44); + body.setDefitem43(defitem43); + body.setDeptidIsNeedConvert("no"); + body.setDefitem42(defitem42); + //body.setDefitem48(fycdbm_NCC); + reimbursementOrderBodyList.add(body); + } + } + List erBxcontrasts = new ArrayList<>(); + String parm=""; + //没有发票时,则对应NCC的对公借款单 + if("1".equals(sfyfp)){ + borrowOrder.setJk_busitem(borrowOrderBodyList); +// borrowList.add(borrowOrder); + parm=JSONObject.toJSONString(borrowOrder, SerializerFeature.DisableCircularReferenceDetect); + log.writeLog(djlxmc+"准备传入中台的数据为------>" + parm); + }else{ + reimbursementOrder.setEr_busitem(reimbursementOrderBodyList); + + RecordSet rs4 = new RecordSet(); + String sql1 = "select * from " + mainTable + "_dt1 where mainid = " + mainId; + log.writeLog("查询当前单据是否有抵扣信息sql-----> " + sql1); + rs.execute(sql1); + while(rs.next()){ + String yfkqptzmxid = Util.null2String(rs.getString("yfkqptzmxid")); //预付欠票台账id + String yfklcmxid = Util.null2String(rs.getString("yfklcmxid")); //预付款流程明细id + String sql2 = "select fylx from uf_gysqktzyy_dt1 where id = " + yfkqptzmxid; + String fylx = ""; + rs4.execute(sql2); + if(rs4.next()){ + fylx = Util.null2String(rs4.getString("fylx")); + } + fylx = DataBaseUtils.getFirstValue("select BM from uf_fylx where id = " + fylx); + String nccdh = Util.null2String(rs.getString("nccdh"));//ncc单号 + String bcdjje = Util.null2o(rs.getString("bcdjje")); //本次抵扣金额 + ErBxcontrast erBxcontrast = new ErBxcontrast(nccdh, fylx, bcdjje, yfklcmxid, yfkqptzmxid); + erBxcontrasts.add(erBxcontrast); + } +// reimbursementOrder.setEr_busitem(reimbursementOrderBodyList); + reimbursementOrder.setEr_bxcontrast(erBxcontrasts); + + + + +// reimbursementList.add(reimbursementOrder); + parm=JSONObject.toJSONString(reimbursementOrder, SerializerFeature.DisableCircularReferenceDetect); + + + + + + + log.writeLog(djlxmc+"准备传入中台的数据为------>" + parm); + } + +// JSONObject jsonObject1 = JSONObject.parseObject(parm); +// jsonObject1.put("deptidIsNeedConvert", "no"); +// parm = jsonObject1.toJSONString(); + + //获取TOKEN + String token = HttpClientToDC.getToken(); + log.writeLog("获取数据中台的token------>" + token); + if ("".equals(Util.null2String(token))) { + String tokenMsg="流程提交失败,未获取到数据中台接口TOKEN,请联系管理员处理!"; + //将NCC返回结果回写至OA流程表单 + rs.execute(" update " + mainTable + " set sfcgscnccfkd = 1 ,nccfhxx='" + tokenMsg.replace("'", "''") + "' where requestid = " + requestId); + //是否需要显示报错信息 + if("yes".equals(isShowErrorMsg)){ + requestInfo.getRequestManager().setMessagecontent(tokenMsg); + return Action.FAILURE_AND_CONTINUE; + }else{ + return SUCCESS; + } + } + + log.writeLog("url:"+url); + log.writeLog("token:"+token); + log.writeLog("param:"+parm); + + //调用NCC接口,将数据传给NCC + String returndata = HttpClientToDC.sendPostApi(url,token, parm); + log.writeLog("【调用数据中台报销接口返回结果result:】" + returndata); + if (!"".equals(returndata) && returndata != null) { + JSONObject jsonObject = JSONObject.parseObject(returndata); + String success = Util.null2String(jsonObject.get("succ")); + log.writeLog("--------发送请求返回的success值为:" + success); + if ("true".equals(success)) { + JSONObject data = jsonObject.getJSONObject("data"); + String billno = Util.null2String(data.get("billno"));//NCC单号 + log.writeLog("--------发送请求返回的billno值为:" + billno); + //将NCC返回结果回写至OA流程表单 + rs.execute(" update " + mainTable + " set sfcgscnccfkd = 0 , nccfkdh = '" + billno + "',nccfhxx='' where requestid = " + requestId); + } else { + String message = Util.null2String(jsonObject.get("msg")); + String message2=message.replace("'", "''"); + //超出1333个字符,则只截取前面这部分 + if(message2.length()>1334){ + message2=message2.substring(0,1333); + } + //将NCC返回结果回写至OA流程表单 + rs.execute(" update " + mainTable + " set sfcgscnccfkd = 1 ,nccfhxx='" + message2 + "' where requestid = " + requestId); + //是否需要显示报错信息 + if("yes".equals(isShowErrorMsg)){ + requestInfo.getRequestManager().setMessagecontent("流程数据写入NCC生成"+djlxmc+"失败,失败信息:
"+message); + return Action.FAILURE_AND_CONTINUE; + }else{ + return SUCCESS; + } + } + } else { + String ermsg="流程数据写入NCC生成"+djlxmc+"失败,未获取到接口返回结果,请联系系统管理员处理!"; + //将NCC返回结果回写至OA流程表单 + rs.execute(" update " + mainTable + " set sfcgscnccfkd = 1 ,nccfhxx='" + ermsg.replace("'", "''") + "' where requestid = " + requestId); + //是否需要显示报错信息 + if("yes".equals(isShowErrorMsg)){ + requestInfo.getRequestManager().setMessagecontent(ermsg); + return Action.FAILURE_AND_CONTINUE; + }else{ + return SUCCESS; + } + } + + } catch (Exception e) { + String ermsg="流程数据生成中台对公报销单/对公借款单失败!" + e.toString(); + //将NCC返回结果回写至OA流程表单 + rs.execute(" update " + mainTable + " set sfcgscnccfkd = 1 ,nccfhxx='" + ermsg.replace("'", "''") + "' where requestid = " + requestId); + //是否需要显示报错信息 + if("yes".equals(isShowErrorMsg)){ + requestInfo.getRequestManager().setMessagecontent(ermsg); + return Action.FAILURE_AND_CONTINUE; + }else{ + return SUCCESS; + } + } + log.writeLog("--------付款单数据传入中台完毕----requestId值为:" + requestId); + return Action.SUCCESS; + } +} \ No newline at end of file diff --git a/src/main/youhong_ai_jitu_src/jntchina/action/PayApplicationDataValid.java b/src/main/youhong_ai_jitu_src/jntchina/action/PayApplicationDataValid.java new file mode 100644 index 0000000..c240040 --- /dev/null +++ b/src/main/youhong_ai_jitu_src/jntchina/action/PayApplicationDataValid.java @@ -0,0 +1,189 @@ +package jntchina.action; + +import java.math.BigDecimal; +import java.math.RoundingMode; +import java.util.HashMap; +import java.util.Map; + +import com.working.util.WorkflowUtil; + +import selfdev.util.log.LogTool; +import weaver.conn.RecordSet; +import weaver.general.Util; +import weaver.interfaces.workflow.action.Action; +import weaver.interfaces.workflow.action.BaseAction; +import weaver.soa.workflow.request.RequestInfo; + +/** + * @Author KangMD + * @Description 付款流程提交时数据校验 + * @Date 2021/6/7 16:27 + */ +public class PayApplicationDataValid extends BaseAction { + + @Override + public String execute(RequestInfo requestInfo) { + + String src = requestInfo.getRequestManager().getSrc();//获取操作方式 + if (!"submit".equals(src)) { // 只有submit才执行接口 + return SUCCESS; + } + + LogTool log = new LogTool("/log/selfdev/action", false); + String requestId = requestInfo.getRequestid(); // 获取requestid + log.writeLog("--------付款单数据校验开始----requestId值为:" + requestId); + + RecordSet rs = new RecordSet(); + RecordSet rs2 = new RecordSet(); + RecordSet rs3 = new RecordSet(); + String mainTable = WorkflowUtil.getMainTable(requestId); + String mainId = ""; + String sql = " select id from " + mainTable + " where requestid='" + requestId + "'"; + rs.execute(sql); + while (rs.next()) { + mainId = Util.null2String(rs.getString("id")); + } + + StringBuilder message = new StringBuilder(); + + //查询是否有发票被多行分摊 + sql="select fphm from " + mainTable + "_dt2 where fphm is not null and mainid="+mainId+" group by fphm having count(*)>1"; + rs.execute(sql); + int row=rs.getCounts(); + if(row>0){ + while(rs.next()){ + BigDecimal bd_temp=new BigDecimal("0"); + String fphm=Util.null2String(rs.getString("fphm"));//发票号码 + String sql2="select a.*,b.invoicecode,b.invoicenumber,b.taxincludedprice,b.tax from " + mainTable + "_dt2 a,fnainvoiceledger b where a.mainid="+mainId+" and a.fphm=b.id and a.fphm ='"+fphm+"'"; + rs2.execute(sql2); + int row2=rs2.getCounts(); + int temp2=0; + while(rs2.next()){ + String id=Util.null2String(rs2.getString("id"));//主键ID + String je=Util.null2o(rs2.getString("je"));//付款金额 + String sl=Util.null2o(rs2.getString("sl"));//税率 + String tax=Util.null2o(rs2.getString("tax"));//发票税金 + BigDecimal bd_tax=new BigDecimal(tax); + //税额=总金额/(1+税率)*税率 + BigDecimal bd_se=new BigDecimal(je).divide(new BigDecimal("100").add(new BigDecimal(sl)), 10, BigDecimal.ROUND_HALF_UP).multiply(new BigDecimal(sl)).setScale(2, RoundingMode.HALF_UP); + + bd_temp=bd_temp.add(bd_se); + temp2++; + + if(row2==temp2){//最后一行 + //可能存在相除有差额的情况 + if(bd_temp.compareTo(bd_tax)!=0){ + //两者相差多少 + BigDecimal bd_xe=bd_temp.subtract(bd_tax); + log.writeLog("bd_temp=【"+bd_temp+"】、bd_tax=【"+bd_tax+"】,两者相差的税额bd_xe------------>"+bd_xe); + //当相差低于0.2元时,则将差额算在最后一行上面 + if(bd_xe.compareTo(new BigDecimal("0.2"))<=0&&bd_xe.compareTo(new BigDecimal("-0.2"))>=0){ + bd_se=bd_se.subtract(bd_xe).setScale(2, RoundingMode.HALF_UP); + } + } + } + //不含税金额=付款金额-税额 + BigDecimal bhsje=new BigDecimal(je).subtract(bd_se).setScale(2, RoundingMode.HALF_UP); + + //一张发票是否被多个明细行引用时,将此行的税额和不含税金额刷新,其中税额=总金额/(1+税率)*税率 + sql = "update " + mainTable + "_dt2 set se="+bd_se+",bhsje="+bhsje+" where mainid= "+mainId+" and id= "+id; + log.writeLog("一张发票被多个明细行引用刷新其税额和不含税金额sql------------>"+sql); + rs3.execute(sql); + } + } + } + +// //一张发票是否被多个明细行引用时,将此行的税额和不含税金额刷新,其中税额=总金额/(1+税率)*税率 +// sql = "update " + mainTable + "_dt2 set se=je/(1+(nvl(sl,0)*1.00/100))*(nvl(sl,0)*1.00/100)," +// +"bhsje=je-je/(1+(nvl(sl,0)*1.00/100))*(nvl(sl,0)*1.00/100) where mainid= "+mainId+" and fphm in ( "; +// sql+=" select fphm from " + mainTable + "_dt2 where fphm is not null and mainid="+mainId+" group by fphm having count(*)>1"; +// sql+=" ) "; +// log.writeLog("查询一张发票是否被多个明细行引用,若存在则刷新其税额和不含税金额sql------------>"+sql); +// rs.execute(sql); + + Map map=new HashMap(); + map.put("901063", "0");//客服理赔备用金报销 + map.put("901059", "1");//客服理赔备用金专项核销 + map.put("901069", "2");//工资发放申请 + map.put("901058", "3");//客服理赔备用金申请 + map.put("901060", "4");//押金保证金 + map.put("901009", "4");//保证金退款 + map.put("901072", "5");//提现 + map.put("901056", "6");//航空费 + map.put("901094", "9");//投标保证金退款 + + int p=0; + String sfxnccfk="0";//是否对接NCC + String ygdsfzyxtjzyzlx="1";//一个单是否只允许提交这一种类型 + String fylxmcwb="";//费用类型没错 + String fylxbmwb="";//费用类型编码 + sql="select a.*, nvl(b.sfdjncc,0) as sfdjncc, nvl(b.ygdsfzyxtjzyzlx,1) as ygdsfzyxtjzyzlx,b.fylx as fylxmcwb,b.bm as fylxbmwb from " + mainTable + "_dt2 a left join uf_fylx b on a.fylx=b.id where a.mainid="+mainId; + rs.execute(sql); + while (rs.next()) { + + if(p==0){//第一行 + sfxnccfk=Util.null2String(rs.getString("sfdjncc"));//是否对接NCC + ygdsfzyxtjzyzlx=Util.null2String(rs.getString("ygdsfzyxtjzyzlx"));//一个单是否只允许提交这一种类型 + fylxmcwb=Util.null2String(rs.getString("fylxmcwb"));//费用类型名称 + fylxbmwb=Util.null2String(rs.getString("fylxbmwb"));//费用类型编码 + }else{ + //第二行以下与第一行是否相同 + if(!ygdsfzyxtjzyzlx.equals(Util.null2String(rs.getString("ygdsfzyxtjzyzlx")))){ + message.append("一个付款单中不可同时选择【"+fylxmcwb+"】【"+Util.null2String(rs.getString("fylxmcwb"))+"】两种费用类型,若需要申请这2种费用,则请拆分成2个单发起申请!
"); + }else{ + if("0".equals(ygdsfzyxtjzyzlx)){//如果是选择一个单只允许提交这一种类型的费用科目,那么判断 + if(!fylxbmwb.equals(Util.null2String(rs.getString("fylxbmwb")))){ + message.append("一个付款单中不可同时选择【"+fylxmcwb+"】【"+Util.null2String(rs.getString("fylxmcwb"))+"】两种费用类型,若需要申请这2种费用,则请拆分成2个单发起申请!
"); + } + } + } + } + String je=Util.null2o(rs.getString("je"));//付款金额 + if(Double.parseDouble(je)<=0){ + message.append("明细中的付款金额【"+je+"】填写有误,付款金额需大于0
"); + } + p++; + } + //获取费用类型下拉框的值 + String fklx1=Util.null2String(map.get(fylxbmwb)); + if("".equals(fklx1)){ + fklx1="null"; + } + //给“是否对接NCC”赋值 + rs.execute("update " + mainTable + " set sfxnccfk='"+sfxnccfk+"',fklx1="+fklx1+" where requestid="+requestId); + + //查询付款金额合计是否超出发票金额,付款税额合计是否超出发票税金 + String sql1 = " select a.*,b.invoicecode,b.invoicenumber,b.taxincludedprice,b.tax," + + "(case when a.je-b.taxincludedprice>0 then 'yes' else 'no' end) as bxjesfcc," + + "(case when a.se-b.tax>0 then 'yes' else 'no' end) as sjsfcc from ( "; + sql1+=" select fphm,sum(je) as je,sum(se) as se from " + mainTable + "_dt2 where fphm is not null and mainid="+mainId+" group by fphm"; + sql1+=" ) a ,fnainvoiceledger b where a.fphm=b.id and (a.je>b.taxincludedprice or a.se>b.tax) "; + log.writeLog("查询付款金额合计是否超出发票金额,付款税额合计是否超出发票税金sql1------------>"+sql1); + rs.execute(sql1); + while (rs.next()) { + + String bxjesfcc=Util.null2String(rs.getString("bxjesfcc"));//付款是否已超出 + String sjsfcc=Util.null2String(rs.getString("sjsfcc"));//税金是否已超出 + String invoiceNumber=Util.null2String(rs.getString("invoicenumber"));//发票号码 + String je=Util.null2String(rs.getString("je"));//付款金额 + String se=Util.null2String(rs.getString("se"));//付款税金 + String taxincludedprice=Util.null2String(rs.getString("taxincludedprice"));//发票金额 + String tax=Util.null2o(rs.getString("tax"));//发票税金 + if("yes".equals(bxjesfcc)){ + message.append("付款明细表中发票号【").append(invoiceNumber).append("】的明细行付款金额合计【"+je+"】元超出发票金额【"+taxincludedprice+"】元!
"); + } + if("yes".equals(sjsfcc)){ + //可能存在相除有差额的情况,当相差低于0.2元时可以正常通过 + if(new BigDecimal(se).subtract(new BigDecimal(tax)).compareTo(new BigDecimal("0.2"))>0){ + message.append("付款明细表中发票号【").append(invoiceNumber).append("】的明细行税额合计【"+se+"】元超出发票税金【"+tax+"】元!
"); + } + } + } + if (!"".equals(message.toString())) { + requestInfo.getRequestManager().setMessagecontent(message.toString()); + return Action.FAILURE_AND_CONTINUE; + } + log.writeLog("--------付款单数据校验完毕----requestId值为:" + requestId); + return Action.SUCCESS; + } +} diff --git a/src/main/youhong_ai_jitu_src/jntchina/action/QiankaCheckAction.java b/src/main/youhong_ai_jitu_src/jntchina/action/QiankaCheckAction.java new file mode 100644 index 0000000..4e0ded8 --- /dev/null +++ b/src/main/youhong_ai_jitu_src/jntchina/action/QiankaCheckAction.java @@ -0,0 +1,102 @@ +package jntchina.action; + +import weaver.general.Util; +import selfdev.util.base.BaseUtil; +import selfdev.util.log.LogTool; +import weaver.conn.RecordSet; +import weaver.soa.workflow.request.*; +import weaver.interfaces.workflow.action.BaseAction; + +/** + * @description: 签卡校验 + * @author: daizhishun + * @date: 2021/9/8 + **/ +public class QiankaCheckAction extends BaseAction { + public String execute(RequestInfo ri){ + LogTool log=new LogTool("/log/selfdev/action/hrm", true); + //获取requestid + String requestid=ri.getRequestid(); + String workflowid=ri.getWorkflowid(); + String workflowname=BaseUtil.getBaseInfoByParm("workflowname", "workflow_base", "id", workflowid, ""); + log.writeLog("---------------"+workflowname+"数据写入HR系统开始-------------requestId:" + requestid); + try { + //获取表名 + String tablename=BaseUtil.getBaseInfoByParm("tablename", "workflow_bill", "1", "1", " and id in (select formid from workflow_base where id="+workflowid+")"); + log.writeLog("获取到的主表名为:"+tablename); + RecordSet rs=new RecordSet(); + //查询主表数据 + String sql=" select a.*,b.* from "+tablename+" a " + + "left join "+tablename+"_dt1 b on a.id=b.mainid where a.requestid="+requestid+""; + log.writeLog("查询主表数据sql------------->" + sql); + String xm = "";//姓名 + String mainid = "";//id + rs.execute(sql); + while(rs.next()){ + xm=Util.null2String(rs.getString("resourceId"));//姓名 + mainid = Util.null2String(rs.getString("mainid"));//id + } + String msg=""; + sql="select detail_signdate,detail_signtime from "+tablename+"_dt1 a where mainid="+mainid+" group by detail_signdate,detail_signtime having COUNT(*)>1"; + log.writeLog("查询当前流程签卡明细中是否有2行相同的签卡时间sql------------->" + sql); + rs.execute(sql); + while(rs.next()){ + String date = Util.null2String(rs.getString("detail_signdate"));//签卡日期 + String time = Util.null2String(rs.getString("detail_signtime"));//签卡时间 + String rq_sj = date+" "+time; + msg+=rq_sj+"、"; + } + if(!"".equals(msg)){ + msg="明细中的签卡时间【"+(msg.substring(0,msg.length()-1))+"】存在重复!"; + ri.getRequestManager().setMessageid("111100"); + ri.getRequestManager().setMessagecontent(msg); + return "0"; + } + + //明细表 + DetailTable dtTable = ri.getDetailTableInfo().getDetailTable(0); + String rq = ""; + String sj = ""; + String con = ""; + //遍历明细表字段数据 + Row[] row = dtTable.getRow(); + for (int i = 0 ; i< row.length; i++){ + Cell[] cell = row[i].getCell(); + for (int j = 0;j "+e.toString()); + ri.getRequestManager().setMessageid("111100"); + ri.getRequestManager().setMessagecontent(workflowname+"数据写入HR系统失败,错误信息为:------>"+e.toString()); + return "0"; + } + } + +} diff --git a/src/main/youhong_ai_jitu_src/jntchina/action/QiankaForceDrawBackAction.java b/src/main/youhong_ai_jitu_src/jntchina/action/QiankaForceDrawBackAction.java new file mode 100644 index 0000000..1ee9d11 --- /dev/null +++ b/src/main/youhong_ai_jitu_src/jntchina/action/QiankaForceDrawBackAction.java @@ -0,0 +1,38 @@ +package jntchina.action; + +import selfdev.util.base.BaseUtil; +import selfdev.util.log.LogTool; +import weaver.interfaces.workflow.action.BaseAction; +import weaver.soa.workflow.request.RequestInfo; + +/** + * @description: 签卡流程强制收回时的节点附加操作 + * @author: KangMD + * @date: 2021-12-19 + **/ +public class QiankaForceDrawBackAction extends BaseAction { + + public static LogTool log=new LogTool("/log/selfdev/action/hrm", false); + public String execute(RequestInfo requestInfo){ + String requestId = requestInfo.getRequestid(); // 获取requestid + String workflowid = requestInfo.getWorkflowid(); // 获取workflowid + + //获取工作流名称 + String workflowname = BaseUtil.getBaseInfoByParm("workflowname", "workflow_base", "id", workflowid, ""); + log.writeLog("--------【"+workflowname+"】强制收回时的节点附加操作----requestId值为:" + requestId); + try{ + QiankaForceDrawBackThread forceDrawBackThread=new QiankaForceDrawBackThread(); + //设置参数 + forceDrawBackThread.setRequestInfo(requestInfo); + Thread thread = new Thread(forceDrawBackThread); + //启动线程 + thread.start(); + log.writeLog("--------【"+workflowname+"】强制收回时启用线程--------"); + }catch (Exception e){ + //返回0,调用失败 + log.writeLog("------------------------捕获到的异常是:" + e.toString()); + return "0"; + } + return SUCCESS; + } +} diff --git a/src/main/youhong_ai_jitu_src/jntchina/action/QiankaForceDrawBackThread.java b/src/main/youhong_ai_jitu_src/jntchina/action/QiankaForceDrawBackThread.java new file mode 100644 index 0000000..d6d223c --- /dev/null +++ b/src/main/youhong_ai_jitu_src/jntchina/action/QiankaForceDrawBackThread.java @@ -0,0 +1,125 @@ +package jntchina.action; + +import com.alibaba.fastjson.JSONObject; +import jntchina.util.HttpClientToDC; +import selfdev.util.base.BaseUtil; +import selfdev.util.log.LogTool; +import weaver.conn.RecordSet; +import weaver.file.Prop; +import weaver.general.Util; +import weaver.soa.workflow.request.RequestInfo; + +import java.util.HashMap; +import java.util.Map; + +/** + * @description: 签卡结果回传-成功-放归档节点前操作 + * @author: daizhishun + * @date: 2021/9/10 + **/ +public class QiankaForceDrawBackThread implements Runnable { + + public static LogTool log=new LogTool("/log/selfdev/action/hrm", true); + public RequestInfo requestInfo; + + public RequestInfo getRequestInfo() { + return requestInfo; + } + + public void setRequestInfo(RequestInfo requestInfo) { + this.requestInfo = requestInfo; + } + + public void run(){ + String requestId = requestInfo.getRequestid(); // 获取requestid + try { + log.writeLog("----------1.5秒后再启动【requestId:" + requestId+"】-------------"); + Thread.sleep(1500);//延迟执行 + } catch (InterruptedException e1) { + // TODO Auto-generated catch block + e1.printStackTrace(); + } + log.writeLog("----------1.5秒结束,开启执行代码【requestId:" +requestId+"】-------------"); + + String workflowid = requestInfo.getWorkflowid(); // 获取workflowid + //获取工作流名称 + String workflowname = BaseUtil.getBaseInfoByParm("workflowname", "workflow_base", "id", workflowid, ""); + log.writeLog("--------【"+workflowname+"】数据传入中台开始----requestId值为:" + requestId); + + try{ + //流程当前状态 + String currentnodetype=""; + RecordSet rs = new RecordSet(); + String sql = "select * from workflow_requestbase where requestid = "+requestId+""; + rs.execute(sql); + while (rs.next()) { + currentnodetype = Util.null2String(rs.getString("currentnodetype"));//当前流程状态 + } + log.writeLog("currentnodetype---------------->"+currentnodetype); + //流程当前处于申请节点,才需要调用HR接口 + if(!"0".equals(currentnodetype)){ + log.writeLog("*************流程不是强制收回到申请节点,不需要调用HR接口*************"); + return; + } + + //获取配置文件中的参数,到时候URL路径 + String mode = Prop.getPropValue("DevToDC_jntchina", "mode"); + // 服务器ip:port + String baseUrl = Prop.getPropValue("DevToDC_jntchina", mode + "_baseUrl"); + //访问路径拼接 + String url = baseUrl + "/dcoaapi/hr/attendance"; + + //根据流程id获取主表名称 + String mainTable = RegularizationApplyForAction.getMainTable(requestId); + log.writeLog("--------获取到的表名为----:" + mainTable); + //申请单号 + String C_OA_NUM = ""; + //单据来源:默认OA + String C_APPLY_SOURCE = "OA"; + //流程名称:签卡流程为:10 + String C_WORKFLOW = "10"; + //审批状态 已通过:3,驳回:5驳回至发起人 + String C_STATUS = "5"; + + sql = "select lcbh from "+mainTable+" where requestid = "+requestId+""; + rs.execute(sql); + log.writeLog("---------------->打印sql语句"+sql); + while (rs.next()) { + C_OA_NUM = Util.null2String(rs.getString("lcbh"));//申请单号 + } + + Map map = new HashMap(); + map.put("C_OA_NUM",C_OA_NUM); + map.put("C_APPLY_SOURCE",C_APPLY_SOURCE); + map.put("C_WORKFLOW",C_WORKFLOW); + map.put("C_STATUS",C_STATUS); + String strParm = JSONObject.toJSONString(map); + log.writeLog("---------------打印的Map数据为:-----------------:"+strParm); + + //获取Token + String token = HttpClientToDC.getToken(); + log.writeLog("签卡申请单token------>" + token); + log.writeLog("签卡申请单url------>" + url); + + //调用NCC接口,将数据传给NCC + String returndata = HttpClientToDC.sendPostApi(url,token,strParm); + log.writeLog("【调用数据中台签卡申请单接口返回结果:】" + returndata); + if (!"".equals(returndata) && returndata != null) { + JSONObject jsonObject = JSONObject.parseObject(returndata); + String code = Util.null2String(jsonObject.get("code")); + log.writeLog("--------发送请求返回的code值为:" + code); + if ("1".equals(code)) { + + } else { + String msg = Util.null2String(jsonObject.get("msg")); + log.writeLog("调用HR接口返回错误信息----->" + msg); + } + }else { + log.writeLog("调用HR接口返回为空----->"); + } + }catch (Exception e){ + //返回0,调用失败 + log.writeLog("------------------------捕获到的异常是:" + e.toString()); + } + } +} diff --git a/src/main/youhong_ai_jitu_src/jntchina/action/QiankaHuiChuanReturnAction.java b/src/main/youhong_ai_jitu_src/jntchina/action/QiankaHuiChuanReturnAction.java new file mode 100644 index 0000000..f03b184 --- /dev/null +++ b/src/main/youhong_ai_jitu_src/jntchina/action/QiankaHuiChuanReturnAction.java @@ -0,0 +1,99 @@ +package jntchina.action; + +import com.alibaba.fastjson.JSONObject; +import jntchina.util.HttpClientToDC; +import selfdev.util.base.BaseUtil; +import selfdev.util.log.LogTool; +import weaver.conn.RecordSet; +import weaver.file.Prop; +import weaver.general.Util; +import weaver.interfaces.workflow.action.BaseAction; +import weaver.soa.workflow.request.RequestInfo; + +import java.util.HashMap; +import java.util.Map; + +/** + * @description: 签卡结果回传-退回至发起人 + * @author: daizhishun + * @date: 2021/9/10 + **/ +public class QiankaHuiChuanReturnAction extends BaseAction { + public static LogTool log=new LogTool("/log/selfdev/action/hrm", true); + public String execute(RequestInfo requestInfo){ + String requestId = requestInfo.getRequestid(); // 获取requestid + String workflowid = requestInfo.getWorkflowid(); // 获取workflowid + + //获取工作流名称 + String workflowname = BaseUtil.getBaseInfoByParm("workflowname", "workflow_base", "id", workflowid, ""); + log.writeLog("--------【"+workflowname+"】退回到申请节点时数据传入中台开始----requestId值为:" + requestId); + + try{ + //获取配置文件中的参数,到时候URL路径 + String mode = Prop.getPropValue("DevToDC_jntchina", "mode"); + // 服务器ip:port + String baseUrl = Prop.getPropValue("DevToDC_jntchina", mode + "_baseUrl"); + //访问路径拼接 + String url = baseUrl + "/dcoaapi/hr/attendance"; + + //根据流程id获取主表名称 + String mainTable = RegularizationApplyForAction.getMainTable(requestId); + log.writeLog("--------获取到的表名为----:" + mainTable); + //申请单号 + String C_OA_NUM = ""; + //单据来源:默认OA + String C_APPLY_SOURCE = "OA"; + //流程名称:签卡流程为:10 + String C_WORKFLOW = "10"; + //审批状态:已通过:3,驳回:5 + String C_STATUS = "5"; + + RecordSet rs = new RecordSet(); + String sql = "select lcbh from "+mainTable+" where requestid = "+requestId+""; + rs.execute(sql); + log.writeLog("---------------->打印sql语句"+sql); + while (rs.next()) { + C_OA_NUM = Util.null2String(rs.getString("lcbh"));//申请单号 + } + + Map map = new HashMap(); + map.put("C_OA_NUM",C_OA_NUM); + map.put("C_APPLY_SOURCE",C_APPLY_SOURCE); + map.put("C_WORKFLOW",C_WORKFLOW); + map.put("C_STATUS",C_STATUS); + String strParm = JSONObject.toJSONString(map); + log.writeLog("---------------打印的Map数据为:-----------------:"+strParm); + + //获取Token + String token = HttpClientToDC.getToken(); + log.writeLog("签卡申请单token------>" + token); + log.writeLog("签卡申请单url------>" + url); + + //调用NCC接口,将数据传给NCC + String returndata = HttpClientToDC.sendPostApi(url,token,strParm); + log.writeLog("【调用数据中台签卡申请单接口返回结果:】" + returndata); + if (!"".equals(returndata) && returndata != null) { + JSONObject jsonObject = JSONObject.parseObject(returndata); + String code = Util.null2String(jsonObject.get("code")); + log.writeLog("--------发送请求返回的code值为:" + code); + if ("1".equals(code)) { + return SUCCESS; + } else { + String msg = Util.null2String(jsonObject.get("msg")); + requestInfo.getRequestManager().setMessageid("111100"); + requestInfo.getRequestManager().setMessagecontent(msg); + return "0"; + } + }else { + String ermsg = "流程数据已审批状态提交至中台失败,请联系系统管理员处理!"; + requestInfo.getRequestManager().setMessageid("111100"); + requestInfo.getRequestManager().setMessagecontent(ermsg); + return "0"; + } + }catch (Exception e){ + //返回0,调用失败 + log.writeLog("------------------------捕获到的异常是:" + e.toString()); + return "0"; + } + } +} diff --git a/src/main/youhong_ai_jitu_src/jntchina/action/QiankaHuiChuanSuccessAction.java b/src/main/youhong_ai_jitu_src/jntchina/action/QiankaHuiChuanSuccessAction.java new file mode 100644 index 0000000..70ff469 --- /dev/null +++ b/src/main/youhong_ai_jitu_src/jntchina/action/QiankaHuiChuanSuccessAction.java @@ -0,0 +1,101 @@ +package jntchina.action; + +import com.alibaba.fastjson.JSONObject; +import jntchina.util.HttpClientToDC; +import selfdev.util.base.BaseUtil; +import selfdev.util.log.LogTool; +import weaver.conn.RecordSet; +import weaver.file.Prop; +import weaver.general.Util; +import weaver.interfaces.workflow.action.BaseAction; +import weaver.soa.workflow.request.RequestInfo; + +import java.util.HashMap; +import java.util.Map; + +/** + * @description: 签卡结果回传-成功-放归档节点前操作 + * @author: daizhishun + * @date: 2021/9/10 + **/ +public class QiankaHuiChuanSuccessAction extends BaseAction { + + public static LogTool log=new LogTool("/log/selfdev/action/hrm", true); + public String execute(RequestInfo requestInfo){ + String requestId = requestInfo.getRequestid(); // 获取requestid + String workflowid = requestInfo.getWorkflowid(); // 获取workflowid + + //获取工作流名称 + String workflowname = BaseUtil.getBaseInfoByParm("workflowname", "workflow_base", "id", workflowid, ""); + log.writeLog("--------【"+workflowname+"】数据传入中台开始----requestId值为:" + requestId); + + try{ + //获取配置文件中的参数,到时候URL路径 + String mode = Prop.getPropValue("DevToDC_jntchina", "mode"); + // 服务器ip:port + String baseUrl = Prop.getPropValue("DevToDC_jntchina", mode + "_baseUrl"); + //访问路径拼接 + String url = baseUrl + "/dcoaapi/hr/attendance"; + + //根据流程id获取主表名称 + String mainTable = RegularizationApplyForAction.getMainTable(requestId); + log.writeLog("--------获取到的表名为----:" + mainTable); + //申请单号 + String C_OA_NUM = ""; + //单据来源:默认OA + String C_APPLY_SOURCE = "OA"; + //流程名称:签卡流程为:10 + String C_WORKFLOW = "10"; + //审批状态:已通过:3,驳回:5 + String C_STATUS = "3"; + + RecordSet rs = new RecordSet(); + String sql = "select lcbh from "+mainTable+" where requestid = "+requestId+""; + rs.execute(sql); + log.writeLog("---------------->打印sql语句"+sql); + while (rs.next()) { + C_OA_NUM = Util.null2String(rs.getString("lcbh"));//申请单号 + } + + + Map map = new HashMap(); + map.put("C_OA_NUM",C_OA_NUM); + map.put("C_APPLY_SOURCE",C_APPLY_SOURCE); + map.put("C_WORKFLOW",C_WORKFLOW); + map.put("C_STATUS",C_STATUS); + String strParm = JSONObject.toJSONString(map); + log.writeLog("---------------打印的Map数据为:-----------------:"+strParm); + + //获取Token + String token = HttpClientToDC.getToken(); + log.writeLog("签卡申请单token------>" + token); + log.writeLog("签卡申请单url------>" + url); + + //调用NCC接口,将数据传给NCC + String returndata = HttpClientToDC.sendPostApi(url,token,strParm); + log.writeLog("【调用数据中台签卡申请单接口返回结果:】" + returndata); + if (!"".equals(returndata) && returndata != null) { + JSONObject jsonObject = JSONObject.parseObject(returndata); + String code = Util.null2String(jsonObject.get("code")); + log.writeLog("--------发送请求返回的code值为:" + code); + if ("1".equals(code)) { + return SUCCESS; + } else { + String msg = Util.null2String(jsonObject.get("msg")); + requestInfo.getRequestManager().setMessageid("111100"); + requestInfo.getRequestManager().setMessagecontent(msg); + return "0"; + } + }else { + String ermsg = "流程数据已审批状态提交至中台失败,请联系系统管理员处理!"; + requestInfo.getRequestManager().setMessageid("111100"); + requestInfo.getRequestManager().setMessagecontent(ermsg); + return "0"; + } + }catch (Exception e){ + //返回0,调用失败 + log.writeLog("------------------------捕获到的异常是:" + e.toString()); + return "0"; + } + } +} diff --git a/src/main/youhong_ai_jitu_src/jntchina/action/QingjiaForceDrawBackAction.java b/src/main/youhong_ai_jitu_src/jntchina/action/QingjiaForceDrawBackAction.java new file mode 100644 index 0000000..c0e06fa --- /dev/null +++ b/src/main/youhong_ai_jitu_src/jntchina/action/QingjiaForceDrawBackAction.java @@ -0,0 +1,38 @@ +package jntchina.action; + +import selfdev.util.base.BaseUtil; +import selfdev.util.log.LogTool; +import weaver.interfaces.workflow.action.BaseAction; +import weaver.soa.workflow.request.RequestInfo; + +/** + * @description: 请假强制收回时的节点附加操作 + * @author: KangMD + * @date: 2021-12-13 + **/ +public class QingjiaForceDrawBackAction extends BaseAction { + + public static LogTool log=new LogTool("/log/selfdev/action/hrm", false); + public String execute(RequestInfo requestInfo){ + String requestId = requestInfo.getRequestid(); // 获取requestid + String workflowid = requestInfo.getWorkflowid(); // 获取workflowid + + //获取工作流名称 + String workflowname = BaseUtil.getBaseInfoByParm("workflowname", "workflow_base", "id", workflowid, ""); + log.writeLog("--------【"+workflowname+"】强制收回时的节点附加操作----requestId值为:" + requestId); + try{ + QingjiaForceDrawBackThread forceDrawBackThread=new QingjiaForceDrawBackThread(); + //设置参数 + forceDrawBackThread.setRequestInfo(requestInfo); + Thread thread = new Thread(forceDrawBackThread); + //启动线程 + thread.start(); + log.writeLog("--------【"+workflowname+"】强制收回时启用线程--------"); + }catch (Exception e){ + //返回0,调用失败 + log.writeLog("------------------------捕获到的异常是:" + e.toString()); + return "0"; + } + return SUCCESS; + } +} diff --git a/src/main/youhong_ai_jitu_src/jntchina/action/QingjiaForceDrawBackThread.java b/src/main/youhong_ai_jitu_src/jntchina/action/QingjiaForceDrawBackThread.java new file mode 100644 index 0000000..fdc345d --- /dev/null +++ b/src/main/youhong_ai_jitu_src/jntchina/action/QingjiaForceDrawBackThread.java @@ -0,0 +1,126 @@ +package jntchina.action; + +import java.util.HashMap; +import java.util.Map; + +import com.alibaba.fastjson.JSONObject; + +import jntchina.util.HttpClientToDC; +import selfdev.util.base.BaseUtil; +import selfdev.util.log.LogTool; +import weaver.conn.RecordSet; +import weaver.file.Prop; +import weaver.general.Util; +import weaver.soa.workflow.request.RequestInfo; + +/** + * @description: 请假强制收回时的节点附加操作 + * @author: KangMD + * @date: 2021-12-13 + **/ +public class QingjiaForceDrawBackThread implements Runnable { + + public static LogTool log=new LogTool("/log/selfdev/action/hrm", false); + public RequestInfo requestInfo; + + public RequestInfo getRequestInfo() { + return requestInfo; + } + + public void setRequestInfo(RequestInfo requestInfo) { + this.requestInfo = requestInfo; + } + + public void run(){ + String requestId = requestInfo.getRequestid(); // 获取requestid + try { + log.writeLog("----------1.5秒后再启动【requestId:" + requestId+"】-------------"); + Thread.sleep(1500);//延迟执行 + } catch (InterruptedException e1) { + // TODO Auto-generated catch block + e1.printStackTrace(); + } + log.writeLog("----------1.5秒结束,开启执行代码【requestId:" +requestId+"】-------------"); + + String workflowid = requestInfo.getWorkflowid(); // 获取workflowid + //获取工作流名称 + String workflowname = BaseUtil.getBaseInfoByParm("workflowname", "workflow_base", "id", workflowid, ""); + log.writeLog("--------【"+workflowname+"】强制收回时的节点附加操作----requestId值为:" + requestId); + + try{ + //流程当前状态 + String currentnodetype=""; + RecordSet rs = new RecordSet(); + String sql = "select * from workflow_requestbase where requestid = "+requestId+""; + rs.execute(sql); + while (rs.next()) { + currentnodetype = Util.null2String(rs.getString("currentnodetype"));//当前流程状态 + } + log.writeLog("currentnodetype---------------->"+currentnodetype); + //流程当前处于申请节点,才需要调用HR接口 + if(!"0".equals(currentnodetype)){ + log.writeLog("*************流程不是强制收回到申请节点,不需要调用HR接口*************"); + return; + } + //获取配置文件中的参数,到时候URL路径 + String mode = Prop.getPropValue("DevToDC_jntchina", "mode"); + // 服务器ip:port + String baseUrl = Prop.getPropValue("DevToDC_jntchina", mode + "_baseUrl"); + //访问路径拼接 + String url = baseUrl + "/dcoaapi/hr/attendance"; + + //根据流程id获取主表名称 + String mainTable = RegularizationApplyForAction.getMainTable(requestId); + log.writeLog("--------获取到的表名为----:" + mainTable); + //申请单号 + String C_OA_NUM = ""; + //单据来源:默认OA + String C_APPLY_SOURCE = "OA"; + //流程名称:请假流程为:20 + String C_WORKFLOW = "20"; + //审批状态:已通过:3,驳回:5 + String C_STATUS = "5"; + + sql = "select lcbh from "+mainTable+" where requestid = "+requestId+""; + rs.execute(sql); + log.writeLog("---------------->打印sql语句"+sql); + while (rs.next()) { + C_OA_NUM = Util.null2String(rs.getString("lcbh"));//申请单号 + } + + + Map map = new HashMap(); + map.put("C_OA_NUM",C_OA_NUM); + map.put("C_APPLY_SOURCE",C_APPLY_SOURCE); + map.put("C_WORKFLOW",C_WORKFLOW); + map.put("C_STATUS",C_STATUS); + String strParm = JSONObject.toJSONString(map); + log.writeLog("---------------打印的Map数据为:-----------------:"+strParm); + + //获取Token + String token = HttpClientToDC.getToken(); + log.writeLog("请假申请单token------>" + token); + log.writeLog("请假申请单url------>" + url); + + //调用NCC接口,将数据传给NCC + String returndata = HttpClientToDC.sendPostApi(url,token,strParm); + log.writeLog("【请假强制收回时的节点附加操作调用数据中台请假申请单接口返回结果:】" + returndata); + if (!"".equals(returndata) && returndata != null) { + JSONObject jsonObject = JSONObject.parseObject(returndata); + String code = Util.null2String(jsonObject.get("code")); + log.writeLog("--------发送请求返回的code值为:" + code); + if ("1".equals(code)) { + + }else { + String msg = Util.null2String(jsonObject.get("msg")); + log.writeLog("调用HR接口返回错误信息----->" + msg); + } + }else { + log.writeLog("调用HR接口返回为空----->"); + } + }catch (Exception e){ + //返回0,调用失败 + log.writeLog("------------------------捕获到的异常是:" + e.toString()); + } + } +} diff --git a/src/main/youhong_ai_jitu_src/jntchina/action/QingjiaHuiChuanReturnAction.java b/src/main/youhong_ai_jitu_src/jntchina/action/QingjiaHuiChuanReturnAction.java new file mode 100644 index 0000000..6e65a97 --- /dev/null +++ b/src/main/youhong_ai_jitu_src/jntchina/action/QingjiaHuiChuanReturnAction.java @@ -0,0 +1,102 @@ +package jntchina.action; + +import com.alibaba.fastjson.JSONObject; +import jntchina.util.HttpClientToDC; +import selfdev.util.base.BaseUtil; +import selfdev.util.log.LogTool; +import weaver.conn.RecordSet; +import weaver.file.Prop; +import weaver.general.Util; +import weaver.interfaces.workflow.action.BaseAction; +import weaver.soa.workflow.request.RequestInfo; + +import java.util.HashMap; +import java.util.Map; + +/** + * @description: 请假结果回传-退回至发起人 + * @author: daizhishun + * @date: 2021/9/10 + **/ +public class QingjiaHuiChuanReturnAction extends BaseAction{ + public static LogTool log=new LogTool("/log/selfdev/action/hrm", true); + public String execute(RequestInfo requestInfo){ + String requestId = requestInfo.getRequestid(); // 获取requestid + String workflowid = requestInfo.getWorkflowid(); // 获取workflowid + + //获取工作流名称 + String workflowname = BaseUtil.getBaseInfoByParm("workflowname", "workflow_base", "id", workflowid, ""); + log.writeLog("---------------工作流名称-----------workflowname为:" + workflowname); + log.writeLog("--------【"+workflowname+"】退回到申请节点时数据传入中台开始----requestId值为:" + requestId); + + try{ + //获取配置文件中的参数,到时候URL路径 + String mode = Prop.getPropValue("DevToDC_jntchina", "mode"); + // 服务器ip:port + String baseUrl = Prop.getPropValue("DevToDC_jntchina", mode + "_baseUrl"); + //访问路径拼接 + String url = baseUrl + "/dcoaapi/hr/attendance"; + + //根据流程id获取主表名称 + String mainTable = RegularizationApplyForAction.getMainTable(requestId); + log.writeLog("--------获取到的表名为----:" + mainTable); + //申请单号 + String C_OA_NUM = ""; + //单据来源:默认OA + String C_APPLY_SOURCE = "OA"; + //流程名称:请假流程为:20 + String C_WORKFLOW = "20"; + //审批状态:已通过:3,驳回:5 + String C_STATUS = "5"; + + RecordSet rs = new RecordSet(); + String sql = "select lcbh from "+mainTable+" where requestid = "+requestId+""; + rs.execute(sql); + log.writeLog("----------------》打印sql语句"+sql); + while (rs.next()) { + C_OA_NUM = Util.null2String(rs.getString("lcbh"));//申请单号 + } + + + Map map = new HashMap(); + map.put("C_OA_NUM",C_OA_NUM); + map.put("C_APPLY_SOURCE",C_APPLY_SOURCE); + map.put("C_WORKFLOW",C_WORKFLOW); + map.put("C_STATUS",C_STATUS); + String strParm = JSONObject.toJSONString(map); + log.writeLog("---------------打印的Map数据为:-----------------:"+strParm); + + //获取Token + String token = HttpClientToDC.getToken(); + log.writeLog("请假申请单token------>" + token); + log.writeLog("请假申请单url------>" + url); + + //调用NCC接口,将数据传给NCC + String returndata = HttpClientToDC.sendPostApi(url,token,strParm); + log.writeLog("【调用数据中台请假申请单接口返回结果:】" + returndata); + if (!"".equals(returndata) && returndata != null) { + JSONObject jsonObject = JSONObject.parseObject(returndata); + String code = Util.null2String(jsonObject.get("code")); + log.writeLog("--------发送请求返回的code值为:" + code); + if ("1".equals(code)) { + return SUCCESS; + } else { + String msg = Util.null2String(jsonObject.get("msg")); + requestInfo.getRequestManager().setMessageid("111100"); + requestInfo.getRequestManager().setMessagecontent(msg); + return "0"; + } + }else { + String ermsg = "流程数据已审批状态提交至中台失败,请联系系统管理员处理!"; + requestInfo.getRequestManager().setMessageid("111100"); + requestInfo.getRequestManager().setMessagecontent(ermsg); + return "0"; + } + }catch (Exception e){ + //返回0,调用失败 + log.writeLog("------------------------捕获到的异常是:" + e.toString()); + return "0"; + } + } + +} diff --git a/src/main/youhong_ai_jitu_src/jntchina/action/QingjiaHuiChuanSuccessAction.java b/src/main/youhong_ai_jitu_src/jntchina/action/QingjiaHuiChuanSuccessAction.java new file mode 100644 index 0000000..b266bc8 --- /dev/null +++ b/src/main/youhong_ai_jitu_src/jntchina/action/QingjiaHuiChuanSuccessAction.java @@ -0,0 +1,101 @@ +package jntchina.action; + +import com.alibaba.fastjson.JSONObject; +import jntchina.util.HttpClientToDC; +import selfdev.util.base.BaseUtil; +import selfdev.util.log.LogTool; +import weaver.conn.RecordSet; +import weaver.file.Prop; +import weaver.general.Util; +import weaver.interfaces.workflow.action.BaseAction; +import weaver.soa.workflow.request.RequestInfo; + +import java.util.HashMap; +import java.util.Map; + +/** + * @description: 请假结果回传-成功-放归档节点前操作 + * @author: daizhishun + * @date: 2021/9/10 + **/ +public class QingjiaHuiChuanSuccessAction extends BaseAction { + + public static LogTool log=new LogTool("/log/selfdev/action/hrm", true); + public String execute(RequestInfo requestInfo){ + String requestId = requestInfo.getRequestid(); // 获取requestid + String workflowid = requestInfo.getWorkflowid(); // 获取workflowid + + //获取工作流名称 + String workflowname = BaseUtil.getBaseInfoByParm("workflowname", "workflow_base", "id", workflowid, ""); + log.writeLog("--------【"+workflowname+"】数据传入中台开始----requestId值为:" + requestId); + + try{ + //获取配置文件中的参数,到时候URL路径 + String mode = Prop.getPropValue("DevToDC_jntchina", "mode"); + // 服务器ip:port + String baseUrl = Prop.getPropValue("DevToDC_jntchina", mode + "_baseUrl"); + //访问路径拼接 + String url = baseUrl + "/dcoaapi/hr/attendance"; + + //根据流程id获取主表名称 + String mainTable = RegularizationApplyForAction.getMainTable(requestId); + log.writeLog("--------获取到的表名为----:" + mainTable); + //申请单号 + String C_OA_NUM = ""; + //单据来源:默认OA + String C_APPLY_SOURCE = "OA"; + //流程名称:请假流程为:20 + String C_WORKFLOW = "20"; + //审批状态:已通过:3,驳回:5 + String C_STATUS = "3"; + + RecordSet rs = new RecordSet(); + String sql = "select lcbh from "+mainTable+" where requestid = "+requestId+""; + rs.execute(sql); + log.writeLog("----------------》打印sql语句"+sql); + while (rs.next()) { + C_OA_NUM = Util.null2String(rs.getString("lcbh"));//申请单号 + } + + + Map map = new HashMap(); + map.put("C_OA_NUM",C_OA_NUM); + map.put("C_APPLY_SOURCE",C_APPLY_SOURCE); + map.put("C_WORKFLOW",C_WORKFLOW); + map.put("C_STATUS",C_STATUS); + String strParm = JSONObject.toJSONString(map); + log.writeLog("---------------打印的Map数据为:-----------------:"+strParm); + + //获取Token + String token = HttpClientToDC.getToken(); + log.writeLog("请假申请单token------>" + token); + log.writeLog("请假申请单url------>" + url); + + //调用NCC接口,将数据传给NCC + String returndata = HttpClientToDC.sendPostApi(url,token,strParm); + log.writeLog("【调用数据中台请假申请单接口返回结果:】" + returndata); + if (!"".equals(returndata) && returndata != null) { + JSONObject jsonObject = JSONObject.parseObject(returndata); + String code = Util.null2String(jsonObject.get("code")); + log.writeLog("--------发送请求返回的code值为:" + code); + if ("1".equals(code)) { + return SUCCESS; + } else { + String msg = Util.null2String(jsonObject.get("msg")); + requestInfo.getRequestManager().setMessageid("111100"); + requestInfo.getRequestManager().setMessagecontent(msg); + return "0"; + } + }else { + String ermsg = "流程数据已审批状态提交至中台失败,请联系系统管理员处理!"; + requestInfo.getRequestManager().setMessageid("111100"); + requestInfo.getRequestManager().setMessagecontent(ermsg); + return "0"; + } + }catch (Exception e){ + //返回0,调用失败 + log.writeLog("------------------------捕获到的异常是:" + e.toString()); + return "0"; + } + } +} diff --git a/src/main/youhong_ai_jitu_src/jntchina/action/RegularizationApplyForAction.java b/src/main/youhong_ai_jitu_src/jntchina/action/RegularizationApplyForAction.java new file mode 100644 index 0000000..68206ec --- /dev/null +++ b/src/main/youhong_ai_jitu_src/jntchina/action/RegularizationApplyForAction.java @@ -0,0 +1,138 @@ +package jntchina.action; + + + + +import com.alibaba.fastjson.JSONObject; +import jntchina.util.HttpClientToDC; +import selfdev.util.base.BaseUtil; +import selfdev.util.log.LogTool; +import weaver.conn.RecordSet; +import weaver.file.Prop; +import weaver.general.Util; +import weaver.interfaces.workflow.action.BaseAction; +import weaver.soa.workflow.request.RequestInfo; + +import java.util.HashMap; +import java.util.Map; + + +/** + * @description: 转正申请单 - 审批结果回传 + * @author: dzs + * @date: 2021/7/22 + **/ +public class RegularizationApplyForAction extends BaseAction { + + @Override + public String execute(RequestInfo requestInfo) { + LogTool log = new LogTool("/log/selfdev/action/hrm", true); + String requestId = requestInfo.getRequestid(); // 获取requestid + String workflowid=requestInfo.getWorkflowid(); // 获取workflowid + //获取工作流名称 + String workflowname= BaseUtil.getBaseInfoByParm("workflowname", "workflow_base", "id", workflowid, ""); + log.writeLog("---------------工作流名称-----------workflowname为:" + workflowname); + log.writeLog("--------转正申请单数据传入中台开始----requestId值为:" + requestId); + + //获取配置文件中的参数 + String mode = Prop.getPropValue("DevToDC_jntchina","mode"); + // 服务器ip:port + String baseUrl = Prop.getPropValue("DevToDC_jntchina", mode+"_baseUrl"); + //访问路径拼接 + String url = baseUrl+"/dcoaapi/hr/becomeRegular"; + + + //根据流程id获取主表名称 + String mainTable = RegularizationApplyForAction.getMainTable(requestId); + log.writeLog("--------获取到的表名为----:" + mainTable); + //申请单号 + String C_APP_SEQ = ""; + //申请日期 + String C_APP_DT = ""; + //审批状态 3:已通过(默认) + String C_APPLI_RS = "3"; + //发起人工号 + String EMPLID = ""; + //转正人工号 + String EMPLID2 = ""; + //转正日期 + String C_PRD_DT = ""; + + RecordSet rs = new RecordSet(); + try { + String sql = "select C_APP_SEQ,C_APP_DT,EMPLID,EMPLID2,C_PRD_DT from " + mainTable + " where requestid='" + requestId + "'"; + rs.execute(sql); + log.writeLog("----------------》打印sql语句"+sql); + while (rs.next()) { + C_APP_SEQ = Util.null2String(rs.getString("C_APP_SEQ"));//申请单号 + + C_APP_DT = Util.null2String(rs.getString("C_APP_DT"));//申请日期 + + EMPLID = Util.null2String(rs.getString("EMPLID"));//发起人工号 + + EMPLID2 = Util.null2String(rs.getString("EMPLID2"));//转正人工号 + + C_PRD_DT = Util.null2String(rs.getString("C_PRD_DT"));//转正日期 + } + + //使用Map封装数据 + Map map = new HashMap(); + map.put("C_APP_SEQ",C_APP_SEQ); + map.put("C_APP_DT",C_APP_DT); + map.put("C_APPLI_RS",C_APPLI_RS); + map.put("EMPLID",EMPLID); + map.put("EMPLID2",EMPLID2); + map.put("C_PRD_DT",C_PRD_DT); + String strParm = JSONObject.toJSONString(map); + log.writeLog("---------------打印的Map数据为:-----------------:"+strParm); + + //获取Token + String token = HttpClientToDC.getToken(); + log.writeLog("转正申请单token------>" + token); + log.writeLog("转正申请单url------>" + url); + + + //调用NCC接口,将数据传给NCC + String returndata = HttpClientToDC.sendPostApi(url,token,strParm); + log.writeLog("【调用数据中台转正申请单接口返回结果result:】" + returndata); + if (!"".equals(returndata) && returndata != null) { + JSONObject jsonObject = JSONObject.parseObject(returndata); + String code = Util.null2String(jsonObject.get("code")); + log.writeLog("--------发送请求返回的code值为:" + code); + if("1".equals(code)){ + return SUCCESS; + }else{ + String msg = Util.null2String(jsonObject.get("msg")); + requestInfo.getRequestManager().setMessageid("111100"); + requestInfo.getRequestManager().setMessagecontent(msg); + return "0"; + } + }else{ + String ermsg="流程数据写入NCC转正申请单失败,未获取到接口返回结果,请联系系统管理员处理!"; + requestInfo.getRequestManager().setMessageid("111100"); + requestInfo.getRequestManager().setMessagecontent(ermsg); + return "0"; + } + }catch (Exception e) { + //返回0,调用失败 + log.writeLog("------------------------捕获到的异常是:" + e.toString()); + return "0"; + } + } + + /** + * 使用requestid获取数据库表名 + * @param requestid + * @return + */ + public static String getMainTable(String requestid){ + String tablename = ""; + RecordSet rs = new RecordSet(); + rs.executeQuery("select * from workflow_requestbase a,workflow_base b,workflow_bill c " + +"where a.requestid=? and a.workflowid = b.id and b.formid = c.id",requestid); + while(rs.next()){ + tablename = Util.null2String(rs.getString("tablename")); + } + return tablename; + } +} diff --git a/src/main/youhong_ai_jitu_src/jntchina/action/ReimbursementDataValid.java b/src/main/youhong_ai_jitu_src/jntchina/action/ReimbursementDataValid.java new file mode 100644 index 0000000..7333cd9 --- /dev/null +++ b/src/main/youhong_ai_jitu_src/jntchina/action/ReimbursementDataValid.java @@ -0,0 +1,135 @@ +package jntchina.action; + +import java.math.BigDecimal; +import java.math.RoundingMode; + +import com.working.util.WorkflowUtil; +import selfdev.util.log.LogTool; +import weaver.conn.RecordSet; +import weaver.general.Util; +import weaver.interfaces.workflow.action.Action; +import weaver.interfaces.workflow.action.BaseAction; +import weaver.soa.workflow.request.RequestInfo; + +/** + * @Author Administrator + * @Description 报销单数据校验 + * @Date 2021/1/16 16:27 + */ +public class ReimbursementDataValid extends BaseAction { + + @Override + public String execute(RequestInfo requestInfo) { + + String src = requestInfo.getRequestManager().getSrc();//获取操作方式 + if (!"submit".equals(src)) { // 只有submit才执行接口 + return SUCCESS; + } + + LogTool log = new LogTool("/log/selfdev/action", false); + String requestId = requestInfo.getRequestid(); // 获取requestid + log.writeLog("--------报销单数据校验开始----requestId值为:" + requestId); + + RecordSet rs = new RecordSet(); + RecordSet rs2 = new RecordSet(); + RecordSet rs3 = new RecordSet(); + String mainTable = WorkflowUtil.getMainTable(requestId); + String mainId = ""; + String sql = " select id from " + mainTable + " where requestid='" + requestId + "'"; + rs.execute(sql); + while (rs.next()) { + mainId = Util.null2String(rs.getString("id")); + } + + StringBuilder message = new StringBuilder(); + + + //查询是否有发票被多行分摊 + sql="select fphm from " + mainTable + "_dt8 where fphm is not null and mainid="+mainId+" group by fphm having count(*)>1"; + rs.execute(sql); + int row=rs.getCounts(); + if(row>0){ + while(rs.next()){ + BigDecimal bd_temp=new BigDecimal("0"); + String fphm=Util.null2String(rs.getString("fphm"));//发票号码 + String sql2="select a.*,b.invoicecode,b.invoicenumber,b.taxincludedprice,b.tax from " + mainTable + "_dt8 a,fnainvoiceledger b where a.mainid="+mainId+" and a.fphm=b.id and a.fphm ='"+fphm+"'"; + rs2.execute(sql2); + int row2=rs2.getCounts(); + int temp2=0; + while(rs2.next()){ + String id=Util.null2String(rs2.getString("id"));//主键ID + String je=Util.null2o(rs2.getString("je"));//付款金额 + String sl=Util.null2o(rs2.getString("sl"));//税率 + String tax=Util.null2o(rs2.getString("tax"));//发票税金 + BigDecimal bd_tax=new BigDecimal(tax); + //税额=总金额/(1+税率)*税率 + BigDecimal bd_se=new BigDecimal(je).divide(new BigDecimal("100").add(new BigDecimal(sl)), 10, BigDecimal.ROUND_HALF_UP).multiply(new BigDecimal(sl)).setScale(2, RoundingMode.HALF_UP); + + bd_temp=bd_temp.add(bd_se); + temp2++; + + if(row2==temp2){//最后一行 + //可能存在相除有差额的情况 + if(bd_temp.compareTo(bd_tax)!=0){ + //两者相差多少 + BigDecimal bd_xe=bd_temp.subtract(bd_tax); + log.writeLog("bd_temp=【"+bd_temp+"】、bd_tax=【"+bd_tax+"】,两者相差的税额bd_xe------------>"+bd_xe); + //当相差低于0.2元时,则将差额算在最后一行上面 + if(bd_xe.compareTo(new BigDecimal("0.2"))<=0&&bd_xe.compareTo(new BigDecimal("-0.2"))>=0){ + bd_se=bd_se.subtract(bd_xe).setScale(2, RoundingMode.HALF_UP); + } + } + } + //不含税金额=付款金额-税额 + BigDecimal bhsje=new BigDecimal(je).subtract(bd_se).setScale(2, RoundingMode.HALF_UP); + + //一张发票是否被多个明细行引用时,将此行的税额和不含税金额刷新,其中税额=总金额/(1+税率)*税率 + sql = "update " + mainTable + "_dt8 set se="+bd_se+",bhsje="+bhsje+" where mainid= "+mainId+" and id= "+id; + log.writeLog("一张发票被多个明细行引用刷新其税额和不含税金额sql------------>"+sql); + rs3.execute(sql); + } + } + } + + //判断不含税金额是否小于等于0 + sql="select * from " + mainTable + "_dt8 where bhsje<=0 and mainId="+mainId; + rs.execute(sql); + while (rs.next()) { + message.append("报销明细表中报销金额【"+Util.null2String(rs.getString("je"))+"】-税额【"+Util.null2String(rs.getString("se"))+"】=不含税金额【"+Util.null2String(rs.getString("bhsje"))+"】须大于0
"); + } + + //查询报销金额合计是否超出发票金额,报销税额合计是否超出发票税金 + sql = " select a.*,b.invoicecode,b.invoicenumber,b.taxincludedprice,b.tax," + + "(case when a.je-b.taxincludedprice>0 then 'yes' else 'no' end) as bxjesfcc," + + "(case when a.se-b.tax>0 then 'yes' else 'no' end) as sjsfcc from ( "; + sql+=" select fphm,sum(je) as je,sum(se) as se from " + mainTable + "_dt8 where fphm is not null and mainid="+mainId+" group by fphm"; + sql+=" ) a ,fnainvoiceledger b where a.fphm=b.id and (a.je>b.taxincludedprice or a.se>b.tax) "; + log.writeLog("查询报销金额合计是否超出发票金额,报销税额合计是否超出发票税金sql------------>"+sql); + rs.execute(sql); + while (rs.next()) { + String bxjesfcc=Util.null2String(rs.getString("bxjesfcc"));//报销是否已超出 + String sjsfcc=Util.null2String(rs.getString("sjsfcc"));//税金是否已超出 + String invoiceNumber=Util.null2String(rs.getString("invoicenumber"));//发票号码 + String je=Util.null2String(rs.getString("je"));//报销金额 + String se=Util.null2String(rs.getString("se"));//报销税金 + String taxincludedprice=Util.null2String(rs.getString("taxincludedprice"));//发票金额 + String tax=Util.null2String(rs.getString("tax"));//发票税金 + if("yes".equals(bxjesfcc)){ + message.append("报销明细表中发票号【").append(invoiceNumber).append("】的明细行报销金额合计【"+je+"】元超出发票金额【"+taxincludedprice+"】元!
"); + } + if("yes".equals(sjsfcc)){ + //可能存在相除有差额的情况,当相差低于0.2元时可以正常通过 + if(new BigDecimal(se).subtract(new BigDecimal(tax)).compareTo(new BigDecimal("0.2"))>0){ + message.append("报销明细表中发票号【").append(invoiceNumber).append("】的明细行税额合计【"+se+"】元超出发票税金【"+tax+"】元!
"); + } + } + } + if (!"".equals(message.toString())) { + requestInfo.getRequestManager().setMessagecontent(message.toString()); + return Action.FAILURE_AND_CONTINUE; + } + + log.writeLog("--------报销单数据校验完毕----requestId值为:" + requestId); + return Action.SUCCESS; + } +} diff --git a/src/main/youhong_ai_jitu_src/jntchina/action/ReimbursementOrderAction.java b/src/main/youhong_ai_jitu_src/jntchina/action/ReimbursementOrderAction.java new file mode 100644 index 0000000..9fb6155 --- /dev/null +++ b/src/main/youhong_ai_jitu_src/jntchina/action/ReimbursementOrderAction.java @@ -0,0 +1,316 @@ +package jntchina.action; + +import com.alibaba.fastjson.JSONObject; +import com.alibaba.fastjson.serializer.SerializerFeature; +import com.working.util.WorkflowUtil; +import jntchina.entity.ReimbursementOrder; +import jntchina.entity.ReimbursementOrderBody; +import jntchina.util.DataBaseUtils; +import jntchina.util.HttpClientToDC; +import selfdev.util.base.BaseUtil; +import selfdev.util.base.TimeCommonUtil; +import selfdev.util.log.LogTool; +import weaver.conn.RecordSet; +import weaver.file.Prop; +import weaver.general.Util; +import weaver.hrm.resource.ResourceComInfo; +import weaver.interfaces.workflow.action.Action; +import weaver.interfaces.workflow.action.BaseAction; +import weaver.soa.workflow.request.RequestInfo; + +import java.util.*; + +/** + * @Author Administrator + * @Description 报销单数据传入NCC生成单据 + * @Date 2021/1/8 12:14 + */ +public class ReimbursementOrderAction extends BaseAction { + @Override + public String execute(RequestInfo requestInfo) { + String src = requestInfo.getRequestManager().getSrc();//获取操作方式 + if (!"submit".equals(src)) { // 只有submit才执行接口 + return SUCCESS; + } + LogTool log = new LogTool("/log/selfdev/action", false); + String requestId = requestInfo.getRequestid(); // 获取requestid + //获取当前用户的登录账号(即工号) + String loginid=requestInfo.getRequestManager().getUser().getLoginid(); + log.writeLog("--------报销单数据传入中台开始----requestId值为:" + requestId); + //获取配置文件中的参数 + String mode = Prop.getPropValue("DevToDC_jntchina","mode"); + // 服务器ip:port + String baseUrl = Prop.getPropValue("DevToDC_jntchina", mode+"_baseUrl"); + //String url = baseUrl+ "/dcoaapi/claimForm/receiveData"; + String url = baseUrl+ "/dcnccapi/claimForm/receiveData"; +// List reimbursementList=new ArrayList(); + ReimbursementOrder reimbursementOrder = new ReimbursementOrder(); + + String mainTable = WorkflowUtil.getMainTable(requestId); + String mainId = ""; + String isShowErrorMsg = "";//写入NCC失败时是否显示报错信息 + String pk_org = ""; // 报销单位 JTSDCN0001 + String total = ""; // 报销金额 金额由表体相应字段汇总得出 + String deptid = ""; // 报销人部门 传输编码--------------SD3300201 + String djlxbm = "264X-Cxx-DSBXD"; // 单据类型编码 对私报销单:264X-Cxx-DSBXD 对公报销单:264X-Cxx-DGBXD,此处固定传【264X-Cxx-DSBXD】 + String djrq = TimeCommonUtil.obtainDate(0); // 单据日期 yyyy-mm-dd hh:mm:ss + String payflag = ""; // 支付状态 + String paytarget = "0"; // 收款对象 0=员工,1=供应商,2=客户,默认为员工 + String receiver = ""; // 收款人 + String skyhzh = ""; // 收款人银行账号 + String jkbxr = ""; // 借款报销人 传输编码 + String operator = ""; // 录入人 + String jsfs = ""; // 结算方式 3 网银 + String fkyhzh = ""; // 单位银行账户 传输编码 + String jobid = ""; // 项目 + String zy = ""; // 报销事由 + String kjqj = ""; // 会计期间 + String kjnd = ""; // 会计年度 + String fjzs = ""; // 附件张数 需业务人员在OA上传附件同时填写附件张数后传数据到NCC + String zyx1 = ""; // OA单据号 OA传过来,用于联查单据 + String zyx2 = ""; // 提交人 提交人姓名 + String zyx3 = ""; // OA核销单号 + String zyx5 = ""; // OARequestID + + String xm="";//申请人 + String bxrbm="";//报销人部门 + String bxr="";//报销人 + String zyx8="";//银行付款备注 + String zyx9=requestInfo.getRequestManager().getRequestname();//标题 + + RecordSet rs = new RecordSet(); + try { + String sql = " select * from " + mainTable + " where requestid='" + requestId + "'"; + rs.execute(sql); + while (rs.next()) { + mainId = Util.null2String(rs.getString("id")); + isShowErrorMsg = Util.null2String(rs.getString("xrnccsbcsfts")); + pk_org = Util.null2String(rs.getString("gsmc")); // 报销单位 + xm = Util.null2String(rs.getString("xm")); // 申请人 + bxr = Util.null2String(rs.getString("bxr")); // 报销人 + total = Util.null2String(rs.getString("bxje")); // 报销金额 金额由表体相应字段汇总得出 +// djrq = Util.null2String(rs.getString("cjrq")); // 单据日期 yyyy-mm-dd hh:mm:ss + payflag = Util.null2String(rs.getString("")); // 支付状态 + bxrbm = Util.null2String(rs.getString("bxrbm")); //报销人部门 + zyx8 = Util.null2String(rs.getString("yxfkbz")); //银行付款备注 + jsfs = Util.null2String(rs.getString("bxfs")); //付款方式 + skyhzh = Util.null2String(rs.getString("skkh")).replace(" ", ""); //收款人银行账号(中间若有空格过滤) + fkyhzh = Util.null2String(rs.getString("")); // 付款银行账户 传输编码 + jobid = Util.null2String(rs.getString("")); // 项目 + zy = Util.null2String(rs.getString("bxsm")); // 报销事由 + + fjzs = Util.null2String(rs.getString("fjzs")); // 附件张数 需业务人员在OA上传附件同时填写附件张数后传数据到NCC + zyx1 = Util.null2String(rs.getString("lcbh")); // OA单据号 OA传过来,用于联查单据 + zyx2 = new ResourceComInfo().getLastname(xm); // 提交人 提交人姓名 + zyx5 = requestId; // OARequestID + } + kjqj = djrq.substring(5,7); // 会计期间 + kjnd = djrq.substring(0,4); // 会计年度 + //查询冲抵明细 + sql = " select * from " + mainTable + "_dt2 where mainid='" + mainId + "'"; + rs.execute(sql); + while (rs.next()) { + zyx3+=Util.null2String(rs.getString("jklcbh"))+","; + } + //将借款单号赋值到zyx3字段中 + if(!"".equals(zyx3)){ + zyx3=zyx3.substring(0,zyx3.length()-1); + } + //根据部门ID查询部门编码 + deptid=BaseUtil.getBaseInfoByParm("departmentcode", "hrmdepartment", "id", bxrbm, ""); + + operator = loginid;//当前节点操作者 + receiver = new ResourceComInfo().getWorkcode(bxr); //收款人,与报销人一致 + jkbxr = receiver; // 报销人,与报销人一致 + //截取前150位 + if(zy.length()>120){ + zy=zy.substring(0,120); + } + //结算方式 + if("0".equals(jsfs)){ + jsfs = "3"; //网银 + }else{ + jsfs = "0"; //现金 + } + //获取UUID + String uuid=UUID.randomUUID().toString().replace("-", "").toUpperCase(); + + reimbursementOrder.setUuid(uuid); + reimbursementOrder.setPk_org(pk_org); + reimbursementOrder.setTotal(total); + reimbursementOrder.setDeptid(deptid); + reimbursementOrder.setDjlxbm(djlxbm); + reimbursementOrder.setDjrq(djrq); + reimbursementOrder.setPayflag(payflag); + reimbursementOrder.setPaytarget(paytarget); + reimbursementOrder.setReceiver(receiver); + reimbursementOrder.setSkyhzh(skyhzh); + reimbursementOrder.setJkbxr(jkbxr); + reimbursementOrder.setOperator(operator); + reimbursementOrder.setJsfs(jsfs); + reimbursementOrder.setFkyhzh(fkyhzh); + reimbursementOrder.setJobid(jobid); + reimbursementOrder.setZy(zy); + reimbursementOrder.setKjqj(kjqj); + reimbursementOrder.setKjnd(kjnd); + reimbursementOrder.setFjzs(fjzs); + reimbursementOrder.setZyx1(zyx1); + reimbursementOrder.setZyx2(zyx2); + reimbursementOrder.setZyx3(zyx3); + reimbursementOrder.setZyx5(zyx5); + reimbursementOrder.setZyx8(zyx8); + reimbursementOrder.setZyx9(zyx9); + log.writeLog("【header数据准备完毕...】"); + + //获取OA-NCC发票映射关系表 + Map map_oafplx_nccfplcx=BaseUtil.getMapKeyValueInfoByParm("uf_oafplx_nccfplx", "", "oafplxid", "nccfplxbm"); + List reimbursementOrderBodyList = new ArrayList(); + String tablecode = "arap_bxbusitem"; // 默认固定值 arap_bxbusitem + int rowno = 10; + rs.execute(" select b.bm as szxmbm,c.INVOICECODE,c.INVOICENUMBER,c.invoicetype,a.* from " + mainTable + "_dt8 a " + + "left join uf_fylx b on to_char(a.bxlx,'9999')=to_char(b.id,'9999') " + + "left join fnainvoiceledger c on a.fphm=c.id " + + "where a.mainid = " + mainId); + log.writeLog("查询报销明细sql------>"+sql); + while (rs.next()) { + rowno++;//行号 + ReimbursementOrderBody body = new ReimbursementOrderBody(); + String jobid1 = Util.null2String(rs.getString("")); // 项目 + String amount = Util.null2o(rs.getString("je")); // 报销金额 + String tax_rate = Util.null2o(rs.getString("sl")); // 税率 3% + String tax_amount = Util.null2o(rs.getString("se")); // 税额 + String tni_amount = Util.null2String(rs.getString("bhsje")); // 无税金额 + String szxmid = Util.null2String(rs.getString("szxmbm")); // 收支项目 0101 汽车费用 + String fpdm = Util.null2String(rs.getString("INVOICECODE")); // 发票代码 + String fphm = Util.null2String(rs.getString("INVOICENUMBER")); // 发票号码 + String defitem46 = Util.null2String(rs.getString("wd")); // 网点(成本中心) + String defitem45 = Util.null2String(rs.getString("gj")); // 国家 + String defitem44 = Util.null2String(rs.getString("ck")); // 仓库 + String defitem43 = Util.null2String(rs.getString("cph")); //车牌号 + String defitem42 = Util.null2String(rs.getString("id")); // OA明细行ID + String defitem36 = Util.null2o(rs.getString("fpje")); // 发票金额 + String invoicetype = Util.null2String(rs.getString("invoicetype")); // OA发票类型 + + String fygsbm = Util.null2String(rs.getString("fygsbm")); // 费用承担部门 + //根据部门ID查询部门编码 + String fygsbm_NCC=BaseUtil.getBaseInfoByParm("departmentcode", "hrmdepartment", "id", fygsbm, ""); + //发票金额为空时,默认等于付款金额 + if(Double.parseDouble(defitem36)==0){ + defitem36=amount; + } + + //NCC发票类型 + String fplxpk=Util.null2String(map_oafplx_nccfplcx.get(invoicetype)); + log.writeLog("----amount:" + amount); + log.writeLog("----tax_rate:" + tax_rate); + log.writeLog("----tax_amount:" + tax_amount); + log.writeLog("----tni_amount:" + tni_amount); + log.writeLog("----fygsbm_NCC:" + fygsbm_NCC); + log.writeLog("----defitem36:" + defitem36); + + body.setJobid(jobid1); + body.setDeptid(fygsbm_NCC); + body.setAmount(amount); + body.setTax_rate(tax_rate); + body.setTax_amount(tax_amount); + body.setTni_amount(tni_amount); + body.setTablecode(tablecode); + body.setRowno(rowno+""); + body.setSzxmid(szxmid); + body.setFpdm(fpdm); + body.setFphm(fphm); + body.setFplxpk(fplxpk); + body.setDefitem46(defitem46); + body.setDefitem45(defitem45); + body.setDefitem44(defitem44); + body.setDefitem43(defitem43); + body.setDefitem42(defitem42); + //body.setDefitem48(fygsbm_NCC); + body.setDefitem36(defitem36); + reimbursementOrderBodyList.add(body); + } + reimbursementOrder.setEr_busitem(reimbursementOrderBodyList); +// reimbursementList.add(reimbursementOrder); + String parm=JSONObject.toJSONString(reimbursementOrder, SerializerFeature.DisableCircularReferenceDetect); + log.writeLog("报销单准备传入NCC的数据为------>" + parm); + + //获取TOKEN + String token = HttpClientToDC.getToken(); + log.writeLog("获取数据中台的token------>" + token); + if ("".equals(Util.null2String(token))) { + String tokenMsg="流程提交失败,未获取到数据中台接口TOKEN,请联系管理员处理!"; + //将NCC返回结果回写至OA流程表单 + rs.execute(" update " + mainTable + " set sfcgscnccfkd = 1 ,nccfhxx='" + tokenMsg.replace("'", "''") + "' where requestid = " + requestId); + //是否需要显示报错信息 + if("yes".equals(isShowErrorMsg)){ + requestInfo.getRequestManager().setMessagecontent(tokenMsg); + return Action.FAILURE_AND_CONTINUE; + }else{ + return SUCCESS; + } + } + + + + log.writeLog("param:"+parm); + + + //调用NCC接口,将数据传给NCC + String returndata = HttpClientToDC.sendPostApi(url,token, parm); + log.writeLog("【调用数据中台报销接口返回结果result:】" + returndata); + if (!"".equals(returndata) && returndata != null) { + JSONObject jsonObject = JSONObject.parseObject(returndata); + String success = Util.null2String(jsonObject.get("succ")); + log.writeLog("--------发送请求返回的success值为:" + success); + if ("true".equals(success)) { + JSONObject data = jsonObject.getJSONObject("data"); + String billno = Util.null2String(data.get("billno"));//NCC单号 + log.writeLog("--------发送请求返回的billno值为:" + billno); + //将NCC返回结果回写至OA流程表单 + rs.execute(" update " + mainTable + " set sfcgscnccfkd = 0 , nccfkdh = '" + billno + "',nccfhxx='' where requestid = " + requestId); + } else { + String message = Util.null2String(jsonObject.get("msg")); + String message2=message.replace("'", "''"); + //超出1333个字符,则只截取前面这部分 + if(message2.length()>1334){ + message2=message2.substring(0,1333); + } + //将NCC返回结果回写至OA流程表单 + rs.execute(" update " + mainTable + " set sfcgscnccfkd = 1 ,nccfhxx='" + message2 + "' where requestid = " + requestId); + //是否需要显示报错信息 + if("yes".equals(isShowErrorMsg)){ + requestInfo.getRequestManager().setMessagecontent("流程数据写入NCC对私报销单失败,失败信息:
"+message); + return Action.FAILURE_AND_CONTINUE; + }else{ + return SUCCESS; + } + } + } else { + String ermsg="流程数据写入NCC对私报销单失败,未获取到接口返回结果,请联系系统管理员处理!"; + //将NCC返回结果回写至OA流程表单 + rs.execute(" update " + mainTable + " set sfcgscnccfkd = 1 ,nccfhxx='" + ermsg.replace("'", "''") + "' where requestid = " + requestId); + //是否需要显示报错信息 + if("yes".equals(isShowErrorMsg)){ + requestInfo.getRequestManager().setMessagecontent(ermsg); + return Action.FAILURE_AND_CONTINUE; + }else{ + return SUCCESS; + } + } + + } catch (Exception e) { + String ermsg="流程数据生成NCC对私报销单失败!" + e.toString(); + //将NCC返回结果回写至OA流程表单 + rs.execute(" update " + mainTable + " set sfcgscnccfkd = 1 ,nccfhxx='" + ermsg.replace("'", "''") + "' where requestid = " + requestId); + //是否需要显示报错信息 + if("yes".equals(isShowErrorMsg)){ + requestInfo.getRequestManager().setMessagecontent(ermsg); + return Action.FAILURE_AND_CONTINUE; + }else{ + return SUCCESS; + } + } + log.writeLog("--------报销单数据传入NCC完毕----requestId值为:" + requestId); + return Action.SUCCESS; + } +} \ No newline at end of file diff --git a/src/main/youhong_ai_jitu_src/jntchina/action/ReimbursementOrderActionAddCD.java b/src/main/youhong_ai_jitu_src/jntchina/action/ReimbursementOrderActionAddCD.java new file mode 100644 index 0000000..84b67c3 --- /dev/null +++ b/src/main/youhong_ai_jitu_src/jntchina/action/ReimbursementOrderActionAddCD.java @@ -0,0 +1,335 @@ +package jntchina.action; + +import java.util.*; + +import com.alibaba.fastjson.JSONObject; +import com.alibaba.fastjson.serializer.SerializerFeature; +import com.working.util.WorkflowUtil; + +import jntchina.entity.ReimbursementOrder; +import jntchina.entity.ReimbursementOrderBody; +import jntchina.util.DataBaseUtils; +import jntchina.util.HttpClientToDC; +import selfdev.util.base.BaseUtil; +import selfdev.util.base.TimeCommonUtil; +import selfdev.util.log.LogTool; +import weaver.conn.RecordSet; +import weaver.file.Prop; +import weaver.general.Util; +import weaver.hrm.resource.ResourceComInfo; +import weaver.interfaces.workflow.action.Action; +import weaver.interfaces.workflow.action.BaseAction; +import weaver.soa.workflow.request.RequestInfo; + +/** + * @Author Administrator + * @Description 报销单数据传入NCC生成单据 + * @Date 2021/1/8 12:14 + */ + public class ReimbursementOrderActionAddCD extends BaseAction { + @Override + public String execute(RequestInfo requestInfo) { + String src = requestInfo.getRequestManager().getSrc();//获取操作方式 + if (!"submit".equals(src)) { // 只有submit才执行接口 + return SUCCESS; + } + LogTool log = new LogTool("/log/selfdev/action", false); + String requestId = requestInfo.getRequestid(); // 获取requestid + //获取当前用户的登录账号(即工号) + String loginid=requestInfo.getRequestManager().getUser().getLoginid(); + log.writeLog("--------报销单数据传入中台开始----requestId值为:" + requestId); + //获取配置文件中的参数 + String mode = Prop.getPropValue("DevToDC_jntchina","mode"); + // 服务器ip:port + String baseUrl = Prop.getPropValue("DevToDC_jntchina", mode+"_baseUrl"); + //String url = baseUrl+ "/dcoaapi/claimForm/receiveData"; + String url = baseUrl+ "/dcnccapi/claimForm/receiveData"; +// List reimbursementList=new ArrayList(); + ReimbursementOrder reimbursementOrder = new ReimbursementOrder(); + + String mainTable = WorkflowUtil.getMainTable(requestId); + String mainId = ""; + String isShowErrorMsg = "";//写入NCC失败时是否显示报错信息 + String pk_org = ""; // 报销单位 JTSDCN0001 + String total = ""; // 报销金额 金额由表体相应字段汇总得出 + String deptid = ""; // 报销人部门 传输编码--------------SD3300201 + String djlxbm = "264X-Cxx-DSBXD"; // 单据类型编码 对私报销单:264X-Cxx-DSBXD 对公报销单:264X-Cxx-DGBXD,此处固定传【264X-Cxx-DSBXD】 + String djrq = TimeCommonUtil.obtainDate(0); // 单据日期 yyyy-mm-dd hh:mm:ss + String payflag = ""; // 支付状态 + String paytarget = "0"; // 收款对象 0=员工,1=供应商,2=客户,默认为员工 + String receiver = ""; // 收款人 + String skyhzh = ""; // 收款人银行账号 + String jkbxr = ""; // 借款报销人 传输编码 + String operator = ""; // 录入人 + String jsfs = ""; // 结算方式 3 网银 + String fkyhzh = ""; // 单位银行账户 传输编码 + String jobid = ""; // 项目 + String zy = ""; // 报销事由 + String kjqj = ""; // 会计期间 + String kjnd = ""; // 会计年度 + String fjzs = ""; // 附件张数 需业务人员在OA上传附件同时填写附件张数后传数据到NCC + String zyx1 = ""; // OA单据号 OA传过来,用于联查单据 + String zyx2 = ""; // 提交人 提交人姓名 + String zyx3 = ""; // OA核销单号 + String zyx5 = ""; // OARequestID + + String xm="";//申请人 + String bxrbm="";//报销人部门 + String bxr="";//报销人 + String zyx8="";//银行付款备注 +// String zyx9=requestInfo.getRequestManager().getRequestname();//标题 + String zyx9=requestInfo.getRequestManager().getRequestname().length()>140?requestInfo.getRequestManager().getRequestname().substring(0,140):requestInfo.getRequestManager().getRequestname();//标题 + + RecordSet rs = new RecordSet(); + try { + String sql = " select * from " + mainTable + " where requestid='" + requestId + "'"; + rs.execute(sql); + while (rs.next()) { + mainId = Util.null2String(rs.getString("id")); + isShowErrorMsg = Util.null2String(rs.getString("xrnccsbcsfts")); + pk_org = Util.null2String(rs.getString("gsmc")); // 报销单位 + xm = Util.null2String(rs.getString("xm")); // 申请人 + bxr = Util.null2String(rs.getString("bxr")); // 报销人 + total = Util.null2String(rs.getString("bxje")); // 报销金额 金额由表体相应字段汇总得出 +// djrq = Util.null2String(rs.getString("cjrq")); // 单据日期 yyyy-mm-dd hh:mm:ss + payflag = Util.null2String(rs.getString("")); // 支付状态 + bxrbm = Util.null2String(rs.getString("bxrbm")); //报销人部门 + zyx8 = Util.null2String(rs.getString("yxfkbz")); //银行付款备注 + jsfs = Util.null2String(rs.getString("bxfs")); //付款方式 + skyhzh = Util.null2String(rs.getString("skkh")).replace(" ", ""); //收款人银行账号(中间若有空格过滤) + fkyhzh = Util.null2String(rs.getString("")); // 付款银行账户 传输编码 + jobid = Util.null2String(rs.getString("")); // 项目 + zy = Util.null2String(rs.getString("bxsm")); // 报销事由 + + fjzs = Util.null2String(rs.getString("fjzs")); // 附件张数 需业务人员在OA上传附件同时填写附件张数后传数据到NCC + zyx1 = Util.null2String(rs.getString("lcbh")); // OA单据号 OA传过来,用于联查单据 + zyx2 = new ResourceComInfo().getLastname(xm); // 提交人 提交人姓名 + zyx5 = requestId; // OARequestID + } + kjqj = djrq.substring(5,7); // 会计期间 + kjnd = djrq.substring(0,4); // 会计年度 + //查询冲抵明细 + sql = " select * from " + mainTable + "_dt2 where mainid='" + mainId + "'"; + rs.execute(sql); + while (rs.next()) { + zyx3+=Util.null2String(rs.getString("jklcbh"))+","; + } + //将借款单号赋值到zyx3字段中 + if(!"".equals(zyx3)){ + zyx3=zyx3.substring(0,zyx3.length()-1); + } + //根据部门ID查询部门编码 + deptid=BaseUtil.getBaseInfoByParm("departmentcode", "hrmdepartment", "id", bxrbm, ""); + + operator = loginid;//当前节点操作者 + receiver = new ResourceComInfo().getWorkcode(bxr); //收款人,与报销人一致 + jkbxr = receiver; // 报销人,与报销人一致 + //截取前150位 + if(zy.length()>120){ + zy=zy.substring(0,120); + } + //结算方式 + if("0".equals(jsfs)){ + jsfs = "3"; //网银 + }else{ + jsfs = "0"; //现金 + } + //获取UUID + String uuid=UUID.randomUUID().toString().replace("-", "").toUpperCase(); + + reimbursementOrder.setUuid(uuid); + reimbursementOrder.setPk_org(pk_org); + reimbursementOrder.setTotal(total); + reimbursementOrder.setDeptid(deptid); + reimbursementOrder.setDjlxbm(djlxbm); + reimbursementOrder.setDjrq(djrq); + reimbursementOrder.setPayflag(payflag); + reimbursementOrder.setPaytarget(paytarget); + reimbursementOrder.setReceiver(receiver); + reimbursementOrder.setSkyhzh(skyhzh); + reimbursementOrder.setJkbxr(jkbxr); + reimbursementOrder.setOperator(operator); + reimbursementOrder.setJsfs(jsfs); + reimbursementOrder.setFkyhzh(fkyhzh); + reimbursementOrder.setJobid(jobid); + reimbursementOrder.setZy(zy); + reimbursementOrder.setKjqj(kjqj); + reimbursementOrder.setKjnd(kjnd); + reimbursementOrder.setFjzs(fjzs); + reimbursementOrder.setZyx1(zyx1); + reimbursementOrder.setZyx2(zyx2); + reimbursementOrder.setZyx3(zyx3); + reimbursementOrder.setZyx5(zyx5); + reimbursementOrder.setZyx8(zyx8); + reimbursementOrder.setZyx9(zyx9); + log.writeLog("【header数据准备完毕...】"); + + //获取OA-NCC发票映射关系表 + Map map_oafplx_nccfplcx=BaseUtil.getMapKeyValueInfoByParm("uf_oafplx_nccfplx", "", "oafplxid", "nccfplxbm"); + List reimbursementOrderBodyList = new ArrayList(); + String tablecode = "arap_bxbusitem"; // 默认固定值 arap_bxbusitem + int rowno = 10; + rs.execute(" select b.bm as szxmbm,c.INVOICECODE,c.INVOICENUMBER,c.invoicetype,a.* from " + mainTable + "_dt8 a " + + "left join uf_fylx b on to_char(a.bxlx)=to_char(b.id) " + + "left join fnainvoiceledger c on a.fphm=c.id " + + "where a.mainid = " + mainId); + log.writeLog("查询报销明细sql------>"+sql); + while (rs.next()) { + rowno++;//行号 + ReimbursementOrderBody body = new ReimbursementOrderBody(); + String jobid1 = Util.null2String(rs.getString("")); // 项目 + String amount = Util.null2o(rs.getString("je")); // 报销金额 + String tax_rate = Util.null2o(rs.getString("sl")); // 税率 3% + String tax_amount = Util.null2o(rs.getString("se")); // 税额 + String tni_amount = Util.null2String(rs.getString("bhsje")); // 无税金额 + String szxmid = Util.null2String(rs.getString("szxmbm")); // 收支项目 0101 汽车费用 + String fpdm = Util.null2String(rs.getString("INVOICECODE")); // 发票代码 + String fphm = Util.null2String(rs.getString("INVOICENUMBER")); // 发票号码 + String defitem46 = Util.null2String(rs.getString("wd")); // 网点(成本中心) + String defitem45 = Util.null2String(rs.getString("gj")); // 国家 + String defitem44 = Util.null2String(rs.getString("ck")); // 仓库 + String defitem43 = Util.null2String(rs.getString("cph")); //车牌号 + String defitem42 = Util.null2String(rs.getString("id")); // OA明细行ID + String defitem36 = Util.null2o(rs.getString("fpje")); // 发票金额 + String invoicetype = Util.null2String(rs.getString("invoicetype")); // OA发票类型 + + String fygsbm = Util.null2String(rs.getString("fygsbm")); // 费用承担部门 + //根据部门ID查询部门编码 + String fygsbm_NCC=BaseUtil.getBaseInfoByParm("departmentcode", "hrmdepartment", "id", fygsbm, ""); + //发票金额为空时,默认等于付款金额 + if(Double.parseDouble(defitem36)==0){ + defitem36=amount; + } + + //NCC发票类型 + String fplxpk=Util.null2String(map_oafplx_nccfplcx.get(invoicetype)); + log.writeLog("----amount:" + amount); + log.writeLog("----tax_rate:" + tax_rate); + log.writeLog("----tax_amount:" + tax_amount); + log.writeLog("----tni_amount:" + tni_amount); + log.writeLog("----fygsbm_NCC:" + fygsbm_NCC); + log.writeLog("----defitem36:" + defitem36); + + body.setJobid(jobid1); + body.setDeptid(fygsbm_NCC); + body.setAmount(amount); + body.setTax_rate(tax_rate); + body.setTax_amount(tax_amount); + body.setTni_amount(tni_amount); + body.setTablecode(tablecode); + body.setRowno(rowno+""); + body.setSzxmid(szxmid); + body.setFpdm(fpdm); + body.setFphm(fphm); + body.setFplxpk(fplxpk); + body.setDefitem46(defitem46); + body.setDefitem45(defitem45); + body.setDefitem44(defitem44); + body.setDefitem43(defitem43); + body.setDefitem42(defitem42); + //body.setDefitem48(fygsbm_NCC); + body.setDefitem36(defitem36); + reimbursementOrderBodyList.add(body); + } + reimbursementOrder.setEr_busitem(reimbursementOrderBodyList); +// reimbursementList.add(reimbursementOrder); + String parm=JSONObject.toJSONString(reimbursementOrder, SerializerFeature.DisableCircularReferenceDetect); + log.writeLog("报销单准备传入NCC的数据为------>" + parm); + + //获取TOKEN + String token = HttpClientToDC.getToken(); + log.writeLog("获取数据中台的token------>" + token); + if ("".equals(Util.null2String(token))) { + String tokenMsg="流程提交失败,未获取到数据中台接口TOKEN,请联系管理员处理!"; + //将NCC返回结果回写至OA流程表单 + rs.execute(" update " + mainTable + " set sfcgscnccfkd = 1 ,nccfhxx='" + tokenMsg.replace("'", "''") + "' where requestid = " + requestId); + //是否需要显示报错信息 + if("yes".equals(isShowErrorMsg)){ + requestInfo.getRequestManager().setMessagecontent(tokenMsg); + return Action.FAILURE_AND_CONTINUE; + }else{ + return SUCCESS; + } + } + + + { + //新增代码 + JSONObject jsonObject1 = JSONObject.parseObject(parm); + ArrayList> list = new ArrayList<>(); + ArrayList> dt2List = DataBaseUtils.getProcessData(requestInfo, 2); + for (Map dtmap : dt2List) { + HashMap map = new HashMap<>(); + map.put("jkbillcode", dtmap.get("NCCJKDH")); + map.put("szxmid", "901038"); + map.put("cxmny", dtmap.get("CDJE")); + list.add(map); + } + + jsonObject1.put("er_bxcontrast", list); + parm = jsonObject1.toJSONString(); + } + + + log.writeLog("param:"+parm); + + + //调用NCC接口,将数据传给NCC + String returndata = HttpClientToDC.sendPostApi(url,token, parm); + log.writeLog("【调用数据中台报销接口返回结果result:】" + returndata); + if (!"".equals(returndata) && returndata != null) { + JSONObject jsonObject = JSONObject.parseObject(returndata); + String success = Util.null2String(jsonObject.get("succ")); + log.writeLog("--------发送请求返回的success值为:" + success); + if ("true".equals(success)) { + JSONObject data = jsonObject.getJSONObject("data"); + String billno = Util.null2String(data.get("billno"));//NCC单号 + log.writeLog("--------发送请求返回的billno值为:" + billno); + //将NCC返回结果回写至OA流程表单 + rs.execute(" update " + mainTable + " set sfcgscnccfkd = 0 , nccfkdh = '" + billno + "',nccfhxx='' where requestid = " + requestId); + } else { + String message = Util.null2String(jsonObject.get("msg")); + String message2=message.replace("'", "''"); + //超出1333个字符,则只截取前面这部分 + if(message2.length()>1334){ + message2=message2.substring(0,1333); + } + //将NCC返回结果回写至OA流程表单 + rs.execute(" update " + mainTable + " set sfcgscnccfkd = 1 ,nccfhxx='" + message2 + "' where requestid = " + requestId); + //是否需要显示报错信息 + if("yes".equals(isShowErrorMsg)){ + requestInfo.getRequestManager().setMessagecontent("流程数据写入NCC对私报销单失败,失败信息:
"+message); + return Action.FAILURE_AND_CONTINUE; + }else{ + return SUCCESS; + } + } + } else { + String ermsg="流程数据写入NCC对私报销单失败,未获取到接口返回结果,请联系系统管理员处理!"; + //将NCC返回结果回写至OA流程表单 + rs.execute(" update " + mainTable + " set sfcgscnccfkd = 1 ,nccfhxx='" + ermsg.replace("'", "''") + "' where requestid = " + requestId); + //是否需要显示报错信息 + if("yes".equals(isShowErrorMsg)){ + requestInfo.getRequestManager().setMessagecontent(ermsg); + return Action.FAILURE_AND_CONTINUE; + }else{ + return SUCCESS; + } + } + + } catch (Exception e) { + String ermsg="流程数据生成NCC对私报销单失败!" + e.toString(); + //将NCC返回结果回写至OA流程表单 + rs.execute(" update " + mainTable + " set sfcgscnccfkd = 1 ,nccfhxx='" + ermsg.replace("'", "''") + "' where requestid = " + requestId); + //是否需要显示报错信息 + if("yes".equals(isShowErrorMsg)){ + requestInfo.getRequestManager().setMessagecontent(ermsg); + return Action.FAILURE_AND_CONTINUE; + }else{ + return SUCCESS; + } + } + log.writeLog("--------报销单数据传入NCC完毕----requestId值为:" + requestId); + return Action.SUCCESS; + } +} \ No newline at end of file diff --git a/src/main/youhong_ai_jitu_src/jntchina/action/ReimbursementOrderActionYY.java b/src/main/youhong_ai_jitu_src/jntchina/action/ReimbursementOrderActionYY.java new file mode 100644 index 0000000..9ace62a --- /dev/null +++ b/src/main/youhong_ai_jitu_src/jntchina/action/ReimbursementOrderActionYY.java @@ -0,0 +1,341 @@ +package jntchina.action; + +import com.alibaba.fastjson.JSONObject; +import com.alibaba.fastjson.serializer.SerializerFeature; +import com.working.util.WorkflowUtil; +import jntchina.entity.ReimbursementOrderYY; +import jntchina.entity.ReimbursementOrderBodyYY; +import jntchina.util.DataBaseUtils; +import jntchina.util.HttpClientToDC; +import selfdev.util.base.BaseUtil; +import selfdev.util.base.TimeCommonUtil; +import selfdev.util.log.LogTool; +import weaver.conn.RecordSet; +import weaver.file.Prop; +import weaver.general.Util; +import weaver.hrm.resource.ResourceComInfo; +import weaver.interfaces.workflow.action.Action; +import weaver.interfaces.workflow.action.BaseAction; +import weaver.soa.workflow.request.RequestInfo; + +import java.util.*; + +/** + * @Author Administrator + * @Description 报销单数据传入NCC生成单据(紜毅)2 + * @Date 2021/1/8 12:14 + */ +public class ReimbursementOrderActionYY extends BaseAction { + @Override + public String execute(RequestInfo requestInfo) { + String src = requestInfo.getRequestManager().getSrc();//获取操作方式 + if (!"submit".equals(src)) { // 只有submit才执行接口 + return SUCCESS; + } + LogTool log = new LogTool("/log/selfdev/action", false); + String requestId = requestInfo.getRequestid(); // 获取requestid + //获取当前用户的登录账号(即工号) + String loginid=requestInfo.getRequestManager().getUser().getLoginid(); + log.writeLog("--------报销单数据传入中台开始----requestId值为:" + requestId); + //获取配置文件中的参数 + String mode = Prop.getPropValue("DevToDC_jntchina","mode"); + // 服务器ip:port + String baseUrl = Prop.getPropValue("DevToDC_jntchina", mode+"_baseUrl"); + //String url = baseUrl+ "/dcoaapi/claimForm/receiveData"; + String url = baseUrl+ "/dcnccapi/claimForm/receiveData"; +// List reimbursementList=new ArrayList(); + ReimbursementOrderYY reimbursementOrder = new ReimbursementOrderYY(); + + String mainTable = WorkflowUtil.getMainTable(requestId); + String mainId = ""; + String isShowErrorMsg = "";//写入NCC失败时是否显示报错信息 + String pk_org = ""; // 报销单位 JTSDCN0001 + String total = ""; // 报销金额 金额由表体相应字段汇总得出 + String deptid = ""; // 报销人部门 传输编码--------------SD3300201 + String djlxbm = "264X-Cxx-DSBXD"; // 单据类型编码 对私报销单:264X-Cxx-DSBXD 对公报销单:264X-Cxx-DGBXD,此处固定传【264X-Cxx-DSBXD】 + String djrq = TimeCommonUtil.obtainDate(0); // 单据日期 yyyy-mm-dd hh:mm:ss + String payflag = ""; // 支付状态 + String paytarget = "0"; // 收款对象 0=员工,1=供应商,2=客户,默认为员工 + String receiver = ""; // 收款人 + String skyhzh = ""; // 收款人银行账号 + String jkbxr = ""; // 借款报销人 传输编码 + String operator = ""; // 录入人 + String jsfs = ""; // 结算方式 3 网银 + String fkyhzh = ""; // 单位银行账户 传输编码 + String jobid = ""; // 项目 + String zy = ""; // 报销事由 + String kjqj = ""; // 会计期间 + String kjnd = ""; // 会计年度 + String fjzs = ""; // 附件张数 需业务人员在OA上传附件同时填写附件张数后传数据到NCC + String zyx1 = ""; // OA单据号 OA传过来,用于联查单据 + String zyx2 = ""; // 提交人 提交人姓名 + String zyx3 = ""; // OA核销单号 + String zyx5 = ""; // OARequestID + + String xm="";//申请人 + String bxrbm="";//报销人部门 + String bxr="";//报销人 + String zyx8="";//银行付款备注 +// String zyx9=requestInfo.getRequestManager().getRequestname();//标题 + String zyx9=requestInfo.getRequestManager().getRequestname().length()>140?requestInfo.getRequestManager().getRequestname().substring(0,140):requestInfo.getRequestManager().getRequestname();//标题 + + RecordSet rs = new RecordSet(); + try { + String sql = " select * from " + mainTable + " where requestid='" + requestId + "'"; + rs.execute(sql); + while (rs.next()) { + mainId = Util.null2String(rs.getString("id")); + isShowErrorMsg = Util.null2String(rs.getString("xrnccsbcsfts")); + pk_org = Util.null2String(rs.getString("gsmc")); // 报销单位 + xm = Util.null2String(rs.getString("xm")); // 申请人 + bxr = Util.null2String(rs.getString("bxr")); // 报销人 + total = Util.null2String(rs.getString("bxje")); // 报销金额 金额由表体相应字段汇总得出 +// djrq = Util.null2String(rs.getString("cjrq")); // 单据日期 yyyy-mm-dd hh:mm:ss + payflag = Util.null2String(rs.getString("")); // 支付状态 + bxrbm = Util.null2String(rs.getString("bxrbm")); //报销人部门 + zyx8 = Util.null2String(rs.getString("yxfkbz")); //银行付款备注 + jsfs = Util.null2String(rs.getString("bxfs")); //付款方式 + skyhzh = Util.null2String(rs.getString("skkh")).replace(" ", ""); //收款人银行账号(中间若有空格过滤) + fkyhzh = Util.null2String(rs.getString("")); // 付款银行账户 传输编码 + jobid = Util.null2String(rs.getString("")); // 项目 + zy = Util.null2String(rs.getString("bxsm")); // 报销事由 + + fjzs = Util.null2String(rs.getString("fjzs")); // 附件张数 需业务人员在OA上传附件同时填写附件张数后传数据到NCC + zyx1 = Util.null2String(rs.getString("lcbh")); // OA单据号 OA传过来,用于联查单据 + zyx2 = new ResourceComInfo().getLastname(xm); // 提交人 提交人姓名 + zyx5 = requestId; // OARequestID + } + kjqj = djrq.substring(5,7); // 会计期间 + kjnd = djrq.substring(0,4); // 会计年度 + //查询冲抵明细 + sql = " select * from " + mainTable + "_dt2 where mainid='" + mainId + "'"; + rs.execute(sql); + while (rs.next()) { + zyx3+=Util.null2String(rs.getString("jklcbh"))+","; + } + //将借款单号赋值到zyx3字段中 + if(!"".equals(zyx3)){ + zyx3=zyx3.substring(0,zyx3.length()-1); + } + //根据部门ID查询部门编码 + deptid=BaseUtil.getBaseInfoByParm("departmentcode", "hrmdepartment", "id", bxrbm, ""); +// deptid=BaseUtil.getBaseInfoByParm("BM", "uf_dept_ncc", "id", bxrbm, ""); + + operator = loginid;//当前节点操作者 + receiver = new ResourceComInfo().getWorkcode(bxr); //收款人,与报销人一致 + jkbxr = receiver; // 报销人,与报销人一致 + //截取前150位 + if(zy.length()>120){ + zy=zy.substring(0,120); + } + //结算方式 + if("0".equals(jsfs)){ + jsfs = "3"; //网银 + }else{ + jsfs = "0"; //现金 + } + //获取UUID + String uuid=UUID.randomUUID().toString().replace("-", "").toUpperCase(); + + reimbursementOrder.setUuid(uuid); + reimbursementOrder.setPk_org(pk_org); + reimbursementOrder.setTotal(total); + reimbursementOrder.setDeptid(deptid); + reimbursementOrder.setDjlxbm(djlxbm); + reimbursementOrder.setDjrq(djrq); + reimbursementOrder.setPayflag(payflag); + reimbursementOrder.setPaytarget(paytarget); + reimbursementOrder.setReceiver(receiver); + reimbursementOrder.setSkyhzh(skyhzh); + reimbursementOrder.setJkbxr(jkbxr); + reimbursementOrder.setOperator(operator); + reimbursementOrder.setJsfs(jsfs); + reimbursementOrder.setFkyhzh(fkyhzh); + reimbursementOrder.setJobid(jobid); + reimbursementOrder.setZy(zy); + reimbursementOrder.setKjqj(kjqj); + reimbursementOrder.setKjnd(kjnd); + reimbursementOrder.setFjzs(fjzs); + reimbursementOrder.setZyx1(zyx1); + reimbursementOrder.setZyx2(zyx2); + reimbursementOrder.setZyx3(zyx3); + reimbursementOrder.setZyx5(zyx5); + reimbursementOrder.setZyx8(zyx8); + reimbursementOrder.setZyx9(zyx9); +// reimbursementOrder.setDeptidIsNeedConvert("no"); + + log.writeLog("【header数据准备完毕...】"); + + //获取OA-NCC发票映射关系表 + Map map_oafplx_nccfplcx=BaseUtil.getMapKeyValueInfoByParm("uf_oafplx_nccfplx", "", "oafplxid", "nccfplxbm"); + List reimbursementOrderBodyList = new ArrayList(); + String tablecode = "arap_bxbusitem"; // 默认固定值 arap_bxbusitem + int rowno = 10; + rs.execute(" select b.bm as szxmbm,c.INVOICECODE,c.INVOICENUMBER,c.invoicetype,a.* from " + mainTable + "_dt8 a " + + "left join uf_fylx b on to_char(a.bxlx)=to_char(b.id) " + + "left join fnainvoiceledger c on a.fphm=c.id " + + "where a.mainid = " + mainId); + log.writeLog("查询报销明细sql------>"+sql); + while (rs.next()) { + rowno++;//行号 + ReimbursementOrderBodyYY body = new ReimbursementOrderBodyYY(); + String jobid1 = Util.null2String(rs.getString("")); // 项目 + String amount = Util.null2o(rs.getString("je")); // 报销金额 + String tax_rate = Util.null2o(rs.getString("sl")); // 税率 3% + String tax_amount = Util.null2o(rs.getString("se")); // 税额 + String tni_amount = Util.null2String(rs.getString("bhsje")); // 无税金额 + String szxmid = Util.null2String(rs.getString("fylx")); // 收支项目 0101 汽车费用 + szxmid = DataBaseUtils.getFirstValue("select bm from uf_fylx where id = " + szxmid); + String fpdm = Util.null2String(rs.getString("INVOICECODE")); // 发票代码 + String fphm = Util.null2String(rs.getString("INVOICENUMBER")); // 发票号码 + String defitem46 = Util.null2String(rs.getString("wd")); // 网点(成本中心) + String defitem45 = Util.null2String(rs.getString("gj")); // 国家 + String defitem44 = Util.null2String(rs.getString("ck")); // 仓库 + String defitem43 = Util.null2String(rs.getString("cph")); //车牌号 + String defitem42 = Util.null2String(rs.getString("id")); // OA明细行ID + String defitem36 = Util.null2o(rs.getString("fpje")); // 发票金额 + String invoicetype = Util.null2String(rs.getString("invoicetype")); // OA发票类型 + + String fygsbm = Util.null2String(rs.getString("fygsbm")); // 费用承担部门 + //根据部门ID查询部门编码 +// String fygsbm_NCC=BaseUtil.getBaseInfoByParm("bm", "uf_dept_ncc", "id", fygsbm, ""); + String fygsbm_NCC = fygsbm; + //发票金额为空时,默认等于付款金额 + if(Double.parseDouble(defitem36)==0){ + defitem36=amount; + } + + //NCC发票类型 + String fplxpk=Util.null2String(map_oafplx_nccfplcx.get(invoicetype)); + log.writeLog("----amount:" + amount); + log.writeLog("----tax_rate:" + tax_rate); + log.writeLog("----tax_amount:" + tax_amount); + log.writeLog("----tni_amount:" + tni_amount); + log.writeLog("----fygsbm_NCC:" + fygsbm_NCC); + log.writeLog("----defitem36:" + defitem36); + + body.setJobid(jobid1); + body.setDeptid(fygsbm_NCC); + body.setAmount(amount); + body.setTax_rate(tax_rate); + body.setTax_amount(tax_amount); + body.setTni_amount(tni_amount); + body.setTablecode(tablecode); + body.setRowno(rowno+""); + body.setSzxmid(szxmid); + body.setFpdm(fpdm); + body.setFphm(fphm); + body.setFplxpk(fplxpk); + body.setDefitem46(defitem46); + body.setDefitem45(defitem45); + body.setDefitem44(defitem44); + body.setDefitem43(defitem43); + body.setDefitem42(defitem42); + body.setDeptidIsNeedConvert("no"); + //body.setDefitem48(fygsbm_NCC); + body.setDefitem36(defitem36); + reimbursementOrderBodyList.add(body); + } + reimbursementOrder.setEr_busitem(reimbursementOrderBodyList); +// reimbursementList.add(reimbursementOrder); + String parm=JSONObject.toJSONString(reimbursementOrder, SerializerFeature.DisableCircularReferenceDetect); + log.writeLog("报销单准备传入NCC的数据为------>" + parm); + + //获取TOKEN + String token = HttpClientToDC.getToken(); + log.writeLog("获取数据中台的token------>" + token); + if ("".equals(Util.null2String(token))) { + String tokenMsg="流程提交失败,未获取到数据中台接口TOKEN,请联系管理员处理!"; + //将NCC返回结果回写至OA流程表单 + rs.execute(" update " + mainTable + " set sfcgscnccfkd = 1 ,nccfhxx='" + tokenMsg.replace("'", "''") + "' where requestid = " + requestId); + //是否需要显示报错信息 + if("yes".equals(isShowErrorMsg)){ + requestInfo.getRequestManager().setMessagecontent(tokenMsg); + return Action.FAILURE_AND_CONTINUE; + }else{ + return SUCCESS; + } + } + + JSONObject jsonObject1 = JSONObject.parseObject(parm); + ArrayList> list = new ArrayList<>(); + ArrayList> dt2List = DataBaseUtils.getProcessData(requestInfo, 2); + for (Map dtmap : dt2List) { + HashMap map = new HashMap<>(); + map.put("jkbillcode", dtmap.get("NCCJKDH")); + map.put("szxmid", "901038"); + map.put("cxmny", dtmap.get("CDJE")); + list.add(map); + } + + + + + + jsonObject1.put("er_bxcontrast", list); + parm = jsonObject1.toJSONString(); + + + log.writeLog("url2:"+url); + log.writeLog("token2:"+token); + log.writeLog("param2:"+parm); + + //调用NCC接口,将数据传给NCC + String returndata = HttpClientToDC.sendPostApi(url,token, parm); + log.writeLog("【调用数据中台报销接口返回结果result:】" + returndata); + if (!"".equals(returndata) && returndata != null) { + JSONObject jsonObject = JSONObject.parseObject(returndata); + String success = Util.null2String(jsonObject.get("succ")); + log.writeLog("--------发送请求返回的success值为:" + success); + if ("true".equals(success)) { + JSONObject data = jsonObject.getJSONObject("data"); + String billno = Util.null2String(data.get("billno"));//NCC单号 + log.writeLog("--------发送请求返回的billno值为:" + billno); + //将NCC返回结果回写至OA流程表单 + rs.execute(" update " + mainTable + " set sfcgscnccfkd = 0 , nccfkdh = '" + billno + "',nccfhxx='' where requestid = " + requestId); + } else { + String message = Util.null2String(jsonObject.get("msg")); + String message2=message.replace("'", "''"); + //超出1333个字符,则只截取前面这部分 + if(message2.length()>1334){ + message2=message2.substring(0,1333); + } + //将NCC返回结果回写至OA流程表单 + rs.execute(" update " + mainTable + " set sfcgscnccfkd = 1 ,nccfhxx='" + message2 + "' where requestid = " + requestId); + //是否需要显示报错信息 + if("yes".equals(isShowErrorMsg)){ + requestInfo.getRequestManager().setMessagecontent("流程数据写入NCC对私报销单失败,失败信息:
"+message); + return Action.FAILURE_AND_CONTINUE; + }else{ + return SUCCESS; + } + } + } else { + String ermsg="流程数据写入NCC对私报销单失败,未获取到接口返回结果,请联系系统管理员处理!"; + //将NCC返回结果回写至OA流程表单 + rs.execute(" update " + mainTable + " set sfcgscnccfkd = 1 ,nccfhxx='" + ermsg.replace("'", "''") + "' where requestid = " + requestId); + //是否需要显示报错信息 + if("yes".equals(isShowErrorMsg)){ + requestInfo.getRequestManager().setMessagecontent(ermsg); + return Action.FAILURE_AND_CONTINUE; + }else{ + return SUCCESS; + } + } + + } catch (Exception e) { + String ermsg="流程数据生成NCC对私报销单失败!" + e.toString(); + //将NCC返回结果回写至OA流程表单 + rs.execute(" update " + mainTable + " set sfcgscnccfkd = 1 ,nccfhxx='" + ermsg.replace("'", "''") + "' where requestid = " + requestId); + //是否需要显示报错信息 + if("yes".equals(isShowErrorMsg)){ + requestInfo.getRequestManager().setMessagecontent(ermsg); + return Action.FAILURE_AND_CONTINUE; + }else{ + return SUCCESS; + } + } + log.writeLog("--------报销单数据传入NCC完毕----requestId值为:" + requestId); + return Action.SUCCESS; + } +} \ No newline at end of file diff --git a/src/main/youhong_ai_jitu_src/jntchina/action/ReimbursementOrderActionYYSJ.java b/src/main/youhong_ai_jitu_src/jntchina/action/ReimbursementOrderActionYYSJ.java new file mode 100644 index 0000000..3192053 --- /dev/null +++ b/src/main/youhong_ai_jitu_src/jntchina/action/ReimbursementOrderActionYYSJ.java @@ -0,0 +1,331 @@ +package jntchina.action; + +import com.alibaba.fastjson.JSONObject; +import com.alibaba.fastjson.serializer.SerializerFeature; +import com.working.util.WorkflowUtil; +import jntchina.entity.ReimbursementOrderBodyYY; +import jntchina.entity.ReimbursementOrderYY; +import jntchina.util.HttpClientToDC; +import selfdev.util.base.BaseUtil; +import selfdev.util.base.TimeCommonUtil; +import selfdev.util.log.LogTool; +import weaver.conn.RecordSet; +import weaver.file.Prop; +import weaver.general.Util; +import weaver.hrm.resource.ResourceComInfo; +import weaver.interfaces.workflow.action.Action; +import weaver.interfaces.workflow.action.BaseAction; +import weaver.soa.workflow.request.RequestInfo; + +import java.util.ArrayList; +import java.util.List; +import java.util.Map; +import java.util.UUID; + +/** + * @Author Administrator + * @Description 报销单数据传入NCC生成单据(紜毅)2 + * @Date 2021/1/8 12:14 + */ +public class ReimbursementOrderActionYYSJ extends BaseAction { + @Override + public String execute(RequestInfo requestInfo) { + String src = requestInfo.getRequestManager().getSrc();//获取操作方式 + if (!"submit".equals(src)) { // 只有submit才执行接口 + return SUCCESS; + } + LogTool log = new LogTool("/log/selfdev/action", false); + String requestId = requestInfo.getRequestid(); // 获取requestid + //获取当前用户的登录账号(即工号) + String loginid=requestInfo.getRequestManager().getUser().getLoginid(); + log.writeLog("--------报销单数据传入中台开始----requestId值为:" + requestId); + //获取配置文件中的参数 + String mode = Prop.getPropValue("DevToDC_jntchina","mode"); + // 服务器ip:port + String baseUrl = Prop.getPropValue("DevToDC_jntchina", mode+"_baseUrl"); + //String url = baseUrl+ "/dcoaapi/claimForm/receiveData"; + String url = baseUrl+ "/dcnccapi/claimForm/receiveData"; +// List reimbursementList=new ArrayList(); + ReimbursementOrderYY reimbursementOrder = new ReimbursementOrderYY(); + + String mainTable = WorkflowUtil.getMainTable(requestId); + String mainId = ""; + String isShowErrorMsg = "";//写入NCC失败时是否显示报错信息 + String pk_org = ""; // 报销单位 JTSDCN0001 + String total = ""; // 报销金额 金额由表体相应字段汇总得出 + String deptid = ""; // 报销人部门 传输编码--------------SD3300201 + String djlxbm = "264X-Cxx-DSBXD"; // 单据类型编码 对私报销单:264X-Cxx-DSBXD 对公报销单:264X-Cxx-DGBXD,此处固定传【264X-Cxx-DSBXD】 + String djrq = TimeCommonUtil.obtainDate(0); // 单据日期 yyyy-mm-dd hh:mm:ss + String payflag = ""; // 支付状态 + String paytarget = "0"; // 收款对象 0=员工,1=供应商,2=客户,默认为员工 + String receiver = ""; // 收款人 + String skyhzh = ""; // 收款人银行账号 + String jkbxr = ""; // 借款报销人 传输编码 + String operator = ""; // 录入人 + String jsfs = ""; // 结算方式 3 网银 + String fkyhzh = ""; // 单位银行账户 传输编码 + String jobid = ""; // 项目 + String zy = ""; // 报销事由 + String kjqj = ""; // 会计期间 + String kjnd = ""; // 会计年度 + String fjzs = ""; // 附件张数 需业务人员在OA上传附件同时填写附件张数后传数据到NCC + String zyx1 = ""; // OA单据号 OA传过来,用于联查单据 + String zyx2 = ""; // 提交人 提交人姓名 + String zyx3 = ""; // OA核销单号 + String zyx5 = ""; // OARequestID + String sqrbm = ""; + String bm = ""; + + String xm="";//申请人 + String bxrbm="";//报销人部门 + String bxr="";//报销人 + String zyx8="";//银行付款备注 +// String zyx9=requestInfo.getRequestManager().getRequestname();//标题 + String zyx9=requestInfo.getRequestManager().getRequestname().length()>140?requestInfo.getRequestManager().getRequestname().substring(0,140):requestInfo.getRequestManager().getRequestname();//标题 + + RecordSet rs = new RecordSet(); + try { + String sql = " select * from " + mainTable + " where requestid='" + requestId + "'"; + rs.execute(sql); + while (rs.next()) { + mainId = Util.null2String(rs.getString("id")); + isShowErrorMsg = Util.null2String(rs.getString("xrnccsbcsfts")); + pk_org = Util.null2String(rs.getString("gsmc")); // 报销单位 + xm = Util.null2String(rs.getString("xm")); // 申请人 + bxr = Util.null2String(rs.getString("sjbm")); // 报销人 + total = Util.null2String(rs.getString("bxje")); // 报销金额 金额由表体相应字段汇总得出 +// djrq = Util.null2String(rs.getString("cjrq")); // 单据日期 yyyy-mm-dd hh:mm:ss + payflag = Util.null2String(rs.getString("")); // 支付状态 + bxrbm = Util.null2String(rs.getString("bxrbm")); //报销人部门 + zyx8 = Util.null2String(rs.getString("yxfkbz")); //银行付款备注 + jsfs = Util.null2String(rs.getString("bxfs")); //付款方式 + skyhzh = Util.null2String(rs.getString("skkh")).replace(" ", ""); //收款人银行账号(中间若有空格过滤) + fkyhzh = Util.null2String(rs.getString("")); // 付款银行账户 传输编码 + jobid = Util.null2String(rs.getString("")); // 项目 + zy = Util.null2String(rs.getString("bxsm")); // 报销事由 + sqrbm = Util.null2String(rs.getString("bm")); // 申请人部门 + + fjzs = Util.null2String(rs.getString("fjzs")); // 附件张数 需业务人员在OA上传附件同时填写附件张数后传数据到NCC + zyx1 = Util.null2String(rs.getString("lcbh")); // OA单据号 OA传过来,用于联查单据 + zyx2 = new ResourceComInfo().getLastname(xm); // 提交人 提交人姓名 + zyx5 = requestId; // OARequestID + } + kjqj = djrq.substring(5,7); // 会计期间 + kjnd = djrq.substring(0,4); // 会计年度 + //查询冲抵明细 + sql = " select * from " + mainTable + "_dt2 where mainid='" + mainId + "'"; + rs.execute(sql); + while (rs.next()) { + zyx3+=Util.null2String(rs.getString("jklcbh"))+","; + } + //将借款单号赋值到zyx3字段中 + if(!"".equals(zyx3)){ + zyx3=zyx3.substring(0,zyx3.length()-1); + } + //根据部门ID查询部门编码 + deptid=BaseUtil.getBaseInfoByParm("departmentcode", "hrmdepartment", "id", sqrbm, ""); +// deptid=BaseUtil.getBaseInfoByParm("BM", "uf_dept_ncc", "id", bxrbm, ""); + + operator = loginid;//当前节点操作者 + receiver = bxr; //收款人,与报销人一致 + jkbxr = bxr; // 报销人,与报销人一致 + //截取前150位 + if(zy.length()>120){ + zy=zy.substring(0,120); + } + //结算方式 + if("0".equals(jsfs)){ + jsfs = "3"; //网银 + }else{ + jsfs = "0"; //现金 + } + //获取UUID + String uuid=UUID.randomUUID().toString().replace("-", "").toUpperCase(); + + reimbursementOrder.setUuid(uuid); + reimbursementOrder.setPk_org(pk_org); + reimbursementOrder.setTotal(total); + reimbursementOrder.setDeptid(deptid); + reimbursementOrder.setDjlxbm(djlxbm); + reimbursementOrder.setDjrq(djrq); + reimbursementOrder.setPayflag(payflag); + reimbursementOrder.setPaytarget(paytarget); + reimbursementOrder.setReceiver(receiver); + reimbursementOrder.setSkyhzh(skyhzh); + reimbursementOrder.setJkbxr(jkbxr); + reimbursementOrder.setOperator(operator); + reimbursementOrder.setJsfs(jsfs); + reimbursementOrder.setFkyhzh(fkyhzh); + reimbursementOrder.setJobid(jobid); + reimbursementOrder.setZy(zy); + reimbursementOrder.setKjqj(kjqj); + reimbursementOrder.setKjnd(kjnd); + reimbursementOrder.setFjzs(fjzs); + reimbursementOrder.setZyx1(zyx1); + reimbursementOrder.setZyx2(zyx2); + reimbursementOrder.setZyx3(zyx3); + reimbursementOrder.setZyx5(zyx5); + reimbursementOrder.setZyx8(zyx8); + reimbursementOrder.setZyx9(zyx9); +// reimbursementOrder.setDeptidIsNeedConvert("no"); + + log.writeLog("【header数据准备完毕...】"); + + //获取OA-NCC发票映射关系表 + Map map_oafplx_nccfplcx=BaseUtil.getMapKeyValueInfoByParm("uf_oafplx_nccfplx", "", "oafplxid", "nccfplxbm"); + List reimbursementOrderBodyList = new ArrayList(); + String tablecode = "arap_bxbusitem"; // 默认固定值 arap_bxbusitem + int rowno = 10; + rs.execute(" select b.bm as szxmbm,c.INVOICECODE,c.INVOICENUMBER,c.invoicetype,a.* from " + mainTable + "_dt8 a " + + "left join uf_fylx b on to_char(a.bxlx)=to_char(b.id) " + + "left join fnainvoiceledger c on a.fphm=c.id " + + "where a.mainid = " + mainId); + log.writeLog("查询报销明细sql------>"+sql); + while (rs.next()) { + rowno++;//行号 + ReimbursementOrderBodyYY body = new ReimbursementOrderBodyYY(); + String jobid1 = Util.null2String(rs.getString("")); // 项目 + String amount = Util.null2o(rs.getString("fkje")); // 报销金额 + String tax_rate = Util.null2o(rs.getString("sl")); // 税率 3% + String tax_amount = Util.null2o(rs.getString("se")); // 税额 +// String tni_amount = Util.null2String(rs.getString("bhsje")); // 无税金额 + String tni_amount = amount; // 无税金额-----表体含税金额等于税金加不含税金额 + String szxmid =BaseUtil.getBaseInfoByParm("bm", "uf_fylx", "id", Util.null2String(rs.getString("fylx")), "") ; // 收支项目 0101 汽车费用 + String fpdm = Util.null2String(rs.getString("INVOICECODE")); // 发票代码 + String fphm = Util.null2String(rs.getString("INVOICENUMBER")); // 发票号码 + String defitem46 = Util.null2String(rs.getString("cbzx")); // 网点(成本中心) + String defitem45 = Util.null2String(rs.getString("gj")); // 国家 + String defitem44 = Util.null2String(rs.getString("ck")); // 仓库 + String defitem43 = Util.null2String(rs.getString("cph")); //车牌号 + String defitem42 = Util.null2String(rs.getString("id")); // OA明细行ID + String defitem36 = Util.null2o(rs.getString("fpje")); // 发票金额 + String invoicetype = Util.null2String(rs.getString("invoicetype")); // OA发票类型 + + String fygsbm = Util.null2String(rs.getString("fygsbm")); // 费用承担部门 + //根据部门ID查询部门编码 + String fygsbm_NCC=fygsbm; + //发票金额为空时,默认等于付款金额 +// if(Double.parseDouble(defitem36)==0){ + defitem36=amount; +// } + + //NCC发票类型 + String fplxpk=Util.null2String(map_oafplx_nccfplcx.get(invoicetype)); + log.writeLog("----amount:" + amount); + log.writeLog("----tax_rate:" + tax_rate); + log.writeLog("----tax_amount:" + tax_amount); + log.writeLog("----tni_amount:" + tni_amount); + log.writeLog("----fygsbm_NCC:" + fygsbm_NCC); + log.writeLog("----defitem36:" + defitem36); + + body.setJobid(jobid1); + body.setDeptid(fygsbm_NCC); + body.setAmount(amount); + body.setTax_rate(tax_rate); + body.setTax_amount(tax_amount); + body.setTni_amount(tni_amount); + body.setTablecode(tablecode); + body.setRowno(rowno+""); + body.setSzxmid(szxmid); + body.setFpdm(fpdm); + body.setFphm(fphm); + body.setFplxpk(fplxpk); + body.setDefitem46(defitem46); + body.setDefitem45(defitem45); + body.setDefitem44(defitem44); + body.setDefitem43(defitem43); + body.setDefitem42(defitem42); + body.setDeptidIsNeedConvert("no"); + //body.setDefitem48(fygsbm_NCC); + body.setDefitem36(defitem36); + reimbursementOrderBodyList.add(body); + } + reimbursementOrder.setEr_busitem(reimbursementOrderBodyList); +// reimbursementList.add(reimbursementOrder); + String parm=JSONObject.toJSONString(reimbursementOrder, SerializerFeature.DisableCircularReferenceDetect); + log.writeLog("报销单准备传入NCC的数据为------>" + parm); + + //获取TOKEN + String token = HttpClientToDC.getToken(); + log.writeLog("获取数据中台的token------>" + token); + if ("".equals(Util.null2String(token))) { + String tokenMsg="流程提交失败,未获取到数据中台接口TOKEN,请联系管理员处理!"; + //将NCC返回结果回写至OA流程表单 + rs.execute(" update " + mainTable + " set sfcgscnccfkd = 1 ,nccfhxx='" + tokenMsg.replace("'", "''") + "' where requestid = " + requestId); + //是否需要显示报错信息 + if("yes".equals(isShowErrorMsg)){ + requestInfo.getRequestManager().setMessagecontent(tokenMsg); + return Action.FAILURE_AND_CONTINUE; + }else{ + return SUCCESS; + } + } + + JSONObject jsonObject1 = JSONObject.parseObject(parm); + jsonObject1.put("zyx30", "批量"); + parm = jsonObject1.toJSONString(); + + + log.writeLog("url2:"+url); + log.writeLog("token2:"+token); + log.writeLog("param2:"+parm); + + //调用NCC接口,将数据传给NCC + String returndata = HttpClientToDC.sendPostApi(url,token, parm); + log.writeLog("【调用数据中台报销接口返回结果result:】" + returndata); + if (!"".equals(returndata) && returndata != null) { + JSONObject jsonObject = JSONObject.parseObject(returndata); + String success = Util.null2String(jsonObject.get("succ")); + log.writeLog("--------发送请求返回的success值为:" + success); + if ("true".equals(success)) { + JSONObject data = jsonObject.getJSONObject("data"); + String billno = Util.null2String(data.get("billno"));//NCC单号 + log.writeLog("--------发送请求返回的billno值为:" + billno); + //将NCC返回结果回写至OA流程表单 + rs.execute(" update " + mainTable + " set sfcgscnccfkd = 0 , nccfkdh = '" + billno + "',nccfhxx='' where requestid = " + requestId); + } else { + String message = Util.null2String(jsonObject.get("msg")); + String message2=message.replace("'", "''"); + //超出1333个字符,则只截取前面这部分 + if(message2.length()>1334){ + message2=message2.substring(0,1333); + } + //将NCC返回结果回写至OA流程表单 + rs.execute(" update " + mainTable + " set sfcgscnccfkd = 1 ,nccfhxx='" + message2 + "' where requestid = " + requestId); + //是否需要显示报错信息 + if("yes".equals(isShowErrorMsg)){ + requestInfo.getRequestManager().setMessagecontent("流程数据写入NCC对私报销单失败,失败信息:
"+message); + return Action.FAILURE_AND_CONTINUE; + }else{ + return SUCCESS; + } + } + } else { + String ermsg="流程数据写入NCC对私报销单失败,未获取到接口返回结果,请联系系统管理员处理!"; + //将NCC返回结果回写至OA流程表单 + rs.execute(" update " + mainTable + " set sfcgscnccfkd = 1 ,nccfhxx='" + ermsg.replace("'", "''") + "' where requestid = " + requestId); + //是否需要显示报错信息 + if("yes".equals(isShowErrorMsg)){ + requestInfo.getRequestManager().setMessagecontent(ermsg); + return Action.FAILURE_AND_CONTINUE; + }else{ + return SUCCESS; + } + } + + } catch (Exception e) { + String ermsg="流程数据生成NCC对私报销单失败!" + e.toString(); + //将NCC返回结果回写至OA流程表单 + rs.execute(" update " + mainTable + " set sfcgscnccfkd = 1 ,nccfhxx='" + ermsg.replace("'", "''") + "' where requestid = " + requestId); + //是否需要显示报错信息 + if("yes".equals(isShowErrorMsg)){ + requestInfo.getRequestManager().setMessagecontent(ermsg); + return Action.FAILURE_AND_CONTINUE; + }else{ + return SUCCESS; + } + } + log.writeLog("--------报销单数据传入NCC完毕----requestId值为:" + requestId); + return Action.SUCCESS; + } +} \ No newline at end of file diff --git a/src/main/youhong_ai_jitu_src/jntchina/action/ResignationFormWriteBackAction.bak b/src/main/youhong_ai_jitu_src/jntchina/action/ResignationFormWriteBackAction.bak new file mode 100644 index 0000000..88bdd12 --- /dev/null +++ b/src/main/youhong_ai_jitu_src/jntchina/action/ResignationFormWriteBackAction.bak @@ -0,0 +1,240 @@ +package jntchina.action; + +import com.alibaba.fastjson.JSONObject; +import jntchina.util.HttpClientToDC; +import selfdev.util.base.BaseUtil; +import selfdev.util.log.LogTool; +import weaver.conn.RecordSet; +import weaver.file.Prop; +import weaver.general.Util; +import weaver.hrm.resource.ResourceComInfo; +import weaver.interfaces.workflow.action.Action; +import weaver.soa.workflow.request.RequestInfo; + +import java.util.HashMap; +import java.util.Map; + +/** + * 离职申请单写入中台(HR系统) + */ +public class ResignationFormWriteBackAction implements Action { + + public String execute(RequestInfo requestInfo) { + + LogTool log=new LogTool("/log/selfdev/action/hrm", false); + + String requestId = requestInfo.getRequestid(); + String workflowid=requestInfo.getWorkflowid(); + String workflowname= BaseUtil.getBaseInfoByParm("workflowname", "workflow_base", "id", workflowid, ""); + log.writeLog("---------------"+workflowname+"开始写入HR-------------requestId:" + requestId); + + //获取配置文件中的参数 + String mode = Prop.getPropValue("DevToDC_jntchina","mode"); + // 服务器ip:port + String baseUrl = Prop.getPropValue("DevToDC_jntchina", mode+"_baseUrl"); + String url = baseUrl+"/dcoaapi/hr/resignation"; + //获取OA表名称 + String tablename=BaseUtil.getBaseInfoByParm("tablename", "workflow_bill", "1", "1", " and id in (select formid from workflow_base where id="+workflowid+")"); + + + String sql = " select C_APP_SEQ," + + "C_APP_DT," + + "XM EMPLID," + + "EMPLID2," + + "DESCR254," + + "lzyyACT_REASON_SUB2 ACT_REASON_SUB," + + "lzyyACT_REASON_SUB1 ACTION_REASON," + + "LAST_WORK_DAY," + + "C_BLACKLIST," + + "hmdlx C_BCKST_VTN_TPYE," + + "C_BLACKLIST_REASON," + + "EMPLID3," + + "C_DEPT_MANAGER," + + "MANAGER_ID," + + "C_SUPERVISOR1," + + "SUPERVISOR_ID," + + "C_DEPT_MANAGER1," + + "C_DEPT_EXPAND1," + + "EXPAND_EMPLID," + + "MANAGER_ID1 " + + "from "+tablename+" where requestid = "+requestId+" "; + log.writeLog("---------------sql------------->" + sql); + RecordSet rs = new RecordSet(); + + try { + rs.executeQuery(sql); + + Map map = new HashMap(); + String[] columnName = rs.getColumnName(); + rs.next(); + for (int i = 0; i < columnName.length; i++) { + map.put(columnName[i], Util.null2String(rs.getString(columnName[i]))); + } + + //是否部门负责人 + if (map.get("C_DEPT_MANAGER").equals("0")){ + map.put("C_DEPT_MANAGER","Y"); + String MANAGER_ID = new ResourceComInfo().getWorkcode(map.get("MANAGER_ID").toString()); + map.put("MANAGER_ID",MANAGER_ID);//变更部门负责人 + }else{ + map.put("C_DEPT_MANAGER","N"); + map.put("MANAGER_ID","");//变更部门负责人 + } + + //是否变更直接上级 + if (map.get("C_SUPERVISOR1").equals("0")){ + map.put("C_SUPERVISOR1","Y"); + String SUPERVISOR_ID = new ResourceComInfo().getWorkcode(map.get("SUPERVISOR_ID").toString()); + map.put("SUPERVISOR_ID",SUPERVISOR_ID);//变更直接上级 + }else{ + map.put("C_SUPERVISOR1","N"); + map.put("SUPERVISOR_ID","");//变更直接上级 + } + + //是否变更分管领导 + if (map.get("C_DEPT_MANAGER1").equals("0")){ + map.put("C_DEPT_MANAGER1","Y"); + String MANAGER_ID1 = new ResourceComInfo().getWorkcode(map.get("MANAGER_ID1").toString()); + map.put("MANAGER_ID1",MANAGER_ID1);//变更分管领导 + }else{ + map.put("C_DEPT_MANAGER1","N"); + map.put("MANAGER_ID1","");//变更分管领导 + } + + + log.writeLog("是否为部门拓展者角色map.get(C_DEPT_EXPAND1)-------->"+map.get("C_DEPT_EXPAND1")); + //是否为部门拓展者角色 + if (map.get("C_DEPT_EXPAND1").equals("0")){ + map.put("C_DEPT_EXPAND1","Y");//是否为部门拓展者角色 + String EXPAND_EMPLID = new ResourceComInfo().getWorkcode(map.get("EXPAND_EMPLID").toString()); + map.put("EXPAND_EMPLID",EXPAND_EMPLID);//变更拓展者角色 + }else{ + map.put("C_DEPT_EXPAND1","N");//是否为部门拓展者角色 + log.writeLog("拓展者角色map.get(EXPAND_EMPLID)-------->"+map.get("EXPAND_EMPLID")); + map.put("EXPAND_EMPLID","");//变更拓展者角色 + } + + //申请人工号 + String EMPLID = new ResourceComInfo().getWorkcode(map.get("EMPLID").toString()); + map.put("EMPLID",EMPLID); + + //离职详细说明 + String DESCR254=Util.null2String(map.get("DESCR254")); + if(DESCR254.length()>250){//长度超过250,则截取前250位 + DESCR254=DESCR254.substring(0,250); + } + map.put("DESCR254",DESCR254); + + //离职类别 + if (!map.get("ACTION_REASON").equals("")){ + String itemName = getItemName2("lzyyACT_REASON_SUB1", map.get("ACTION_REASON").toString(),workflowid); + log.writeLog("----------lzyyACT_REASON_SUB1-----------转显示值:"+itemName); + String[] ACTION_REASON_arr = itemName.split("-"); + map.put("ACTION_REASON",ACTION_REASON_arr[0]); + }else{ + map.put("ACT_REASON_SUB",""); + } + //离职原因 + if (!map.get("ACT_REASON_SUB").equals("")){ + String itemName = getItemName2("lzyyACT_REASON_SUB2", map.get("ACT_REASON_SUB").toString(),workflowid); + String[] ACT_REASON_SUB_arr = itemName.split("-"); + map.put("ACT_REASON_SUB",ACT_REASON_SUB_arr[0]); + }else{ + map.put("ACT_REASON_SUB",""); + } + + map.put("C_APPLI_RS","3");//审批状态 默认为3 + + if (map.get("C_BLACKLIST").equals("0")){ //0为是 + map.put("C_BLACKLIST","Y");//是否加入黑名单 + if (map.get("C_BCKST_VTN_TPYE").equals("")){ //存在历史问题 所以加判断 + map.put("C_BCKST_VTN_TPYE","4");//黑名单类型 + } + }else{ + map.put("C_BLACKLIST","N");//是否加入黑名单 + map.put("C_BCKST_VTN_TPYE","");//黑名单类型 + map.put("C_BLACKLIST_REASON","");//加入黑名单原因 + map.put("EMPLID3","");//加入黑名单发起人 + } + + + String strParm = JSONObject.toJSONString(map); + log.writeLog("离职单准备传入数据中台的数据为------>" + strParm); + + String token = HttpClientToDC.getToken(); + log.writeLog("离职单token------>" + token); + log.writeLog("离职单url------>" + url); + + String returndata = HttpClientToDC.sendPostApi(url,token, strParm); + log.writeLog("离职单返回数据returndata------>" + returndata); + if (!"".equals(returndata) && returndata != null) { + JSONObject jsonObject = JSONObject.parseObject(returndata); + String code = Util.null2String(jsonObject.get("code")); + log.writeLog("--------发送请求返回的code值为:" + code); + if (code.equals("1")){ + return SUCCESS; + }else{ + String msg = Util.null2String(jsonObject.get("msg")); + requestInfo.getRequestManager().setMessageid("111100"); + requestInfo.getRequestManager().setMessagecontent(msg); + return "0"; + } + }else{ + String ermsg="流程数据写入HR调动申请单失败,未获取到接口返回结果,请联系系统管理员处理!"; + requestInfo.getRequestManager().setMessageid("111100"); + requestInfo.getRequestManager().setMessagecontent(ermsg); + return "0"; + } + } catch (Exception e) { + e.printStackTrace(); + requestInfo.getRequestManager().setMessageid("111100"); + requestInfo.getRequestManager().setMessagecontent("流程发生错误,错误信息:"+e.toString()); + return "0"; + } + } + + /** + * 根据用户id获取用户工号 + * @param uid + * @return + */ + public static String getWorkcodeByUid(String uid){ + RecordSet rs = new RecordSet(); + String sql = "select workcode from hrmresource where id = "+uid+" "; + rs.executeQuery(sql); + rs.next(); + return rs.getString("workcode"); + } + + /** + * 根据下拉框字段名以及值获取显示名称 + * + * 废弃 + * + * @param fieldName + * @param selectVle + * @return + */ + public static String getItemName(String fieldName,String selectVle){ + RecordSet rs = new RecordSet(); + String sql = "select wkf_slt.selectname from workflow_billfield wkf_bi INNER JOIN WORKFLOW_SELECTITEM wkf_slt on wkf_bi.id = wkf_slt.fieldid " + + "where wkf_bi.fieldname = '"+fieldName+"' and wkf_slt.selectvalue = "+selectVle+""; + rs.executeQuery(sql); + rs.next(); + return Util.null2String(rs.getString("selectname")); + } + + /** + * 根据下拉框字段名以及值获取显示名称 + * @param fieldName + * @param selectVle + * @param workflowid + * @return + */ + public static String getItemName2(String fieldName,String selectVle,String workflowid){ + String code=BaseUtil.getBaseInfoByParm("selectname", "workflow_selectitem", "selectvalue", selectVle, + " and fieldid in (select id from workflow_billfield where billid in (select formid from workflow_base where id="+workflowid+") and fieldname='"+fieldName+"' and viewtype=0)"); + String SelectName = Util.formatMultiLang(code, "7"); + return SelectName; + } +} diff --git a/src/main/youhong_ai_jitu_src/jntchina/action/ResignationFormWriteBackAction.java b/src/main/youhong_ai_jitu_src/jntchina/action/ResignationFormWriteBackAction.java new file mode 100644 index 0000000..4d6c89c --- /dev/null +++ b/src/main/youhong_ai_jitu_src/jntchina/action/ResignationFormWriteBackAction.java @@ -0,0 +1,257 @@ +package jntchina.action; + +import com.alibaba.fastjson.JSONObject; +import jntchina.util.HttpClientToDC; +import selfdev.util.base.BaseUtil; +import selfdev.util.log.LogTool; +import weaver.conn.RecordSet; +import weaver.file.Prop; +import weaver.general.StringUtil; +import weaver.general.Util; +import weaver.hrm.resource.ResourceComInfo; +import weaver.interfaces.workflow.action.Action; +import weaver.soa.workflow.request.RequestInfo; + +import java.util.HashMap; +import java.util.Map; + +/** + * 离职申请单写入中台(HR系统) + */ +public class ResignationFormWriteBackAction implements Action { + + public String execute(RequestInfo requestInfo) { + + LogTool log = new LogTool("/log/selfdev/action/hrm", false); + + String requestId = requestInfo.getRequestid(); + String workflowid = requestInfo.getWorkflowid(); + String workflowname = BaseUtil.getBaseInfoByParm("workflowname", "workflow_base", "id", workflowid, ""); + log.writeLog("---------------" + workflowname + "开始写入HR-------------requestId:" + requestId); + + //获取配置文件中的参数 + String mode = Prop.getPropValue("DevToDC_jntchina", "mode"); + // 服务器ip:port + String baseUrl = Prop.getPropValue("DevToDC_jntchina", mode + "_baseUrl"); + String url = baseUrl + "/dcoaapi/hr/resignation"; + //获取OA表名称 + String tablename = BaseUtil.getBaseInfoByParm("tablename", "workflow_bill", "1", "1", " and id in (select formid from workflow_base where id=" + workflowid + ")"); + + String sql = " select C_APP_SEQ," + + "C_APP_DT," + + "XM EMPLID," + + "EMPLID2," + + "DESCR254," + + "lzyyACT_REASON_SUB2 ACT_REASON_SUB," + + "lzyyACT_REASON_SUB1 ACTION_REASON," + + "LAST_WORK_DAY," + + "C_BLACKLIST," + + "C_BCKST_VTN_TPYE," + + "C_BLACKLIST_REASON," + + "EMPLID3," + + "C_DEPT_MANAGER," + + "MANAGER_ID," + + "C_SUPERVISOR1," + + "SUPERVISOR_ID," + + "C_DEPT_MANAGER1," + + "C_DEPT_EXPAND1," + + "EXPAND_EMPLID," + + "MANAGER_ID1 " + + "from " + tablename + " where requestid = " + requestId + " "; + log.writeLog("---------------sql------------->" + sql); + RecordSet rs = new RecordSet(); + + try { + rs.executeQuery(sql); + + Map map = new HashMap(); + String[] columnName = rs.getColumnName(); + rs.next(); + for (int i = 0; i < columnName.length; i++) { + map.put(columnName[i], Util.null2String(rs.getString(columnName[i]))); + } + + //是否部门负责人 + if (map.get("C_DEPT_MANAGER").equals("0")) { + map.put("C_DEPT_MANAGER", "Y"); + String MANAGER_ID = new ResourceComInfo().getWorkcode(map.get("MANAGER_ID").toString()); + map.put("MANAGER_ID", MANAGER_ID);//变更部门负责人 + } else { + map.put("C_DEPT_MANAGER", "N"); + map.put("MANAGER_ID", "");//变更部门负责人 + } + + //是否变更直接上级 + if (map.get("C_SUPERVISOR1").equals("0")) { + map.put("C_SUPERVISOR1", "Y"); + String SUPERVISOR_ID = new ResourceComInfo().getWorkcode(map.get("SUPERVISOR_ID").toString()); + map.put("SUPERVISOR_ID", SUPERVISOR_ID);//变更直接上级 + } else { + map.put("C_SUPERVISOR1", "N"); + map.put("SUPERVISOR_ID", "");//变更直接上级 + } + + //是否变更分管领导 + if (map.get("C_DEPT_MANAGER1").equals("0")) { + map.put("C_DEPT_MANAGER1", "Y"); + String MANAGER_ID1 = new ResourceComInfo().getWorkcode(map.get("MANAGER_ID1").toString()); + map.put("MANAGER_ID1", MANAGER_ID1);//变更分管领导 + } else { + map.put("C_DEPT_MANAGER1", "N"); + map.put("MANAGER_ID1", "");//变更分管领导 + } + + + log.writeLog("是否为部门拓展者角色map.get(C_DEPT_EXPAND1)-------->" + map.get("C_DEPT_EXPAND1")); + //是否为部门拓展者角色 + if (map.get("C_DEPT_EXPAND1").equals("0")) { + map.put("C_DEPT_EXPAND1", "Y");//是否为部门拓展者角色 + String EXPAND_EMPLID = new ResourceComInfo().getWorkcode(map.get("EXPAND_EMPLID").toString()); + map.put("EXPAND_EMPLID", EXPAND_EMPLID);//变更拓展者角色 + } else { + map.put("C_DEPT_EXPAND1", "N");//是否为部门拓展者角色 + log.writeLog("拓展者角色map.get(EXPAND_EMPLID)-------->" + map.get("EXPAND_EMPLID")); + map.put("EXPAND_EMPLID", "");//变更拓展者角色 + } + + //申请人工号 + String EMPLID = new ResourceComInfo().getWorkcode(map.get("EMPLID").toString()); + map.put("EMPLID", EMPLID); + + //离职详细说明 + String DESCR254 = Util.null2String(map.get("DESCR254")); + if (DESCR254.length() > 250) {//长度超过250,则截取前250位 + DESCR254 = DESCR254.substring(0, 250); + } + map.put("DESCR254", DESCR254); + + //离职类别 + if (!map.get("ACTION_REASON").equals("")) { + String itemName = getItemName2("lzyyACT_REASON_SUB1", map.get("ACTION_REASON").toString(), workflowid); + log.writeLog("----------lzyyACT_REASON_SUB1-----------转显示值:" + itemName); + String[] ACTION_REASON_arr = itemName.split("-"); + map.put("ACTION_REASON", ACTION_REASON_arr[0]); + } else { + map.put("ACT_REASON_SUB", ""); + } + //离职原因 + if (!map.get("ACT_REASON_SUB").equals("")) { + String itemName = getItemName2("lzyyACT_REASON_SUB2", map.get("ACT_REASON_SUB").toString(), workflowid); + String[] ACT_REASON_SUB_arr = itemName.split("-"); + map.put("ACT_REASON_SUB", ACT_REASON_SUB_arr[0]); + } else { + map.put("ACT_REASON_SUB", ""); + } + + map.put("C_APPLI_RS", "3");//审批状态 默认为3 + + if (map.get("C_BLACKLIST").equals("0")) { //0为是 + map.put("C_BLACKLIST", "Y");//是否加入黑名单 + String emplid3 = (String) map.get("EMPLID3"); + RecordSet recordSet = new RecordSet(); + String sqlUser = "select workcode from hrmresource where id = ?"; + if (StringUtil.isEmpty(emplid3)) {//如果提报人为空 默认传当前节点操作人,也就是当前操作这条流程的user + int userId = requestInfo.getRequestManager().getUserId(); + if (recordSet.executeQuery(sqlUser, userId) && recordSet.next()) { + map.put("EMPLID3", recordSet.getString("workcode")); + } + } else { + recordSet.executeQuery(sqlUser, emplid3); + if (recordSet.next()) { + map.put("EMPLID3", recordSet.getString("workcode")); + } + } + if (StringUtil.isEmpty(Util.null2String(map.get("C_BCKST_VTN_TPYE")))) { + map.put("C_BCKST_VTN_TPYE", "");//黑名单类型 + } else { + map.put("C_BCKST_VTN_TPYE", "" + ((Util.getIntValue(map.get("C_BCKST_VTN_TPYE").toString())) + 1));//黑名单类型 + } + } else { + map.put("C_BLACKLIST", "N");//是否加入黑名单 + map.put("C_BCKST_VTN_TPYE", "");//黑名单类型 + map.put("C_BLACKLIST_REASON", "");//加入黑名单原因 + map.put("EMPLID3", "");//加入黑名单发起人 + } + + String strParm = JSONObject.toJSONString(map); + log.writeLog("离职单准备传入数据中台的数据为------>" + strParm); + + String token = HttpClientToDC.getToken(); + log.writeLog("离职单token------>" + token); + log.writeLog("离职单url------>" + url); + + String returndata = HttpClientToDC.sendPostApi(url, token, strParm); + log.writeLog("离职单返回数据returndata------>" + returndata); + if (!"".equals(returndata) && returndata != null) { + JSONObject jsonObject = JSONObject.parseObject(returndata); + String code = Util.null2String(jsonObject.get("code")); + log.writeLog("--------发送请求返回的code值为:" + code); + if (code.equals("1")) { + return SUCCESS; + } else { + String msg = Util.null2String(jsonObject.get("msg")); + requestInfo.getRequestManager().setMessageid("111100"); + requestInfo.getRequestManager().setMessagecontent(msg); + return "0"; + } + } else { + String ermsg = "流程数据写入HR调动申请单失败,未获取到接口返回结果,请联系系统管理员处理!"; + requestInfo.getRequestManager().setMessageid("111100"); + requestInfo.getRequestManager().setMessagecontent(ermsg); + return "0"; + } + } catch (Exception e) { + e.printStackTrace(); + requestInfo.getRequestManager().setMessageid("111100"); + requestInfo.getRequestManager().setMessagecontent("流程发生错误,错误信息:" + e.toString()); + return "0"; + } + } + + /** + * 根据用户id获取用户工号 + * + * @param uid + * @return + */ + public static String getWorkcodeByUid(String uid) { + RecordSet rs = new RecordSet(); + String sql = "select workcode from hrmresource where id = " + uid + " "; + rs.executeQuery(sql); + rs.next(); + return rs.getString("workcode"); + } + + /** + * 根据下拉框字段名以及值获取显示名称 + *

+ * 废弃 + * + * @param fieldName + * @param selectVle + * @return + */ + public static String getItemName(String fieldName, String selectVle) { + RecordSet rs = new RecordSet(); + String sql = "select wkf_slt.selectname from workflow_billfield wkf_bi INNER JOIN WORKFLOW_SELECTITEM wkf_slt on wkf_bi.id = wkf_slt.fieldid " + + "where wkf_bi.fieldname = '" + fieldName + "' and wkf_slt.selectvalue = " + selectVle + ""; + rs.executeQuery(sql); + rs.next(); + return Util.null2String(rs.getString("selectname")); + } + + /** + * 根据下拉框字段名以及值获取显示名称 + * + * @param fieldName + * @param selectVle + * @param workflowid + * @return + */ + public static String getItemName2(String fieldName, String selectVle, String workflowid) { + String code = BaseUtil.getBaseInfoByParm("selectname", "workflow_selectitem", "selectvalue", selectVle, + " and fieldid in (select id from workflow_billfield where billid in (select formid from workflow_base where id=" + workflowid + ") and fieldname='" + fieldName + "' and viewtype=0)"); + String SelectName = Util.formatMultiLang(code, "7"); + return SelectName; + } +} diff --git a/src/main/youhong_ai_jitu_src/jntchina/action/ReturnBiaoShuAuditResultAction.java b/src/main/youhong_ai_jitu_src/jntchina/action/ReturnBiaoShuAuditResultAction.java new file mode 100644 index 0000000..c1a7b8c --- /dev/null +++ b/src/main/youhong_ai_jitu_src/jntchina/action/ReturnBiaoShuAuditResultAction.java @@ -0,0 +1,133 @@ +package jntchina.action; + +import com.alibaba.fastjson.JSONObject; +import weaver.file.Prop; +import jntchina.util.HttpClientToDC; +import org.apache.http.util.EntityUtils; +import selfdev.util.base.BaseUtil; +import selfdev.util.log.LogTool; +import weaver.conn.RecordSet; +import weaver.general.Util; +import weaver.interfaces.workflow.action.Action; +import weaver.soa.workflow.request.RequestInfo; + +import java.text.SimpleDateFormat; +import java.util.Date; + +/** + * 极兔-> OA标书审核完毕状态回传接口 + * @title: ReturnBiaoShuAuditResultAction + * @Author LJL + * @Date: 2021/9/28 10:19 + * @Version 1.0 + */ + +public class ReturnBiaoShuAuditResultAction implements Action { + @Override + public String execute(RequestInfo requestInfo) { + String state = ""; + LogTool log = new LogTool("/log/selfdev/action", false); + SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd"); + + + //封装参数 + JSONObject date = new JSONObject(); + String requestid = requestInfo.getRequestid(); + String workflowid = requestInfo.getWorkflowid(); + String tablename = BaseUtil.getBaseInfoByParm("tablename", "workflow_bill", "1", "1", " and id in (select formid from workflow_base where id=" + workflowid + ")"); + + String src = requestInfo.getRequestManager().getSrc();//获取流程是提交还是驳回 + log.writeLog("状态是 "+src); + String name=requestInfo.getRequestManager().getUser().getLastname();//获取当前审批人 + name=Util.formatMultiLang(name,"7");//增加多语言过滤 7代表简体中文 8英文 9繁体中文 + + + if("".equals(src)){ + + requestInfo.getRequestManager().setMessagecontent("审批状态为空"); + return FAILURE_AND_CONTINUE; + } + if("reject".equals(src)){ + state="1"; + + }else if("submit".equals(src)){ + state="2"; + } + log.writeLog("表名是"+tablename); + + //连接数据库 + RecordSet rs = new RecordSet(); + + rs.execute("select * from "+tablename+" "+"where requestid="+requestid); + log.writeLog("查表Sql是"+"select * from "+tablename+" where requestid="+requestid); + String biddingType =""; + while(rs.next()){ + date.put("tenderCode", Util.null2String(rs.getString("bsbm")));//获取标书编码 + if("0".equals(Util.null2String(rs.getString("biddingType")))){ + biddingType= "1"; + }else if("1".equals(Util.null2String(rs.getString("biddingType")))){ + biddingType= "2"; + }else{ + return FAILURE_AND_CONTINUE; + } + date.put("biddingType",biddingType);//获取标书类型 + date.put("auditStatus", state);//获取审批状态 + date.put("auditName", name);//获取审批人 + date.put("auditTime", df.format(new Date()));//获取审批时间 + date.put("remark", Util.null2String(rs.getString("remark")));//获取审批备注 + } + String s = date.toString(); + if("".equals(s)){ + return FAILURE_AND_CONTINUE+" 传入参数为空 请仔细检查传入参数"; + } + String uri = ""; + String mode = Prop.getPropValue("DevToDC_jntchina", "mode"); + String url = Prop.getPropValue("DevToDC_jntchina", mode + "_baseUrl"); + + + if("2".equals(biddingType)){ +// uri = "http://vpm.sinoservices.com/srm-web/srmweb/oaConventionTenderAuditresultController/auditResult.shtml"; + uri = url+"/dcoaapi/srm/auditResult";//传数据到中台(标书申请运力) + }else if ("1".equals(biddingType)){ + uri =url+"/dcoaapi/srm/materialTenderAuditResult"; +// uri = "http://dev-jtdcapi.jms.com/dcoaapi/srm/";//传数据到中台(标书申请物资) + } + + //获取TOKEN + String token = HttpClientToDC.getToken(); + log.writeLog("获取数据中台的token------>" + token+" uri:"+uri); + try { + String s1 = HttpClientToDC.sendPostApi(uri, token, s); + log.writeLog("传过去的数据是:==> " + s+"返回参数是==>" + s1); + JSONObject jsonObject = JSONObject.parseObject(s1); + log.writeLog("接口执行之后回传的参数====>" + jsonObject); + Object msg = jsonObject.get("data"); + if (!"success".equals(msg)){ + requestInfo.getRequestManager().setMessagecontent("接口执行失败 原因为:"+jsonObject.get("msg")); + return FAILURE_AND_CONTINUE + "请联系后台管理员"; + } + + + return SUCCESS; + }catch (Exception e){ + e.printStackTrace(); + requestInfo.getRequestManager().setMessagecontent("后台出现异常:::"+e); + return FAILURE_AND_CONTINUE; + } +// try { +// httpPost.addHeader("Content-Type", "application/json; charset=utf-8"); +// httpPost.setEntity(new StringEntity(s, StandardCharsets.UTF_8)); +// CloseableHttpResponse response = httpClient.execute(httpPost); +// if (response != null && response.getEntity() != null) { +// String resultString = EntityUtils.toString(response.getEntity()); +// log.writeLog("返回的结果信息为:" + resultString); +// return "1"; +// } else { +// return "0 获取数据失败 请查看日志"; +// } +// } catch (Exception var16) { +// return "0 请求失败"; +// } + + } +} diff --git a/src/main/youhong_ai_jitu_src/jntchina/action/ReturnFeiYongAuditResultAction.java b/src/main/youhong_ai_jitu_src/jntchina/action/ReturnFeiYongAuditResultAction.java new file mode 100644 index 0000000..61ab167 --- /dev/null +++ b/src/main/youhong_ai_jitu_src/jntchina/action/ReturnFeiYongAuditResultAction.java @@ -0,0 +1,102 @@ +package jntchina.action; + +import com.alibaba.fastjson.JSONObject; +import weaver.file.Prop; +import jntchina.util.HttpClientToDC; +import selfdev.util.base.BaseUtil; +import selfdev.util.log.LogTool; +import weaver.conn.RecordSet; +import weaver.general.Util; +import weaver.interfaces.workflow.action.Action; +import weaver.soa.workflow.request.RequestInfo; + +import java.text.SimpleDateFormat; +import java.util.Date; + + +/** + * @title: ReturnFeiYongAuditResultAction + * @Author LJL + * @Date: 2021/9/28 10:19 + * @Version 1.0 + * 备注: 用于费用审核流程 OA审批完毕数据回传给SRM + * + */ + +public class ReturnFeiYongAuditResultAction implements Action { + @Override + public String execute(RequestInfo requestInfo) { + String state = ""; + LogTool log = new LogTool("/log/selfdev/action", false);//上传日志 + SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd"); + + + //封装参数 + JSONObject date = new JSONObject(); + + //获取表名 和唯一标识 + String requestid = requestInfo.getRequestid(); + String workflowid = requestInfo.getWorkflowid(); + String tablename = BaseUtil.getBaseInfoByParm("tablename", "workflow_bill", "1", "1", " and id in (select formid from workflow_base where id=" + workflowid + ")"); + log.writeLog("表名是"+tablename); + + //连接数据库 + RecordSet rs = new RecordSet(); + + //获取流程状态 + String src = requestInfo.getRequestManager().getSrc(); + String name=requestInfo.getRequestManager().getUser().getLastname();//获取当前审批人 + name=Util.formatMultiLang(name,"7");//增加多语言过滤 7代表简体中文 8英文 9繁体中文 + + if("reject".equals(src)){ + state="1"; + + }else if("submit".equals(src)){ + state="2"; + } + + //从配置文件动态获取url + String mode = Prop.getPropValue("DevToDC_jntchina", "mode"); + String url = Prop.getPropValue("DevToDC_jntchina", mode + "_baseUrl"); + String uri = url +"/dcoaapi/srm/paymentAuditResult";//待定 + + rs.execute("select * from " + tablename + " " + "where requestid=" + requestid); + log.writeLog("查表Sql是" + "select * from " + tablename + "where requestid=" + requestid); + while (rs.next()) { + date.put("payNo", Util.null2String(rs.getString("payNo")));//缴纳单号 + date.put("auditStatus", state);//审批状态 + date.put("auditName", name);//审批人 + date.put("auditTime", df.format(new Date()));//审批时间 + date.put("remark", Util.null2String(rs.getString("spbz")));//审批备注 + } + String s = date.toString(); + log.writeLog("传过去的JSON数据是:==> " + s+" uri"+uri); + String token = HttpClientToDC.getToken(); + + try { + String s1 = HttpClientToDC.sendPostApi(uri, token, s); + if(s1!=null&&s1!=""){ + log.writeLog("回传数据成功 回传的状态是: " + s1); + + JSONObject jsonObject = JSONObject.parseObject(s1); + log.writeLog("接口执行之后回传的参数====>" + jsonObject); + Object msg = jsonObject.get("data"); + if (!"success".equals(msg)){ + requestInfo.getRequestManager().setMessagecontent("接口执行失败 原因为:"+jsonObject.get("msg")); + return FAILURE_AND_CONTINUE + "请联系后台管理员"; + } + + return SUCCESS; + }else{ + log.writeLog("回传数据失败"); + return FAILURE_AND_CONTINUE; + } + + + } catch (Exception e) { + return FAILURE_AND_CONTINUE + " 请求失败"; + } + + + } +} diff --git a/src/main/youhong_ai_jitu_src/jntchina/action/ReturnHeTongStatusAction.java b/src/main/youhong_ai_jitu_src/jntchina/action/ReturnHeTongStatusAction.java new file mode 100644 index 0000000..21dab94 --- /dev/null +++ b/src/main/youhong_ai_jitu_src/jntchina/action/ReturnHeTongStatusAction.java @@ -0,0 +1,88 @@ +package jntchina.action; + +import com.alibaba.fastjson.JSONObject; +import weaver.file.Prop; +import weaver.general.Util; +import jntchina.util.HttpClientToDC; +import selfdev.util.base.BaseUtil; +import selfdev.util.log.LogTool; +import weaver.conn.RecordSet; +import weaver.interfaces.workflow.action.Action; +import weaver.soa.workflow.request.RequestInfo; + +import java.text.SimpleDateFormat; +import java.util.Date; +import java.util.Hashtable; + +/** + * @title: ReturnHeTongStatusAction + * @Author LJL + * @Date: 2021/10/27 10:02 + * @Version 1.0 + * + * /合同审批数据回传至中台至SRM/ + */ +public class ReturnHeTongStatusAction implements Action { + LogTool log = new LogTool("/log/selfdev/action", false); + @Override + public String execute(RequestInfo requestInfo) { + log.writeLog("合同审批流程开始"); + JSONObject date = new JSONObject(); + String requestid = requestInfo.getRequestid(); + String workflowid = requestInfo.getWorkflowid(); + String tablename = BaseUtil.getBaseInfoByParm("tablename", "workflow_bill", "1", "1", " and id in (select formid from workflow_base where id=" + workflowid + ")"); + String state = "2"; + + String name=requestInfo.getRequestManager().getUser().getLastname(); + name=Util.formatMultiLang(name,"7");//增加多语言过滤 7代表简体中文 8英文 9繁体中文 + String bz = ""; + String src = requestInfo.getRequestManager().getSrc();//获取流程是提交还是驳回 + if("reject".equals(src)){ + state="1"; + bz="被退回"; + }else if("submit".equals(src)){ + state="2"; + bz="审批通过!"; + } + RecordSet rs = new RecordSet(); + + String SQL = "select * from "+tablename+" "+"where requestid="+requestid; + log.writeLog("查表Sql是"+SQL); + rs.execute(SQL); + while (rs.next()) { + date.put("contractCode", Util.null2String(rs.getString("lcbh")));//合同编号 + date.put("auditStatus",state); + date.put("auditName",name);//审批人 + date.put("auditTime",new SimpleDateFormat("yyyy-MM-dd HH:mm:ss ").format(new Date(System.currentTimeMillis())));//审批时间 + date.put("remark",bz);//备注 + } + log.writeLog("数据已获取===>"+date); + String mode = Prop.getPropValue("DevToDC_jntchina", "mode"); + String url = Prop.getPropValue("DevToDC_jntchina", mode + "_baseUrl")+"/dcoaapi/srm/contractAuditResult"; + String token = HttpClientToDC.getToken(); + log.writeLog("url:"+url); + try { + String s1 = HttpClientToDC.sendPostApi(url, token, date.toString()); + if(s1.equals("")){ + requestInfo.getRequestManager().setMessagecontent("接口未成功访问"); + return FAILURE_AND_CONTINUE; + }else{ + JSONObject jsonObject = JSONObject.parseObject(s1); + log.writeLog("接口执行之后回传的参数====>" + jsonObject+"返回结果是:"+s1); + Object msg = jsonObject.get("data"); + if (!"success".equals(msg)){ + requestInfo.getRequestManager().setMessagecontent("接口执行失败 原因为:"+jsonObject.get("msg")); + return FAILURE_AND_CONTINUE + "请联系后台管理员"; + } + } + + + }catch (Exception e){ + requestInfo.getRequestManager().setMessagecontent("后台出现异常"+e); + return FAILURE_AND_CONTINUE; + } + + return SUCCESS; + + } +} diff --git a/src/main/youhong_ai_jitu_src/jntchina/action/ReturnWuZiAuditResultAction.java b/src/main/youhong_ai_jitu_src/jntchina/action/ReturnWuZiAuditResultAction.java new file mode 100644 index 0000000..45508fc --- /dev/null +++ b/src/main/youhong_ai_jitu_src/jntchina/action/ReturnWuZiAuditResultAction.java @@ -0,0 +1,163 @@ +package jntchina.action; + +import com.alibaba.fastjson.JSONObject; +import com.weaver.file.Prop; +import jntchina.util.HttpClientToDC; +import selfdev.util.base.BaseUtil; +import weaver.conn.RecordSet; +import weaver.general.Util; +import weaver.interfaces.workflow.action.Action; +import weaver.soa.workflow.request.RequestInfo; + +import java.nio.charset.StandardCharsets; + +/** + * @title: ReturnWuZiAuditResultAction + * @Author LJL + * @Date: 2021/9/28 10:19 + * @Version 1.0 + * 备注: 用物资审核流程 OA审批完毕数据回传给SRM + * + */ + +public class ReturnWuZiAuditResultAction implements Action { + @Override + public String execute(RequestInfo requestInfo) { + String applicantPerson = "";//流程申请人 + String applicantTime = "";//申请时间 + String applicantDep = "";//申请部门 + String orderQuantity = "";//订购数量 + String demandAllocation = "";//需求分配 + String applicantReason = "";//申请理由 + String processCode = "";//流程编码 + String materialCode = "";//物料编码 + String materialName = "";//物料名称 + String spec = "";//规格型号 + String quantity = "";//数量 + String categoryCode = "";//物料大类 + String description = "";//品名 + String creatorName = "";//使用者 + String demand = "";//需求部门 + String price = "";//单价 + String totalPrice = "";//总价 + String invoiceHead = "";//开票抬头 + String demandReason = "";//需求原因 + + String s = "["; + String mode = Prop.getPropValue("DevToDC_jntchina", "mode"); + String url = Prop.getPropValue("DevToDC_jntchina", mode + "_baseUrl"); + String uri =url + "/dcoaapi/srm/synMaterialTender";// + + String requestid = requestInfo.getRequestid(); + String workflowid = requestInfo.getWorkflowid(); + String tablename = BaseUtil.getBaseInfoByParm("tablename", "workflow_bill", "1", "1", " and id in (select formid from workflow_base where id=" + workflowid + ")"); + String SQl = "select t1.xm,t1.sqsj,t1.bmdm,t1.dgsl,t1.xqfp,t1.sqly,t1.lcbm,t2.zcbh,t2.wpmc,t2.ggxh,t2.sl,t2.lx,t2.pm,t2.jsr,t2.xqbm,t2.dj," + + "t2.zje,t2.kpfktt,t2.bz from formtable_main_727 t1 left join formtable_main_727_dt1 t2 on t1.id = t2.mainid where t1.requestid = "+requestid; + RecordSet rs = new RecordSet(); + rs.execute(SQl); + while (rs.next()) { + applicantPerson = Util.null2String(rs.getString("xm")); + applicantTime = Util.null2String(rs.getString("sqsj")); + applicantDep = Util.null2String(rs.getString("bmdm")); + orderQuantity = Util.null2String(rs.getString("dgsl")); + demandAllocation = Util.null2String(rs.getString("xqfp")); + applicantReason = Util.null2String(rs.getString("sqly")); + processCode = Util.null2String(rs.getString("lcbm")); + materialCode = Util.null2String(rs.getString("zcbh")); + materialName = Util.null2String(rs.getString("wpmc")); + spec = Util.null2String(rs.getString("ggxh")); + quantity = Util.null2String(rs.getString("sl")); + categoryCode = Util.null2String(rs.getString("wzlx")); + description = Util.null2String(rs.getString("pm")); + creatorName = Util.null2String(rs.getString("jsr")); + demand = Util.null2String(rs.getString("xqbm")); + price = Util.null2String(rs.getString("dj")); + totalPrice = Util.null2String(rs.getString("zje")); + invoiceHead = Util.null2String(rs.getString("kpfktt")); + demandReason = Util.null2String(rs.getString("bz")); + JSONObject date = new JSONObject(); + date.put("applicantTime",applicantTime); + date.put("orderQuantity",orderQuantity); + date.put("processCode",processCode); + date.put("applicantReason",applicantReason); + date.put("materialCode",materialCode); + date.put("quantity",quantity); + date.put("description",description); + date.put("price",price); + date.put("totalPrice",totalPrice); + date.put("demandReason",demandReason); + + materialName= BaseUtil.getBaseInfoByParm("selectname", "workflow_selectitem", "selectvalue", materialName, + " and fieldid in (select id from workflow_billfield where billid in (select formid from workflow_base where id="+workflowid+") and fieldname='wpmc' and viewtype=1)"); + date.put("materialName",materialName); + + spec=BaseUtil.getBaseInfoByParm("selectname", "workflow_selectitem", "selectvalue", spec, + " and fieldid in (select id from workflow_billfield where billid in (select formid from workflow_base where id="+workflowid+") and fieldname='ggxh' and viewtype=1)"); + date.put("spec",spec); + + categoryCode=BaseUtil.getBaseInfoByParm("selectname", "workflow_selectitem", "selectvalue", categoryCode, + " and fieldid in (select id from workflow_billfield where billid in (select formid from workflow_base where id="+workflowid+") and fieldname='wzlx' and viewtype=1)"); + date.put("categoryCode",categoryCode); + + invoiceHead=BaseUtil.getBaseInfoByParm("selectname", "workflow_selectitem", "selectvalue", invoiceHead, + " and fieldid in (select id from workflow_billfield where billid in (select formid from workflow_base where id="+workflowid+") and fieldname='kpfktt' and viewtype=1)"); + date.put("invoiceHead",invoiceHead); + + + + String SQL2 = "select * from hrmdepartment where id = "+applicantDep; + RecordSet rs2 = new RecordSet(); + rs2.execute(SQL2); + if (rs2.next()) { + applicantDep = rs2.getString("DEPARTMENTNAME"); + } + date.put("applicantDep",applicantDep); + + String SQL3 = "select * from hrmdepartment where id = "+demand; + RecordSet rs3 = new RecordSet(); + rs3.execute(SQL3); + if (rs3.next()) { + demand = rs3.getString("DEPARTMENTNAME"); + } + date.put("demand",demand); + + String SQL4 = "select * from hrmresource where id = "+applicantPerson; + RecordSet rs4 = new RecordSet(); + rs4.execute(SQL4); + if (rs4.next()) { + applicantPerson = rs4.getString("LASTNAME"); + } + date.put("applicantPerson",applicantPerson); + + String SQL5 = "select * from hrmresource where id = "+creatorName; + RecordSet rs5 = new RecordSet(); + rs5.execute(SQL5); + if (rs5.next()) { + creatorName = rs5.getString("LASTNAME"); + } + date.put("creatorName",creatorName); + + String SQL6 = "select * from hrmresource where id = "+demandAllocation; + RecordSet rs6 = new RecordSet(); + rs6.execute(SQL6); + if (rs6.next()) { + demandAllocation = rs6.getString("LASTNAME"); + } + date.put("demandAllocation",demandAllocation); + + s=s+date+","; + + } + s=s.substring(0,s.length()-1)+"]"; + String token = HttpClientToDC.getToken(); + try{ + String s1 = HttpClientToDC.sendPostApi(uri, token, s); + }catch(Exception e){ + + return FAILURE_AND_CONTINUE + " 请求失败 因为: "+e+" 具体请看日志"; + } + + + return SUCCESS; + } +} diff --git a/src/main/youhong_ai_jitu_src/jntchina/action/ReturnZhongBiaoAuditResultAction.java b/src/main/youhong_ai_jitu_src/jntchina/action/ReturnZhongBiaoAuditResultAction.java new file mode 100644 index 0000000..dd20627 --- /dev/null +++ b/src/main/youhong_ai_jitu_src/jntchina/action/ReturnZhongBiaoAuditResultAction.java @@ -0,0 +1,104 @@ +package jntchina.action; + +import com.alibaba.fastjson.JSONObject; +import weaver.file.Prop; +import jntchina.util.HttpClientToDC; +import selfdev.util.base.BaseUtil; +import selfdev.util.log.LogTool; +import weaver.conn.RecordSet; +import weaver.general.Util; +import weaver.interfaces.workflow.action.Action; +import weaver.soa.workflow.request.RequestInfo; + +import java.text.SimpleDateFormat; +import java.util.Date; + +/** + * @title: ReturnZhongBiaoAuditResultAction + * @Author LJL + * @Date: 2021/9/28 10:19 + * @Version 1.0 + * 备注: 用于中标审核流程 OA审批完毕数据回传给SRM + * + */ +public class ReturnZhongBiaoAuditResultAction implements Action { + @Override + public String execute(RequestInfo requestInfo) { + String state = ""; + LogTool log = new LogTool("/log/selfdev/action", false); + SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd"); + //封装参数 + JSONObject date = new JSONObject(); + String requestid = requestInfo.getRequestid(); + String workflowid = requestInfo.getWorkflowid(); + String tablename = BaseUtil.getBaseInfoByParm("tablename", "workflow_bill", "1", "1", " and id in (select formid from workflow_base where id=" + workflowid + ")"); + String src = requestInfo.getRequestManager().getSrc();//获取流程是提交还是驳回 + String name=requestInfo.getRequestManager().getUser().getLastname();//获取当前审批人 + name= Util.formatMultiLang(name,"7");//增加多语言过滤 7代表简体中文 8英文 9繁体中文 + if("reject".equals(src)){ + state="1"; + + }else if("submit".equals(src)){ + state="2"; + } + log.writeLog("表名是"+tablename); + + RecordSet rs = new RecordSet(); + rs.execute("select * from "+tablename+" "+"where requestid="+requestid); + log.writeLog("查表Sql是"+"select * from "+tablename+" "+"where requestid="+requestid); + String biddingType=""; + + while(rs.next()){ + + date.put("tenderCode", Util.null2String(rs.getString("bsbm")));//获取标书编码 + if ("0".equals(Util.null2String(rs.getString("biddingType")))) { + biddingType = "1"; + } else if("1".equals(Util.null2String(rs.getString("biddingType")))) { + biddingType = "2"; + } + date.put("biddingType",biddingType );//获取标书类型 + date.put("auditStatus", state);//获取审批状态 + date.put("auditName", name);//获取审批人 + date.put("auditTime", df.format(new Date()));//获取审批时间 + date.put("remark", Util.null2String(rs.getString("remark")));//获取审批备注 + } + + String uri = ""; + String mode = Prop.getPropValue("DevToDC_jntchina", "mode"); + String url = Prop.getPropValue("DevToDC_jntchina", mode + "_baseUrl"); + log.writeLog(mode+" "+url+" "+biddingType); + if ("1".equals(biddingType)){ + uri = url+"/dcoaapi/srm/materialWinResult";//中台传入数据(物料) + + }else if("2".equals(biddingType)){ + uri = url+"/dcoaapi/srm/conventionWinResult"; +// uri = "http://dev-jtdcapi.jms.com/dcoaapi/srm/ //中标中台接口 + + }else{ + return FAILURE_AND_CONTINUE; + } + String s = date.toString(); + log.writeLog(s); + String token = HttpClientToDC.getToken(); + log.writeLog(token); + log.writeLog("获取数据中台的token------>" + token); + log.writeLog("传过去的数据是:==> "+s+" url:"+uri); + try { + String s1 = HttpClientToDC.sendPostApi(uri, token, s); + log.writeLog("传过去的数据是:==> " + s+"返回参数是==>" + s1); + JSONObject jsonObject = JSONObject.parseObject(s1); + log.writeLog("接口执行之后回传的参数====>" + jsonObject); + Object msg = jsonObject.get("data"); + if (!"success".equals(msg)){ + requestInfo.getRequestManager().setMessagecontent("接口执行失败 原因为:"+jsonObject.get("msg")); + return FAILURE_AND_CONTINUE + "请联系后台管理员"; + } + return SUCCESS; + }catch (Exception e){ + log.writeLog(e); + return FAILURE_AND_CONTINUE; + } + + + } +} diff --git a/src/main/youhong_ai_jitu_src/jntchina/action/RewardAndPunishmentAction.java b/src/main/youhong_ai_jitu_src/jntchina/action/RewardAndPunishmentAction.java new file mode 100644 index 0000000..f17f74f --- /dev/null +++ b/src/main/youhong_ai_jitu_src/jntchina/action/RewardAndPunishmentAction.java @@ -0,0 +1,162 @@ +package jntchina.action; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.JSONObject; +import jntchina.util.HttpClientToDC; +import selfdev.util.base.BaseUtil; +import selfdev.util.log.LogTool; +import weaver.conn.RecordSet; +import weaver.file.Prop; +import weaver.general.Util; +import weaver.interfaces.workflow.action.BaseAction; +import weaver.soa.workflow.request.RequestInfo; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.Map; + +/** + * @title: 奖惩申请数据传HR系统 + * @Author ycf + * @Date: 2022/1/6 15:14 + * @Version 1.0 + */ +public class RewardAndPunishmentAction extends BaseAction { + @Override + public String execute(RequestInfo requestInfo) { + LogTool log = new LogTool("/log/selfdev/action/hrm", false); + String requestId = requestInfo.getRequestid(); // 获取requestid + String workflowid = requestInfo.getWorkflowid(); // 获取workflowid + //获取工作流名称 + String workflowname = BaseUtil.getBaseInfoByParm("workflowname", "workflow_base", "id", workflowid, ""); + log.writeLog("---------------工作流名称-----------workflowname为:" + workflowname); + log.writeLog("--------奖惩申请单数据传入中台开始----requestId值为:" + requestId); + + //获取配置文件中的参数,到时候URL路径 + String mode = Prop.getPropValue("DevToDC_jntchina", "mode"); + // 服务器ip:port + String baseUrl = Prop.getPropValue("DevToDC_jntchina", mode + "_baseUrl"); + //访问路径拼接 + String url = baseUrl + "/dcoaapi/hr/rewardInfoResult"; + + + //根据流程id获取主表名称 + String mainTable = RegularizationApplyForAction.getMainTable(requestId); + log.writeLog("--------获取到的表名为----:" + mainTable); + + + RecordSet recordSet = new RecordSet(); + String sql = ""; + Map map = new HashMap(); + ArrayList> list = new ArrayList>(); + HashMap hashMap = new HashMap(); + + try { + //获取部门和日期 + sql = "select LCBH C_APP_SEQ, bjcrgh EMPLID, '1' C_SEQUENCE_NUM, jcrq C_RWD_DATE, jclb C_REWARD_CATEGORY, \n" + + " jcdw C_RWDPNS_UNIT,\n" + + " jclx C_RWDPNS_TYP, jcyy C_RWD_REASON, (select WORKCODE from HrmResource a where a.ID = b.tbr) C_INFORM_PERSON,\n" + + " sflzxc C_SALARY_TRANSFER, jcfs C_RWDPNS_SCORE, jcje C_RWDPNS_AMOUNT , bz C_RWD_COMMENT from "+mainTable+" b where requestid = "+requestId; + log.writeLog("获取奖惩信息的SQL:"+sql); + + recordSet.execute(sql); + recordSet.next(); + //C_APP_SEQ流程编号 + map.put("C_APP_SEQ", Util.null2String(recordSet.getString("C_APP_SEQ"))); + //EMPLID员工ID + map.put("EMPLID", Util.null2String(recordSet.getString("EMPLID"))); + //C_SEQUENCE_NUM序号 + hashMap.put("C_SEQUENCE_NUM", Util.null2String(recordSet.getString("C_SEQUENCE_NUM"))); + + //C_RWD_DATE奖惩日期 + hashMap.put("C_RWD_DATE", Util.null2String(recordSet.getString("C_RWD_DATE")).replace("-","/")); + //C_RWDPNS_UNIT提报人单位 + hashMap.put("C_RWDPNS_UNIT", Util.null2String(recordSet.getString("C_RWDPNS_UNIT"))); + + + //C_REWARD_CATEGORY奖惩类别 +// hashMap.put("C_REWARD_CATEGORY", Util.null2String(recordSet.getString("C_REWARD_CATEGORY")).equals("0")?"10":"20"); + + String jclb = BaseUtil.getBaseInfoByParm("selectname", "workflow_selectitem", "selectvalue", Util.null2String(recordSet.getString("C_REWARD_CATEGORY")), + " and fieldid in (select id from workflow_billfield where billid in (select formid from workflow_base where id="+requestInfo.getWorkflowid()+") and fieldname='jclb' and viewtype=0)"); + log.writeLog("获取的奖惩类别中文名:"+jclb); + + hashMap.put("C_REWARD_CATEGORY", getType(jclb,"C_REWARD_CATEGORY")); + + + String jclx = BaseUtil.getBaseInfoByParm("selectname", "workflow_selectitem", "selectvalue", Util.null2String(recordSet.getString("C_RWDPNS_TYP")), + " and fieldid in (select id from workflow_billfield where billid in (select formid from workflow_base where id="+requestInfo.getWorkflowid()+") and fieldname='jclx' and viewtype=0)"); + log.writeLog("获取的奖惩类别中文名:"+jclx); + + //奖惩原因 + String C_RWD_REASON=Util.null2String(recordSet.getString("C_RWD_REASON")); + if(C_RWD_REASON.length()>84){//长度超过250时,截取前250位 + C_RWD_REASON=C_RWD_REASON.substring(0,84); + } + //备注 + String C_RWD_COMMENT=Util.null2String(recordSet.getString("C_RWD_COMMENT")); + if(C_RWD_COMMENT.length()>84){//长度超过250时,截取前250位 + C_RWD_COMMENT=C_RWD_COMMENT.substring(0,84); + } + //C_RWDPNS_TYP奖惩类型 + hashMap.put("C_RWDPNS_TYP", getType(jclx,"C_RWDPNS_TYP")); + //C_RWD_REASON奖惩原因 + hashMap.put("C_RWD_REASON", C_RWD_REASON); + //C_INFORM_PERSON提报人 + hashMap.put("C_INFORM_PERSON", Util.null2String(recordSet.getString("C_INFORM_PERSON"))); + //C_SALARY_TRANSFER是否薪资流转,如果为 是:0->"Y" + hashMap.put("C_SALARY_TRANSFER", "0".equals(Util.null2String(recordSet.getString("C_SALARY_TRANSFER")))?"Y":"N"); + //C_RWDPNS_SCORE奖惩分数 + hashMap.put("C_RWDPNS_SCORE", Util.null2String(recordSet.getString("C_RWDPNS_SCORE"))); + //C_RWDPNS_AMOUNT奖惩金额 + hashMap.put("C_RWDPNS_AMOUNT", "0".equals(Util.null2String(recordSet.getString("C_SALARY_TRANSFER")))?Util.null2String(recordSet.getString("C_RWDPNS_AMOUNT")):""); + //C_RWD_COMMENT备注 + hashMap.put("C_RWD_COMMENT", C_RWD_COMMENT); + list.add(hashMap); + map.put("C_RW_INFO_ARRAY", list); + + + String param = JSON.toJSONString(map); + log.writeLog("map-----------》json:"+param); + + String token = HttpClientToDC.getToken(); + log.writeLog("奖惩token------>" + token); + log.writeLog("奖惩url------>" + url); + String rdata = HttpClientToDC.sendPostApi(url,token, param); + log.writeLog("请求的结果:"+rdata); + + if (!"".equals(rdata) && rdata != null) { + JSONObject jsonObject = JSONObject.parseObject(rdata); + String code = Util.null2String(jsonObject.getString("code")); + log.writeLog("--------发送请求返回的code值为:" + code); + if (code.equals("1")){ + return SUCCESS; + }else{ + String msg = Util.null2String(jsonObject.getString("msg")); + requestInfo.getRequestManager().setMessageid("111100"); + requestInfo.getRequestManager().setMessagecontent(msg); + return "0"; + } + }else{ + String ermsg="流程数据写入HR失败,未获取到接口返回结果,请联系系统管理员处理!"; + requestInfo.getRequestManager().setMessageid("111100"); + requestInfo.getRequestManager().setMessagecontent(ermsg); + return "0"; + } + } catch (Exception e) { + log.writeLog("奖惩数据写入HR失败,错误信息:"+e.toString()); + requestInfo.getRequestManager().setMessageid("111100"); + requestInfo.getRequestManager().setMessagecontent("奖惩数据写入HR失败,错误信息:"+e.toString()); + return "0"; + } + } + + private String getType(String value,String type) { + RecordSet recordSet = new RecordSet(); + recordSet.execute("select FIELDVALUE from uf_fieldvalue where FIELDNAME = '" + type + "' and XlADLONGNAME like '%" + value + "%' "); + //获取值 + recordSet.next(); + + return Util.null2String(recordSet.getString("FIELDVALUE")); + } +} diff --git a/src/main/youhong_ai_jitu_src/jntchina/action/SellOffAction.java b/src/main/youhong_ai_jitu_src/jntchina/action/SellOffAction.java new file mode 100644 index 0000000..6bc320d --- /dev/null +++ b/src/main/youhong_ai_jitu_src/jntchina/action/SellOffAction.java @@ -0,0 +1,125 @@ +package jntchina.action; + + +import com.alibaba.fastjson.JSONObject; +import jntchina.util.HttpClientToDC; +import selfdev.util.base.BaseUtil; +import selfdev.util.log.LogTool; +import weaver.conn.RecordSet; +import weaver.file.Prop; +import weaver.general.Util; +import weaver.interfaces.workflow.action.BaseAction; +import weaver.soa.workflow.request.RequestInfo; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +/** + * @title: 销假(作废) + * @author: ycf + * @date: 2021/01/11 + **/ +public class SellOffAction extends BaseAction { + + @Override + public String execute(RequestInfo requestInfo) { + LogTool log = new LogTool("/log/selfdev/action", true); + String requestId = requestInfo.getRequestid(); // 获取requestid + String workflowid = requestInfo.getWorkflowid(); // 获取workflowid + //获取工作流名称 + String workflowname = BaseUtil.getBaseInfoByParm("workflowname", "workflow_base", "id", workflowid, ""); + log.writeLog("---------------工作流名称-----------workflowname为:" + workflowname); + log.writeLog("--------加班申请单数据传入中台开始----requestId值为:" + requestId); + + //获取配置文件中的参数,到时候URL路径 + String mode = Prop.getPropValue("DevToDC_jntchina", "mode"); + // 服务器ip:port + String baseUrl = Prop.getPropValue("DevToDC_jntchina", mode + "_baseUrl"); + //访问路径拼接 + String url = baseUrl + "/dcoaapi/hr/work"; + //String url = "http://121.37.156.206:21005/PSIGW/RESTListeningConnector/PSFT_HR/C_WORK_APPLY.v1/"; + + + //根据流程id获取主表名称 + String mainTable = RegularizationApplyForAction.getMainTable(requestId); + log.writeLog("--------获取到的表名为----:" + mainTable); + + //{ + //加班数据 + List> list = new ArrayList<>(); + + + + RecordSet rs = new RecordSet(); + try { + String sql = "select * from " + mainTable + " where requestid='" + requestId + "'"; + rs.execute(sql); + log.writeLog("查询sql语句---------------->"+sql); + Map map = new HashMap<>(); + String id = ""; + + while (rs.next()) { + id = rs.getString("ID"); + + map.put("C_LEAVE_NUM",Util.null2String(rs.getString("leaverequestid")));//请假流程 + map.put("EMPLID",Util.null2String(rs.getString("gh")));//工号 + map.put("C_OA_NUM",Util.null2String(rs.getString("LCBH")));//流程编号 + } + sql = "select b.*, from " + mainTable + "_dt1 b where mainid = " + id; + log.writeLog("查找销假明细:"+sql); + rs.execute(sql); + while (rs.next()) { + HashMap map2 = new HashMap<>(); + //C_FLAG是否销假 + map2.put("C_FLAG", "Y"); + //员工编码 + map2.put("EMPLID", Util.null2String(rs.getString("jbksrq"))); + //请假日期 + map2.put("C_START_DT", Util.null2String(rs.getString("jbkssj"))); + //请假开始时间 + map2.put("C_START_DTM", Util.null2String(rs.getString("jbjssj"))); + //请假结束时间 + map2.put("C_END_DTM", Util.null2String(rs.getString("jbjssj"))); + list.add(map2); + } + map.put("LINES",list); + + String strParm = JSONObject.toJSONString(map); + log.writeLog("---------------加班打印的Map数据为:-----------------:"+strParm); + + //获取Token + String token = HttpClientToDC.getToken(); + log.writeLog("加班申请单token------>" + token); + log.writeLog("加班申请单url------>" + url); + + + //调用NCC接口,将数据传给NCC + String returndata = HttpClientToDC.sendPostApi(url,token, strParm); + log.writeLog("【调用数据中台出差申请单接口返回结果result:】" + returndata); + if (!"".equals(returndata) && returndata != null) { + JSONObject jsonObject = JSONObject.parseObject(returndata); + String code = Util.null2String(jsonObject.getString("code")); + log.writeLog("--------发送请求返回的code值为:" + code); + if (code.equals("1")){ + return SUCCESS; + }else{ + String msg = Util.null2String(jsonObject.getString("msg")); + requestInfo.getRequestManager().setMessageid("111100"); + requestInfo.getRequestManager().setMessagecontent(msg); + return "0"; + } + }else{ + String ermsg="流程数据写入NCC调动申请单失败,未获取到接口返回结果,请联系系统管理员处理!"; + requestInfo.getRequestManager().setMessageid("111100"); + requestInfo.getRequestManager().setMessagecontent(ermsg); + return "0"; + } + }catch (Exception e){ + //返回0,调用失败 + log.writeLog("------------------------捕获到的异常是:" + e.toString()); + return "0"; + } + } +} diff --git a/src/main/youhong_ai_jitu_src/jntchina/action/SignHelper.java b/src/main/youhong_ai_jitu_src/jntchina/action/SignHelper.java new file mode 100644 index 0000000..84bc0f2 --- /dev/null +++ b/src/main/youhong_ai_jitu_src/jntchina/action/SignHelper.java @@ -0,0 +1,144 @@ +package jntchina.action; + +import io.jsonwebtoken.Jwts; +import io.jsonwebtoken.SignatureAlgorithm; +import io.jsonwebtoken.impl.compression.CompressionCodecs; +import weaver.file.Prop; + +import java.io.FileInputStream; +import java.io.IOException; +import java.io.UnsupportedEncodingException; +import java.security.*; +import java.security.cert.CertificateException; +import java.security.interfaces.RSAPrivateKey; +import java.util.Map; + +/** + * @program: yesfp-demo + * @description: + * @author: kw + * @create: 2020/05/21 12:37 + */ +public class SignHelper { + + /** + * 签名 + * + * @param paramsMap 表单参数 + * @return 签名值 + * @throws Exception + */ + public static String sign(Map paramsMap) throws Exception { + //读取证书私钥 + PrivateKey privateKey = loadPrivateKeyOfCA(); + Map claims = + JwtParamBuilder.build().setSubject("tester").setIssuer("einvoice").setAudience("einvoice") + .addJwtId().addIssuedAt().setExpirySeconds(3600).setNotBeforeSeconds(3600).getClaims(); + // 需要将表单参数requestdatas的数据进行md5加密,然后放到签名数据的requestdatas中。 + // 此签名数据必须存在,否则在验证签名时会不通过。 + if (paramsMap.containsKey("requestdatas")) { + String value = paramsMap.get("requestdatas"); + claims.put("requestdatas", getMD5(value)); + } + else if (paramsMap.containsKey("nsrsbh")) { + String value = paramsMap.get("nsrsbh"); + claims.put("nsrsbh", getMD5(value)); + } else { + //throw new Exception("签名错误"); + } +//// String value = paramsMap.get("nsrsbh"); +//// claims.put("nsrsbh", getMD5(value)); +// String value = paramsMap.get("requestdatas"); +// System.out.println("============requestdatas=========="+value); +// claims.put("requestdatas", getMD5(value)); + // 使用jdk1.6版本时,删除下面代码的中.compressWith(CompressionCodecs.DEFLATE) + String compactJws = Jwts.builder().signWith(SignatureAlgorithm.RS512, privateKey) + .setClaims(claims).compressWith(CompressionCodecs.DEFLATE).compact(); + return compactJws; + } + +// /** +// * 当在linux环境下运行代码,签名方法报空指针异常的时候,采用该签名方法可以避免这个问题 +// * 使用该方法需要添加新的maven依赖,如下: +// * +// * com.auth0 +// * java-jwt +// * 3.3.0 +// * +// * @param paramsMap +// * @return +// * @throws Exception +// */ +// private String sign(Map paramsMap) throws Exception { +// +// RSAPrivateKey privateKey = loadPrivateKeyOfCA(); +// Map claims = +// JwtParamBuilder.build().setSubject("tester").setIssuer("einvoice").setAudience("einvoice") +// .addJwtId().addIssuedAt().setExpirySeconds(300).setNotBeforeSeconds(300).getClaims(); +// String token; +// try { +// Algorithm algorithm = Algorithm.RSA512(null, privateKey); +// token = JWT.create() +// .withClaim("requestdatas",getMD5(paramsMap.get("requestdatas"))) +// .withHeader(claims) +// .sign(algorithm); +// } catch (JWTCreationException exception){ +// //Invalid Signing configuration / Couldn't convert Claims. +// return null; +// } +// +// return token; +// } + + /** + * 读取证书私钥 + * + * @return + * @throws UnrecoverableKeyException + * @throws KeyStoreException + * @throws NoSuchAlgorithmException + * @throws CertificateException + * @throws IOException + */ + protected static RSAPrivateKey loadPrivateKeyOfCA() throws UnrecoverableKeyException, KeyStoreException, + NoSuchAlgorithmException, CertificateException, IOException { + //获取配置文件中的参数 + String mode = Prop.getPropValue("DevToTaxCould_jntchina","mode"); + //证书路径 + String certpath = Prop.getPropValue("DevToTaxCould_jntchina",mode+"_certpath"); + //证书密码 + String PASSWORD = Prop.getPropValue("DevToTaxCould_jntchina",mode+"_certpassword"); + + FileInputStream in = new FileInputStream(certpath); + KeyStore ks = KeyStore.getInstance("pkcs12"); + ks.load(in, PASSWORD.toCharArray()); + String alias = ks.aliases().nextElement(); + RSAPrivateKey caprk = (RSAPrivateKey) ks.getKey(alias, PASSWORD.toCharArray()); + return caprk; + } + + /** + * 计算参数MD5 + * + * @param str + * @return + * @throws UnsupportedEncodingException + * @throws NoSuchAlgorithmException + */ + private static String getMD5(String str) throws UnsupportedEncodingException, + NoSuchAlgorithmException { + byte[] buf; + buf = str.getBytes("utf-8"); + MessageDigest md5 = null; + md5 = MessageDigest.getInstance("MD5"); + md5.update(buf); + byte[] tmp = md5.digest(); + StringBuilder sb = new StringBuilder(); + for (byte b : tmp) { + sb.append(String.format("%02x", b & 0xff)); + } + return sb.toString(); + } + + +} diff --git a/src/main/youhong_ai_jitu_src/jntchina/action/StaBookBuildParam.java b/src/main/youhong_ai_jitu_src/jntchina/action/StaBookBuildParam.java new file mode 100644 index 0000000..11c6cc1 --- /dev/null +++ b/src/main/youhong_ai_jitu_src/jntchina/action/StaBookBuildParam.java @@ -0,0 +1,373 @@ +package jntchina.action; + + +import jntchina.util.Base64Util; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +/** + * 台账 + */ +public class StaBookBuildParam { + /** + * OCR识别 + * @return + */ + public static Map buildRecognisePostParam() { + Map paramsMap = new HashMap(); + paramsMap.put("nsrsbh", "201609140000001"); + // paramsMap.put("nsrsbh", "91110105MA0084MW37"); + paramsMap.put("orgcode", "20160914001"); + // paramsMap.put("orgcode", "91110105MA0084MW37"); + //注意 base64编码不能有换行 选择BASE64Encoder需要将换行处理 用Base64比较好 + //paramsMap.put("file", Base64Util.imageToBase64("D:\\3.jpg")); + paramsMap.put("file", Base64Util.NetImageToBase64("https://ss0.bdstatic.com/94oJfD_bAAcT8t7mm9GUKT-xh_/timg?image&quality=100&size=b4000_4000&sec=1590057248&di=a298d5f9728d9ded45906a643d8b8b2d&src=http://5b0988e595225.cdn.sohucs.com/images/20180810/75d14550cff44cf4bcc0346dd50c3aae.jpeg"));//ImageToBase64("D:\\1.png")); + return paramsMap; + } + /** + * 识别结果保存台帐 + */ + public static Map OCR_Save(){ + Map paramsMap = new HashMap(); + paramsMap.put("nsrsbh", "201609140000001"); + paramsMap.put("orgcode", "20160914001"); + paramsMap.put("bills",OCR_SaveBills()); + + return paramsMap; + } + + + /** + * 保存报销票据明细 + */ + public static List OCR_SaveBills(){ + List bills = new ArrayList(); + Map datas = new HashMap(); + datas.put("imageId","60214"); + datas.put("billType","train"); + datas.put("data", OCR_SaveTrainData()); + bills.add(datas); + return bills; + } + /** + * 机打发票data + */ + public static Map OCR_SaveMachineData(){ + Map data = new HashMap(); + //开票日期"yyyyMMdd" + data.put("date","20200610"); + //消费类型 + data.put("kind","交通"); + data.put("sellerName","销方名称"); + data.put("buyerName","购方名称"); + //发票代码 + data.put("invoiceCode","211001111013"); + //发票号码 + data.put("invoiceNum","87650531"); + //购方税号 + data.put("buyerTaxId","1234"); + //校验码 + data.put("checkCode",""); + //合计金额BigDecimal + data.put("totalAmount",9); + //报销状态 + data.put("purchaserStatus",""); + //买方税号 + data.put("sellerTaxId",12345); + data.put("time",""); + + return data; + } + /** + * 增值税发票data + *//* + + public static Map OCR_SaveInvoiceData(){ + Map data = new HashMap(); + data.put("hasExist",false); + data.put("hjje",5000); + data.put("xsfMc","成都郫县希望职业学校"); + data.put("gmfNsrsbh",""); + data.put("gmfMc","吴星君计算机应用"); + //售方纳税人识别号 + data.put("xsfNsrsbh","52510124551090719U"); + //发票id + data.put("pkInvoice","0"); + data.put("jshj","5600"); + //作废标志 + data.put("zfbz","N"); + //发票代码 + data.put("fpDm","211001111012"); + //发票类型 + data.put("fplx","9"); + //报销状态 + data.put("purchaserStatus",0); + data.put("hasattache",false); + //开票日期 + data.put("kprq","20171018"); + //发票号码 + data.put("fpHm","87650531"); + //校验码 + data.put("jym","557129"); + //征税方式 + data.put("zsfs","0"); + //表体明细行 + data.put("items",items()); + return data; + } + public static Listitems(){ + List items = new ArrayList(); + Map item = new HashMap(); + //项目名称 + item.put("xmmc","服务费"); + //项目数量 + item.put("xmsl",1); + //项目金额 + item.put("xmje","100"); + //税率 + item.put("sl",0.06); + items.add(item); + return items; + }*/ + /** + * 航空电子行程单DATA + */ + public static Map OCR_SaveAirData(){ + Map data = new HashMap(); + //开票日期"yyyyMMdd" + data.put("date","20200610"); + data.put("id","20200610"); + data.put("fare",4444); + + data.put("agentCode","HKK068,08688003"); + data.put("issueBy","成都携程旅行社有限公司北京分社"); + //消费类型 + data.put("kind","交通"); + data.put("userName","www"); + data.put("userId","371102198004020527"); + data.put("caacDevelopFund",50); + //校验码 + data.put("checkCode",""); + //合计金额BigDecimal + data.put("totalAmount",9); + data.put("ticketNum","8802175000276"); + //发票代码 + data.put("itemList",itemList()); + //发票号码 + data.put("fuelSurcharge",30); + return data; + } + public static ListitemList(){ + List items = new ArrayList(); + Map item = new HashMap(); + //项目名称 + item.put("id","111"); + //项目数量 + item.put("airId","123"); + item.put("date","20200610"); + //项目金额 + item.put("seat","Y"); + //税率 + item.put("carrier","海航"); + item.put("from","杭州"); + item.put("time","19:23"); + item.put("to","北京"); + item.put("flightNumber","HU7678"); + + + items.add(item); + return items; + } + + /** + * 火车票台账data + */ + public static Map OCR_SaveTrainData(){ + Map data = new HashMap(); + //开票日期"yyyyMMdd" + data.put("date","20200610"); + data.put("id","20200610"); + //消费类型 + data.put("kind","交通"); + data.put("origin","北京南"); + data.put("destination","北京北"); + data.put("number","P026491"); + //合计金额BigDecimal + data.put("totalAmount",9); + data.put("trainNum","G9"); + data.put("name","XXX"); + data.put("time","12:00"); + data.put("seatNo","二等座"); + + return data; + } + + /** + * 出租车保存报销data + * @return + */ + + public static Map OCR_SaveTaxiData(){ + Map data = new HashMap(); + //发票代码 + data.put("invoiceCode","211001111012"); + //发票号码 + data.put("invoiceNum","87650531"); + //开票日期"yyyyMMdd" + data.put("date","20200610"); + data.put("id","20200610"); + //消费类型 + data.put("kind","交通"); + //合计金额BigDecimal + data.put("totalAmount",9); + //里程 + data.put("mileage",8); + //上车时间 + data.put("startTime","13:23"); + //结束时间 + data.put("endTime","13:25"); + //发票所在地 + data.put("place","黑龙江省哈尔滨市"); + return data; + } + + + + /** + * 台账报销 + */ + public static Map reimbursed(){ + Map paramsMap = new HashMap(); +// paramsMap.put("nsrsbh", "201609140000001"); +// paramsMap.put("orgcode", "20160914001"); +// paramsMap.put("bills",reimbursedBills()); + paramsMap.put("nsrsbh", "91340122MA2U7J5C88"); + paramsMap.put("orgcode", "JTSDCN0019"); + paramsMap.put("bills",reimbursedBills()); + return paramsMap; + + } + public static List reimbursedBills(){ + List datas = new ArrayList(); + Map data = new HashMap(); +// //发票代码 +// data.put("invoiceCode","211001111012"); +// //发票号码 +// data.put("invoiceNum","87650531"); +// data.put("billType","taxi"); +// data.put("reimburseUser","XXX"); + //发票代码 + data.put("invoiceCode","3400211130"); + //发票号码 + data.put("invoiceNum","08871435"); + data.put("billType","invoice"); + data.put("reimburseUser","时海盟"); + datas.add(data); + return datas; + } + /** + * 台账取消报销 + */ + public static Map cancelReimbursed(){ + Map paramsMap = new HashMap(); + paramsMap.put("nsrsbh", "201609140000001"); + paramsMap.put("orgcode", "20160914001"); + paramsMap.put("bills",reimbursedBills()); + return paramsMap; + + } + /** + * 台账记账 + */ + public static Map account(){ + Map paramsMap = new HashMap(); + paramsMap.put("nsrsbh", "201609140000001"); + paramsMap.put("orgcode", "20160914001"); + paramsMap.put("bills",accountBills()); + return paramsMap; + } + /** + * 台账记账Bills + */ + public static List accountBills(){ + List datas = new ArrayList(); + Map data = new HashMap(); + //发票代码 + data.put("invoiceCode","211001111012"); + //发票号码 + data.put("invoiceNum","87650531"); + data.put("billType","taxi"); + data.put("accountUser","记账人"); + data.put("accountNote","记账人备注"); + datas.add(data); + return datas; + } + /** + * 台账取消记账 + */ + public static Map cancelAccount(){ + Map paramsMap = new HashMap(); + paramsMap.put("nsrsbh", "201609140000001"); + paramsMap.put("orgcode", "20160914001"); + paramsMap.put("bills",accountBills()); + return paramsMap; + } + /** + * 报销台账删除 + */ + public static Map delete(){ + Map paramsMap = new HashMap(); + paramsMap.put("nsrsbh", "201609140000001"); + paramsMap.put("orgcode", "20160914001"); + paramsMap.put("bills",accountBills()); + return paramsMap; + } + /** + * 飞机票、火车票,出租车台账查询 + */ + public static Map find(){ + Map paramsMap = new HashMap(); + paramsMap.put("orgcode", "20160914001"); + paramsMap.put("submitDate_begin","2000-07-05"); + paramsMap.put("submitDate_end","2020-06-11"); + return paramsMap; + } + + /** + * 个人票夹提交发票到报销台账_全票种 + * @return + */ + public static Map commit(){ + Map paramsMap = new HashMap(); + paramsMap.put("usermobile", "15011181852"); + paramsMap.put("useremail", "wangyer@yonyou.com"); + paramsMap.put("orgcode", "20160914001"); + paramsMap.put("nsrsbh", "201609140000001"); + paramsMap.put("submitter", "提交人"); + paramsMap.put("srcBillCode", "23456789"); + paramsMap.put("srcBillType", "taxi"); + paramsMap.put("reimburseUser", "测试报销人1"); + paramsMap.put("returnEnclosure", "Y"); + paramsMap.put("busiOp", "1"); + paramsMap.put("summarys", summarys()); + return paramsMap; + } + public static List summarys(){ + List datas = new ArrayList(); + Map data1 = new HashMap(); + Map data2 = new HashMap(); + data1.put("invoiceNum","68706393"); + data1.put("invoiceCode","042001700107"); + data1.put("billType","invoice"); + data2.put("invoiceNum","51266661"); + data2.put("invoiceCode","111001881002"); + data2.put("billType","taxi"); + datas.add(data1); + datas.add(data2); + return datas; + } + +} diff --git a/src/main/youhong_ai_jitu_src/jntchina/action/TeamBuildingExpensesReturnAction.java b/src/main/youhong_ai_jitu_src/jntchina/action/TeamBuildingExpensesReturnAction.java new file mode 100644 index 0000000..4316cc1 --- /dev/null +++ b/src/main/youhong_ai_jitu_src/jntchina/action/TeamBuildingExpensesReturnAction.java @@ -0,0 +1,117 @@ +package jntchina.action; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.JSONObject; +import jntchina.util.HttpClientToDC; +import selfdev.util.base.BaseUtil; +import selfdev.util.log.LogTool; +import weaver.conn.RecordSet; +import weaver.file.Prop; +import weaver.general.Util; +import weaver.interfaces.workflow.action.BaseAction; +import weaver.soa.workflow.request.RequestInfo; + +import java.util.HashMap; +import java.util.Map; + +/** + * @title: 团建费用报销数据写入HR + * @Author ycf + * @Date: 2022/1/6 15:14 + * @Version 1.0 + */ +public class TeamBuildingExpensesReturnAction extends BaseAction { + @Override + public String execute(RequestInfo requestInfo) { + LogTool log = new LogTool("/log/selfdev/action/hrm", false); + String requestId = requestInfo.getRequestid(); // 获取requestid + String workflowid = requestInfo.getWorkflowid(); // 获取workflowid + //获取工作流名称 + String workflowname = BaseUtil.getBaseInfoByParm("workflowname", "workflow_base", "id", workflowid, ""); + log.writeLog("---------------工作流名称-----------workflowname为:" + workflowname); + log.writeLog("--------团建申请单数据传入中台开始----requestId值为:" + requestId); + + //获取配置文件中的参数,到时候URL路径 + String mode = Prop.getPropValue("DevToDC_jntchina", "mode"); + // 服务器ip:port + String baseUrl = Prop.getPropValue("DevToDC_jntchina", mode + "_baseUrl"); + //访问路径拼接 + String url = baseUrl + "/dcoaapi/hr/groupResult"; + + + //根据流程id获取主表名称 + String mainTable = RegularizationApplyForAction.getMainTable(requestId); + log.writeLog("--------获取到的表名为----:" + mainTable); + + + RecordSet recordSet = new RecordSet(); + String sql = ""; + Map map = new HashMap(); + + try { + //获取部门和日期 + sql = "select (select OUTKEY from hrmdepartment a where a.ID= b.bxrbm) outkey, " + + "fyfsrq,lcbh,cjrq, (select WORKCODE " + + "from HrmResource a where a.ID = b.bxr) sqrgh,bxje,sfcgxrhr " + + "from " + mainTable + " b where REQUESTID = "+requestId; + log.writeLog("获取团建信息的SQL:"+sql); + + recordSet.execute(sql); + recordSet.next(); + //是否成功写入HR + String sfcgxrhr=Util.null2String(recordSet.getString("sfcgxrhr")); + if("0".equals(sfcgxrhr)){ + log.writeLog("*************requestid=【"+requestId+"】之前已成功写入HR,本次不再重复写入*************"); + return SUCCESS; + } + //申请单号 + map.put("C_APP_SEQ", Util.null2String(recordSet.getString("lcbh"))); + //申请日期 + map.put("C_APP_DT", Util.null2String(recordSet.getString("cjrq")).replace("-","/")); + //申请人工号 + map.put("EMPLID", Util.null2String(recordSet.getString("sqrgh"))); + //部门 + map.put("DEPTID", Util.null2String(recordSet.getString("outkey"))); + //金额 + map.put("AMOUNT", Util.null2String(recordSet.getString("bxje"))); + map.put("C_APPLI_RS", "3"); + //发生日期 + map.put("OCCURRENCE_DT", Util.null2String(recordSet.getString("fyfsrq")).replace("-","/")); + + + + String params = JSON.toJSONString(map); + log.writeLog("团建费用报销传入参数JSON----------->"+params); + + String token = HttpClientToDC.getToken(); + log.writeLog("团建token------>" + token); + log.writeLog("团建url------>" + url); + String rdata = HttpClientToDC.sendPostApi(url,token, params); + log.writeLog("请求的结果:"+rdata); + + if (!"".equals(rdata) && rdata != null) { + JSONObject jsonObject = JSONObject.parseObject(rdata); + String code = Util.null2String(jsonObject.getString("code")); + log.writeLog("--------发送请求返回的code值为:" + code); + if (code.equals("1")){ + return SUCCESS; + }else{ + String msg = Util.null2String(jsonObject.getString("msg")); + requestInfo.getRequestManager().setMessageid("111100"); + requestInfo.getRequestManager().setMessagecontent(msg); + return "0"; + } + }else{ + String ermsg="流程数据写入HR失败,未获取到接口返回结果,请联系系统管理员处理!"; + requestInfo.getRequestManager().setMessageid("111100"); + requestInfo.getRequestManager().setMessagecontent(ermsg); + return "0"; + } + } catch (Exception e) { + log.writeLog("团建报销数据写入HR失败,错误信息:"+e.toString()); + requestInfo.getRequestManager().setMessageid("111100"); + requestInfo.getRequestManager().setMessagecontent("团建报销数据写入HR失败,错误信息:"+e.toString()); + return "0"; + } + } +} diff --git a/src/main/youhong_ai_jitu_src/jntchina/action/TransferWriteBackAction.java b/src/main/youhong_ai_jitu_src/jntchina/action/TransferWriteBackAction.java new file mode 100644 index 0000000..bf8196a --- /dev/null +++ b/src/main/youhong_ai_jitu_src/jntchina/action/TransferWriteBackAction.java @@ -0,0 +1,229 @@ +package jntchina.action; + +import com.alibaba.fastjson.JSONObject; +import jntchina.util.HttpClientToDC; +import selfdev.util.base.BaseUtil; +import selfdev.util.log.LogTool; +import weaver.conn.RecordSet; +import weaver.file.Prop; +import weaver.general.Util; +import weaver.hrm.resource.ResourceComInfo; +import weaver.interfaces.workflow.action.Action; +import weaver.soa.workflow.request.RequestInfo; + +import java.util.HashMap; +import java.util.Map; + +/** + * 调动申请单写入中台(HR系统) + */ +public class TransferWriteBackAction implements Action { + + public String execute(RequestInfo requestInfo) { + LogTool log=new LogTool("/log/selfdev/action/hrm", false); + + String requestId = requestInfo.getRequestid(); + String workflowid=requestInfo.getWorkflowid(); + String workflowname= BaseUtil.getBaseInfoByParm("workflowname", "workflow_base", "id", workflowid, ""); + log.writeLog("---------------"+workflowname+"开始写入HR-------------requestId:" + requestId); + + //获取配置文件中的参数 + String mode = Prop.getPropValue("DevToDC_jntchina","mode"); + // 服务器ip:port + String baseUrl = Prop.getPropValue("DevToDC_jntchina", mode+"_baseUrl"); + String url = baseUrl+"/dcoaapi/hr/callApplication"; + //获取OA表名称 + String tablename=BaseUtil.getBaseInfoByParm("tablename", "workflow_bill", "1", "1", " and id in (select formid from workflow_base where id="+workflowid+")"); + + try { + RecordSet rs = new RecordSet(); + String sql = " select C_APP_SEQ," + + "C_APP_DT," + + "EMPLID," + + "EMPLID2," + + "ddsxrq as ACTION_DT," + + "POSITION_NBR2,"+ + "drzj C_POSN_GRDE_ID1," + + "drxzz GP_PAYGROUP2," + + "C_SB_LOC_ID1," + + "SUPERVISOR_ID2," + + "C_JOB_INSP_DT," + + "IS_DEPT_MANAGER," + + "IS_EMPL_SUPER_VISOR," + + "IS_DEPT_BRCH_LEADER," + + "MANAGER_ID," + + "SUPERVISOR_ID3," + + "IS_DEPT_EXPAND," + + "C_EXPAND_EMPLID," + + "ddlx1 ACTION_REASON," + + "ddzlx ACT_REASON_SUB," + + "C_BRCH_LEADR_ID," + + "C_SB_LOC_COMPANY," + + "C_SB_LOC_RULE," + + "C_ENDO_INSU," + + "C_ENDO_INSU1," + + "C_GJJ_RULE_ID," + + "C_HOUS_FUND," + + "C_HOUS_FUND1," + + "C_SB_EFFDT,sbgjjsfbg from "+tablename+" where requestid = "+requestId+" "; + //添加查询【社保公积金是否变更】 sbgjjsfbg -N + log.writeLog("调动申请单OA查询sql:"+sql); + rs.executeQuery(sql); + + Map map = new HashMap(); + String[] columnName = rs.getColumnName(); + rs.next(); + for (int i = 0; i < columnName.length; i++) { + map.put(columnName[i], Util.null2String(rs.getString(columnName[i]))); + } + //获取【社保公积金是否变更】的数据 -N + String sbgjjsfbg=Util.null2String(rs.getString("sbgjjsfbg")); + + + map.put("C_APPLI_RS","3");//审批状态 默认为3 + + //是否为部门负责人 + if (map.get("IS_DEPT_MANAGER").equals("0")){ + map.put("IS_DEPT_MANAGER","Y"); + }else{ + map.put("IS_DEPT_MANAGER","N"); + } + + //是否为部门分管领导 + if (map.get("IS_DEPT_BRCH_LEADER").equals("0")){ + map.put("IS_DEPT_BRCH_LEADER","Y"); + }else{ + map.put("IS_DEPT_BRCH_LEADER","N"); + } + + //是否为员工直接上级 + if (map.get("IS_EMPL_SUPER_VISOR").equals("0")){ + map.put("IS_EMPL_SUPER_VISOR","Y"); + }else{ + map.put("IS_EMPL_SUPER_VISOR","N"); + } + //是否为部门拓展者角色 + if (map.get("IS_DEPT_EXPAND").equals("0")){ + map.put("IS_DEPT_EXPAND","Y"); + }else{ + map.put("IS_DEPT_EXPAND","N"); + } + + //变更拓展者角色 + if (map.get("C_EXPAND_EMPLID").equals("")){ + map.put("C_EXPAND_EMPLID",""); + }else{ + String C_EXPAND_EMPLID = new ResourceComInfo().getWorkcode(map.get("C_EXPAND_EMPLID").toString()); + map.put("C_EXPAND_EMPLID",C_EXPAND_EMPLID); + } + //分管领导接替人 + if (map.get("C_BRCH_LEADR_ID").equals("")){ + map.put("C_BRCH_LEADR_ID",""); + }else{ + String C_BRCH_LEADR_ID = new ResourceComInfo().getWorkcode(map.get("C_BRCH_LEADR_ID").toString()); + map.put("C_BRCH_LEADR_ID",C_BRCH_LEADR_ID); + } + //直接上级接替人 + if (map.get("SUPERVISOR_ID3").equals("")){ + map.put("SUPERVISOR_ID3",""); + }else{ + String SUPERVISOR_ID3 = new ResourceComInfo().getWorkcode(map.get("SUPERVISOR_ID3").toString()); + map.put("SUPERVISOR_ID3",SUPERVISOR_ID3); + } + + //部门负责人接替人 + if (map.get("MANAGER_ID").equals("")){ + map.put("MANAGER_ID",""); + }else{ + String MANAGER_ID = new ResourceComInfo().getWorkcode(map.get("MANAGER_ID").toString()); + map.put("MANAGER_ID",MANAGER_ID); + } + + //调入直属领导 + if (map.get("SUPERVISOR_ID2").equals("")){ + map.put("SUPERVISOR_ID2",""); + }else{ + String SUPERVISOR_ID2 = new ResourceComInfo().getWorkcode(map.get("SUPERVISOR_ID2").toString()); + map.put("SUPERVISOR_ID2",SUPERVISOR_ID2); + } + //操作原因 X01-部门内调动 X02-跨部门调动 X03-跨公司调动 + //根据下拉框的值获取对应的描述 + String ddlx1Name=BaseUtil.getBaseInfoByParm("selectname", "workflow_selectitem", "selectvalue", map.get("ACTION_REASON").toString(), + " and fieldid in (select id from workflow_billfield where billid in (select formid from workflow_base where id="+workflowid+") and fieldname='ddlx1' and viewtype=0)"); + //过滤多语言 + ddlx1Name=Util.formatMultiLang(ddlx1Name,"7"); + + String[] ACTION_REASON = ddlx1Name.split("-"); + map.put("ACTION_REASON",ACTION_REASON[0]);//调动类型 + + //操作子原因 10-晋级 20-降职 30-平调 + //根据下拉框的值获取对应的描述 + String ddzlxName=BaseUtil.getBaseInfoByParm("selectname", "workflow_selectitem", "selectvalue", map.get("ACT_REASON_SUB").toString(), + " and fieldid in (select id from workflow_billfield where billid in (select formid from workflow_base where id="+workflowid+") and fieldname='ddzlx' and viewtype=0)"); + //过滤多语言 + ddzlxName=Util.formatMultiLang(ddzlxName,"7"); + String[] ACT_REASON_SUB = ddzlxName.split("-");//截取横线前面的编码 + map.put("ACT_REASON_SUB",ACT_REASON_SUB[0]);//调动原因 + + + if (map.get("C_POSN_GRDE_ID1").equals("")){//存在历史问题 所以加判断 调入职级 + map.put("C_POSN_GRDE_ID1","101");//调入职级 + } + + if (map.get("GP_PAYGROUP2").equals("")){//存在历史问题 所以加判断 + map.put("GP_PAYGROUP2","100");//调入薪资组 默认100 G0 + } + //sbgjjsfbg 【社保公积金是否变更】如果为否的话,清空数据 -N + if("1".equals(sbgjjsfbg)){ + //否为: 1 + map.put("C_SB_LOC_COMPANY","");//社保缴纳公司 + map.put("C_SB_LOC_RULE","");//社保缴纳规则 + map.put("C_ENDO_INSU","");//个人缴费基数及比例 + map.put("C_ENDO_INSU1","");//单位缴费基数及比例 + map.put("C_GJJ_RULE_ID","");//公积金缴费规则 + map.put("C_HOUS_FUND","");//个人公积金基数 + map.put("C_HOUS_FUND1","");//公司公积金基数 + map.put("C_SB_EFFDT","");//社保公积金生效日期 + map.put("C_SB_LOC_ID1","");//调入社保缴纳地 + } + //清除【sbgjjsfbg】 + map.remove("sbgjjsfbg"); + + + String strParm = JSONObject.toJSONString(map); + log.writeLog("调动申请单准备传入数据中台的数据为------>" + strParm); + + String token = HttpClientToDC.getToken(); + log.writeLog("调动申请单token------>" + token); + log.writeLog("调动申请单url------>" + url); + + String returndata = HttpClientToDC.sendPostApi(url,token, strParm); + log.writeLog("调动流程HR接口返回结果returndata-------->" + returndata); + if (!"".equals(returndata) && returndata != null) { + JSONObject jsonObject = JSONObject.parseObject(returndata); + String code = Util.null2String(jsonObject.get("code")); + log.writeLog("--------发送请求返回的code值为:" + code); + if (code.equals("1")){ + return SUCCESS; + }else{ + String msg = Util.null2String(jsonObject.get("msg")); + requestInfo.getRequestManager().setMessageid("111100"); + requestInfo.getRequestManager().setMessagecontent(msg); + return "0"; + } + }else{ + String ermsg="流程数据写入NCC调动申请单失败,未获取到接口返回结果,请联系系统管理员处理!"; + requestInfo.getRequestManager().setMessageid("111100"); + requestInfo.getRequestManager().setMessagecontent(ermsg); + return "0"; + } + } catch (Exception e) { + e.printStackTrace(); + requestInfo.getRequestManager().setMessageid("111100"); + requestInfo.getRequestManager().setMessagecontent("流程发生错误!"); + return "0"; + } + } + + +} diff --git a/src/main/youhong_ai_jitu_src/jntchina/action/XiaojiaAction.java b/src/main/youhong_ai_jitu_src/jntchina/action/XiaojiaAction.java new file mode 100644 index 0000000..a979a23 --- /dev/null +++ b/src/main/youhong_ai_jitu_src/jntchina/action/XiaojiaAction.java @@ -0,0 +1,134 @@ +package jntchina.action; + +import com.alibaba.fastjson.JSONObject; +import jntchina.util.HttpClientToDC; +import selfdev.util.base.BaseUtil; +import selfdev.util.log.LogTool; +import weaver.conn.RecordSet; +import weaver.file.Prop; +import weaver.general.Util; +import weaver.interfaces.workflow.action.BaseAction; +import weaver.soa.workflow.request.RequestInfo; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +/** + * @description: 销假数据传入HR + * @author: KangMD + * @date: 2022-02-11 + **/ +public class XiaojiaAction extends BaseAction { + + @Override + public String execute(RequestInfo requestInfo) { + LogTool log = new LogTool("/log/selfdev/action/hrm", true); + String requestId = requestInfo.getRequestid(); // 获取requestid + String workflowid = requestInfo.getWorkflowid(); // 获取workflowid + + //获取工作流名称 + String workflowname = BaseUtil.getBaseInfoByParm("workflowname", "workflow_base", "id", workflowid, ""); + log.writeLog("--------【"+workflowname+"】数据传入中台开始----requestId值为:" + requestId); + //获取配置文件中的参数,到时候URL路径 + String mode = Prop.getPropValue("DevToDC_jntchina", "mode"); + //服务器ip:port + String baseUrl = Prop.getPropValue("DevToDC_jntchina", mode + "_baseUrl"); + //访问路径拼接 + String url = baseUrl + "/dcoaapi/hr/leaveOff"; + //根据流程id获取主表名称 + String mainTable = RegularizationApplyForAction.getMainTable(requestId); + log.writeLog("-------------获取到的表名为-------------:" + mainTable); + String mainid=""; + //销假单号 + String C_OA_NUM = ""; + //请假单号 + String C_LEAVE_NUM = ""; + //员工编码 + String EMPLID = ""; + //销假list + List> list = new ArrayList>(); + + RecordSet rs = new RecordSet(); + try { + String sql = "select a.* from "+mainTable+" a where a.requestid = '" + requestId + "'"; + rs.execute(sql); + log.writeLog("查询主表数据sql语句---------------->"+sql); + while (rs.next()) { + mainid = Util.null2String(rs.getString("id"));//主表主键ID + C_OA_NUM = Util.null2String(rs.getString("lcbh"));//OA销假单号 + EMPLID = Util.null2String(rs.getString("gh"));//OA提单人工号 + C_LEAVE_NUM = Util.null2String(rs.getString("qjlcbh"));//OA请假单号 + } + log.writeLog("C_OA_NUM---------------->"+C_OA_NUM); + log.writeLog("C_LEAVE_NUM---------------->"+C_LEAVE_NUM); + log.writeLog("EMPLID---------------->"+EMPLID); + //查询明细数据 + sql = "select * from "+mainTable+"_dt1 a where a.mainid = '" + mainid + "'"; + rs.execute(sql); + log.writeLog("查询sql语句---------------->"+sql); + while (rs.next()) { + String sfxj=Util.null2String(rs.getString("sfxj")); + String C_FLAG = "1".equals(sfxj)?"Y":"N";//是否销假 Y:是;N:否 + String C_START_DT = Util.null2String(rs.getString("detail_leavefromDate"));//请假日期 + String C_START_DTM = Util.null2String(rs.getString("detail_leavefromTime"));//请假开始时间 + String C_END_DTM = Util.null2String(rs.getString("detail_leavetoTime"));//请假结束时间 + if(C_START_DTM.length()==5){ + C_START_DTM=C_START_DTM+":00"; + } + if(C_END_DTM.length()==5){ + C_END_DTM=C_END_DTM+":00"; + } + + //将签卡数据进行包装 + Map maps= new HashMap(); + maps.put("EMPLID",EMPLID); + maps.put("C_FLAG",C_FLAG); + maps.put("C_START_DT",C_START_DT); + maps.put("C_START_DTM",C_START_DTM); + maps.put("C_END_DTM",C_END_DTM); + list.add(maps); + } + //最后再将数据全部打包 + Map map = new HashMap(); + map.put("C_OA_NUM",C_OA_NUM); + map.put("C_LEAVE_NUM",C_LEAVE_NUM); + map.put("EMPLID",EMPLID); + map.put("LINES",list); + String strParm = JSONObject.toJSONString(map); + log.writeLog("销假传入参数JSON----------------->"+strParm); + + //获取Token + String token = HttpClientToDC.getToken(); + log.writeLog("销假申请token------>" + token); + log.writeLog("销假申请url------>" + url); + + //调用NCC接口,将数据传给NCC + String returndata = HttpClientToDC.sendPostApi(url,token, strParm); + log.writeLog("【调用数据中台销假单接口返回结果result:】" + returndata); + if (!"".equals(returndata) && returndata != null) { + JSONObject jsonObject = JSONObject.parseObject(returndata); + String code = Util.null2String(jsonObject.get("code")); + log.writeLog("--------发送请求返回的code值为:" + code); + if (code.equals("1")){ + return SUCCESS; + }else{ + String msg = Util.null2String(jsonObject.get("msg")); + requestInfo.getRequestManager().setMessageid("111100"); + requestInfo.getRequestManager().setMessagecontent(msg); + return "0"; + } + }else{ + String ermsg="流程数据调用HR销假接口失败,未获取到接口返回结果,请联系系统管理员处理!"; + requestInfo.getRequestManager().setMessageid("111100"); + requestInfo.getRequestManager().setMessagecontent(ermsg); + return "0"; + } + }catch (Exception e){ + //返回0,调用失败 + log.writeLog("------------------------捕获到的异常是:" + e.toString()); + return "0"; + } + } +} diff --git a/src/main/youhong_ai_jitu_src/jntchina/action/XiaojiaForceDrawBackAction.java b/src/main/youhong_ai_jitu_src/jntchina/action/XiaojiaForceDrawBackAction.java new file mode 100644 index 0000000..99f2dd2 --- /dev/null +++ b/src/main/youhong_ai_jitu_src/jntchina/action/XiaojiaForceDrawBackAction.java @@ -0,0 +1,38 @@ +package jntchina.action; + +import selfdev.util.base.BaseUtil; +import selfdev.util.log.LogTool; +import weaver.interfaces.workflow.action.BaseAction; +import weaver.soa.workflow.request.RequestInfo; + +/** + * @description: 销假强制收回时的节点附加操作 + * @author: KangMD + * @date: 2022-02-11 + **/ +public class XiaojiaForceDrawBackAction extends BaseAction { + + public static LogTool log=new LogTool("/log/selfdev/action/hrm", false); + public String execute(RequestInfo requestInfo){ + String requestId = requestInfo.getRequestid(); // 获取requestid + String workflowid = requestInfo.getWorkflowid(); // 获取workflowid + + //获取工作流名称 + String workflowname = BaseUtil.getBaseInfoByParm("workflowname", "workflow_base", "id", workflowid, ""); + log.writeLog("--------【"+workflowname+"】强制收回时的节点附加操作----requestId值为:" + requestId); + try{ + XiaojiaForceDrawBackThread forceDrawBackThread=new XiaojiaForceDrawBackThread(); + //设置参数 + forceDrawBackThread.setRequestInfo(requestInfo); + Thread thread = new Thread(forceDrawBackThread); + //启动线程 + thread.start(); + log.writeLog("--------【"+workflowname+"】强制收回时启用线程--------"); + }catch (Exception e){ + //返回0,调用失败 + log.writeLog("------------------------捕获到的异常是:" + e.toString()); + return "0"; + } + return SUCCESS; + } +} diff --git a/src/main/youhong_ai_jitu_src/jntchina/action/XiaojiaForceDrawBackThread.java b/src/main/youhong_ai_jitu_src/jntchina/action/XiaojiaForceDrawBackThread.java new file mode 100644 index 0000000..f8a62a8 --- /dev/null +++ b/src/main/youhong_ai_jitu_src/jntchina/action/XiaojiaForceDrawBackThread.java @@ -0,0 +1,125 @@ +package jntchina.action; + +import java.util.HashMap; +import java.util.Map; + +import com.alibaba.fastjson.JSONObject; + +import jntchina.util.HttpClientToDC; +import selfdev.util.base.BaseUtil; +import selfdev.util.log.LogTool; +import weaver.conn.RecordSet; +import weaver.file.Prop; +import weaver.general.Util; +import weaver.soa.workflow.request.RequestInfo; + +/** + * @description: 销假强制收回时的节点附加操作 + * @author: KangMD + * @date: 2022-02-11 + **/ +public class XiaojiaForceDrawBackThread implements Runnable { + + public static LogTool log=new LogTool("/log/selfdev/action/hrm", false); + public RequestInfo requestInfo; + + public RequestInfo getRequestInfo() { + return requestInfo; + } + + public void setRequestInfo(RequestInfo requestInfo) { + this.requestInfo = requestInfo; + } + + public void run(){ + String requestId = requestInfo.getRequestid(); // 获取requestid + try { + log.writeLog("----------1.5秒后再启动【requestId:" + requestId+"】-------------"); + Thread.sleep(1500);//延迟执行 + } catch (InterruptedException e1) { + // TODO Auto-generated catch block + e1.printStackTrace(); + } + log.writeLog("----------1.5秒结束,开启执行代码【requestId:" +requestId+"】-------------"); + + String workflowid = requestInfo.getWorkflowid(); // 获取workflowid + //获取工作流名称 + String workflowname = BaseUtil.getBaseInfoByParm("workflowname", "workflow_base", "id", workflowid, ""); + log.writeLog("--------【"+workflowname+"】强制收回时的节点附加操作----requestId值为:" + requestId); + + try{ + //流程当前状态 + String currentnodetype=""; + RecordSet rs = new RecordSet(); + String sql = "select * from workflow_requestbase where requestid = "+requestId+""; + rs.execute(sql); + while (rs.next()) { + currentnodetype = Util.null2String(rs.getString("currentnodetype"));//当前流程状态 + } + log.writeLog("currentnodetype---------------->"+currentnodetype); + //流程当前处于申请节点,才需要调用HR接口 + if(!"0".equals(currentnodetype)){ + log.writeLog("*************流程不是强制收回到申请节点,不需要调用HR接口*************"); + return; + } + //获取配置文件中的参数,到时候URL路径 + String mode = Prop.getPropValue("DevToDC_jntchina", "mode"); + // 服务器ip:port + String baseUrl = Prop.getPropValue("DevToDC_jntchina", mode + "_baseUrl"); + //访问路径拼接 + String url = baseUrl + "/dcoaapi/hr/attendance"; + + //根据流程id获取主表名称 + String mainTable = RegularizationApplyForAction.getMainTable(requestId); + log.writeLog("--------获取到的表名为----:" + mainTable); + //申请单号 + String C_OA_NUM = ""; + //单据来源:默认OA + String C_APPLY_SOURCE = "OA"; + //流程名称:销假流程为:50 + String C_WORKFLOW = "50"; + //审批状态:已通过:3,驳回:5 + String C_STATUS = "5"; + + sql = "select * from "+mainTable+" where requestid = "+requestId+""; + rs.execute(sql); + log.writeLog("查询主表sql---------------->"+sql); + while (rs.next()) { + C_OA_NUM = Util.null2String(rs.getString("lcbh"));//申请单号 + } + + Map map = new HashMap(); + map.put("C_OA_NUM",C_OA_NUM); + map.put("C_APPLY_SOURCE",C_APPLY_SOURCE); + map.put("C_WORKFLOW",C_WORKFLOW); + map.put("C_STATUS",C_STATUS); + String strParm = JSONObject.toJSONString(map); + log.writeLog("销假状态回传JSON----------------->"+strParm); + + //获取Token + String token = HttpClientToDC.getToken(); + log.writeLog("销假申请单token------>" + token); + log.writeLog("销假申请单url------>" + url); + + //调用NCC接口,将数据传给NCC + String returndata = HttpClientToDC.sendPostApi(url,token,strParm); + log.writeLog("【销假强制收回时的节点附加操作调用数据中台销假申请单接口返回结果:】" + returndata); + if (!"".equals(returndata) && returndata != null) { + JSONObject jsonObject = JSONObject.parseObject(returndata); + String code = Util.null2String(jsonObject.get("code")); + log.writeLog("--------发送请求返回的code值为:" + code); + if ("1".equals(code)) { + + }else { + String msg = Util.null2String(jsonObject.get("msg")); + log.writeLog("调用HR接口返回错误信息----->" + msg); + } + }else { + log.writeLog("调用HR接口返回为空----->"); + } + }catch (Exception e){ + //返回0,调用失败 + log.writeLog("------------------------捕获到的异常是:" + e.toString()); + } + } +} diff --git a/src/main/youhong_ai_jitu_src/jntchina/action/XiaojiaHuiChuanReturnAction.java b/src/main/youhong_ai_jitu_src/jntchina/action/XiaojiaHuiChuanReturnAction.java new file mode 100644 index 0000000..c6ab042 --- /dev/null +++ b/src/main/youhong_ai_jitu_src/jntchina/action/XiaojiaHuiChuanReturnAction.java @@ -0,0 +1,100 @@ +package jntchina.action; + +import com.alibaba.fastjson.JSONObject; +import jntchina.util.HttpClientToDC; +import selfdev.util.base.BaseUtil; +import selfdev.util.log.LogTool; +import weaver.conn.RecordSet; +import weaver.file.Prop; +import weaver.general.Util; +import weaver.interfaces.workflow.action.BaseAction; +import weaver.soa.workflow.request.RequestInfo; + +import java.util.HashMap; +import java.util.Map; + +/** + * @description: 销假流程退回至申请节点时将驳回状态回传HR + * @author: KangMD + * @date: 2022-02-11 + **/ +public class XiaojiaHuiChuanReturnAction extends BaseAction{ + public static LogTool log=new LogTool("/log/selfdev/action/hrm", true); + public String execute(RequestInfo requestInfo){ + String requestId = requestInfo.getRequestid(); // 获取requestid + String workflowid = requestInfo.getWorkflowid(); // 获取workflowid + + //获取工作流名称 + String workflowname = BaseUtil.getBaseInfoByParm("workflowname", "workflow_base", "id", workflowid, ""); + log.writeLog("---------------工作流名称-----------workflowname为:" + workflowname); + log.writeLog("--------【"+workflowname+"】退回到申请节点时数据传入中台开始----requestId值为:" + requestId); + + try{ + //获取配置文件中的参数,到时候URL路径 + String mode = Prop.getPropValue("DevToDC_jntchina", "mode"); + // 服务器ip:port + String baseUrl = Prop.getPropValue("DevToDC_jntchina", mode + "_baseUrl"); + //访问路径拼接 + String url = baseUrl + "/dcoaapi/hr/attendance"; + + //根据流程id获取主表名称 + String mainTable = RegularizationApplyForAction.getMainTable(requestId); + log.writeLog("--------获取到的表名为----:" + mainTable); + //申请单号 + String C_OA_NUM = ""; + //单据来源:默认OA + String C_APPLY_SOURCE = "OA"; + //流程名称:销假流程为:50 + String C_WORKFLOW = "50"; + //审批状态:已通过:3,驳回:5 + String C_STATUS = "5"; + + RecordSet rs = new RecordSet(); + String sql = "select * from "+mainTable+" where requestid = "+requestId+""; + log.writeLog("查询主表sql---------------->"+sql); + rs.execute(sql); + while (rs.next()) { + C_OA_NUM = Util.null2String(rs.getString("lcbh"));//申请单号 + } + + Map map = new HashMap(); + map.put("C_OA_NUM",C_OA_NUM); + map.put("C_APPLY_SOURCE",C_APPLY_SOURCE); + map.put("C_WORKFLOW",C_WORKFLOW); + map.put("C_STATUS",C_STATUS); + String strParm = JSONObject.toJSONString(map); + log.writeLog("销假状态回传JSON----------------->"+strParm); + + //获取Token + String token = HttpClientToDC.getToken(); + log.writeLog("销假申请单token------>" + token); + log.writeLog("销假申请单url------>" + url); + + //调用接口 + String returndata = HttpClientToDC.sendPostApi(url,token,strParm); + log.writeLog("【调用数据中台销假申请单接口返回结果:】" + returndata); + if (!"".equals(returndata) && returndata != null) { + JSONObject jsonObject = JSONObject.parseObject(returndata); + String code = Util.null2String(jsonObject.get("code")); + log.writeLog("--------发送请求返回的code值为:" + code); + if ("1".equals(code)) { + return SUCCESS; + } else { + String msg = Util.null2String(jsonObject.get("msg")); + requestInfo.getRequestManager().setMessageid("111100"); + requestInfo.getRequestManager().setMessagecontent(msg); + return "0"; + } + }else { + String ermsg = "流程数据已审批状态提交至中台失败,请联系系统管理员处理!"; + requestInfo.getRequestManager().setMessageid("111100"); + requestInfo.getRequestManager().setMessagecontent(ermsg); + return "0"; + } + }catch (Exception e){ + //返回0,调用失败 + log.writeLog("------------------------捕获到的异常是:" + e.toString()); + return "0"; + } + } +} diff --git a/src/main/youhong_ai_jitu_src/jntchina/action/XiaojiaHuiChuanSuccessAction.java b/src/main/youhong_ai_jitu_src/jntchina/action/XiaojiaHuiChuanSuccessAction.java new file mode 100644 index 0000000..db5b205 --- /dev/null +++ b/src/main/youhong_ai_jitu_src/jntchina/action/XiaojiaHuiChuanSuccessAction.java @@ -0,0 +1,100 @@ +package jntchina.action; + +import com.alibaba.fastjson.JSONObject; +import jntchina.util.HttpClientToDC; +import selfdev.util.base.BaseUtil; +import selfdev.util.log.LogTool; +import weaver.conn.RecordSet; +import weaver.file.Prop; +import weaver.general.Util; +import weaver.interfaces.workflow.action.BaseAction; +import weaver.soa.workflow.request.RequestInfo; + +import java.util.HashMap; +import java.util.Map; + +/** + * @description: 销假流程归档时将已通过状态回传HR + * @author: KangMD + * @date: 2021-02-11 + **/ +public class XiaojiaHuiChuanSuccessAction extends BaseAction { + + public static LogTool log=new LogTool("/log/selfdev/action/hrm", true); + public String execute(RequestInfo requestInfo){ + String requestId = requestInfo.getRequestid(); // 获取requestid + String workflowid = requestInfo.getWorkflowid(); // 获取workflowid + + //获取工作流名称 + String workflowname = BaseUtil.getBaseInfoByParm("workflowname", "workflow_base", "id", workflowid, ""); + log.writeLog("--------【"+workflowname+"】数据传入中台开始----requestId值为:" + requestId); + + try{ + //获取配置文件中的参数,到时候URL路径 + String mode = Prop.getPropValue("DevToDC_jntchina", "mode"); + // 服务器ip:port + String baseUrl = Prop.getPropValue("DevToDC_jntchina", mode + "_baseUrl"); + //访问路径拼接 + String url = baseUrl + "/dcoaapi/hr/attendance"; + + //根据流程id获取主表名称 + String mainTable = RegularizationApplyForAction.getMainTable(requestId); + log.writeLog("--------获取到的表名为----:" + mainTable); + //申请单号 + String C_OA_NUM = ""; + //单据来源:默认OA + String C_APPLY_SOURCE = "OA"; + //流程名称:销假流程为:50 + String C_WORKFLOW = "50"; + //审批状态:已通过:3,驳回:5 + String C_STATUS = "3"; + + RecordSet rs = new RecordSet(); + String sql = "select * from "+mainTable+" where requestid = "+requestId+""; + rs.execute(sql); + log.writeLog("查询主表sql---------------->"+sql); + while (rs.next()) { + C_OA_NUM = Util.null2String(rs.getString("lcbh"));//申请单号 + } + + Map map = new HashMap(); + map.put("C_OA_NUM",C_OA_NUM); + map.put("C_APPLY_SOURCE",C_APPLY_SOURCE); + map.put("C_WORKFLOW",C_WORKFLOW); + map.put("C_STATUS",C_STATUS); + String strParm = JSONObject.toJSONString(map); + log.writeLog("销假状态回传JSON----------------->"+strParm); + + //获取Token + String token = HttpClientToDC.getToken(); + log.writeLog("销假申请单token------>" + token); + log.writeLog("销假申请单url------>" + url); + + //调用接口 + String returndata = HttpClientToDC.sendPostApi(url,token,strParm); + log.writeLog("【调用数据中台销假申请单接口返回结果:】" + returndata); + if (!"".equals(returndata) && returndata != null) { + JSONObject jsonObject = JSONObject.parseObject(returndata); + String code = Util.null2String(jsonObject.get("code")); + log.writeLog("--------发送请求返回的code值为:" + code); + if ("1".equals(code)) { + return SUCCESS; + } else { + String msg = Util.null2String(jsonObject.get("msg")); + requestInfo.getRequestManager().setMessageid("111100"); + requestInfo.getRequestManager().setMessagecontent(msg); + return "0"; + } + }else { + String ermsg = "流程数据已审批状态提交至中台失败,请联系系统管理员处理!"; + requestInfo.getRequestManager().setMessageid("111100"); + requestInfo.getRequestManager().setMessagecontent(ermsg); + return "0"; + } + }catch (Exception e){ + //返回0,调用失败 + log.writeLog("------------------------捕获到的异常是:" + e.toString()); + return "0"; + } + } +} diff --git a/src/main/youhong_ai_jitu_src/jntchina/action/hrm/BranchAddAction.java b/src/main/youhong_ai_jitu_src/jntchina/action/hrm/BranchAddAction.java new file mode 100644 index 0000000..ac1fb15 --- /dev/null +++ b/src/main/youhong_ai_jitu_src/jntchina/action/hrm/BranchAddAction.java @@ -0,0 +1,181 @@ +package jntchina.action.hrm; + +import com.alibaba.fastjson.JSONObject; +import com.working.util.WorkflowUtil; +import jntchina.util.HttpClientToJT; +import jntchina.util.JTHrmApiUtil; + +import selfdev.util.base.BaseUtil; +import selfdev.util.log.LogTool; +import weaver.conn.RecordSet; +import weaver.general.Util; +import weaver.interfaces.workflow.action.BaseAction; +import weaver.soa.workflow.request.RequestInfo; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.Map; + +/** + * 网点新增Action + * CYQ + * @date 2021年7月7日 02:18:38 + */ +public class BranchAddAction extends BaseAction { + + private LogTool log = new LogTool("/log/hrmAction/", false); + + @Override + public String execute(RequestInfo requestInfo) { + + //todo 流程与字段映射 + + //C_APP_SEQ 申请单号 + //C_APP_DT 申请日期 + //C_APPLI_RS 审批状态 + //EMPLID 申请人工号 + //C_ORG_TYPE 组织类别 + //C_ORG_COMPANY 组织所在公司 + //C_ORG_EFFDT 组织生效日期 + //C_ORG_DESCR 组织描述 + //C_ORG_SHORTDESCR 组织短描述 + //C_PARENT_ORG 上级组织 + //C_LOCATION 地点 + //C_ORG_GENRE 组织类型 + //C_POSITION_SET_ID 岗位集 + //C_ORG_LEVEL 组织层级 + //C_DEPT_CODE 组织代码 + //C_ORG_GRADE 组织等级 + //C_COST_CENTER_ID 成本中心 + //C_MANAGER_ID 组织负责人 + //C_BRCH_LEADR_ID 分管领导 + //C_CEO_ID CEO CEO + //C_CONTRACT_M_ID 合同管理员 + //C_MAX_RANK 部门最高职级 + //主表 formtable_main_1581 + Map userCodeIdMap = getUserCodeIdMap(); + RecordSet rs = new RecordSet(); + RecordSet rs1 = new RecordSet(); + String requestId = requestInfo.getRequestid(); //获取requestid + log.writeLog("------------requestId值为:" + requestId); + String mainTable = WorkflowUtil.getMainTable(requestId); + String sql = " select * from " + mainTable + " where requestid='" + requestId + "'"; + rs.executeQuery(sql); + Map paramMap = new HashMap<>(); + if(rs.next()){ + + String C_APP_SEQ = rs.getString("lcbh");//流程编号 + log.writeLog("------------C_APP_SEQ:" + C_APP_SEQ); + String C_APP_DT = rs.getString("C_APP_DT");//申请时间 + String C_APPLI_RS = "3"; + String EMPLID = Util.null2String(rs.getString("EMPLID")); //需要处理 - 姓名 + String C_ORG_TYPE = Util.null2String(rs.getString("C_ORG_TYPE"));//未找到 + String C_ORG_COMPANY = Util.null2String(rs.getString("C_ORG_COMPANY"));// 需要处理 + String C_ORG_EFFDT = Util.null2String(rs.getString("C_ORG_EFFDT"));// 系统开通时间 + String C_ORG_DESCR = Util.null2String(rs.getString("wdmc"));// 网点名称 + String C_ORG_SHORTDESCR = Util.null2String(rs.getString("wdjc"));// 网点简称 + String C_PARENT_ORG = Util.null2String(rs.getString("C_PARENT_ORG"));//上级组织 + String C_JMS_ORG_LEVEL = Util.null2String(rs.getString("jmszzcj"));//JMS组织层级 + + //HR最多只能10位,判断长度超出10,则截取前10位 + if(C_ORG_SHORTDESCR.length()>10){ + C_ORG_SHORTDESCR=C_ORG_SHORTDESCR.substring(0,10); + } + + if(!"".equals(C_JMS_ORG_LEVEL)){ + //根据下拉框的值获取对应的描述 + C_JMS_ORG_LEVEL=BaseUtil.getBaseInfoByParm("selectname", "workflow_selectitem", "selectvalue", C_JMS_ORG_LEVEL, + " and fieldid in (select id from workflow_billfield where billid in (select formid from workflow_base where id="+requestInfo.getWorkflowid()+") and fieldname='jmszzcj' and viewtype=0)"); + log.writeLog("------------C_JMS_ORG_LEVEL2:" + C_JMS_ORG_LEVEL); + //过滤多语言 + C_JMS_ORG_LEVEL=Util.formatMultiLang(C_JMS_ORG_LEVEL,"7").split("-")[0]; + log.writeLog("------------C_JMS_ORG_LEVEL3:" + C_JMS_ORG_LEVEL); + }else{ + C_JMS_ORG_LEVEL="60"; + } + + if(!"".equals(C_PARENT_ORG)){ + sql = "select outkey,id from hrmsubcompany where id = " +C_PARENT_ORG; + rs1.executeQuery(sql); + rs1.next(); + C_PARENT_ORG = Util.null2String(rs1.getString("outkey")); + }else{ + requestInfo.getRequestManager().setMessagecontent("上级组织C_PARENT_ORG必传!"); + return FAILURE_AND_CONTINUE; + } + String C_LOCATION = rs.getString("C_LOCATION"); // 网点地址 + String C_ORG_GENRE = rs.getString("C_ORG_GENRE"); + String C_POSITION_SET_ID = "100041";//岗位集 + String C_ORG_LEVEL = rs.getString("C_ORG_LEVEL1"); // 未找到 + String C_DEPT_CODE = rs.getString("wdbh"); // 网点编号 + String C_ORG_GRADE = Util.null2String(rs.getString("C_ORG_GRADE")); +// String C_COST_CENTER_ID = Util.null2String(rs.getString("C_COST_CENTER_ID")); //成本中心 + String C_COST_CENTER_ID = ""; //成本中心 + String C_MANAGER_ID = Util.null2String(userCodeIdMap.get(rs.getString("C_MANAGER_ID")));// 负责人 +// String C_BRCH_LEADR_ID = rs.getString("sqsj");// 未找到 +// String C_CEO_ID = rs.getString("sqsj");// 未找到 +// String C_CONTRACT_M_ID = rs.getString("sqsj");// 未找到 +// String C_MAX_RANK = rs.getString("sqsj");// 未找到 + paramMap.put("C_APP_SEQ",C_APP_SEQ); + paramMap.put("C_APP_DT",C_APP_DT); + paramMap.put("C_APPLI_RS",C_APPLI_RS); + paramMap.put("EMPLID",EMPLID); + paramMap.put("C_ORG_TYPE",C_ORG_TYPE); + paramMap.put("C_ORG_COMPANY",C_ORG_COMPANY); + paramMap.put("C_ORG_EFFDT",C_ORG_EFFDT); + paramMap.put("C_ORG_DESCR",C_ORG_DESCR); + paramMap.put("C_ORG_SHORTDESCR",C_ORG_SHORTDESCR); + paramMap.put("C_PARENT_ORG",C_PARENT_ORG); + paramMap.put("C_LOCATION",C_LOCATION); + paramMap.put("C_ORG_GENRE",C_ORG_GENRE); + paramMap.put("C_POSITION_SET_ID",C_POSITION_SET_ID); + paramMap.put("C_ORG_LEVEL",C_ORG_LEVEL); + paramMap.put("C_DEPT_CODE",C_DEPT_CODE); + paramMap.put("C_ORG_GRADE",C_ORG_GRADE); + paramMap.put("C_COST_CENTER_ID",C_COST_CENTER_ID); + paramMap.put("C_MANAGER_ID",C_MANAGER_ID); + paramMap.put("C_JMS_ORG_LEVEL", C_JMS_ORG_LEVEL);//JMS组织层级 + paramMap.put("C_BRCH_LEADR_ID",""); +// paramMap.put("C_CEO_ID",""); +// paramMap.put("C_CONTRACT_M_ID",""); + + paramMap.put("C_MAX_RANK", new ArrayList<>()); + paramMap.put("C_EXPAND", new ArrayList<>()); + paramMap.put("C_COMP_SUB", new ArrayList<>()); + paramMap.put("MULT_LANGUAGE",new ArrayList<>()); + + //主表 formtable_main_1581 + + + String token = HttpClientToJT.getToken(); + String paramStr = JSONObject.toJSONString(paramMap); + log.writeLog("---------开始添加网点------参数:"+paramStr+"------------"); + JSONObject json= JTHrmApiUtil.deptAddOrEdit(token, paramStr); + log.writeLog("---------结束添加网点-----返回结果:"+json.toJSONString()+"------------"); + if (json.getInteger("code").equals(1)) { + JSONObject data = json.getJSONObject("data"); + String deptid = data.getString("DEPTID"); + log.writeLog("HR deptid------------>"+deptid); + //将HR部门ID插入流程表单中 + rs1.execute("update "+mainTable+" set hrbmid='"+deptid+"' where requestid='"+requestId+"'");// + }else{ + requestInfo.getRequestManager().setMessageid("111100"); + requestInfo.getRequestManager().setMessagecontent(json.getString("msg")); + return FAILURE_AND_CONTINUE; + } + + return SUCCESS; + } + return FAILURE_AND_CONTINUE; + } + + public Map getUserCodeIdMap() { + RecordSet rs = new RecordSet(); + Map map = new HashMap<>(); + rs.executeQuery("select outkey,loginid,id from hrmresource where loginid is not null "); + while (rs.next()) { + map.put(rs.getString("id"),rs.getString("loginid")); + } + return map; + } +} diff --git a/src/main/youhong_ai_jitu_src/jntchina/action/hrm/BranchInvalidAction.java b/src/main/youhong_ai_jitu_src/jntchina/action/hrm/BranchInvalidAction.java new file mode 100644 index 0000000..9a573a9 --- /dev/null +++ b/src/main/youhong_ai_jitu_src/jntchina/action/hrm/BranchInvalidAction.java @@ -0,0 +1,96 @@ +package jntchina.action.hrm; + +import com.alibaba.fastjson.JSONArray; +import com.alibaba.fastjson.JSONObject; +import com.working.util.WorkflowUtil; +import jntchina.util.HttpClientToJT; +import jntchina.util.JTHrmApiUtil; +import selfdev.util.base.BaseUtil; +import selfdev.util.log.LogTool; +import weaver.conn.RecordSet; +import weaver.interfaces.workflow.action.BaseAction; +import weaver.soa.workflow.request.RequestInfo; + +import java.time.LocalDateTime; +import java.time.format.DateTimeFormatter; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +/** + * 网点退网失效Action + * CYQ + * @date 2021年7月17日 02:18:38 + */ +public class BranchInvalidAction extends BaseAction { + + private LogTool log = new LogTool("/log/hrmAction/", false); + + @Override + public String execute(RequestInfo requestInfo) { + RecordSet rs = new RecordSet(); + String requestId = requestInfo.getRequestid(); //获取requestid + log.writeLog("------------requestId值为:" + requestId); + String mainTable = WorkflowUtil.getMainTable(requestId); + String sql = " select * from " + mainTable + " where requestid='" + requestId + "'"; + rs.executeQuery(sql); + Map paramMap = new HashMap<>(); + //C_APP_SEQ 申请单号 + //C_APP_DT 申请日期 + //C_APPLI_RS 审批状态 + //EMPLID 申请人工号 + //C_INVALID_EFFDT 组织失效日期 + //C_INVALID_DEPTID 数组, C_DEPTID: 部门编码 + List detps = new ArrayList<>(); + if(rs.next()){ + String C_APP_SEQ = rs.getString("lcbh"); + String C_APP_DT = rs.getString("sqsj"); + String C_APPLI_RS = "3"; + String EMPLID = rs.getString("EMPLID");// 需要处理 + String C_INVALID_EFFDT = rs.getString("C_INVALID_EFFDT"); + //String C_INVALID_DEPTID = rs.getString("wdbm"); + String C_INVALID_DEPTID = rs.getString("C_DEPTID");//失效网点/集散点 + log.writeLog("C_INVALID_DEPTID转换前--------->"+C_INVALID_DEPTID); + //根据部门ID获取outkey + C_INVALID_DEPTID=BaseUtil.getBaseInfoByParm("outkey", "hrmdepartment", "id", C_INVALID_DEPTID, ""); + log.writeLog("C_INVALID_DEPTID转换后--------->"+C_INVALID_DEPTID); + paramMap.put("C_APP_SEQ", C_APP_SEQ); + paramMap.put("C_APP_DT", getDateTime(C_APP_DT)); + paramMap.put("C_APPLI_RS",C_APPLI_RS); + paramMap.put("EMPLID", EMPLID); + paramMap.put("C_INVALID_EFFDT", C_INVALID_EFFDT); + //失效部门列表 + JSONArray jsonArray = new JSONArray(); + detps.add(C_INVALID_DEPTID); + detps.forEach(x->{ + JSONObject xx = new JSONObject(); + xx.put("C_DEPTID",x); + jsonArray.add(xx); + }); + paramMap.put("C_INVALID_DEPTID", jsonArray); + String token = HttpClientToJT.getToken(); + String paramStr = JSONObject.toJSONString(paramMap); + log.writeLog("---------开始网点退网------参数:"+paramStr+"------------"); + JSONObject json= JTHrmApiUtil.deptInvalid(token, paramStr); + log.writeLog("---------结束网点退网-----返回结果:"+json.toJSONString()+"------------"); + if (json.getInteger("code").equals(1)) { + + }else{ + requestInfo.getRequestManager().setMessagecontent(json.getString("msg")); + return FAILURE_AND_CONTINUE; + } + return SUCCESS; + } + return FAILURE_AND_CONTINUE; + } + + public String getDateTime(String date){ + DateTimeFormatter fmt = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm"); + DateTimeFormatter fmt1 = DateTimeFormatter.ofPattern("yyyy-MM-dd"); + LocalDateTime localDate = LocalDateTime.parse(date,fmt); + String dateStr = localDate.format(fmt1); + return dateStr; + } + +} diff --git a/src/main/youhong_ai_jitu_src/jntchina/action/hrm/ContracRenewtAction.java b/src/main/youhong_ai_jitu_src/jntchina/action/hrm/ContracRenewtAction.java new file mode 100644 index 0000000..5b5df93 --- /dev/null +++ b/src/main/youhong_ai_jitu_src/jntchina/action/hrm/ContracRenewtAction.java @@ -0,0 +1,95 @@ +package jntchina.action.hrm; + +import com.alibaba.fastjson.JSONObject; +import com.working.util.WorkflowUtil; +import jntchina.util.HttpClientToJT; +import jntchina.util.JTHrmApiUtil; +import selfdev.util.log.LogTool; +import weaver.conn.RecordSet; +import weaver.general.Util; +import weaver.interfaces.workflow.action.BaseAction; +import weaver.soa.workflow.request.RequestInfo; + +import java.util.HashMap; +import java.util.Map; + +/** + * 合同续签Action + * CYQ + * + * @date 2021年7月7日 02:18:38 + */ +public class ContracRenewtAction extends BaseAction { + + private LogTool log = new LogTool("/log/hrmAction/", false); + + @Override + public String execute(RequestInfo requestInfo) { + Map userCodeIdMap = getUserCodeIdMap(); + RecordSet rs = new RecordSet(); + String requestId = requestInfo.getRequestid(); //获取requestid + log.writeLog("------------requestId值为:" + requestId); + String mainTable = WorkflowUtil.getMainTable(requestId); + String sql = " select * from " + mainTable + " where requestid='" + requestId + "'"; + rs.executeQuery(sql); + //todo 流程与字段映射 + Map paramMap = new HashMap(); + if (rs.next()) { +// C_APP_SEQ 申请单号 +// C_APP_DT 申请日期 +// C_APPLI_RS 审批状态 +// EMPLID 申请人 +// EMPLID2 合同续签员工 +// CONTRACT_TYPE 续签合同类型 +// CONTRACT_SUB_TYPE 续签合同子类 +// COMPANY 续签合同法人主体 +// CONTRACT_BEGIN_DT 续签合同开始日期 +// CONTRACT_END_DT 续签合同结束日期 + String C_APP_SEQ = rs.getString("C_APP_SEQ");//流程编号 + String C_APP_DT = rs.getString("C_APP_DT");//申请日期 + String C_APPLI_RS = "3";//审批状态 + String EMPLID = rs.getString("EMPLID");//申请人 + String EMPLID2 = rs.getString("EMPLID2");//合同续签员工 + String CONTRACT_TYPE = rs.getString("CONTRACT_TYPE");//续签合同类型 + String CONTRACT_SUB_TYPE = rs.getString("CONTRACT_SUB_TYPE");//续签合同子类 + String COMPANY = rs.getString("COMPANY");//续签合同法人主体 + String CONTRACT_BEGIN_DT = rs.getString("htzzrq");//续签合同开始日期 + String CONTRACT_END_DT = rs.getString("htjsrq");//续签合同结束日期 + + paramMap.put("C_APP_SEQ", C_APP_SEQ); + paramMap.put("C_APP_DT", C_APP_DT); + paramMap.put("C_APPLI_RS", C_APPLI_RS); + paramMap.put("EMPLID", EMPLID); + paramMap.put("EMPLID2", EMPLID2); + paramMap.put("CONTRACT_TYPE", CONTRACT_TYPE); + paramMap.put("CONTRACT_SUB_TYPE", CONTRACT_SUB_TYPE); + paramMap.put("COMPANY", COMPANY); + paramMap.put("CONTRACT_BEGIN_DT", CONTRACT_BEGIN_DT); + paramMap.put("CONTRACT_END_DT", CONTRACT_END_DT); + + String token = HttpClientToJT.getToken(); + String paramStr = JSONObject.toJSONString(paramMap); + log.writeLog("---------开始添加合同续签------参数:" + paramStr + "------------"); + JSONObject result = JTHrmApiUtil.contracRenewt(token, paramStr); + log.writeLog("---------结束合同续签-----返回结果:"+result+"------------"); + if (result.getInteger("code").equals(1)) { + JSONObject data = result.getJSONObject("data"); + }else{ + requestInfo.getRequestManager().setMessagecontent(result.getString("msg")); + return FAILURE_AND_CONTINUE; + } + + return SUCCESS; + } + return FAILURE_AND_CONTINUE; + } + public Map getUserCodeIdMap() { + RecordSet rs = new RecordSet(); + Map map = new HashMap<>(); + rs.executeQuery("select outkey,loginid,id from hrmresource where loginid is not null "); + while (rs.next()) { + map.put(rs.getString("id"),rs.getString("loginid")); + } + return map; + } +} diff --git a/src/main/youhong_ai_jitu_src/jntchina/action/hrm/DepartmentAddOrEditAction.java b/src/main/youhong_ai_jitu_src/jntchina/action/hrm/DepartmentAddOrEditAction.java new file mode 100644 index 0000000..d950a9c --- /dev/null +++ b/src/main/youhong_ai_jitu_src/jntchina/action/hrm/DepartmentAddOrEditAction.java @@ -0,0 +1,195 @@ +package jntchina.action.hrm; + +import com.alibaba.fastjson.JSONObject; +import com.working.util.WorkflowUtil; +import jntchina.util.HttpClientToJT; +import jntchina.util.JTHrmApiUtil; + +import selfdev.util.base.BaseUtil; +import selfdev.util.log.LogTool; +import weaver.conn.RecordSet; +import weaver.general.Util; +import weaver.interfaces.workflow.action.BaseAction; +import weaver.soa.workflow.request.RequestInfo; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.Map; + +/** + * 部门新增Action + * CYQ + * + * @date 2021年7月17日 02:18:38 + */ +public class DepartmentAddOrEditAction extends BaseAction { + + private LogTool log = new LogTool("/log/hrmAction/", false); + + + @Override + public String execute(RequestInfo requestInfo) { + + Map userCodeIdMap = getUserCodeIdMap(); + //todo 流程与字段映射 新增和修改在同一个表单 + //主表 formtable_main_1581 + RecordSet rs = new RecordSet(); + RecordSet rs1 = new RecordSet(); + String requestId = requestInfo.getRequestid(); //获取requestid + log.writeLog("------------requestId值为:" + requestId); + String mainTable = WorkflowUtil.getMainTable(requestId); + String sql = " select C_APP_SEQ," + + "C_APP_DT," + + "EMPLID," + + "C_ORG_EFFDT," + + "C_ORG_TYPE," + + "C_ORG_COMPANY," + + "C_ORG_DESCR," + + "C_ORG_SHORTDESCR," + + "C_PARENT_ORG," + + "C_LOCATION," + + "C_ORG_GENRE," + + "C_ORG_LEVEL1," + + "C_DEPT_CODE," + + "C_ORG_GRADE," + + "C_COST_CENTER_ID," + + "C_MANAGER_ID," + + "C_BRCH_LEADR_ID," + + "JMSZZCJ," + + "C_POSITION_SET_ID " + + "from " + mainTable + " where requestid = " + requestId + " "; + log.writeLog("------------sql:" + sql); + rs.executeQuery(sql); + Map paramMap = new HashMap<>(); + if (rs.next()) { + + //C_APP_SEQ 申请单号 + //C_APP_DT 申请日期 + //C_APPLI_RS 审批状态 + //EMPLID 申请人工号 + //C_ORG_TYPE 组织类别 + //C_ORG_COMPANY 组织所在公司 + //C_ORG_EFFDT 组织生效日期 + //C_ORG_DESCR 组织描述 + //C_ORG_SHORTDESCR 组织短描述 + //C_PARENT_ORG 上级组织 + //C_LOCATION 地点 + //C_ORG_GENRE 组织类型 + //C_POSITION_SET_ID 岗位集 + //C_ORG_LEVEL 组织层级 + //C_DEPT_CODE 组织代码 + //C_ORG_GRADE 组织等级 + //C_COST_CENTER_ID 成本中心 + //C_MANAGER_ID 组织负责人 + //C_BRCH_LEADR_ID 分管领导 + //C_CEO_ID CEO CEO + //C_CONTRACT_M_ID 合同管理员 + //C_MAX_RANK 部门最高职级 + + + String[] columnName = rs.getColumnName(); + rs.next(); + for (int i = 0; i < columnName.length; i++) { + paramMap.put(columnName[i], Util.null2String(rs.getString(columnName[i]))); + } + paramMap.remove("C_ORG_LEVEL1"); + paramMap.remove("JMSZZCJ"); + //需要转换字段 + String C_PARENT_ORG = Util.null2String(rs.getString("C_PARENT_ORG"));//上级组织 现在是分部 + String C_JMS_ORG_LEVEL = Util.null2String(rs.getString("JMSZZCJ"));//JMS组织层级 + String C_ORG_SHORTDESCR = Util.null2String(rs.getString("C_ORG_SHORTDESCR"));//组织名称 + log.writeLog("------------C_PARENT_ORG:" + C_PARENT_ORG); + log.writeLog("------------C_JMS_ORG_LEVEL:" + C_JMS_ORG_LEVEL); + log.writeLog("------------C_ORG_SHORTDESCR:" + C_ORG_SHORTDESCR); + + //HR最多只能10位,判断长度超出10,则截取前10位 + if (C_ORG_SHORTDESCR.length() > 10) { + C_ORG_SHORTDESCR = C_ORG_SHORTDESCR.substring(0, 10); + paramMap.put("C_ORG_SHORTDESCR", C_ORG_SHORTDESCR); + } + + if (!"".equals(C_PARENT_ORG)) { + sql = "select outkey,id from hrmsubcompany where id = " + C_PARENT_ORG; + rs1.executeQuery(sql); + rs1.next(); + C_PARENT_ORG = Util.null2String(rs1.getString("outkey")); + } else { + requestInfo.getRequestManager().setMessagecontent("上级组织C_PARENT_ORG必传!"); + return FAILURE_AND_CONTINUE; + } + + if (!"".equals(C_JMS_ORG_LEVEL)) { + //根据下拉框的值获取对应的描述 + C_JMS_ORG_LEVEL = BaseUtil.getBaseInfoByParm("selectname", "workflow_selectitem", "selectvalue", C_JMS_ORG_LEVEL, + " and fieldid in (select id from workflow_billfield where billid in (select formid from workflow_base where id=" + requestInfo.getWorkflowid() + ") and fieldname='jmszzcj' and viewtype=0)"); + log.writeLog("------------C_JMS_ORG_LEVEL2:" + C_JMS_ORG_LEVEL); + //过滤多语言 + C_JMS_ORG_LEVEL = Util.formatMultiLang(C_JMS_ORG_LEVEL, "7").split("-")[0]; + log.writeLog("------------C_JMS_ORG_LEVEL3:" + C_JMS_ORG_LEVEL); + } else { + C_JMS_ORG_LEVEL = "10"; + } + + String C_ORG_LEVEL = Util.null2String(rs.getString("C_ORG_LEVEL1")); + log.writeLog("------------C_PARENT_ORG:" + C_PARENT_ORG); + //成本中心 +// String C_COST_CENTER_ID = Util.null2String(rs.getString("C_COST_CENTER_ID")); + String C_COST_CENTER_ID = ""; + String C_MANAGER_ID = Util.null2String(userCodeIdMap.get(rs.getString("C_MANAGER_ID"))); + log.writeLog("------------C_MANAGER_ID:" + C_MANAGER_ID); + String C_BRCH_LEADR_ID = Util.null2String(userCodeIdMap.get(rs.getString("C_BRCH_LEADR_ID"))); + log.writeLog("------------C_BRCH_LEADR_ID:" + C_BRCH_LEADR_ID); + //字段取消,不要 +// String C_CEO_ID = Util.null2String(userCodeIdMap.get(rs.getString("C_CEO_ID"))); +// String C_CONTRACT_M_ID = Util.null2String(userCodeIdMap.get(rs.getString("C_CONTRACT_M_ID"))); +// log.writeLog("------------C_CONTRACT_M_ID:" + C_CONTRACT_M_ID); + + + paramMap.put("C_ORG_LEVEL", C_ORG_LEVEL);//上级组织 现在是分部 + paramMap.put("C_PARENT_ORG", C_PARENT_ORG);//上级组织 现在是分部 + paramMap.put("C_COST_CENTER_ID", C_COST_CENTER_ID); + paramMap.put("C_MANAGER_ID", C_MANAGER_ID); + paramMap.put("C_BRCH_LEADR_ID", C_BRCH_LEADR_ID); + paramMap.put("C_JMS_ORG_LEVEL", C_JMS_ORG_LEVEL);//JMS组织层级 +// paramMap.put("C_CEO_ID", C_CEO_ID); +// paramMap.put("C_CONTRACT_M_ID", C_CONTRACT_M_ID); + paramMap.put("C_MAX_RANK", new ArrayList<>()); + paramMap.put("C_EXPAND", new ArrayList<>()); + paramMap.put("C_COMP_SUB", new ArrayList<>()); + paramMap.put("MULT_LANGUAGE", new ArrayList<>()); + paramMap.put("C_APPLI_RS", "3"); + + String token = HttpClientToJT.getToken(); + String paramStr = JSONObject.toJSONString(paramMap); + log.writeLog("---------开始部门------参数:" + paramStr + "------------"); + JSONObject json = JTHrmApiUtil.deptAddOrEdit(token, paramStr); + log.writeLog("---------部门新增返回结果:" + json.toJSONString() + "------------"); + if (json.getInteger("code").equals(1)) { + JSONObject data = json.getJSONObject("data"); + String deptid = data.getString("DEPTID"); + log.writeLog("HR deptid------------>" + deptid); + //将HR部门ID插入流程表单中 + rs1.execute("update " + mainTable + " set hrbmid='" + deptid + "' where requestid='" + requestId + "'"); + } else { + requestInfo.getRequestManager().setMessageid("111100"); + requestInfo.getRequestManager().setMessagecontent(json.getString("msg")); + return FAILURE_AND_CONTINUE; + } + return SUCCESS; + } + return FAILURE_AND_CONTINUE; + } + + + public Map getUserCodeIdMap() { + RecordSet rs = new RecordSet(); + Map map = new HashMap<>(); + rs.executeQuery("select outkey,loginid,id from hrmresource where loginid is not null "); + while (rs.next()) { + map.put(rs.getString("id"), rs.getString("loginid")); + } + return map; + } + + +} diff --git a/src/main/youhong_ai_jitu_src/jntchina/action/hrm/DepartmentInvalidAction.java b/src/main/youhong_ai_jitu_src/jntchina/action/hrm/DepartmentInvalidAction.java new file mode 100644 index 0000000..1f356c7 --- /dev/null +++ b/src/main/youhong_ai_jitu_src/jntchina/action/hrm/DepartmentInvalidAction.java @@ -0,0 +1,132 @@ +package jntchina.action.hrm; + +import com.alibaba.fastjson.JSONArray; +import com.alibaba.fastjson.JSONObject; +import com.working.util.WorkflowUtil; +import jntchina.util.HttpClientToJT; +import jntchina.util.JTHrmApiUtil; +import selfdev.util.base.BaseUtil; +import selfdev.util.log.LogTool; +import weaver.conn.RecordSet; +import weaver.interfaces.workflow.action.BaseAction; +import weaver.soa.workflow.request.RequestInfo; + +import java.time.LocalDateTime; +import java.time.format.DateTimeFormatter; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +/** + * 部门失效Action + * CYQ + * + * @date 2021年7月17日 02:18:38 + */ +public class DepartmentInvalidAction extends BaseAction { + + //日志类(/log/hrmAction/可自定义) + private LogTool log = new LogTool("/log/hrmAction/", false); + + @Override + public String execute(RequestInfo requestInfo) { + RecordSet rs = new RecordSet();//数据库连接类(OA自身数据库) + String requestId = requestInfo.getRequestid(); //获取requestid + log.writeLog("------------requestId值为:" + requestId); + //取流程表名 + String mainTable = WorkflowUtil.getMainTable(requestId); + String sql = " select * from " + mainTable + " where requestid='" + requestId + "'"; + rs.executeQuery(sql); + Map paramMap = new HashMap<>(); + //C_APP_SEQ 申请单号 + //C_APP_DT 申请日期 + //C_APPLI_RS 审批状态 + //EMPLID 申请人工号 + //C_INVALID_EFFDT 组织失效日期 + //C_INVALID_DEPTID 数组, C_DEPTID: 部门编码 + List detps = new ArrayList<>(); + if (rs.next()) { + String C_APP_SEQ = rs.getString("lcbh"); + String C_APP_DT = rs.getString("sqsj"); + String C_APPLI_RS = "3"; + String EMPLID = rs.getString("EMPLID");// 需要处理 + String C_INVALID_EFFDT = rs.getString("C_INVALID_EFFDT"); + //String C_INVALID_DEPTID = rs.getString("wdbm"); + String C_INVALID_DEPTID = rs.getString("C_DEPTID");//失效网点/集散点 + + //通过 , 号截取字符串 + for (String s : C_INVALID_DEPTID.split(",")) { + detps.add(s); + + } + log.writeLog("C_INVALID_DEPTID转换前--------->" + C_INVALID_DEPTID); + + ArrayList arrayList = new ArrayList(); + for (String s : C_INVALID_DEPTID.split(",")) { + //根据部门ID获取outkey + C_INVALID_DEPTID = BaseUtil.getBaseInfoByParm("outkey", "hrmdepartment", "id", s, ""); + + arrayList.add(C_INVALID_DEPTID); + } + + //list集合转换为String字符串 + C_INVALID_DEPTID = String.join(",",arrayList); + + + //C_INVALID_DEPTID = BaseUtil.getBaseInfoByParm("outkey", "hrmdepartment", "id", C_INVALID_DEPTID, ""); + log.writeLog("C_INVALID_DEPTID转换后--------->" + C_INVALID_DEPTID); + + paramMap.put("C_APP_SEQ", C_APP_SEQ); + paramMap.put("C_APP_DT", getDateTime(C_APP_DT)); + paramMap.put("C_APPLI_RS", C_APPLI_RS); + paramMap.put("EMPLID", EMPLID); + paramMap.put("C_INVALID_EFFDT", C_INVALID_EFFDT); + + //失效部门列表 + JSONArray jsonArray = new JSONArray(); + arrayList.forEach(x -> { + JSONObject jsonObject = new JSONObject(); + jsonObject.put("C_DEPTID", x); + jsonArray.add(jsonObject); + }); + /*//失效部门列表 + JSONArray jsonArray = new JSONArray(); + detps.add(C_INVALID_DEPTID); + detps.forEach(x->{ + JSONObject xx = new JSONObject(); + xx.put("C_DEPTID",x); + jsonArray.add(xx); + });*/ + + paramMap.put("C_INVALID_DEPTID", jsonArray); + + //获取token + String token = HttpClientToJT.getToken(); + //将MAP转成JSON字符串 + String paramStr = JSONObject.toJSONString(paramMap); + log.writeLog("---------开始部门失效------参数:" + paramStr + "------------"); + //调用接口将数据传 + JSONObject json = JTHrmApiUtil.deptInvalid(token, paramStr); + log.writeLog("---------结束部门失效-----返回结果:" + json.toJSONString() + "------------"); + if (json.getInteger("code").equals(1)) { + + } else { + requestInfo.getRequestManager().setMessagecontent(json.getString("msg")); + return FAILURE_AND_CONTINUE; + } + return SUCCESS; + } + return FAILURE_AND_CONTINUE; + } + + public String getDateTime(String date) { + DateTimeFormatter fmt = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm"); + DateTimeFormatter fmt1 = DateTimeFormatter.ofPattern("yyyy-MM-dd"); + LocalDateTime localDate = LocalDateTime.parse(date, fmt); + String dateStr = localDate.format(fmt1); + return dateStr; + } + + +} diff --git a/src/main/youhong_ai_jitu_src/jntchina/action/hrm/FranchiseeAddAction.java b/src/main/youhong_ai_jitu_src/jntchina/action/hrm/FranchiseeAddAction.java new file mode 100644 index 0000000..476751a --- /dev/null +++ b/src/main/youhong_ai_jitu_src/jntchina/action/hrm/FranchiseeAddAction.java @@ -0,0 +1,261 @@ +package jntchina.action.hrm; + +import com.alibaba.fastjson.JSONObject; +import com.working.util.WorkflowUtil; +import jntchina.util.HttpClientToJT; +import jntchina.util.JTHrmApiUtil; +import selfdev.util.base.BaseUtil; +import selfdev.util.log.LogTool; +import weaver.conn.RecordSet; +import weaver.general.Util; +import weaver.interfaces.workflow.action.BaseAction; +import weaver.soa.workflow.request.RequestInfo; + +import java.time.LocalDateTime; +import java.time.format.DateTimeFormatter; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.Map; + +/** + * 加盟商新增Action + * CYQ + * + * @date 2021年7月7日 02:18:38 + */ +public class FranchiseeAddAction extends BaseAction { + + private LogTool log = new LogTool("/log/hrmAction/", false); + + @Override + public String execute(RequestInfo requestInfo) { + RecordSet rs = new RecordSet(); + RecordSet rs1 = new RecordSet(); +// Map userCodeIdMap = getUserCodeIdMap(); + String requestId = requestInfo.getRequestid(); //获取requestid + log.writeLog("------------requestId值为:" + requestId); + String mainTable = WorkflowUtil.getMainTable(requestId); + String sql = " select * from " + mainTable + " where requestid='" + requestId + "'"; + rs.executeQuery(sql); + Map paramMap = new HashMap(); + if (rs.next()) { + //todo 流程与字段映射 +// C_APP_SEQ 申请单号 +// C_APP_DT 申请日期 +// C_APPLI_RS 审批状态 +// EMPLID 申请人工号 +// C_ORG_TYPE 组织类别 +// C_ORG_COMPANY 组织所在公司 +// C_ORG_EFFDT 组织生效日期 +// C_ORG_DESCR 组织描述 +// C_ORG_SHORTDESCR 组织短描述 +// C_PARENT_ORG 上级组织 +// C_LOCATION 地点 +// C_ORG_GENRE 组织类型 +// C_POSITION_SET_ID 岗位集 +// C_ORG_LEVEL 组织层级 +// C_DEPT_CODE 组织代码 +// C_ORG_GRADE 组织等级 +// C_COST_CENTER_ID 成本中心 +// C_MANAGER_ID 组织负责人 +// C_BRCH_LEADR_ID 分管领导 +// C_CEO_ID CEO CEO +// C_CONTRACT_M_ID 合同管理员 +// C_MAX_RANK 部门最高职级 + String C_APP_SEQ = Util.null2String(rs.getString("lcbh"));//流程编号 + String C_APP_DT = Util.null2String(rs.getString("C_APP_DT"));//申请时间 + String C_APPLI_RS = "3"; + String EMPLID = Util.null2String(rs.getString("EMPLID")); //需要处理 - 姓名 + + //生产环境和测试环境的差异字段 + String C_ORG_TYPE = Util.null2String(rs.getString("C_ORG_TYPE1"));//生产 +// String C_ORG_TYPE = Util.null2String(rs.getString("C_ORG_TYPE"));//测试 + String C_ORG_GENRE = Util.null2String(rs.getString("C_ORG_GENRE1")); //生产 +// String C_ORG_GENRE = Util.null2String(rs.getString("C_ORG_GENRE")); //测试 + +// String C_ORG_COMPANY = Util.null2String(rs.getString("C_ORG_COMPANY"));//组织所在公司 + String C_ORG_EFFDT = Util.null2String(rs.getString("C_ORG_EFFDT"));// 系统开通时间 + String C_ORG_DESCR = Util.null2String(rs.getString("jmsmc"));// 加盟商名称 +// String C_ORG_SHORTDESCR = Util.null2String(rs.getString("jmsmc"));// 加盟商简称 + String C_PARENT_ORG = Util.null2String(rs.getString("C_PARENT_ORG"));// /上级组织 + if (!"".equals(C_PARENT_ORG)) { + sql = "select outkey,id from hrmsubcompany where id = " + C_PARENT_ORG; + rs1.executeQuery(sql); + rs1.next(); + C_PARENT_ORG = Util.null2String(rs1.getString("outkey")); + } else { + requestInfo.getRequestManager().setMessagecontent("上级组织C_PARENT_ORG必传!"); + return FAILURE_AND_CONTINUE; + } + log.writeLog("------------C_PARENT_ORGoutkey:" + C_PARENT_ORG); + + String C_JMS_ORG_LEVEL = Util.null2String(rs.getString("jmszzcj"));//JMS组织层级 + if (!"".equals(C_JMS_ORG_LEVEL)) { + //根据下拉框的值获取对应的描述 + C_JMS_ORG_LEVEL = BaseUtil.getBaseInfoByParm("selectname", "workflow_selectitem", "selectvalue", C_JMS_ORG_LEVEL, + " and fieldid in (select id from workflow_billfield where billid in (select formid from workflow_base where id=" + requestInfo.getWorkflowid() + ") and fieldname='jmszzcj' and viewtype=0)"); + log.writeLog("------------C_JMS_ORG_LEVEL2:" + C_JMS_ORG_LEVEL); + //过滤多语言 + C_JMS_ORG_LEVEL = Util.formatMultiLang(C_JMS_ORG_LEVEL, "7").split("-")[0]; + log.writeLog("------------C_JMS_ORG_LEVEL3:" + C_JMS_ORG_LEVEL); + } else { + C_JMS_ORG_LEVEL = "50"; + } + + + String C_LOCATION = Util.null2String(rs.getString("C_LOCATION")); //结算目的地 + String C_POSITION_SET_ID = "";// 未找到 + String C_ORG_LEVEL = Util.null2String(rs.getString("C_ORG_LEVEL1")); // 未找到 + String C_DEPT_CODE = Util.null2String(rs.getString("jmsbm")); // 加盟商编码 + String C_ORG_GRADE = Util.null2String(rs.getString("C_ORG_GRADE"));// 未找到 + log.writeLog("------------C_ORG_GRADE:" + C_ORG_GRADE); +// String C_COST_CENTER_ID = Util.null2String(rs.getString("C_COST_CENTER_ID")); //所属财务中心公司编码 + String C_COST_CENTER_ID = ""; //所属财务中心公司编码 +// String C_MANAGER_ID = weaver.general.Util.null2String(userCodeIdMap.get(rs.getString("C_MANAGER_ID")));// 负责人 +// String C_MANAGER_ID = "";// 负责人 + String C_BRCH_LEADR_ID = "";// 未找到 +// String C_CEO_ID = "";// 未找到 +// String C_CONTRACT_M_ID = "";// 未找到 +// String C_MAX_RANK = rs.getString("sqsj");// 未找到 + paramMap.put("C_APP_SEQ", C_APP_SEQ); + paramMap.put("C_APP_DT", C_APP_DT); + paramMap.put("C_APPLI_RS", C_APPLI_RS); + paramMap.put("EMPLID", EMPLID); + paramMap.put("C_ORG_TYPE", C_ORG_TYPE); +// paramMap.put("C_ORG_COMPANY",C_ORG_COMPANY);//不从字段取,从查询或者公司创建接口取 + paramMap.put("C_ORG_EFFDT", C_ORG_EFFDT); + paramMap.put("C_ORG_DESCR", C_ORG_DESCR); +// paramMap.put("C_ORG_SHORTDESCR",C_ORG_SHORTDESCR); + paramMap.put("C_ORG_SHORTDESCR", ""); + paramMap.put("C_PARENT_ORG", C_PARENT_ORG); + paramMap.put("C_LOCATION", C_LOCATION); + paramMap.put("C_ORG_GENRE", C_ORG_GENRE); + paramMap.put("C_POSITION_SET_ID", C_POSITION_SET_ID); + paramMap.put("C_ORG_LEVEL", C_ORG_LEVEL); + paramMap.put("C_DEPT_CODE", C_DEPT_CODE); + paramMap.put("C_ORG_GRADE", C_ORG_GRADE); + paramMap.put("C_COST_CENTER_ID", C_COST_CENTER_ID); + paramMap.put("C_MANAGER_ID", ""); +// paramMap.put("C_CEO_ID", C_CEO_ID); +// paramMap.put("C_CONTRACT_M_ID",C_CONTRACT_M_ID); + paramMap.put("C_BRCH_LEADR_ID", C_BRCH_LEADR_ID); + paramMap.put("C_MAX_RANK", new ArrayList<>()); + paramMap.put("C_EXPAND", new ArrayList<>()); + paramMap.put("C_COMP_SUB", new ArrayList<>()); + paramMap.put("MULT_LANGUAGE", new ArrayList<>()); + paramMap.put("C_JMS_ORG_LEVEL", C_JMS_ORG_LEVEL); + + + String token = HttpClientToJT.getToken(); + + //查询法人公司 存在就直接取,不存在先新增 + Map comQueryParamMap = new HashMap<>(); + comQueryParamMap.put("COMPANY_DESCR", Util.null2String(rs.getString("gsmc"))); + String comParamStr = JSONObject.toJSONString(comQueryParamMap); + log.writeLog("---------开始查询公司------参数:" + comParamStr + "------------"); + JSONObject comJson = JTHrmApiUtil.companyQuery(token, comParamStr); + log.writeLog("---------结束查询公司-----返回结果:" + comJson.toJSONString() + "------------"); + if (comJson.getInteger("code").equals(1)) { + JSONObject comData = comJson.getJSONObject("data"); + String companyCode = comData.getString("COMPANY"); + paramMap.put("C_ORG_COMPANY", companyCode); + } else { + Map comAddParamMap = new HashMap<>(); + comAddParamMap.put("C_APP_SEQ", "gs-" + C_APP_SEQ); + comAddParamMap.put("C_APP_DT", C_APP_DT); + comAddParamMap.put("C_APPLI_RS", C_APPLI_RS); + comAddParamMap.put("EMPLID", EMPLID); + comAddParamMap.put("EFFDT", C_ORG_EFFDT); + comAddParamMap.put("DEFAULT_SETID", "JTSD"); + comAddParamMap.put("COMPANY_DESCR", Util.null2String(rs.getString("gsmc"))); + comAddParamMap.put("DESCRLONG", Util.null2String(rs.getString("gsmc"))); + comAddParamMap.put("DESCRSHORT", Util.null2String(rs.getString("gsmc"))); + comAddParamMap.put("COUNTRY", "CHN"); + comAddParamMap.put("BUSINESS_UNIT", Util.null2String(rs.getString("ywdw")));//生产 +// comAddParamMap.put("BUSINESS_UNIT", Util.null2String(rs.getString("BUSINESS_UNIT")));//测试 + comAddParamMap.put("LOCATION", C_LOCATION); + comAddParamMap.put("C_DIRECTLY_FLAG", "0".equals(rs.getString("C_DIRECTLY_FLAG")) ? "Y" : "N"); + comAddParamMap.put("C_UFSC_CODE", Util.null2String(rs.getString("sh"))); + comAddParamMap.put("C_COMPANY_LEVEL", ""); + comAddParamMap.put("C_COMP_SB", new ArrayList<>()); + comAddParamMap.put("MULT_LANGUAGE", new ArrayList<>()); + String comAddParamStr = JSONObject.toJSONString(comAddParamMap); + log.writeLog("---------开始添加公司------参数:" + comAddParamStr + "------------"); + JSONObject comAddJson = JTHrmApiUtil.addCompany(token, comAddParamStr); + log.writeLog("---------结束添加公司-----返回结果:" + comAddJson.toJSONString() + "------------"); + if (comAddJson.getInteger("code").equals(1)) { + JSONObject data = comAddJson.getJSONObject("data"); + String companyCode = data.getString("COMPANY"); + paramMap.put("C_ORG_COMPANY", companyCode); + } else { + requestInfo.getRequestManager().setMessagecontent(comAddJson.getString("msg")); + return FAILURE_AND_CONTINUE; + } + } + + + String paramStr = JSONObject.toJSONString(paramMap); + log.writeLog("---------开始添加加盟商------参数:" + paramStr + "------------"); + JSONObject json = JTHrmApiUtil.deptAddOrEdit(token, paramStr); + log.writeLog("---------添加加盟商返回结果------结果:" + json.toJSONString() + "------------"); + //添加成功继续添加子部门【职能人员】,固定 + if (json.getInteger("code").equals(1)) { + JSONObject data = json.getJSONObject("data"); + String deptid = data.getString("DEPTID"); + log.writeLog("---------加盟商添加成功-----返回加盟商编码:" + deptid + "------------"); + log.writeLog("---------开始添加职能人员部门----------------"); + paramMap.put("C_APP_SEQ", C_APP_SEQ + "-01"); + paramMap.put("C_ORG_TYPE", "20"); + paramMap.put("C_ORG_GENRE", "20"); + paramMap.put("C_ORG_LEVEL", "230"); + paramMap.put("C_ORG_DESCR", "职能人员"); + paramMap.put("C_DEPT_CODE", "JM01"); + paramMap.put("C_PARENT_ORG", deptid); + paramMap.put("C_POSITION_SET_ID", "100021");//职能人员落地时,岗位集默认100021 + String paramStr1 = JSONObject.toJSONString(paramMap); + log.writeLog("---------开始添加加盟商【职能人员】------参数:" + paramStr1 + "------------"); + JSONObject json1 = JTHrmApiUtil.deptAddOrEdit(token, paramStr1); + log.writeLog("---------开始添加加盟商【职能人员】------参数:" + json1.toJSONString() + "------------"); + if (!json1.getInteger("code").equals(1)) { + requestInfo.getRequestManager().setMessagecontent(json1.getString("msg")); + return FAILURE_AND_CONTINUE; + } + JSONObject data1 = json1.getJSONObject("data"); + String znid = data1.getString("DEPTID"); + log.writeLog("---------职能人员添加成功-----返回职能人员编码:" + znid + "------------"); + //将HR部门ID插入流程表单中 + rs1.execute("update " + mainTable + " set hrbmid='" + znid + "' where requestid='" + requestId + "'"); + } else { + requestInfo.getRequestManager().setMessagecontent(json.getString("msg")); + return FAILURE_AND_CONTINUE; + } + log.writeLog("---------结束添加加盟商-----返回结果:" + json.toJSONString() + "------------"); + return SUCCESS; + } + return FAILURE_AND_CONTINUE; + } + + public Map getUserCodeIdMap() { + RecordSet rs = new RecordSet(); + Map map = new HashMap<>(); + rs.executeQuery("select outkey,loginid,id from hrmresource where loginid is not null "); + while (rs.next()) { + map.put(rs.getString("id"), rs.getString("loginid")); + } + return map; + } + + public static String getDateTime(String date) { + DateTimeFormatter fmt = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm"); + DateTimeFormatter fmt1 = DateTimeFormatter.ofPattern("yyyy-MM-dd"); + LocalDateTime localDate = LocalDateTime.parse(date, fmt); + String dateStr = localDate.format(fmt1); + return dateStr; + } + + public static void main(String[] args) { + String dateTime = FranchiseeAddAction.getDateTime("2021-08-01 13:22"); + System.out.println(dateTime); + } +} + diff --git a/src/main/youhong_ai_jitu_src/jntchina/action/hrm/JsdAddAction.java b/src/main/youhong_ai_jitu_src/jntchina/action/hrm/JsdAddAction.java new file mode 100644 index 0000000..01a7b06 --- /dev/null +++ b/src/main/youhong_ai_jitu_src/jntchina/action/hrm/JsdAddAction.java @@ -0,0 +1,179 @@ +package jntchina.action.hrm; + +import com.alibaba.fastjson.JSONObject; +import com.working.util.WorkflowUtil; +import jntchina.util.HttpClientToJT; +import jntchina.util.JTHrmApiUtil; + +import selfdev.util.base.BaseUtil; +import selfdev.util.log.LogTool; +import weaver.conn.RecordSet; +import weaver.general.Util; +import weaver.interfaces.workflow.action.BaseAction; +import weaver.soa.workflow.request.RequestInfo; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.Map; + +/** + * 新开集散点Action + * CYQ + * + * @date 2021年7月7日 02:18:38 + */ +public class JsdAddAction extends BaseAction { + + private LogTool log = new LogTool("/log/hrmAction/", false); + + @Override + public String execute(RequestInfo requestInfo) { + Map userCodeIdMap = getUserCodeIdMap(); + RecordSet rs = new RecordSet(); + RecordSet rs1 = new RecordSet(); + String requestId = requestInfo.getRequestid(); //获取requestid + log.writeLog("------------requestId值为:" + requestId); + String mainTable = WorkflowUtil.getMainTable(requestId); + String sql = " select * from " + mainTable + " where requestid='" + requestId + "'"; + rs.executeQuery(sql); + + //todo 流程与字段映射 + + //C_APP_SEQ 申请单号 + //C_APP_DT 申请日期 + //C_APPLI_RS 审批状态 + //EMPLID 申请人工号 + //C_ORG_TYPE 组织类别 + //C_ORG_COMPANY 组织所在公司 + //C_ORG_EFFDT 组织生效日期 + //C_ORG_DESCR 组织描述 + //C_ORG_SHORTDESCR 组织短描述 + //C_PARENT_ORG 上级组织 + //C_LOCATION 地点 + //C_ORG_GENRE 组织类型 + //C_POSITION_SET_ID 岗位集 + //C_ORG_LEVEL 组织层级 + //C_DEPT_CODE 组织代码 + //C_ORG_GRADE 组织等级 + //C_COST_CENTER_ID 成本中心 + //C_MANAGER_ID 组织负责人 + //C_BRCH_LEADR_ID 分管领导 + //C_CEO_ID CEO CEO + //C_CONTRACT_M_ID 合同管理员 + //C_MAX_RANK 部门最高职级 +// String sqdh = ""; + Map paramMap = new HashMap<>(); + if (rs.next()) { + String C_APP_SEQ = rs.getString("lcbh");//流程编号 + String C_APP_DT = rs.getString("C_APP_DT");//申请时间 + String C_APPLI_RS = "3"; + String EMPLID = rs.getString("EMPLID"); //需要处理 - 姓名 + String C_ORG_TYPE = Util.null2String(rs.getString("C_ORG_TYPE"));//未找到 + String C_ORG_COMPANY = Util.null2String(rs.getString("C_ORG_COMPANY"));// 未找到 + String C_ORG_EFFDT = Util.null2String(rs.getString("C_ORG_EFFDT"));//生效日期 + + String C_ORG_DESCR = Util.null2String(rs.getString("jsdmc"));// 集散点名称 + String C_ORG_SHORTDESCR = Util.null2String(rs.getString("jsdjc"));// 集散点简称 + String C_PARENT_ORG = Util.null2String(rs.getString("C_PARENT_ORG"));// 需要处理 所属代理区 + //HR最多只能10位,判断长度超出10,则截取前10位 + if (C_ORG_SHORTDESCR.length() > 10) { + C_ORG_SHORTDESCR = C_ORG_SHORTDESCR.substring(0, 10); + } + if (!"".equals(C_PARENT_ORG)) { + sql = "select outkey,id from hrmsubcompany where id = " + C_PARENT_ORG; + rs1.executeQuery(sql); + rs1.next(); + C_PARENT_ORG = Util.null2String(rs1.getString("outkey")); + } else { + requestInfo.getRequestManager().setMessagecontent("上级组织C_PARENT_ORG必传!"); + return FAILURE_AND_CONTINUE; + } + + String C_JMS_ORG_LEVEL = Util.null2String(rs.getString("jmszzcj"));//JMS组织层级 + log.writeLog("------------C_JMS_ORG_LEVEL:" + C_JMS_ORG_LEVEL); + if (!"".equals(C_JMS_ORG_LEVEL)) { + //根据下拉框的值获取对应的描述 + C_JMS_ORG_LEVEL = BaseUtil.getBaseInfoByParm("selectname", "workflow_selectitem", "selectvalue", C_JMS_ORG_LEVEL, + " and fieldid in (select id from workflow_billfield where billid in (select formid from workflow_base where id=" + requestInfo.getWorkflowid() + ") and fieldname='jmszzcj' and viewtype=0)"); + log.writeLog("------------C_JMS_ORG_LEVEL2:" + C_JMS_ORG_LEVEL); + //过滤多语言 + C_JMS_ORG_LEVEL = Util.formatMultiLang(C_JMS_ORG_LEVEL, "7").split("-")[0]; + log.writeLog("------------C_JMS_ORG_LEVEL3:" + C_JMS_ORG_LEVEL); + } else { + C_JMS_ORG_LEVEL = "60"; + } + + + String C_LOCATION = Util.null2String(rs.getString("C_LOCATION")); // 详细地址 + String C_ORG_GENRE = Util.null2String(rs.getString("C_ORG_GENRE")); + String C_POSITION_SET_ID = "100042"; + String C_ORG_LEVEL = Util.null2String(rs.getString("C_ORG_LEVEL1")); // 未找到 + String C_DEPT_CODE = Util.null2String(rs.getString("jsdbh")); // 集散点编号 + String C_ORG_GRADE = Util.null2String(rs.getString("C_ORG_GRADE"));// 未找到 + String C_COST_CENTER_ID = ""; //所属财务中心公司编码 + String C_MANAGER_ID = Util.null2String(userCodeIdMap.get(rs.getString("C_MANAGER_ID")));// 负责人 +// String C_MANAGER_ID = "";// 负责人 + String C_BRCH_LEADR_ID = "";// 未找到 +// String C_CEO_ID = "";// 未找到 +// String C_CONTRACT_M_ID = "";// 未找到 +// String C_MAX_RANK = "";// 未找到 + + paramMap.put("C_APP_SEQ", C_APP_SEQ); + paramMap.put("C_APP_DT", C_APP_DT); + paramMap.put("C_APPLI_RS", C_APPLI_RS); + paramMap.put("EMPLID", EMPLID); + paramMap.put("C_ORG_TYPE", C_ORG_TYPE); + paramMap.put("C_ORG_COMPANY", C_ORG_COMPANY); + paramMap.put("C_ORG_EFFDT", C_ORG_EFFDT); + paramMap.put("C_ORG_DESCR", C_ORG_DESCR); + paramMap.put("C_ORG_SHORTDESCR", C_ORG_SHORTDESCR); + paramMap.put("C_PARENT_ORG", C_PARENT_ORG); + paramMap.put("C_LOCATION", C_LOCATION); + paramMap.put("C_ORG_GENRE", C_ORG_GENRE); + paramMap.put("C_POSITION_SET_ID", C_POSITION_SET_ID); + paramMap.put("C_ORG_LEVEL", C_ORG_LEVEL); + paramMap.put("C_DEPT_CODE", C_DEPT_CODE); + paramMap.put("C_ORG_GRADE", C_ORG_GRADE); + paramMap.put("C_COST_CENTER_ID", C_COST_CENTER_ID); + paramMap.put("C_MANAGER_ID", C_MANAGER_ID); + paramMap.put("C_BRCH_LEADR_ID", C_BRCH_LEADR_ID); + paramMap.put("C_JMS_ORG_LEVEL", C_JMS_ORG_LEVEL);//JMS组织层级; +// paramMap.put("C_CEO_ID",C_CEO_ID); +// paramMap.put("C_CONTRACT_M_ID",C_CONTRACT_M_ID); + paramMap.put("C_MAX_RANK", new ArrayList<>()); + paramMap.put("C_EXPAND", new ArrayList<>()); + paramMap.put("C_COMP_SUB", new ArrayList<>()); + paramMap.put("MULT_LANGUAGE", new ArrayList<>()); + String token = HttpClientToJT.getToken(); + String paramStr = JSONObject.toJSONString(paramMap); + log.writeLog("---------开始添加集散点------参数:" + paramStr + "------------"); + JSONObject json = JTHrmApiUtil.deptAddOrEdit(token, paramStr); + log.writeLog("---------结束添加集散点-----返回结果:" + json.toJSONString() + "------------"); + if (json.getInteger("code").equals(1)) { + JSONObject data = json.getJSONObject("data"); + String deptid = data.getString("DEPTID"); + log.writeLog("HR deptid------------>" + deptid); + //将HR部门ID插入流程表单中 + rs1.execute("update " + mainTable + " set hrbmid='" + deptid + "' where requestid='" + requestId + "'"); + } else { + requestInfo.getRequestManager().setMessageid("111100"); + requestInfo.getRequestManager().setMessagecontent(json.getString("msg")); + return FAILURE_AND_CONTINUE; + } + + return SUCCESS; + } + return FAILURE_AND_CONTINUE; + } + + public Map getUserCodeIdMap() { + RecordSet rs = new RecordSet(); + Map map = new HashMap<>(); + rs.executeQuery("select outkey,loginid,id from hrmresource where loginid is not null "); + while (rs.next()) { + map.put(rs.getString("id"), rs.getString("loginid")); + } + return map; + } + +} diff --git a/src/main/youhong_ai_jitu_src/jntchina/action/hrm/OnetimeSalaryPayAction.java b/src/main/youhong_ai_jitu_src/jntchina/action/hrm/OnetimeSalaryPayAction.java new file mode 100644 index 0000000..313a2c3 --- /dev/null +++ b/src/main/youhong_ai_jitu_src/jntchina/action/hrm/OnetimeSalaryPayAction.java @@ -0,0 +1,138 @@ +package jntchina.action.hrm; + +import com.alibaba.fastjson.JSONObject; +import com.alibaba.fastjson.serializer.SerializerFeature; +import com.working.util.WorkflowUtil; +import jntchina.util.HttpClientToDC; +import jntchina.util.HttpClientToJT; +import jntchina.util.JTHrmApiUtil; +import selfdev.util.base.BaseUtil; +import selfdev.util.log.LogTool; +import weaver.conn.RecordSet; +import weaver.general.Util; +import weaver.soa.workflow.request.RequestInfo; +import weaver.workflow.action.BaseAction; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +/** + * 一次性薪资发放数据传入HR系统 + * @author KangMD + * 2022-04-09 + */ +public class OnetimeSalaryPayAction extends BaseAction { + + @Override + public String execute(RequestInfo requestInfo) { + LogTool log = new LogTool("/log/selfdev/action/hrm", false); + String requestId = requestInfo.getRequestid(); //获取requestid + log.writeLog("--------一次性薪资发放数据传入HR----requestId值为:" + requestId); + RecordSet rs = new RecordSet(); + //获取表名 + String mainTable = WorkflowUtil.getMainTable(requestId); + try{ + + String mainid = ""; // + String sqdh = ""; //申请单号 + String sqrxm = ""; //申请人姓名 + String sqrgh = ""; //申请人工号 + String sqrq = ""; //申请日期 + String sqsm = ""; //申请说明 + + String sql = " select * from " + mainTable + " where requestid='" + requestId + "'"; + rs.execute(sql); + while (rs.next()) { + mainid=Util.null2String(rs.getString("id")); + sqdh=Util.null2String(rs.getString("sqdh")); + sqrxm=Util.null2String(rs.getString("sqrxm")); + sqrgh=Util.null2String(rs.getString("sqrgh")); + sqrq=Util.null2String(rs.getString("sqrq")); + sqsm=Util.null2String(rs.getString("sqsm")); + } + //若工号为空(例如字段联动未生效时),则根据姓名再次查询 + if("".equals(sqrgh)){ + sqrgh= BaseUtil.getBaseInfoByParm("workcode","hrmresource","id",sqrxm,""); + } + //明细数据list + List> list=new ArrayList>(); + //查询明细 + sql = " select * from " + mainTable + "_dt1 where mainid='" + mainid + "'"; + rs.execute(sql); + while (rs.next()) { + Map detailMap=new HashMap(); + String yggh=Util.null2String(rs.getString("yggh"));//员工工号 + String jclx=Util.null2String(rs.getString("jclx"));//奖惩类型 + String rlid=Util.null2String(rs.getString("rlid"));//日历ID + String xzzid=Util.null2String(rs.getString("xzzid"));//薪资组ID + String jcje=Util.null2o(rs.getString("jcje"));//奖惩金额 + detailMap.put("EMPLID2",yggh);//奖惩员工编码 + detailMap.put("CAL_ID",rlid);//日历ID + detailMap.put("C_PI_CODE",jclx);//奖惩类型编码 + detailMap.put("C_PI_AMOUNT",jcje);//奖惩金额 + detailMap.put("GP_PAYGROUP",xzzid);//薪资组ID + list.add(detailMap); + } + Map map=new HashMap(); + map.put("C_APP_OA_SEQ",sqdh);//OA单据审批单号 + map.put("C_APP_DT",sqrq);//单据申请日期 + map.put("C_APPLI_RS","3");//单据状态;3-审批通过;4-审批拒绝 + map.put("EMPLID",sqrgh);//申请人编码 + map.put("DESCRLONG",sqsm);//说明 + map.put("DATA",list);//明细数据 + //将传入参数map转成字符串 + String strParm = JSONObject.toJSONString(map, SerializerFeature.DisableCircularReferenceDetect); + log.writeLog("传入参数----------------->"+strParm); + //获取URL地址 + String url = HttpClientToJT.baseUrl + JTHrmApiUtil.oneTimeSalaryPayUrl; + //获取Token + String token = HttpClientToDC.getToken(); + log.writeLog("一次性薪资发放token------>" + token); + log.writeLog("一次性薪资发放url------>" + url); + //调用接口 + String returndata = HttpClientToDC.sendPostApi(url,token,strParm); + log.writeLog("【调用数据中台一次性薪资发放接口返回结果:】" + returndata); + String sfcgxrhr="0";//是否成功写入HR + String hrdh="";//HR单号 + String jkfhxx="";//接口返回信息 + if (!"".equals(returndata) && returndata != null) { + JSONObject jsonObject = JSONObject.parseObject(returndata); + String code = Util.null2String(jsonObject.get("code"));//接口状态码 + if ("1".equals(code)) { + JSONObject data = jsonObject.getJSONObject("data"); + hrdh = Util.null2String(data.get("C_APP_SEQ"));//HR单号 + jkfhxx = Util.null2String(data.get("msg"));//接口返回信息 + }else{ + sfcgxrhr="1"; + jkfhxx = Util.null2String(jsonObject.get("msg"));//接口状态码 + } + log.writeLog("--------发送请求返回的code值为:" + code); + log.writeLog("--------发送请求返回的hrdh值为:" + hrdh); + log.writeLog("--------发送请求返回的msg值为:" + jkfhxx); + }else { + sfcgxrhr="1"; + jkfhxx="调用接口返回值为空"; + } + //将返回结果回写至OA流程表单 + sql=" update " + mainTable + " set sfcgxrhr = "+sfcgxrhr+" ,hrdh = '"+hrdh+"' ,jkfhxx='" + jkfhxx.replace("'", "''") + "' where requestid = " + requestId; + log.writeLog("将返回结果回写至OA流程表单SQL------>"+sql); + + rs.execute(sql); + if("1".equals(sfcgxrhr)){ + requestInfo.getRequestManager().setMessageid("111100"); + requestInfo.getRequestManager().setMessagecontent("数据传HR失败,错误信息:"+jkfhxx); + return "0"; + } + }catch (Exception e){ + String ermsg="流程数据生成中台借款单失败,失败信息:
" + e.toString(); + //将返回结果回写至OA流程表单 + rs.execute(" update " + mainTable + " set sfcgxrhr = 1 ,hrdh = '',jkfhxx='" + ermsg.replace("'", "''") + "' where requestid = " + requestId); + requestInfo.getRequestManager().setMessageid("111100"); + requestInfo.getRequestManager().setMessagecontent(ermsg); + return "0"; + } + return SUCCESS; + } +} \ No newline at end of file diff --git a/src/main/youhong_ai_jitu_src/jntchina/action/hrm/OrganizationAddAction.java b/src/main/youhong_ai_jitu_src/jntchina/action/hrm/OrganizationAddAction.java new file mode 100644 index 0000000..56da9a1 --- /dev/null +++ b/src/main/youhong_ai_jitu_src/jntchina/action/hrm/OrganizationAddAction.java @@ -0,0 +1,116 @@ +package jntchina.action.hrm; + +import com.alibaba.fastjson.JSONObject; +import com.working.util.WorkflowUtil; +import jntchina.util.HttpClientToJT; +import jntchina.util.JTHrmApiUtil; +import selfdev.util.log.LogTool; +import weaver.conn.RecordSet; +import weaver.general.Util; +import weaver.interfaces.workflow.action.BaseAction; +import weaver.soa.workflow.request.RequestInfo; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.Map; + +/** + * 组织新增Action + * CYQ + * + * @date 2021年7月7日 02:18:38 + */ +public class OrganizationAddAction extends BaseAction { + + private LogTool log = new LogTool("/log/hrmAction/", false); + + private final static Map C_COMPANY_LEVEL_MAP = new HashMap<>(); + + static { + C_COMPANY_LEVEL_MAP.put("0", "10"); + C_COMPANY_LEVEL_MAP.put("1", "20"); + C_COMPANY_LEVEL_MAP.put("2", "30"); + C_COMPANY_LEVEL_MAP.put("3", "40"); + C_COMPANY_LEVEL_MAP.put("4", "50"); + } + + @Override + public String execute(RequestInfo requestInfo) { + + //todo 流程与字段映射 + RecordSet rs = new RecordSet(); + String requestId = requestInfo.getRequestid(); //获取requestid + log.writeLog("------------requestId值为:" + requestId); + String mainTable = WorkflowUtil.getMainTable(requestId); + String sql = " select * from " + mainTable + " where requestid='" + requestId + "'"; + rs.executeQuery(sql); + Map paramMap = new HashMap(); + if (rs.next()) { +// C_APP_SEQ 申请单号 +// C_APP_DT 申请日期 +// C_APPLI_RS 审批状态 +// EMPLID 申请人工号 +// EFFDT 生效日期 +// DEFAULT_SETID 默认集合ID +// COMPANY_DESCR 公司名称 +// DESCRLONG 公司名称详细描述 +// DESCRSHORT 公司简短描述 +// COUNTRY 国家地区 +// BUSINESS_UNIT 业务单位代码 +// LOCATION 地点代码 +// C_DIRECTLY_FLAG 是否自营 +// C_UFSC_CODE 统一社会信用代码 +// C_COMPANY_LEVEL 公司级别 + String C_APP_SEQ = Util.null2String(rs.getString("C_APP_SEQ"));//申请单号 + String C_APP_DT = Util.null2String(rs.getString("C_APP_DT"));//申请日期 + String C_APPLI_RS = "3";//审批状态 + String EMPLID = Util.null2String(rs.getString("EMPLID"));//申请人工号 + String EFFDT = Util.null2String(rs.getString("EFFDT"));//生效日期 + String DEFAULT_SETID = "JT01";//默认集合ID + String COMPANY_DESCR = Util.null2String(rs.getString("COMPANY_DESCR"));//公司名称 + String DESCRLONG = Util.null2String(rs.getString("COMPANY_DESCR"));//公司名称详细描述 + String DESCRSHORT = Util.null2String(rs.getString("DESCRSHORT"));//公司简短描述 + String COUNTRY = Util.null2String(rs.getString("COUNTRY"));//国家地区 + String BUSINESS_UNIT = Util.null2String(rs.getString("BUSINESS_UNIT"));//业务单位代码 + String LOCATION = Util.null2String(rs.getString("LOCATION"));//地点代码 + String C_DIRECTLY_FLAG = "0".equals(rs.getString("C_DIRECTLY_FLAG")) ? "Y" : "N";//是否自营 + String C_UFSC_CODE = Util.null2String(rs.getString("C_UFSC_CODE"));//统一社会信用代码 + String C_COMPANY_LEVEL = Util.null2String(C_COMPANY_LEVEL_MAP.get(rs.getString("C_COMPANY_LEVEL")));//下拉框-公司级别 +// String C_SB_LOC_ID = Util.null2String(rs.getString("C_SB_LOC_ID"));// 社保缴纳地ID + + //主表 formtable_main_1581 + paramMap.put("C_APP_SEQ", C_APP_SEQ); + paramMap.put("C_APP_DT", C_APP_DT); + paramMap.put("C_APPLI_RS", C_APPLI_RS); + paramMap.put("EMPLID", EMPLID); + paramMap.put("EFFDT", EFFDT); + paramMap.put("DEFAULT_SETID", DEFAULT_SETID); + paramMap.put("COMPANY_DESCR", COMPANY_DESCR); + paramMap.put("DESCRLONG", DESCRLONG); + paramMap.put("DESCRSHORT", DESCRSHORT); + paramMap.put("COUNTRY", COUNTRY); + paramMap.put("BUSINESS_UNIT", BUSINESS_UNIT); + paramMap.put("LOCATION", LOCATION); + paramMap.put("C_DIRECTLY_FLAG", C_DIRECTLY_FLAG); + paramMap.put("C_UFSC_CODE", C_UFSC_CODE); + paramMap.put("C_COMPANY_LEVEL", C_COMPANY_LEVEL); + paramMap.put("C_COMP_SB", new ArrayList<>()); + paramMap.put("MULT_LANGUAGE", new ArrayList<>()); + + String token = HttpClientToJT.getToken(); + String paramStr = JSONObject.toJSONString(paramMap); + log.writeLog("---------开始添加公司------参数:" + paramStr + "------------"); + JSONObject json = JTHrmApiUtil.addCompany(token, paramStr); + log.writeLog("---------结束添加公司-----返回结果:" + json.toJSONString() + "------------"); + if (json.getInteger("code").equals(1)) { + JSONObject data = json.getJSONObject("data"); + } else { + requestInfo.getRequestManager().setMessagecontent(json.getString("msg")); + return FAILURE_AND_CONTINUE; + } + + return SUCCESS; + } + return FAILURE_AND_CONTINUE; + } +} diff --git a/src/main/youhong_ai_jitu_src/jntchina/action/hrm/postAddAction.java b/src/main/youhong_ai_jitu_src/jntchina/action/hrm/postAddAction.java new file mode 100644 index 0000000..dca1b2b --- /dev/null +++ b/src/main/youhong_ai_jitu_src/jntchina/action/hrm/postAddAction.java @@ -0,0 +1,147 @@ +package jntchina.action.hrm; + +import com.alibaba.fastjson.JSONObject; +import com.working.util.WorkflowUtil; +import jntchina.util.HttpClientToJT; +import jntchina.util.JTHrmApiUtil; +import org.apache.commons.lang3.StringUtils; +import selfdev.util.log.LogTool; +import weaver.conn.RecordSet; +import weaver.interfaces.workflow.action.BaseAction; +import weaver.soa.workflow.request.RequestInfo; + +import java.util.HashMap; +import java.util.Map; + +/** + * 岗位新增Action + * CYQ + * + * @date 2021年7月17日 02:18:38 + */ +public class postAddAction extends BaseAction { + + private LogTool log = new LogTool("/log/hrmAction/", false); + + @Override + public String execute(RequestInfo requestInfo) { + RecordSet rs = new RecordSet(); + String requestId = requestInfo.getRequestid(); //获取requestid + log.writeLog("------------requestId值为:" + requestId); + String mainTable = WorkflowUtil.getMainTable(requestId); + String sql = " select * from " + mainTable + " where requestid='" + requestId + "'"; + rs.executeQuery(sql); + Map standardParamMap = new HashMap(); + Map paramMap = new HashMap(); + + if (rs.next()) { + //1.先添加 标准岗位 +// C_APP_SEQ 申请单号 +// C_APP_DT 申请日期 +// EMPLID 申请人工号 +// EFFDT 生效日期 +// DESCR 标准岗位描述 +// DESCRSHORT 标准岗位短描述 +// C_POSITION_ID 岗编码 默认 +// C_RANK_TYPE 职级类型 +// C_POSN_GRDE_ID_MAX 最高职级 +// C_POSN_GRDE_ID_MIN 最低职级 +// C_POSN_PROPERTY 岗属性 +// C_POSN_DUTY 岗位职责 +// C_JOB_REQMENT 任职要求 +// C_APP_RESOAN 申请原因 +// DEPTID 部门ID +// REG_REGION 管理区域 + String C_APP_SEQ = rs.getString("C_APP_SEQ");//流程编号 + String C_APP_DT = rs.getString("C_APP_DT");//申请日期 + String EMPLID = rs.getString("EMPLID");//申请人工号 + String EFFDT = rs.getString("EFFDT");//生效日期 + String DESCR = rs.getString("DESCR");//标准岗位描述 + String DESCRSHORT = rs.getString("DESCRSHORT");//标准岗位短描述 + String C_POSITION_ID = rs.getString("C_APP_SEQ");//岗编码-默认 + String C_RANK_TYPE = rs.getString("C_RANK_TYPE");//职级类型 + String C_POSN_GRDE_ID_MAX = rs.getString("C_POSN_GRDE_ID_MAX");//最高职级 + String C_POSN_GRDE_ID_MIN = rs.getString("C_POSN_GRDE_ID_MIN");//最低职级 + String C_POSN_PROPERTY = rs.getString("C_POSN_PROPERTY");//岗属性 + String C_POSN_DUTY = rs.getString("C_POSN_DUTY");//岗位职责 + String C_JOB_REQMENT = rs.getString("C_JOB_REQMENT");//任职要求 + String C_APP_RESOAN = rs.getString("C_APP_RESOAN");//申请原因 + String DEPTID = rs.getString("DEPTID");//部门ID + String REG_REGION = rs.getString("REG_REGION");//需要处理-管理区域 + + standardParamMap.put("C_APP_SEQ", C_APP_SEQ); + standardParamMap.put("C_APP_DT", C_APP_DT); + standardParamMap.put("EMPLID", EMPLID); + standardParamMap.put("EFFDT", EFFDT); + standardParamMap.put("DESCR", DESCR); + standardParamMap.put("DESCRSHORT", DESCRSHORT); + standardParamMap.put("C_POSITION_ID", C_POSITION_ID); + standardParamMap.put("C_RANK_TYPE", C_RANK_TYPE); + standardParamMap.put("C_POSN_GRDE_ID_MAX", C_POSN_GRDE_ID_MAX); + standardParamMap.put("C_POSN_GRDE_ID_MIN", C_POSN_GRDE_ID_MIN); + standardParamMap.put("C_POSN_PROPERTY", C_POSN_PROPERTY); + standardParamMap.put("C_POSN_DUTY", C_POSN_DUTY); + standardParamMap.put("C_JOB_REQMENT", C_JOB_REQMENT); + standardParamMap.put("C_APP_RESOAN", C_APP_RESOAN); + standardParamMap.put("DEPTID", DEPTID); + standardParamMap.put("REG_REGION", REG_REGION); + + + //2.再添加 岗位 + //C_APP_SEQ 申请单号 + //C_APP_DT 申请日期 + //C_APPLI_RS 审批状态 + //EMPLID 申请人工号 + //EFFDT 生效日期 + //C_STD_POSN_ID 标准岗位编码 + //DESCR 岗位描述 + //DESCRSHORT 岗位短描述 + //C_POSN_DUTY 岗位职责 + //C_JOB_REQMENT 任职要求 + //C_APP_RESOAN 申请原因 + //DEPTID 部门ID + //REG_REGION 管理区域 + String C_APPLI_RS = "3";//审批状态 + String C_STD_POSN_ID = rs.getString("C_STD_POSN_ID");//标准岗位编码 + + paramMap.put("C_APP_SEQ", C_APP_SEQ); + paramMap.put("C_APP_DT", C_APP_DT); + paramMap.put("C_APPLI_RS", C_APPLI_RS); + paramMap.put("EMPLID", EMPLID); + paramMap.put("EFFDT", EFFDT); + paramMap.put("DESCR", DESCR); + paramMap.put("DESCRSHORT", DESCRSHORT); + paramMap.put("C_POSITION_ID", C_POSITION_ID); + paramMap.put("C_STD_POSN_ID", C_STD_POSN_ID); + paramMap.put("C_RANK_TYPE", C_RANK_TYPE); + paramMap.put("C_POSN_GRDE_ID_MAX", C_POSN_GRDE_ID_MAX); + paramMap.put("C_POSN_GRDE_ID_MIN", C_POSN_GRDE_ID_MIN); + paramMap.put("C_POSN_PROPERTY", C_POSN_PROPERTY); + paramMap.put("C_POSN_DUTY", C_POSN_DUTY); + paramMap.put("C_JOB_REQMENT", C_JOB_REQMENT); + paramMap.put("C_APP_RESOAN", C_APP_RESOAN); + paramMap.put("DEPTID", DEPTID); + paramMap.put("REG_REGION", REG_REGION); + + String token = HttpClientToJT.getToken(); + String standardParamStr = JSONObject.toJSONString(standardParamMap); + log.writeLog("---------开始标准岗位------参数:" + standardParamStr + "------------"); + JSONObject json = JTHrmApiUtil.stdPostApply(token, standardParamStr); + if (json.getInteger("code").equals(1)) { + JSONObject data = json.getJSONObject("data"); + } else { + requestInfo.getRequestManager().setMessagecontent(json.getString("msg")); + return FAILURE_AND_CONTINUE; + } + log.writeLog("---------结束标准岗位-----返回结果:" + json.toJSONString() + "------------"); + String paramStr = JSONObject.toJSONString(paramMap); + log.writeLog("---------开始添加岗位------参数:" + paramStr + "------------"); + JSONObject companyCode = JTHrmApiUtil.postApplication(token, paramStr); + log.writeLog("---------结束添加岗位-----返回结果:" + companyCode + "------------"); + + return SUCCESS; + } + return FAILURE_AND_CONTINUE; + } + +} diff --git a/src/main/youhong_ai_jitu_src/jntchina/action/ncc/CDUpdateToModelAction.java b/src/main/youhong_ai_jitu_src/jntchina/action/ncc/CDUpdateToModelAction.java new file mode 100644 index 0000000..029661b --- /dev/null +++ b/src/main/youhong_ai_jitu_src/jntchina/action/ncc/CDUpdateToModelAction.java @@ -0,0 +1,62 @@ +package jntchina.action.ncc; + +import jntchina.util.DataBaseUtils; +import selfdev.util.log.LogTool; +import weaver.conn.RecordSet; +import weaver.interfaces.workflow.action.BaseAction; +import weaver.soa.workflow.request.RequestInfo; + +import java.util.ArrayList; +import java.util.Map; + +/** + * @title: 冲抵更新到建模台账 + * @Author ycf + * @Date: 2022/4/7 11:51 + * @Version 1.0 + */ +public class CDUpdateToModelAction extends BaseAction { + LogTool log = new LogTool("/log/action/NCC", false); + + @Override + public String execute(RequestInfo requestInfo) { + try { + log.writeLog("--------------------------------冲抵金额更新到建模---------------------------------------"); + RecordSet recordSet = new RecordSet(); + String requestid = requestInfo.getRequestid(); + //判断当前流程是否存在 + String sql = "select id from uf_jktz_dt1 where xglc = " + requestid; + String value = DataBaseUtils.getFirstValue(sql); + if ("".equals(value)) { + ArrayList> dtList = DataBaseUtils.getProcessData(requestInfo, 2); + //明细表循环校验 + for (Map dtmap : dtList) { + log.writeLog("本次冲抵金额【" + dtmap.get("CDJE") + "】剩余未还款金额【" + dtmap.get("SYWHKJE") + "】"); + //借款台账ID + String tzId = dtmap.get("JKLC"); + //更新本次还款金额 + sql = "update uf_jktz set YCDJE = (nvl(YCDJE,0) + " + dtmap.get("CDJE") + ") where id = '" + tzId + "'"; + recordSet.execute(sql); + log.writeLog("更新本次还款金额:" + sql); + + + //更新剩余未还款金额 + sql = "update UF_JKTZ set WHKJE = nvl(JKJE, 0) - nvl(YHKJE, 0) - nvl(YCDJE, 0) where id='" + tzId + "' "; + recordSet.execute(sql); + log.writeLog("更新剩余未还款金额:" + sql); + + //插入到台账明细中 + sql = "insert into UF_JKTZ_DT1 ( mainid, xglc, hkje, bz) values " + + "(" + tzId + ",'" + requestid + "','" + dtmap.get("CDJE") + "','" + dtmap.get("BZ") + "')"; + recordSet.execute(sql); + log.writeLog("插入台账明细:" + sql); + } + } + return SUCCESS; + } catch (Exception e) { + log.writeLog("错误信息:" + DataBaseUtils.getExceptionDetail(e)); + requestInfo.getRequestManager().setMessagecontent("错误信息" + e); + return FAILURE_AND_CONTINUE; + } + } +} diff --git a/src/main/youhong_ai_jitu_src/jntchina/action/ncc/CheckChongdiJinEAction.java b/src/main/youhong_ai_jitu_src/jntchina/action/ncc/CheckChongdiJinEAction.java new file mode 100644 index 0000000..96a765f --- /dev/null +++ b/src/main/youhong_ai_jitu_src/jntchina/action/ncc/CheckChongdiJinEAction.java @@ -0,0 +1,66 @@ +package jntchina.action.ncc; + +import jntchina.util.DataBaseUtils; +import selfdev.util.log.LogTool; +import weaver.general.Util; +import weaver.interfaces.workflow.action.BaseAction; +import weaver.soa.workflow.request.RequestInfo; + +import java.util.ArrayList; +import java.util.Map; + +/** + * @title: 检查冲抵金额 + * @Author ycf + * @Date: 2022/4/7 11:16 + * @Version 1.0 + */ +public class CheckChongdiJinEAction extends BaseAction { + LogTool log = new LogTool("/log/action/NCC", false); + + @Override + public String execute(RequestInfo requestInfo) { + try { + log.writeLog("--------------------------------检查冲抵金额---------------------------------------"); + ArrayList> dtList = DataBaseUtils.getProcessData(requestInfo, 2); + Map mainMap = DataBaseUtils.getProcessData(requestInfo); + + if (!"".equals(Util.null2String(mainMap.get("CDJE"))) && !"".equals(Util.null2String(mainMap.get("BXJE")))) { + + double cdje = Double.parseDouble(Util.null2String(mainMap.get("CDJE"))); + double bxje = Double.parseDouble(Util.null2String(mainMap.get("BXJE"))); + if (cdje > bxje) { + requestInfo.getRequestManager().setMessagecontent("本次冲抵金额【" + cdje + "】不能大于报销金额【" + bxje + "】"); + return FAILURE_AND_CONTINUE; + } + + } + + ArrayList list = new ArrayList<>(); + //明细表循环校验 + for (Map dtmap : dtList) { + //校验是否存在多行明细引用一条流程 + if (list.contains(dtmap.get("JKLC"))) { + requestInfo.getRequestManager().setMessagecontent("冲抵明细中请勿选择重复的借款流程"); + return FAILURE_AND_CONTINUE; + } + list.add(dtmap.get("JKLC")); + + log.writeLog("冲抵明细借款流程编号【" + dtmap.get("JKLCBH") + "】中本次冲抵金额【" + dtmap.get("CDJE") + "】剩余未还款金额【" + dtmap.get("SYWHKJE") + "】"); + if (Double.parseDouble(dtmap.get("CDJE")) < 0) { + requestInfo.getRequestManager().setMessagecontent("冲抵明细借款流程编号【" + dtmap.get("JKLCBH") + "】中本次冲抵金额【" + dtmap.get("CDJE") + "】不能小于或等于0"); + return FAILURE_AND_CONTINUE; + } + if (Double.parseDouble(dtmap.get("CDJE")) > Double.parseDouble(dtmap.get("SYWHKJE"))) { + requestInfo.getRequestManager().setMessagecontent("冲抵明细借款流程编号【" + dtmap.get("JKLCBH") + "】中本次冲抵金额【" + dtmap.get("CDJE") + "】不能大于剩余未还款金额【" + dtmap.get("SYWHKJE") + "】"); + return FAILURE_AND_CONTINUE; + } + } + return SUCCESS; + } catch (Exception e) { + log.writeLog("错误信息:" + DataBaseUtils.getExceptionDetail(e)); + requestInfo.getRequestManager().setMessagecontent("错误信息" + e); + return FAILURE_AND_CONTINUE; + } + } +} diff --git a/src/main/youhong_ai_jitu_src/jntchina/action/ncc/CheckHuanKuanJineAction.java b/src/main/youhong_ai_jitu_src/jntchina/action/ncc/CheckHuanKuanJineAction.java new file mode 100644 index 0000000..e7bbacb --- /dev/null +++ b/src/main/youhong_ai_jitu_src/jntchina/action/ncc/CheckHuanKuanJineAction.java @@ -0,0 +1,52 @@ +package jntchina.action.ncc; + +import jntchina.util.DataBaseUtils; +import selfdev.util.log.LogTool; +import weaver.interfaces.workflow.action.BaseAction; +import weaver.soa.workflow.request.RequestInfo; + +import java.util.ArrayList; +import java.util.Map; + +/** + * @title: 检查还款金额 + * @Author ycf + * @Date: 2022/4/7 11:16 + * @Version 1.0 + */ +public class CheckHuanKuanJineAction extends BaseAction { + LogTool log = new LogTool("/log/action/NCC", false); + @Override + public String execute(RequestInfo requestInfo) { + try { + log.writeLog("--------------------------------检查还款金额---------------------------------------"); + ArrayList> dtList = DataBaseUtils.getProcessData(requestInfo, 1); + + ArrayList list = new ArrayList<>(); + //明细表循环校验 + for (Map dtmap : dtList) { + //校验是否存在多行明细引用一条流程 + if (list.contains(dtmap.get("XGJKLC"))) { + requestInfo.getRequestManager().setMessagecontent("相关借款流程还款重复"); + return FAILURE_AND_CONTINUE; + } + list.add(dtmap.get("XGJKLC")); + + log.writeLog("本次还款金额【"+dtmap.get("BCHKJE")+"】剩余未还款金额【"+dtmap.get("SYJE")+"】"); + if (Double.parseDouble(dtmap.get("BCHKJE")) < 0) { + requestInfo.getRequestManager().setMessagecontent("本次还款金额【"+dtmap.get("BCHKJE")+"】不能小于或等于0"); + return FAILURE_AND_CONTINUE; + } + if (Double.parseDouble(dtmap.get("BCHKJE")) > Double.parseDouble(dtmap.get("SYJE"))) { + requestInfo.getRequestManager().setMessagecontent("本次还款金额【"+dtmap.get("BCHKJE")+"】不能大于剩余未还款金额【"+dtmap.get("SYJE")+"】"); + return FAILURE_AND_CONTINUE; + } + } + return SUCCESS; + } catch (Exception e) { + log.writeLog("错误信息:"+ DataBaseUtils.getExceptionDetail(e)); + requestInfo.getRequestManager().setMessagecontent("错误信息"+e); + return FAILURE_AND_CONTINUE; + } + } +} diff --git a/src/main/youhong_ai_jitu_src/jntchina/action/ncc/CheckHxJeAction.java b/src/main/youhong_ai_jitu_src/jntchina/action/ncc/CheckHxJeAction.java new file mode 100644 index 0000000..416ac4b --- /dev/null +++ b/src/main/youhong_ai_jitu_src/jntchina/action/ncc/CheckHxJeAction.java @@ -0,0 +1,37 @@ +package jntchina.action.ncc; + +import jntchina.util.DataBaseUtils; +import weaver.interfaces.workflow.action.BaseAction; +import weaver.soa.workflow.request.RequestInfo; + +import java.util.ArrayList; +import java.util.Map; + +/** + * @title: CheckHxJeAction + * @Author ycf + * @Date: 2022/5/30 13:56 + * @Version 1.0 + */ +public class CheckHxJeAction extends BaseAction { + @Override + public String execute(RequestInfo requestInfo) { + + try { + ArrayList> processData = DataBaseUtils.getProcessData(requestInfo, 1); + for (Map map : processData) { + double bchxje = Double.parseDouble(map.get("BCHXJE")); + double fpje = Double.parseDouble(map.get("FPJE").equals("") ? "0" : map.get("FPJE")); + if (fpje > 0 && bchxje > fpje) { + requestInfo.getRequestManager().setMessagecontent("本次核销金额【" + bchxje + "】需<=发票金额【" + fpje + "】"); + return FAILURE_AND_CONTINUE; + } + } + } catch (Exception e) { + System.out.println(DataBaseUtils.getExceptionDetail(e)); + requestInfo.getRequestManager().setMessagecontent("错误信息" + e); + return FAILURE_AND_CONTINUE; + } + return SUCCESS; + } +} diff --git a/src/main/youhong_ai_jitu_src/jntchina/action/ncc/CheckSjAction.java b/src/main/youhong_ai_jitu_src/jntchina/action/ncc/CheckSjAction.java new file mode 100644 index 0000000..7150d43 --- /dev/null +++ b/src/main/youhong_ai_jitu_src/jntchina/action/ncc/CheckSjAction.java @@ -0,0 +1,58 @@ +package jntchina.action.ncc; + +import jntchina.util.DataBaseUtils; +import selfdev.util.log.LogTool; +import weaver.conn.RecordSet; +import weaver.interfaces.workflow.action.BaseAction; +import weaver.soa.workflow.request.RequestInfo; + +import java.util.ArrayList; +import java.util.Map; + +/** + * @title: 检查司机是否重复 + * @Author ycf + * @Date: 2022/5/18 09:57 + * @Version 1.0 + */ +public class CheckSjAction extends BaseAction { + LogTool log = new LogTool("/log/action/NCC", false); + @Override + public String execute(RequestInfo requestInfo) { + + try { + + //获取主表数据 + Map mainMap = DataBaseUtils.getProcessData(requestInfo); + //获取明细表数据 + ArrayList> dt5List = DataBaseUtils.getProcessData(requestInfo, 5); + //用于校验的list + ArrayList list = new ArrayList<>(); + //判断司机编码是否重复存在 + for (Map map : dt5List) { + if (list.contains(map.get("SJBM"))) { + requestInfo.getRequestManager().setMessagecontent("报销明细中请勿选择重复【"+map.get("SJBM")+"】司机编码"); + return FAILURE_AND_CONTINUE; + } else { + list.add(map.get("SJBM")); + } + } + + //费用类型赋值给明细表,用于生成批量 + String tableName = requestInfo.getRequestManager().getBillTableName(); + String sql = "update " + tableName + "_dt5 set fylx = " + mainMap.get("FYLX") + " where mainid = " + mainMap.get("ID"); + log.writeLog("更新明细:" + sql); + boolean execute = new RecordSet().execute(sql); + log.writeLog("成功?:"+execute); + + return SUCCESS; + } catch (Exception e) { + + log.writeLog("错误信息:"+ DataBaseUtils.getExceptionDetail(e)); + requestInfo.getRequestManager().setMessagecontent("错误信息"+e); + + return FAILURE_AND_CONTINUE; + } + + } +} diff --git a/src/main/youhong_ai_jitu_src/jntchina/action/ncc/CheckTheWriteOffAmountAction.java b/src/main/youhong_ai_jitu_src/jntchina/action/ncc/CheckTheWriteOffAmountAction.java new file mode 100644 index 0000000..febea47 --- /dev/null +++ b/src/main/youhong_ai_jitu_src/jntchina/action/ncc/CheckTheWriteOffAmountAction.java @@ -0,0 +1,73 @@ +package jntchina.action.ncc; + +import jntchina.util.DataBaseUtils; +import selfdev.util.base.BaseUtil; +import selfdev.util.log.LogTool; +import weaver.conn.RecordSet; +import weaver.interfaces.workflow.action.BaseAction; +import weaver.soa.workflow.request.RequestInfo; + +import java.util.ArrayList; +import java.util.Map; + +/** + * @title: 检查核销金额 + * @Author ycf + * @Date: 2022/3/16 10:34 + * @Version 1.0 + */ +public class CheckTheWriteOffAmountAction extends BaseAction { + @Override + public String execute(RequestInfo requestInfo) { + try { + LogTool log = new LogTool("/log/action/NCC", false); + String requestId = requestInfo.getRequestid(); // 获取requestid + String workflowid = requestInfo.getWorkflowid(); // 获取workflowid + //获取工作流名称 + String workflowname = BaseUtil.getBaseInfoByParm("workflowname", "workflow_base", "id", workflowid, ""); + log.writeLog("---------------工作流名称-----------workflowname为:" + workflowname); + log.writeLog("--------检查核销开始----requestId值为:" + requestId); + String mainTable = requestInfo.getRequestManager().getBillTableName(); + + String sql = "select * from "+mainTable+" where requestid = '"+requestId+"'"; + Map mainMap = DataBaseUtils.getDataMap(sql); + log.writeLog("获取主表的数据:"+sql); + + sql = "select * from "+mainTable+"_dt1 where mainid = "+mainMap.get("ID")+" order by id "; + log.writeLog("获取明细:"+sql); + ArrayList> dtList = DataBaseUtils.getDataList(sql); + + + + RecordSet recordSet = new RecordSet(); + log.writeLog("mainMap:"+mainMap); + log.writeLog("mainMap:"+dtList); + for (Map dtMap : dtList) { + + String whxje = DataBaseUtils.strNull(dtMap.get("WHXJE")).equals("") ? "0.00" : DataBaseUtils.strNull(dtMap.get("WHXJE")); + //本次核销金额 + String bchxje = DataBaseUtils.strNull(dtMap.get("BCHXJE")).equals("") ? "0.00" : DataBaseUtils.strNull(dtMap.get("BCHXJE")); + log.writeLog("未核销"+Float.parseFloat(whxje)); + log.writeLog("本次核销"+Float.parseFloat(bchxje)); + + + //如果本次核销金额大于为核销金额 + if (Float.parseFloat(whxje) < Float.parseFloat(bchxje)) { + + log.writeLog("本次核销金额大于未核销金额"); + requestInfo.getRequestManager().setMessageid("1111000"); + requestInfo.getRequestManager().setMessagecontent("核销明细中采购订单号【"+dtMap.get("CGDDHOA")+"】行明细中本次核销金额【"+ dtMap.get("BCHXJE")+"】不可大于未核销金额【"+ dtMap.get("WHXJE")+"】"); + return FAILURE_AND_CONTINUE; + + } + + } + } catch (Exception e) { + requestInfo.getRequestManager().setMessagecontent("错误信息"+e); + return FAILURE_AND_CONTINUE; + } + return SUCCESS; + + + } +} diff --git a/src/main/youhong_ai_jitu_src/jntchina/action/ncc/CreateNewProcessAction.java b/src/main/youhong_ai_jitu_src/jntchina/action/ncc/CreateNewProcessAction.java new file mode 100644 index 0000000..4eae0a0 --- /dev/null +++ b/src/main/youhong_ai_jitu_src/jntchina/action/ncc/CreateNewProcessAction.java @@ -0,0 +1,401 @@ +package jntchina.action.ncc; + +import jntchina.util.DataBaseUtils; +import selfdev.util.base.BaseUtil; +import selfdev.util.log.LogTool; +import weaver.conn.RecordSet; +import weaver.file.Prop; +import weaver.general.Util; +import weaver.hrm.company.DepartmentComInfo; +import weaver.interfaces.workflow.action.Action; +import weaver.soa.workflow.request.*; +import weaver.workflow.request.SetNewRequestTitle; +import weaver.workflow.workflow.WorkflowVersion; + +import java.time.LocalDate; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Map; + +/** + * @title: 创建子流程 + * @Author ycf + * @Date: 2022/3/11 14:23 + * @Version 1.0 + */ +public class CreateNewProcessAction implements Action { + public static LogTool log = new LogTool("/log/selfdev/action", true); + + @Override + public String execute(RequestInfo requestInfo) { + + try { + String requestId = requestInfo.getRequestid(); // 获取requestid + String workflowid = requestInfo.getWorkflowid(); // 获取workflowid + + String mode = Prop.getPropValue("YunYiSJ", "mode"); + // 服务器ip:port + String workflowidNew = Prop.getPropValue("YunYiSJ", mode + "_workflowid"); +// String workflowidNew = "551521"; + + //获取工作流名称 + String workflowname = BaseUtil.getBaseInfoByParm("workflowname", "workflow_base", "id", workflowid, ""); + log.writeLog("--------【" + workflowname + "】数据传入中台开始----requestId值为:" + requestId); + String mainTable = getMainTable(requestId); + String sql = "select * from " + mainTable + " where requestid = '" + requestId + "'"; + Map mainMap = DataBaseUtils.getDataMap(sql); + + sql = "select * from " + mainTable + "_dt5 where mainid = '" + mainMap.get("ID") + "'"; + log.writeLog("获取明细表:" + sql); + + ArrayList> dataList = DataBaseUtils.getDataList(sql); + + String lcbh = mainMap.get("LCBH"); + String sqr = mainMap.get("XM"); + String sqrq = mainMap.get("CJRQ"); + String sqbm = mainMap.get("FYGSBM"); + String sqfb = mainMap.get("SQFB"); + String qy = mainMap.get("QY"); + + + RequestService service = new RequestService(); + RequestInfo ri = new RequestInfo(); + //创建人id + ri.setCreatorid(mainMap.get("XM")); + log.writeLog("流程创建人id:" + mainMap.get("XM")); + +// String workflowid_zxqy=BaseUtil.getBaseInfoByParm("activeVersionID", "workflow_base", "id", workflowid, ""); +// log.writeLog("workflowid_zxqy------->"+workflowid_zxqy); + WorkflowVersion workflowVersion = new WorkflowVersion(workflowidNew); + log.writeLog("新版本workflowid:" + workflowVersion.getActiveVersionWFID()); + + + //流程Workflowid--------------------- + ri.setWorkflowid(workflowVersion.getActiveVersionWFID()); + //提醒 默认0 + ri.setRemindtype("0"); + //紧急程度 + ri.setRequestlevel("0"); + //流程是否自动提交到下一个节点 1表示自动提交到下一个节点,0表示停留在创建节点 + ri.setIsNextFlow("0"); + + + log.writeLog("明细表的长度:" + dataList.size()); + log.writeLog("list:" + dataList); + + int i = 0; + for (Map map : dataList) { + i++; + //流程标题 + ri.setDescription("支付司机" + map.get("SJMC") + "费用报销-" + LocalDate.now()); + + + //设置主表个字段数据 + Property[] p = new Property[0]; + + //流程编号 + p = Arrays.copyOf(p, (p.length + 1)); + p[p.length - 1] = new Property(); + p[p.length - 1].setName("lcbh"); + p[p.length - 1].setValue(lcbh + "_" + i); + + //申请人 + p = Arrays.copyOf(p, (p.length + 1)); + p[p.length - 1] = new Property(); + p[p.length - 1].setName("xm"); + p[p.length - 1].setValue(sqr); +// +// //申请人部门 + p = Arrays.copyOf(p, (p.length + 1)); + p[p.length - 1] = new Property(); + p[p.length - 1].setName("bm"); + p[p.length - 1].setValue(sqbm); + + p = Arrays.copyOf(p, (p.length + 1)); + p[p.length - 1] = new Property(); + p[p.length - 1].setName("bxrbm"); + p[p.length - 1].setValue(mainMap.get("FYCDBM")); + + //相关流程 + p = Arrays.copyOf(p, (p.length + 1)); + p[p.length - 1] = new Property(); + p[p.length - 1].setName("xglc"); + p[p.length - 1].setValue(requestId); + + //6、主表中的“报销说明”默认取批量流程中的备注 + //7、付款银行备注默认为:付款司机张三报销款 + //报销说明 + p = Arrays.copyOf(p, (p.length + 1)); + p[p.length - 1] = new Property(); + p[p.length - 1].setName("bxsm"); + p[p.length - 1].setValue(map.get("BZ")); + + + //报销备注 + p = Arrays.copyOf(p, (p.length + 1)); + p[p.length - 1] = new Property(); + p[p.length - 1].setName("yxfkbz"); + p[p.length - 1].setValue("付款司机" + map.get("SJMC") + "报销款"); + + + //申请日期 + p = Arrays.copyOf(p, (p.length + 1)); + p[p.length - 1] = new Property(); + p[p.length - 1].setName("cjrq"); + p[p.length - 1].setValue(sqrq); + + // + p = Arrays.copyOf(p, (p.length + 1)); + p[p.length - 1] = new Property(); + p[p.length - 1].setName("fysslx"); + p[p.length - 1].setValue(mainMap.get("FYSSLX")); + + if (!"".equals(qy)) { + //区域 + p = Arrays.copyOf(p, (p.length + 1)); + p[p.length - 1] = new Property(); + p[p.length - 1].setName("qy"); + p[p.length - 1].setValue(qy); + } + + + if (!"".equals(mainMap.get("GSMC"))) { + //付款公司名称 + p = Arrays.copyOf(p, (p.length + 1)); + p[p.length - 1] = new Property(); + p[p.length - 1].setName("gsmc"); + p[p.length - 1].setValue(mainMap.get("GSMC")); + } + + + //付款方式 + p = Arrays.copyOf(p, (p.length + 1)); + p[p.length - 1] = new Property(); + p[p.length - 1].setName("bxfs"); + p[p.length - 1].setValue("0"); + + if (!"".equals(map.get("SJMC"))) { + //司机名称 + p = Arrays.copyOf(p, (p.length + 1)); + p[p.length - 1] = new Property(); + p[p.length - 1].setName("sjmc"); + p[p.length - 1].setValue(map.get("SJMC")); + } + if (!"".equals(map.get("SJBM"))) { + //司机编码 + p = Arrays.copyOf(p, (p.length + 1)); + p[p.length - 1] = new Property(); + p[p.length - 1].setName("sjbm"); + p[p.length - 1].setValue(map.get("SJBM")); + } + if (!"".equals(map.get("ZHMC"))) { + //账户名称 + p = Arrays.copyOf(p, (p.length + 1)); + p[p.length - 1] = new Property(); + p[p.length - 1].setName("zhmc"); + p[p.length - 1].setValue(map.get("ZHMC")); + } + if (!"".equals(map.get("YXZH"))) { + //银行账号 + p = Arrays.copyOf(p, (p.length + 1)); + p[p.length - 1] = new Property(); + p[p.length - 1].setName("skkh"); + p[p.length - 1].setValue(map.get("YXZH")); + } + if (!"".equals(map.get("KHX"))) { + //开户行 + p = Arrays.copyOf(p, (p.length + 1)); + p[p.length - 1] = new Property(); + p[p.length - 1].setName("skyxjkhx"); + p[p.length - 1].setValue(map.get("KHX")); + } + + //报销金额 + p = Arrays.copyOf(p, (p.length + 1)); + p[p.length - 1] = new Property(); + p[p.length - 1].setName("bxje"); + p[p.length - 1].setValue(map.get("FKJE")); + + if (!"".equals(map.get("FJSC"))) { + //开户行 + p = Arrays.copyOf(p, (p.length + 1)); + p[p.length - 1] = new Property(); + p[p.length - 1].setName("fj"); + p[p.length - 1].setValue(map.get("FJSC")); + } + + + //添加主表数据 + MainTableInfo mti = new MainTableInfo(); + mti.setProperty(p); + ri.setMainTableInfo(mti); + //####################################主表字段 stop###########################################// + + + //####################################明细表字段 start###########################################// + //添加明细表数据 + DetailTableInfo dti = new DetailTableInfo(); + //明细表 + DetailTable[] dt = new DetailTable[0];//一个明细表一个对象 + //添加行数据 + Row[] row = new Row[0]; + row = Arrays.copyOf(row, (row.length + 1)); + row[row.length - 1] = new Row(); + row[row.length - 1].setId("100"); + //添加单元格到行 + Cell[] c = new Cell[0]; + + //费用承担部门 + c = Arrays.copyOf(c, (c.length + 1)); + c[c.length - 1] = new Cell(); + c[c.length - 1].setName("fygsbm"); + c[c.length - 1].setValue(mainMap.get("FYCDBM")); + + //费用类型 + c = Arrays.copyOf(c, (c.length + 1)); + c[c.length - 1] = new Cell(); + c[c.length - 1].setName("fylx"); + c[c.length - 1].setValue(map.get("FYLX")); + log.writeLog("map.get(\"FYLX\"):" + map.get("FYLX")); + + + if (!"".equals(map.get("FKJE"))) { + //付款金额 + c = Arrays.copyOf(c, (c.length + 1)); + c[c.length - 1] = new Cell(); + c[c.length - 1].setName("fkje"); + c[c.length - 1].setValue(map.get("FKJE")); + } + + + if (!"".equals(map.get("CPH"))) { + //车牌号 + c = Arrays.copyOf(c, (c.length + 1)); + c[c.length - 1] = new Cell(); + c[c.length - 1].setName("cph"); + c[c.length - 1].setValue(map.get("CPH")); + } + + + if (!"".equals(map.get("CBZX"))) { + //成本中心 + c = Arrays.copyOf(c, (c.length + 1)); + c[c.length - 1] = new Cell(); + c[c.length - 1].setName("cbzx"); + c[c.length - 1].setValue(map.get("CBZX")); + } + + //国家 + c = Arrays.copyOf(c, (c.length + 1)); + c[c.length - 1] = new Cell(); + c[c.length - 1].setName("GJ"); + c[c.length - 1].setValue("CN"); + + if (!"".equals(map.get("BZ"))) { + + //备注 + c = Arrays.copyOf(c, (c.length + 1)); + c[c.length - 1] = new Cell(); + c[c.length - 1].setName("bz"); + c[c.length - 1].setValue(map.get("BZ")); + } + + + //添加一行 + row[row.length - 1].setCell(c); + dt = Arrays.copyOf(dt, (dt.length + 1)); + //添加第一个明细表 + dt[dt.length - 1] = new DetailTable(); + dt[dt.length - 1].setId("8");//明细表 dt1 后面的1 + dt[dt.length - 1].setRow(row); + //明细表添加完毕 + dti.setDetailTable(dt); + ri.setDetailTableInfo(dti); + + String msg_n = ""; + + log.writeLog("ri:" + ri.toString()); + + + //创建流程 + String requestid_new = service.createRequest(ri); + log.writeLog("requestid_new------>" + requestid_new); + if (Integer.parseInt(requestid_new) > 0) { + msg_n = "成功触发子流程,requestid=" + requestid_new; + //更新到父节点的子流程 + sql = "update " + mainTable + "_dt5 set cfxgzlc = '" + requestid_new + "' where id = " + map.get("ID"); + log.writeLog("更新到父流程的明细:" + sql); + + new RecordSet().execute(sql); + log.writeLog(msg_n); + //让流程提交到下一节点 + try { + RequestService requestService = new RequestService(); + boolean flag2 = requestService.nextNodeBySubmit(null, Integer.parseInt(requestid_new), Integer.parseInt(sqr), ""); + + } catch (Exception e) { + log.writeLog("流程自动流转到下一节点失败错误信息:" + DataBaseUtils.getExceptionDetail(e)); + + } + + } else { + switch (requestid_new) { + case "-1": + msg_n = "创建流程失败!"; + break; + case "-2": + msg_n = "用户没有流程创建权限!"; + break; + case "-3": + msg_n = "流程基本信息失败!"; + break; + case "-4": + msg_n = "流程表单主表信息失败!"; + break; + case "-5": + msg_n = "流程紧急程度失败!"; + break; + case "-6": + msg_n = "流程操作者失效!"; + break; + case "-7": + msg_n = "流转至下一节点失败!"; + break; + case "-8": + msg_n = "流程节点附加操作失败!"; + break; + } + + msg_n = "触发子流程失败,错误编码为:" + requestid_new + ",错误信息为:" + msg_n; + log.writeLog(msg_n); + + requestInfo.getRequestManager().setMessagecontent("触发生成付款子流程失败,详细见明细中每行的接口返回信息!"); + return "0"; + } + } + + return SUCCESS; + } catch (Exception e) { + log.writeLog("错误信息1:" + DataBaseUtils.getExceptionDetail(e)); + log.writeLog("错误信息2:" + DataBaseUtils.getThrowableDetail(e)); + + requestInfo.getRequestManager().setMessage("异常" + e); + return FAILURE_AND_CONTINUE; + } + + } + + + public static String getMainTable(String requestid) { + String tablename = ""; + RecordSet rs = new RecordSet(); + rs.executeQuery("select * from workflow_requestbase a,workflow_base b,workflow_bill c " + + "where a.requestid=? and a.workflowid = b.id and b.formid = c.id", requestid); + while (rs.next()) { + tablename = Util.null2String(rs.getString("tablename")); + } + return tablename; + } + + +} diff --git a/src/main/youhong_ai_jitu_src/jntchina/action/ncc/HKUpdateToModelAction.java b/src/main/youhong_ai_jitu_src/jntchina/action/ncc/HKUpdateToModelAction.java new file mode 100644 index 0000000..6e6e5db --- /dev/null +++ b/src/main/youhong_ai_jitu_src/jntchina/action/ncc/HKUpdateToModelAction.java @@ -0,0 +1,61 @@ +package jntchina.action.ncc; + +import jntchina.util.DataBaseUtils; +import selfdev.util.log.LogTool; +import weaver.conn.RecordSet; +import weaver.interfaces.workflow.action.BaseAction; +import weaver.soa.workflow.request.RequestInfo; + +import java.util.ArrayList; +import java.util.Map; + +/** + * @title: 还款更新到建模台账 + * @Author ycf + * @Date: 2022/4/7 11:51 + * @Version 1.0 + */ +public class HKUpdateToModelAction extends BaseAction { + LogTool log = new LogTool("/log/action/NCC", false); + + @Override + public String execute(RequestInfo requestInfo) { + try { + log.writeLog("--------------------------------还款金额更新到建模---------------------------------------"); + RecordSet recordSet = new RecordSet(); + String requestid = requestInfo.getRequestid(); + //判断当前流程是否存在 + String sql = "select id from uf_jktz_dt1 where xglc = "+requestid; + String value = DataBaseUtils.getFirstValue(sql); + if ("".equals(value)) { + ArrayList> dtList = DataBaseUtils.getProcessData(requestInfo, 1); + //明细表循环校验 + for (Map dtmap : dtList ) { + log.writeLog("本次还款金额【"+dtmap.get("BCHKJE")+"】剩余未还款金额【"+dtmap.get("SYJE")+"】"); + //更新本次还款金额 + sql = "update uf_jktz set YHKJE = (nvl(YHKJE,0) + "+dtmap.get("BCHKJE")+") where id = '"+dtmap.get("XGJKLC")+"'"; + recordSet.execute(sql); + log.writeLog("更新本次还款金额:"+sql); + + //更新剩余未还款金额 + sql = "update UF_JKTZ set WHKJE = nvl(JKJE, 0) - nvl(YHKJE, 0) - nvl(YCDJE, 0) where id='"+dtmap.get("XGJKLC")+"' "; + recordSet.execute(sql); + log.writeLog("更新剩余未还款金额:"+sql); + +// //获取当前核销的台账的mainid +// sql = "select id from uf_jktz where xglc = '" + dtmap.get("XGJKLC") + "' "; +// String mainid = DataBaseUtils.getFirstValue(sql); + + //插入到台账明细中 + sql = "insert into UF_JKTZ_DT1 ( mainid, xglc, hkje, bz) values " + + "("+dtmap.get("XGJKLC")+",'"+requestid+"','"+dtmap.get("BCHKJE")+"','"+dtmap.get("BZ")+"')"; + recordSet.execute(sql); + log.writeLog("插入台账明细:"+sql); + } + } + return SUCCESS; + } catch (Exception e) { + return FAILURE_AND_CONTINUE; + } + } +} diff --git a/src/main/youhong_ai_jitu_src/jntchina/action/ncc/HkToNCCAction.java b/src/main/youhong_ai_jitu_src/jntchina/action/ncc/HkToNCCAction.java new file mode 100644 index 0000000..02dd26e --- /dev/null +++ b/src/main/youhong_ai_jitu_src/jntchina/action/ncc/HkToNCCAction.java @@ -0,0 +1,155 @@ +package jntchina.action.ncc; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.JSONObject; +import com.alibaba.fastjson.serializer.SerializerFeature; +import jntchina.util.DataBaseUtils; +import jntchina.util.HttpClientToDC; +import selfdev.util.log.LogTool; +import weaver.conn.RecordSet; +import weaver.file.Prop; +import weaver.general.Util; +import weaver.interfaces.workflow.action.BaseAction; +import weaver.soa.workflow.request.RequestInfo; + +import java.time.LocalDate; +import java.time.LocalTime; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.Map; + +/** + * @title: 还款传入NCC + * @Author ycf + * @Date: 2022/4/12 10:25 + * @Version 1.0 + */ +public class HkToNCCAction extends BaseAction { + + + LogTool log = new LogTool("/log/action/NCC", false); + + @Override + public String execute(RequestInfo requestInfo) { + try { + + Map mainMap = DataBaseUtils.getProcessData(requestInfo); + ArrayList> dtList = DataBaseUtils.getProcessData(requestInfo, 1); + HashMap params = new HashMap<>(); + //NCC组织编码 + params.put("pk_org", Util.null2String(mainMap.get("GSMC"))); + //币种编码 + params.put("bzbm", "CNY"); + //单据类型 + params.put("billtypecode", "2647"); + //申请日期 + params.put("dbilldate", Util.null2String(mainMap.get("SQRQ"))); + //还款金额 + params.put("totalmny", Util.null2String(mainMap.get("HKJE"))); + //申请人工号 + params.put("billmaker", Util.null2String(mainMap.get("SQRGH"))); + //费用承担部门 + params.put("fydeptid", DataBaseUtils.getFirstValue("select DEPARTMENTCODE from HRMDEPARTMENT where id = " + Util.null2String(mainMap.get("SQBM")))); + //默认:0 + params.put("paytarget", "0"); + //收款单位 + params.put("payorg", Util.null2String(mainMap.get("GSMC"))); + //结算方式 + params.put("payment", "3"); + //还款人 + params.put("pk_psndoc", Util.null2String(DataBaseUtils.getFirstValue("select WORKCODE from HRMRESOURCE where id =" + mainMap.get("HKR")))); + //还款人银行账户 + params.put("psnaccnum", ""); + //收款单位银行账户 + params.put("orgaccnum", ""); + //OArequestID + params.put("oarequestid", Util.null2String(mainMap.get("REQUESTID"))); + //流程编号 + params.put("oavbillcode", Util.null2String(mainMap.get("LCBH"))); + //费用承担部门 + params.put("fydwbm", Util.null2String(mainMap.get("GSMC"))); + //收款单位银行账户 + params.put("zy", ""); + ArrayList> arrayList = new ArrayList<>(); + for (Map dtMap : dtList) { + HashMap map = new HashMap<>(); + map.put("jkbillcode", Util.null2String(dtMap.get("NCCJKDH"))); + map.put("inoutbusiclass", "901038"); + map.put("hkmny", Util.null2String(dtMap.get("BCHKJE"))); + + arrayList.add(map); + } + params.put("er_bxcontrast", arrayList); + + //成功传入ncc如果为0,则以前传入过ncc且成功 + if ("0".equals(mainMap.get("SFCRNCC"))) { + return SUCCESS; + + } + + String mode = Prop.getPropValue("DevToDC_jntchina", "mode"); + // 服务器ip:port + String baseUrl = Prop.getPropValue("DevToDC_jntchina", mode + "_baseUrl"); + String url = baseUrl + "/dcoaapi/ncc/repaymentBill"; + + String token = HttpClientToDC.getToken(); + + + String json = JSON.toJSONString(params, SerializerFeature.DisableCircularReferenceDetect); + + log.writeLog("url:" + url); + log.writeLog("token:" + token); + log.writeLog("param:" + json); + + String rdata = HttpClientToDC.sendPostApi(url, token, json); + log.writeLog("【调用数据中台报销接口返回结果result:】" + rdata); + if (!"".equals(rdata) && rdata != null) { + JSONObject jsonObject = JSONObject.parseObject(rdata); + String sql; + RecordSet recordSet = new RecordSet(); + String modeid = DataBaseUtils.getModelIdByName("uf_dynccjkrzb"); + if (jsonObject.getBooleanValue("succ")) { + log.writeLog("传入ncc成功:"); + + String pkBill = jsonObject.getJSONObject("data").getString("pk_bill"); + sql = "update " + requestInfo.getRequestManager().getBillTableName() + + " set SFCRNCC =0 ,NCCFHDXX = '" + jsonObject.getString("msg") + "',NCCDJID='" + pkBill + "' "; + recordSet.execute(sql); + log.writeLog("调用ncc状态存入本地:" + sql); + + sql = "insert into uf_dynccjkrzb (dyjk,cdcs,fhcs,sfcg,lcid,formmodeid,MODEDATACREATEDATE,MODEDATACREATETIME) values " + + "('还款接口','" + json + "','" + rdata + "','1','" + requestInfo.getRequestid() + "','" + modeid + "','" + LocalDate.now() + "','" + LocalTime.now().toString().substring(0, 8) + "')"; + ; + log.writeLog("插入日志SQL:" + sql + recordSet.execute(sql)); + + return SUCCESS; + } else { + log.writeLog("传入ncc失败:"); + sql = "update " + requestInfo.getRequestManager().getBillTableName() + + " set SFCRNCC =1,NCCFHDXX ='" + jsonObject.getString("msg") + "' where requestid = " + requestInfo.getRequestid(); + ; + log.writeLog("调用ncc状态存入本地:" + sql + recordSet.execute(sql)); + + + sql = "insert into uf_dynccjkrzb (dyjk,cdcs,fhcs,sfcg,lcid,formmodeid,MODEDATACREATEDATE,MODEDATACREATETIME) values " + + "('还款接口','" + json + "','" + rdata + "','0','" + requestInfo.getRequestid() + "','" + modeid + "','" + LocalDate.now() + "','" + LocalTime.now().toString().substring(0, 8) + "')"; + log.writeLog("插入日志SQL:" + sql); + recordSet.execute(sql); + + requestInfo.getRequestManager().setMessagecontent("提交流程失败,错误信息" + jsonObject.getString("msg")); + return FAILURE_AND_CONTINUE; + } + } else { + requestInfo.getRequestManager().setMessagecontent("提交流程失败,中台返回数据为空"); + return FAILURE_AND_CONTINUE; + } + } catch (Exception e) { + log.writeLog("异常:" + DataBaseUtils.getExceptionDetail(e)); + requestInfo.getRequestManager().setMessagecontent("错误信息" + e); + return FAILURE_AND_CONTINUE; + } + + +// return SUCCESS; + } +} diff --git a/src/main/youhong_ai_jitu_src/jntchina/action/ncc/PrepaidWriteOffAction.java b/src/main/youhong_ai_jitu_src/jntchina/action/ncc/PrepaidWriteOffAction.java new file mode 100644 index 0000000..45d90fd --- /dev/null +++ b/src/main/youhong_ai_jitu_src/jntchina/action/ncc/PrepaidWriteOffAction.java @@ -0,0 +1,191 @@ +package jntchina.action.ncc; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.JSONObject; +import com.alibaba.fastjson.serializer.SerializerFeature; +import jntchina.util.HttpClientToDC; +import jntchina.util.NCCUtils; +import selfdev.util.base.BaseUtil; +import selfdev.util.log.LogTool; +import weaver.conn.RecordSet; +import weaver.file.Prop; +import weaver.general.Util; +import weaver.interfaces.workflow.action.BaseAction; +import weaver.soa.workflow.request.RequestInfo; +import jntchina.util.DataBaseUtils; + +import java.time.LocalDate; +import java.time.LocalDateTime; +import java.time.LocalTime; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.Map; + +/** + * @title: 审批完成后将数据传入NCC生成预付核销单,并且更新到台账 + * @Author ycf + * @Date: 2022/2/28 09:25 + * @Version 1.0 + */ +public class PrepaidWriteOffAction extends BaseAction { + + + @Override + public String execute(RequestInfo requestInfo) { + LogTool log = new LogTool("/log/action/NCC", false); + String requestId = requestInfo.getRequestid(); // 获取requestid + String workflowid = requestInfo.getWorkflowid(); // 获取workflowid + //获取工作流名称 + String workflowname = BaseUtil.getBaseInfoByParm("workflowname", "workflow_base", "id", workflowid, ""); + log.writeLog("---------------工作流名称-----------workflowname为:" + workflowname); + log.writeLog("--------核销数据传入中台->NCC 开始----requestId值为:" + requestId); + String mainTable = getMainTable(requestId); + + //获取配置文件中的参数 + String mode = Prop.getPropValue("DevToDC_jntchina", "mode"); + // 服务器ip:port + String baseUrl = Prop.getPropValue("DevToDC_jntchina", mode + "_baseUrl"); + //String url = baseUrl+ "/dcoaapi/claimForm/receiveData"; + String url = baseUrl + "/dcoaapi/ncc/preBillVerification"; + + + String sql = "select * from " + mainTable + " where requestid = '" + requestId + "'"; + Map mainMap = DataBaseUtils.getDataMap(sql); + log.writeLog("获取主表的数据:" + sql); + + sql = "select * from " + mainTable + "_dt1 where mainid = " + mainMap.get("ID") + " order by id "; + log.writeLog("获取明细:" + sql); + ArrayList> dtList = DataBaseUtils.getDataList(sql); + + RecordSet recordSet = new RecordSet(); + log.writeLog("mainMap:" + mainMap); + log.writeLog("mainMap:" + dtList); + + + try { +//数据回传NCC + HashMap map = new HashMap<>(); + map.put("pk_org", mainMap.get("GSMC")); + map.put("pk_verify_fa", "核销方案"); + map.put("operator", DataBaseUtils.getFirstValue("select WORKCODE from HRMRESOURCE where id = " + mainMap.get("SQR"))); + map.put("oarequestid", requestId); + map.put("oavbillcode", mainMap.get("LCBH")); + + + ArrayList> payableitems = new ArrayList<>(); + ArrayList> payitems = new ArrayList<>(); + for (Map dtMap : dtList) { + + //唯一id + String wyjhid = DataBaseUtils.getFirstValue("select FKJHWYID\n" + + "from uf_gylyfxxb_dt1 where id = " + dtMap.get("DDMAINID")); + + //付款明细id + String fkmxid = DataBaseUtils.getFirstValue("select fkdmxid \n" + + "from uf_gylyfxxb_dt1 where id = " + dtMap.get("DDMAINID")); + //应付 + HashMap payable = new HashMap<>(); + //采购明细id + payable.put("pk_payableitem", wyjhid); + //预付款金额 + payable.put("payablemny", dtMap.get("YFKJE")); + payable.put("def1", "自定义项"); + payableitems.add(payable); + + //预付 + HashMap pay = new HashMap<>(); + //付款单明细id + pay.put("pk_payitem", fkmxid); + //本次报销金额 + pay.put("paymny", dtMap.get("BCHXJE")); + pay.put("def1", "自定义项"); + payitems.add(pay); + } + map.put("payableitems", payableitems); + map.put("payitems", payitems); + + String json = JSON.toJSONString(map, SerializerFeature.DisableCircularReferenceDetect); +// String url = "http://180.169.229.37:8080/nccloud/api/jitu/arap/wobill/writeoff"; + + boolean success; + + if (!mainMap.get("ISWRITENCC").equals("0")) { + //获取TOKEN + String token = HttpClientToDC.getToken(); + + log.writeLog("请求的json:" + json); + log.writeLog("请求的token:" + token); + log.writeLog("请求的url:" + url); + + String rdata = HttpClientToDC.sendPostApi(url, token, json); + + log.writeLog("写到uf_dynccjkrzb 日志表中:"); + + String modeid = DataBaseUtils.getModelIdByName("uf_dynccjkrzb"); + + + JSONObject jsonObject = JSONObject.parseObject(rdata); + success = jsonObject.getBooleanValue("succ"); + + log.writeLog("请求的返回结果:" + rdata); + + log.writeLog("success:" + success); + + if (!success) { + + sql = "update " + mainTable + " set iswritencc = 1,NCCMsg = '" + jsonObject.getString("msg") + "' where id = " + mainMap.get("ID"); + log.writeLog("写入ncc失败:" + sql); + + recordSet.execute(sql); + + sql = "insert into uf_dynccjkrzb (dyjk,cdcs,fhcs,sfcg,lcid,formmodeid,MODEDATACREATEDATE,MODEDATACREATETIME) values " + + "('预付核销接口','" + json + "','" + rdata + "','1','" + requestId + "','" + modeid + "','" + LocalDate.now() + "','" + LocalTime.now().toString().substring(0, 8) + "')"; + log.writeLog("插入日志SQL:" + sql); + recordSet.execute(sql); + + log.writeLog("err:" + jsonObject.getString("msg")); + + requestInfo.getRequestManager().setMessageid("1111000"); + requestInfo.getRequestManager().setMessagecontent("数据写入NCC失败,NCC错误信息:" + jsonObject.getString("msg")); + return FAILURE_AND_CONTINUE; + } else { + sql = "update " + mainTable + " set iswritencc = 0,NCCMsg = '" + jsonObject.getString("msg") + "' where id = " + mainMap.get("ID"); + log.writeLog("写入ncc字段成功:" + sql); + + recordSet.execute(sql); + + sql = "insert into uf_dynccjkrzb (dyjk,cdcs,fhcs,sfcg,lcid,formmodeid,MODEDATACREATEDATE,MODEDATACREATETIME) values " + + "('预付核销接口','" + json + "','" + rdata + "','0','" + requestId + "','" + modeid + "','" + LocalDate.now() + "','" + LocalTime.now().toString().substring(0, 8) + "')"; + log.writeLog("插入日志SQL:" + sql); + + recordSet.execute(sql); + + } + } else { + log.writeLog("流程requestid【:" + requestId + "】传入给ncc,本次跳过"); + + } + + } catch (Exception e) { + requestInfo.getRequestManager().setMessageid("1111000"); + requestInfo.getRequestManager().setMessagecontent("系统内部发生异常,错误信息:" + e.toString()); + return FAILURE_AND_CONTINUE; + } + + return SUCCESS; + } + + + public static String getMainTable(String requestid) { + String tablename = ""; + RecordSet rs = new RecordSet(); + rs.executeQuery("select * from workflow_requestbase a,workflow_base b,workflow_bill c " + + "where a.requestid=? and a.workflowid = b.id and b.formid = c.id", requestid); + while (rs.next()) { + tablename = Util.null2String(rs.getString("tablename")); + } + return tablename; + } + + +} diff --git a/src/main/youhong_ai_jitu_src/jntchina/action/ncc/UpdateToModelAction.java b/src/main/youhong_ai_jitu_src/jntchina/action/ncc/UpdateToModelAction.java new file mode 100644 index 0000000..3c9e0a8 --- /dev/null +++ b/src/main/youhong_ai_jitu_src/jntchina/action/ncc/UpdateToModelAction.java @@ -0,0 +1,109 @@ +package jntchina.action.ncc; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.JSONObject; +import jntchina.util.DataBaseUtils; +import jntchina.util.NCCUtils; +import selfdev.util.base.BaseUtil; +import selfdev.util.log.LogTool; +import weaver.conn.RecordSet; +import weaver.interfaces.workflow.action.BaseAction; +import weaver.soa.workflow.request.RequestInfo; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.Map; + +/** + * @title: 数据更新到建模 + * @Author ycf + * @Date: 2022/3/22 10:13 + * @Version 1.0 + */ +public class UpdateToModelAction extends BaseAction { + + @Override + public String execute(RequestInfo requestInfo) { + LogTool log = new LogTool("/log/action/NCC", false); + String requestId = requestInfo.getRequestid(); // 获取requestid + String workflowid = requestInfo.getWorkflowid(); // 获取workflowid + //获取工作流名称 + String workflowname = BaseUtil.getBaseInfoByParm("workflowname", "workflow_base", "id", workflowid, ""); + log.writeLog("---------------工作流名称-----------workflowname为:" + workflowname); + log.writeLog("--------核销金额写入建模开始----requestId值为:" + requestId); + String mainTable = requestInfo.getRequestManager().getBillTableName(); + + String sql = "select * from " + mainTable + " where requestid = '" + requestId + "'"; + Map mainMap = DataBaseUtils.getDataMap(sql); + log.writeLog("获取主表的数据:" + sql); + + sql = "select * from " + mainTable + "_dt1 where mainid = " + mainMap.get("ID") + " order by id "; + log.writeLog("获取明细:" + sql); + ArrayList> dtList = DataBaseUtils.getDataList(sql); + + RecordSet recordSet = new RecordSet(); + log.writeLog("mainMap:" + mainMap); + log.writeLog("mainMap:" + dtList); + + try { + //如果当前流程存在,,不更新到台账 + sql = "select id from uf_gylyfxxb_dt2 where lc = '" + requestId + "' "; + String firstValue = DataBaseUtils.getFirstValue(sql); + if (firstValue.equals("")) { + for (Map dtMap : dtList) { + //更新到建模 + String dtId = dtMap.get("WYJHID"); + //建模的核销金额 = 本次核销金额+已核销金额 + String yhxje = DataBaseUtils.strNull(dtMap.get("YHXJE")).equals("") ? "0.00" : DataBaseUtils.strNull(dtMap.get("YHXJE")); + String bchxje = DataBaseUtils.strNull(dtMap.get("BCHXJE")).equals("") ? "0.00" : DataBaseUtils.strNull(dtMap.get("BCHXJE")); + log.writeLog("已核销金额:" + yhxje); + log.writeLog("本次核销金额:" + bchxje); + + float sum = Float.parseFloat(yhxje) + Float.parseFloat(bchxje); + log.writeLog("合计:" + sum); + + sql = "select mainid from uf_gylyfxxb_dt1 where id = " + dtMap.get("DDMAINID"); + String mainid = DataBaseUtils.getFirstValue(sql); + + sql = "update uf_gylyfxxb_dt1 set YHXJE = " + sum + " where id = " + dtId; + log.writeLog("明细表已核销金额更新到建模台账的sql:" + sql); + recordSet.execute(sql); + + sql = "update uf_gylyfxxb_dt1 set SYWFJE = (to_number(nvl(bcfkje,0)) - to_number(nvl(YHXJE,0))) where id = " + dtId; + log.writeLog("明细表剩余核销金额更新到建模台账的sql:" + sql); + recordSet.execute(sql); + + sql = "update UF_GYLYFXXB\n" + + "set YHXJE = to_number((select nvl(yhxje,0)\n" + + "from UF_GYLYFXXB where id = " + mainid + ")) + to_number((select sum(YHXJE)\n" + + "from uf_gylyfxxb_dt1 where mainid = " + mainid + "))\n" + + "where id = " + mainid + ""; + recordSet.execute(sql); + log.writeLog("更新主表已核销金额:" + sql); + + sql = "update UF_GYLYFXXB\n" + + "set SYWHXJE = to_number(nvl(FKJE, 0)) - to_number(nvl(yhxje, 0))\n" + + "where id = " + mainid; + recordSet.execute(sql); + log.writeLog("更新主表剩余未核销金额:" + sql); + + sql = "insert into uf_gylyfxxb_dt2 (yfhxbh,lc,mainid) values ('" + mainMap.get("LCBH") + "','" + requestId + "'," + mainid + ") "; + recordSet.execute(sql); + log.writeLog("插入流程数据:" + sql); + } + } else { + log.writeLog("当前编号已存在不更新建模:" + requestId); + + } + + } catch (Exception e) { + log.writeLog("err:" + DataBaseUtils.getExceptionDetail(e)); + + requestInfo.getRequestManager().setMessageid("1111000"); + requestInfo.getRequestManager().setMessagecontent("数据写入NCC失败,错误信息:" + e.toString()); + return FAILURE_AND_CONTINUE; + } + + return SUCCESS; + } +} diff --git a/src/main/youhong_ai_jitu_src/jntchina/certificate/JTSD.pfx b/src/main/youhong_ai_jitu_src/jntchina/certificate/JTSD.pfx new file mode 100644 index 0000000..5d6895b Binary files /dev/null and b/src/main/youhong_ai_jitu_src/jntchina/certificate/JTSD.pfx differ diff --git a/src/main/youhong_ai_jitu_src/jntchina/certificate/pro22.pfx b/src/main/youhong_ai_jitu_src/jntchina/certificate/pro22.pfx new file mode 100644 index 0000000..77f77b7 Binary files /dev/null and b/src/main/youhong_ai_jitu_src/jntchina/certificate/pro22.pfx differ diff --git a/src/main/youhong_ai_jitu_src/jntchina/entity/BorrowOrder.java b/src/main/youhong_ai_jitu_src/jntchina/entity/BorrowOrder.java new file mode 100644 index 0000000..168faff --- /dev/null +++ b/src/main/youhong_ai_jitu_src/jntchina/entity/BorrowOrder.java @@ -0,0 +1,283 @@ +package jntchina.entity; + +import java.io.Serializable; +import java.util.List; +import java.util.Objects; + +/** + * @Author Administrator + * @Description 借款单 + * @Date 2021/1/16 11:23 + */ +public class BorrowOrder implements Serializable { + + private static final long serialVersionUID = 1L; + + private String uuid; //主键 + private String pk_org; // JTSDCN0001 //借款单位编码 + private String total; // 1000.00 //合计金额 + private String deptid; // SD3300101 //借款人部门 + private String djlxbm; // 263X-Cxx-DSJKD", //交易类型编码 263X-Cxx-DSJKD:对私借款单 263X-Cxx-DGJKD:对公预付/借款单 + private String djrq; // 2021-03-05 10:17:10", //单据日期 + private String payflag; //1", //支付状态 + private String paytarget; // 0" //收款对象(0=员工,1=供应商) + private String hbbm; // 供应商编码 + private String receiver; // yonyou88", //收款人 + private String jkbxr; // yonyou88 //借款报销人 + private String operator; // yonyou88 //录入人 + private String jsfs; // 3 //结算方式 3 网银 。。。 + private String fkyhzh; //付款银行账户 + private String skyhzh; //收款银行账户(员工) + private String custaccount; //收款银行账户(供应商) + private String jobid; //项目 + private String zy; //借款测试", //事由 + private String djzt; // 1", //单据状态 1 保存 + private String kjqj; // 03", //会计期间 + private String kjnd; // 2021", //会计年度 + private String zyx1; // CSBX21020501", //OA单据号 + private String zyx2; // 提交人 + private String zyx3; // OA核销单号 + private String zyx5; // CSBX21020501", // OARequestID + private String zyx8; // 银行付款备注 + private String zyx9; // OA流程标题 + private List jk_busitem; + + public String getPk_org() { + return pk_org; + } + + public String getCustaccount() { + return custaccount; + } + + public String getZyx9() { + return zyx9; + } + + public void setZyx9(String zyx9) { + this.zyx9 = zyx9; + } + + public void setCustaccount(String custaccount) { + this.custaccount = custaccount; + } + + public String getHbbm() { + return hbbm; + } + + public String getUuid() { + return uuid; + } + + public void setUuid(String uuid) { + this.uuid = uuid; + } + + public void setHbbm(String hbbm) { + this.hbbm = hbbm; + } + + public void setPk_org(String pk_org) { + this.pk_org = pk_org; + } + + public String getTotal() { + return total; + } + + public void setTotal(String total) { + this.total = total; + } + + public String getDeptid() { + return deptid; + } + + public String getZyx8() { + return zyx8; + } + + public void setZyx8(String zyx8) { + this.zyx8 = zyx8; + } + + public void setDeptid(String deptid) { + this.deptid = deptid; + } + + public String getDjlxbm() { + return djlxbm; + } + + public void setDjlxbm(String djlxbm) { + this.djlxbm = djlxbm; + } + + public String getDjrq() { + return djrq; + } + + public void setDjrq(String djrq) { + this.djrq = djrq; + } + + public String getPayflag() { + return payflag; + } + + public void setPayflag(String payflag) { + this.payflag = payflag; + } + + public String getPaytarget() { + return paytarget; + } + + public void setPaytarget(String paytarget) { + this.paytarget = paytarget; + } + + public String getReceiver() { + return receiver; + } + + public void setReceiver(String receiver) { + this.receiver = receiver; + } + + public String getJkbxr() { + return jkbxr; + } + + public void setJkbxr(String jkbxr) { + this.jkbxr = jkbxr; + } + + public String getOperator() { + return operator; + } + + public void setOperator(String operator) { + this.operator = operator; + } + + public String getJsfs() { + return jsfs; + } + + public void setJsfs(String jsfs) { + this.jsfs = jsfs; + } + + public String getFkyhzh() { + return fkyhzh; + } + + public void setFkyhzh(String fkyhzh) { + this.fkyhzh = fkyhzh; + } + + public String getJobid() { + return jobid; + } + + public void setJobid(String jobid) { + this.jobid = jobid; + } + + public String getZy() { + return zy; + } + + public void setZy(String zy) { + this.zy = zy; + } + + public String getDjzt() { + return djzt; + } + + public void setDjzt(String djzt) { + this.djzt = djzt; + } + + public String getKjqj() { + return kjqj; + } + + public void setKjqj(String kjqj) { + this.kjqj = kjqj; + } + + public String getKjnd() { + return kjnd; + } + + public void setKjnd(String kjnd) { + this.kjnd = kjnd; + } + + public String getZyx1() { + return zyx1; + } + + public void setZyx1(String zyx1) { + this.zyx1 = zyx1; + } + + public String getZyx2() { + return zyx2; + } + + public void setZyx2(String zyx2) { + this.zyx2 = zyx2; + } + + public String getZyx3() { + return zyx3; + } + + public void setZyx3(String zyx3) { + this.zyx3 = zyx3; + } + + public String getZyx5() { + return zyx5; + } + + public void setZyx5(String zyx5) { + this.zyx5 = zyx5; + } + + public List getJk_busitem() { + return jk_busitem; + } + + public void setJk_busitem(List jk_busitem) { + this.jk_busitem = jk_busitem; + } + + @Override + public int hashCode() { + return Objects.hash(pk_org, total, deptid, djlxbm, djrq, payflag, paytarget, receiver, jkbxr, operator, jsfs, fkyhzh, jobid, zy, djzt, kjqj, kjnd, zyx1, zyx2, zyx3, zyx5, jk_busitem); + } + + public String getSkyhzh() { + return skyhzh; + } + + public void setSkyhzh(String skyhzh) { + this.skyhzh = skyhzh; + } + + @Override + public String toString() { + return "BorrowOrder [uuid=" + uuid + ", pk_org=" + pk_org + ", total=" + total + ", deptid=" + deptid + + ", djlxbm=" + djlxbm + ", djrq=" + djrq + ", payflag=" + payflag + ", paytarget=" + paytarget + + ", hbbm=" + hbbm + ", receiver=" + receiver + ", jkbxr=" + jkbxr + ", operator=" + operator + + ", jsfs=" + jsfs + ", fkyhzh=" + fkyhzh + ", skyhzh=" + skyhzh + ", jobid=" + jobid + ", zy=" + zy + + ", djzt=" + djzt + ", kjqj=" + kjqj + ", kjnd=" + kjnd + ", zyx1=" + zyx1 + ", zyx2=" + zyx2 + + ", zyx3=" + zyx3 + ", zyx5=" + zyx5 + ", zyx8=" + zyx8 + ", jk_busitem=" + jk_busitem + "]"; + } +} diff --git a/src/main/youhong_ai_jitu_src/jntchina/entity/BorrowOrderBody.java b/src/main/youhong_ai_jitu_src/jntchina/entity/BorrowOrderBody.java new file mode 100644 index 0000000..08ea3a8 --- /dev/null +++ b/src/main/youhong_ai_jitu_src/jntchina/entity/BorrowOrderBody.java @@ -0,0 +1,146 @@ +package jntchina.entity; + +import java.io.Serializable; +import java.util.Objects; + +/** + * @Author Administrator + * @Description 借款单表体(明细表) + * @Date 2021/1/8 12:14 + */ +public class BorrowOrderBody implements Serializable { + + private static final long serialVersionUID = 1L; + + private String amount; // 1000.00 //金额 + private String tablecode; // jk_busitem + private String rowno; // 10 + private String szxmid; // 收支项目 101005 电子面单号段费 + private String defitem50; // 发票类型 + private String defitem49; // 发票号码 + private String defitem42; // OA明细ID + private String defitem43; // 车牌号 + private String defitem44; // 仓库 + private String defitem45; // 国家 + private String defitem46; // 网点(成本中心) + private String defitem48; // SD3300301" //分摊部门 + + public String getAmount() { + return amount; + } + + public void setAmount(String amount) { + this.amount = amount; + } + + public String getTablecode() { + return tablecode; + } + + public void setTablecode(String tablecode) { + this.tablecode = tablecode; + } + + public String getRowno() { + return rowno; + } + + public void setRowno(String rowno) { + this.rowno = rowno; + } + + public String getSzxmid() { + return szxmid; + } + + public void setSzxmid(String szxmid) { + this.szxmid = szxmid; + } + + public String getDefitem50() { + return defitem50; + } + + public void setDefitem50(String defitem50) { + this.defitem50 = defitem50; + } + + public String getDefitem49() { + return defitem49; + } + + public void setDefitem49(String defitem49) { + this.defitem49 = defitem49; + } + + public String getDefitem42() { + return defitem42; + } + + public void setDefitem42(String defitem42) { + this.defitem42 = defitem42; + } + + public String getDefitem43() { + return defitem43; + } + + public void setDefitem43(String defitem43) { + this.defitem43 = defitem43; + } + + public String getDefitem44() { + return defitem44; + } + + public void setDefitem44(String defitem44) { + this.defitem44 = defitem44; + } + + public String getDefitem45() { + return defitem45; + } + + public void setDefitem45(String defitem45) { + this.defitem45 = defitem45; + } + + public String getDefitem46() { + return defitem46; + } + + public void setDefitem46(String defitem46) { + this.defitem46 = defitem46; + } + + public String getDefitem48() { + return defitem48; + } + + public void setDefitem48(String defitem48) { + this.defitem48 = defitem48; + } + + @Override + public int hashCode() { + return Objects.hash(amount, tablecode, rowno, szxmid, defitem50, defitem49, defitem42, defitem43, defitem44, defitem45, defitem46, defitem48); + } + + @Override + public String toString() { + return "{" + + "amount='" + amount + '\'' + + ", tablecode='" + tablecode + '\'' + + ", rowno='" + rowno + '\'' + + ", szxmid='" + szxmid + '\'' + + ", defitem50='" + defitem50 + '\'' + + ", defitem49='" + defitem49 + '\'' + + ", defitem42='" + defitem42 + '\'' + + ", defitem43='" + defitem43 + '\'' + + ", defitem44='" + defitem44 + '\'' + + ", defitem45='" + defitem45 + '\'' + + ", defitem46='" + defitem46 + '\'' + + ", defitem48='" + defitem48 + '\'' + + '}'; + } +} diff --git a/src/main/youhong_ai_jitu_src/jntchina/entity/BorrowOrderBodyYY.java b/src/main/youhong_ai_jitu_src/jntchina/entity/BorrowOrderBodyYY.java new file mode 100644 index 0000000..da43c82 --- /dev/null +++ b/src/main/youhong_ai_jitu_src/jntchina/entity/BorrowOrderBodyYY.java @@ -0,0 +1,167 @@ +package jntchina.entity; + +import java.io.Serializable; +import java.util.Objects; + +/** + * @Author Administrator + * @Description 借款单表体(明细表) + * @Date 2021/1/8 12:14 + */ +public class BorrowOrderBodyYY implements Serializable { + + private static final long serialVersionUID = 1L; + + private String amount; // 1000.00 //金额 + private String tablecode; // jk_busitem + private String rowno; // 10 + private String szxmid; // 收支项目 101005 电子面单号段费 + private String defitem50; // 发票类型 + private String defitem49; // 发票号码 + private String defitem42; // OA明细ID + private String defitem43; // 车牌号 + private String defitem44; // 仓库 + private String defitem45; // 国家 + private String defitem46; // 网点(成本中心) + private String defitem48; // SD3300301" //分摊部门 + private String deptidIsNeedConvert ; + private String defitem48IsNeedConvert; + + @Override + public String toString() { + return "BorrowOrderBodyYY{" + + "amount='" + amount + '\'' + + ", tablecode='" + tablecode + '\'' + + ", rowno='" + rowno + '\'' + + ", szxmid='" + szxmid + '\'' + + ", defitem50='" + defitem50 + '\'' + + ", defitem49='" + defitem49 + '\'' + + ", defitem42='" + defitem42 + '\'' + + ", defitem43='" + defitem43 + '\'' + + ", defitem44='" + defitem44 + '\'' + + ", defitem45='" + defitem45 + '\'' + + ", defitem46='" + defitem46 + '\'' + + ", defitem48='" + defitem48 + '\'' + + ", deptidIsNeedConvert='" + deptidIsNeedConvert + '\'' + + ", defitem48IsNeedConvert='" + defitem48IsNeedConvert + '\'' + + '}'; + } + + public String getDefitem48IsNeedConvert() { + return defitem48IsNeedConvert; + } + + public void setDefitem48IsNeedConvert(String defitem48IsNeedConvert) { + this.defitem48IsNeedConvert = defitem48IsNeedConvert; + } + + public String getDeptidIsNeedConvert() { + return deptidIsNeedConvert; + } + + public void setDeptidIsNeedConvert(String deptidIsNeedConvert) { + this.deptidIsNeedConvert = deptidIsNeedConvert; + } + + public String getAmount() { + return amount; + } + + public void setAmount(String amount) { + this.amount = amount; + } + + public String getTablecode() { + return tablecode; + } + + public void setTablecode(String tablecode) { + this.tablecode = tablecode; + } + + public String getRowno() { + return rowno; + } + + public void setRowno(String rowno) { + this.rowno = rowno; + } + + public String getSzxmid() { + return szxmid; + } + + public void setSzxmid(String szxmid) { + this.szxmid = szxmid; + } + + public String getDefitem50() { + return defitem50; + } + + public void setDefitem50(String defitem50) { + this.defitem50 = defitem50; + } + + public String getDefitem49() { + return defitem49; + } + + public void setDefitem49(String defitem49) { + this.defitem49 = defitem49; + } + + public String getDefitem42() { + return defitem42; + } + + public void setDefitem42(String defitem42) { + this.defitem42 = defitem42; + } + + public String getDefitem43() { + return defitem43; + } + + public void setDefitem43(String defitem43) { + this.defitem43 = defitem43; + } + + public String getDefitem44() { + return defitem44; + } + + public void setDefitem44(String defitem44) { + this.defitem44 = defitem44; + } + + public String getDefitem45() { + return defitem45; + } + + public void setDefitem45(String defitem45) { + this.defitem45 = defitem45; + } + + public String getDefitem46() { + return defitem46; + } + + public void setDefitem46(String defitem46) { + this.defitem46 = defitem46; + } + + public String getDefitem48() { + return defitem48; + } + + public void setDefitem48(String defitem48) { + this.defitem48 = defitem48; + } + + @Override + public int hashCode() { + return Objects.hash(amount, tablecode, rowno, szxmid, defitem50, defitem49, defitem42, defitem43, defitem44, defitem45, defitem46, defitem48); + } + +} diff --git a/src/main/youhong_ai_jitu_src/jntchina/entity/BorrowOrderYY.java b/src/main/youhong_ai_jitu_src/jntchina/entity/BorrowOrderYY.java new file mode 100644 index 0000000..8dd0ec4 --- /dev/null +++ b/src/main/youhong_ai_jitu_src/jntchina/entity/BorrowOrderYY.java @@ -0,0 +1,319 @@ +package jntchina.entity; + +import java.io.Serializable; +import java.util.List; +import java.util.Objects; + +/** + * @Author Administrator + * @Description 借款单 + * @Date 2021/1/16 11:23 + */ +public class BorrowOrderYY implements Serializable { + + private static final long serialVersionUID = 1L; + + private String uuid; //主键 + private String pk_org; // JTSDCN0001 //借款单位编码 + private String total; // 1000.00 //合计金额 + private String deptid; // SD3300101 //借款人部门 + private String djlxbm; // 263X-Cxx-DSJKD", //交易类型编码 263X-Cxx-DSJKD:对私借款单 263X-Cxx-DGJKD:对公预付/借款单 + private String djrq; // 2021-03-05 10:17:10", //单据日期 + private String payflag; //1", //支付状态 + private String paytarget; // 0" //收款对象(0=员工,1=供应商) + private String hbbm; // 供应商编码 + private String receiver; // yonyou88", //收款人 + private String jkbxr; // yonyou88 //借款报销人 + private String operator; // yonyou88 //录入人 + private String jsfs; // 3 //结算方式 3 网银 。。。 + private String fkyhzh; //付款银行账户 + private String skyhzh; //收款银行账户(员工) + private String custaccount; //收款银行账户(供应商) + private String jobid; //项目 + private String zy; //借款测试", //事由 + private String djzt; // 1", //单据状态 1 保存 + private String kjqj; // 03", //会计期间 + private String kjnd; // 2021", //会计年度 + private String zyx1; // CSBX21020501", //OA单据号 + private String zyx2; // 提交人 + private String zyx3; // OA核销单号 + private String zyx5; // CSBX21020501", // OARequestID + private String zyx8; // 银行付款备注 + private String zyx9; // OA流程标题 + private List jk_busitem; + + @Override + public String toString() { + return "BorrowOrderYY{" + + "uuid='" + uuid + '\'' + + ", pk_org='" + pk_org + '\'' + + ", total='" + total + '\'' + + ", deptid='" + deptid + '\'' + + ", djlxbm='" + djlxbm + '\'' + + ", djrq='" + djrq + '\'' + + ", payflag='" + payflag + '\'' + + ", paytarget='" + paytarget + '\'' + + ", hbbm='" + hbbm + '\'' + + ", receiver='" + receiver + '\'' + + ", jkbxr='" + jkbxr + '\'' + + ", operator='" + operator + '\'' + + ", jsfs='" + jsfs + '\'' + + ", fkyhzh='" + fkyhzh + '\'' + + ", skyhzh='" + skyhzh + '\'' + + ", custaccount='" + custaccount + '\'' + + ", jobid='" + jobid + '\'' + + ", zy='" + zy + '\'' + + ", djzt='" + djzt + '\'' + + ", kjqj='" + kjqj + '\'' + + ", kjnd='" + kjnd + '\'' + + ", zyx1='" + zyx1 + '\'' + + ", zyx2='" + zyx2 + '\'' + + ", zyx3='" + zyx3 + '\'' + + ", zyx5='" + zyx5 + '\'' + + ", zyx8='" + zyx8 + '\'' + + ", zyx9='" + zyx9 + '\'' + + ", jk_busitem=" + jk_busitem + + ", deptidIsNeedConvert='" + deptidIsNeedConvert + '\'' + + '}'; + } + + public String getDeptidIsNeedConvert() { + return deptidIsNeedConvert; + } + + public void setDeptidIsNeedConvert(String deptidIsNeedConvert) { + this.deptidIsNeedConvert = deptidIsNeedConvert; + } + + private String deptidIsNeedConvert ; + + public String getPk_org() { + return pk_org; + } + + public String getCustaccount() { + return custaccount; + } + + public String getZyx9() { + return zyx9; + } + + public void setZyx9(String zyx9) { + this.zyx9 = zyx9; + } + + public void setCustaccount(String custaccount) { + this.custaccount = custaccount; + } + + public String getHbbm() { + return hbbm; + } + + public String getUuid() { + return uuid; + } + + public void setUuid(String uuid) { + this.uuid = uuid; + } + + public void setHbbm(String hbbm) { + this.hbbm = hbbm; + } + + public void setPk_org(String pk_org) { + this.pk_org = pk_org; + } + + public String getTotal() { + return total; + } + + public void setTotal(String total) { + this.total = total; + } + + public String getDeptid() { + return deptid; + } + + public String getZyx8() { + return zyx8; + } + + public void setZyx8(String zyx8) { + this.zyx8 = zyx8; + } + + public void setDeptid(String deptid) { + this.deptid = deptid; + } + + public String getDjlxbm() { + return djlxbm; + } + + public void setDjlxbm(String djlxbm) { + this.djlxbm = djlxbm; + } + + public String getDjrq() { + return djrq; + } + + public void setDjrq(String djrq) { + this.djrq = djrq; + } + + public String getPayflag() { + return payflag; + } + + public void setPayflag(String payflag) { + this.payflag = payflag; + } + + public String getPaytarget() { + return paytarget; + } + + public void setPaytarget(String paytarget) { + this.paytarget = paytarget; + } + + public String getReceiver() { + return receiver; + } + + public void setReceiver(String receiver) { + this.receiver = receiver; + } + + public String getJkbxr() { + return jkbxr; + } + + public void setJkbxr(String jkbxr) { + this.jkbxr = jkbxr; + } + + public String getOperator() { + return operator; + } + + public void setOperator(String operator) { + this.operator = operator; + } + + public String getJsfs() { + return jsfs; + } + + public void setJsfs(String jsfs) { + this.jsfs = jsfs; + } + + public String getFkyhzh() { + return fkyhzh; + } + + public void setFkyhzh(String fkyhzh) { + this.fkyhzh = fkyhzh; + } + + public String getJobid() { + return jobid; + } + + public void setJobid(String jobid) { + this.jobid = jobid; + } + + public String getZy() { + return zy; + } + + public void setZy(String zy) { + this.zy = zy; + } + + public String getDjzt() { + return djzt; + } + + public void setDjzt(String djzt) { + this.djzt = djzt; + } + + public String getKjqj() { + return kjqj; + } + + public void setKjqj(String kjqj) { + this.kjqj = kjqj; + } + + public String getKjnd() { + return kjnd; + } + + public void setKjnd(String kjnd) { + this.kjnd = kjnd; + } + + public String getZyx1() { + return zyx1; + } + + public void setZyx1(String zyx1) { + this.zyx1 = zyx1; + } + + public String getZyx2() { + return zyx2; + } + + public void setZyx2(String zyx2) { + this.zyx2 = zyx2; + } + + public String getZyx3() { + return zyx3; + } + + public void setZyx3(String zyx3) { + this.zyx3 = zyx3; + } + + public String getZyx5() { + return zyx5; + } + + public void setZyx5(String zyx5) { + this.zyx5 = zyx5; + } + + public List getJk_busitem() { + return jk_busitem; + } + + public void setJk_busitem(List jk_busitem) { + this.jk_busitem = jk_busitem; + } + + @Override + public int hashCode() { + return Objects.hash(pk_org, total, deptid, djlxbm, djrq, payflag, paytarget, receiver, jkbxr, operator, jsfs, fkyhzh, jobid, zy, djzt, kjqj, kjnd, zyx1, zyx2, zyx3, zyx5, jk_busitem); + } + + public String getSkyhzh() { + return skyhzh; + } + + public void setSkyhzh(String skyhzh) { + this.skyhzh = skyhzh; + } + +} diff --git a/src/main/youhong_ai_jitu_src/jntchina/entity/ChangeInfo.java b/src/main/youhong_ai_jitu_src/jntchina/entity/ChangeInfo.java new file mode 100644 index 0000000..ad0ee2b --- /dev/null +++ b/src/main/youhong_ai_jitu_src/jntchina/entity/ChangeInfo.java @@ -0,0 +1,98 @@ +package jntchina.entity; + +import java.io.Serializable; + +/** + * @title: ChangeInfo + * @Author ycf + * @Date: 2021/10/28 14:41 + * @Version 1.0 + */ +public class ChangeInfo implements Serializable { + //企业id + private String mainid; + //日期 + private String rq; + //变更项目 + private String bgxm; + //变更前 + private String bgq; + //变更后 + private String bgh; + //附件 + private String fj; + //备注 + private String bz; + + public ChangeInfo() { + } + + @Override + public String toString() { + return "ChangeInfo{" + + "mainid='" + mainid + '\'' + + ", rq='" + rq + '\'' + + ", bgxm='" + bgxm + '\'' + + ", bgq='" + bgq + '\'' + + ", bgh='" + bgh + '\'' + + ", fj='" + fj + '\'' + + ", bz='" + bz + '\'' + + '}'; + } + + public String getMainid() { + return mainid; + } + + public void setMainid(String mainid) { + this.mainid = mainid; + } + + public String getRq() { + return rq; + } + + public void setRq(String rq) { + this.rq = rq; + } + + public String getBgxm() { + return bgxm; + } + + public void setBgxm(String bgxm) { + this.bgxm = bgxm; + } + + public String getBgq() { + return bgq; + } + + public void setBgq(String bgq) { + this.bgq = bgq; + } + + public String getBgh() { + return bgh; + } + + public void setBgh(String bgh) { + this.bgh = bgh; + } + + public String getFj() { + return fj; + } + + public void setFj(String fj) { + this.fj = fj; + } + + public String getBz() { + return bz; + } + + public void setBz(String bz) { + this.bz = bz; + } +} diff --git a/src/main/youhong_ai_jitu_src/jntchina/entity/EnterInfo.java b/src/main/youhong_ai_jitu_src/jntchina/entity/EnterInfo.java new file mode 100644 index 0000000..6f7f7e5 --- /dev/null +++ b/src/main/youhong_ai_jitu_src/jntchina/entity/EnterInfo.java @@ -0,0 +1,93 @@ +//package jntchina.entity; +// +///** +// * @title: EnterInfo +// * @Author ycf +// * @Date: 2021/11/5 09:07 +// * @Version 1.0 +// */ +//public class EnterInfo { +// //企业id +// private String mainid; +// //日期 +// private String rq; +// //变更项目 +// private String bgxm; +// //变更前 +// private String bgq; +// //变更后 +// private String bgh; +// //附件 +// private String fj; +// //备注 +// private String bz; +// +// @Override +// public String toString() { +// return "EnterInfo{" + +// "mainid='" + mainid + '\'' + +// ", rq='" + rq + '\'' + +// ", bgxm='" + bgxm + '\'' + +// ", bgq='" + bgq + '\'' + +// ", bgh='" + bgh + '\'' + +// ", fj='" + fj + '\'' + +// ", bz='" + bz + '\'' + +// '}'; +// } +// +// public String getMainid() { +// return mainid; +// } +// +// public void setMainid(String mainid) { +// this.mainid = mainid; +// } +// +// public String getRq() { +// return rq; +// } +// +// public void setRq(String rq) { +// this.rq = rq; +// } +// +// public String getBgxm() { +// return bgxm; +// } +// +// public void setBgxm(String bgxm) { +// this.bgxm = bgxm; +// } +// +// public String getBgq() { +// return bgq; +// } +// +// public void setBgq(String bgq) { +// this.bgq = bgq; +// } +// +// public String getBgh() { +// return bgh; +// } +// +// public void setBgh(String bgh) { +// this.bgh = bgh; +// } +// +// public String getFj() { +// return fj; +// } +// +// public void setFj(String fj) { +// this.fj = fj; +// } +// +// public String getBz() { +// return bz; +// } +// +// public void setBz(String bz) { +// this.bz = bz; +// } +//} diff --git a/src/main/youhong_ai_jitu_src/jntchina/entity/ErBxcontrast.java b/src/main/youhong_ai_jitu_src/jntchina/entity/ErBxcontrast.java new file mode 100644 index 0000000..9e851f9 --- /dev/null +++ b/src/main/youhong_ai_jitu_src/jntchina/entity/ErBxcontrast.java @@ -0,0 +1,82 @@ +package jntchina.entity; + + +/** + * @ClassName ErBxcontrast + * @Description 冲借款信息 + * @Author louh + * @Date 2022/5/5 15:04 + * @Version 1.0 + */ +public class ErBxcontrast { + private String jkbillcode; //ncc借款单号 + private String szxmid; //收支项目编码, 为空默认901017--团队活动费. + private String cxmny; //冲销金额 + private String jkitemid; //借款单明细id + private String fkitemid; //NC付款单明细id + + public ErBxcontrast(String jkbillcode, + String szxmid, + String cxmny, + String jkitemid, + String fkitemid) { + this.jkbillcode = jkbillcode; + this.szxmid = szxmid == "" ? "901017" : szxmid; + this.cxmny = cxmny; + this.jkitemid = jkitemid; + this.fkitemid = fkitemid; + } + + private ErBxcontrast(){} + + public String getJkbillcode() { + return jkbillcode; + } + + public void setJkbillcode(String jkbillcode) { + this.jkbillcode = jkbillcode; + } + + public String getSzxmid() { + return szxmid; + } + + public void setSzxmid(String szxmid) { + this.szxmid = szxmid == "" ? "901017" : szxmid; + } + + public String getCxmny() { + return cxmny; + } + + public void setCxmny(String cxmny) { + this.cxmny = cxmny; + } + + public String getJkitemid() { + return jkitemid; + } + + public void setJkitemid(String jkitemid) { + this.jkitemid = jkitemid; + } + + public String getFkitemid() { + return fkitemid; + } + + public void setFkitemid(String fkitemid) { + this.fkitemid = fkitemid; + } + + @Override + public String toString() { + return "ErBxcontrast{" + + "jkbillcode='" + jkbillcode + '\'' + + ", szxmid='" + szxmid + '\'' + + ", cxmny='" + cxmny + '\'' + + ", jkitemid='" + jkitemid + '\'' + + ", fkitemid='" + fkitemid + '\'' + + '}'; + } +} diff --git a/src/main/youhong_ai_jitu_src/jntchina/entity/ReimbursementOrder.java b/src/main/youhong_ai_jitu_src/jntchina/entity/ReimbursementOrder.java new file mode 100644 index 0000000..7291bfc --- /dev/null +++ b/src/main/youhong_ai_jitu_src/jntchina/entity/ReimbursementOrder.java @@ -0,0 +1,377 @@ +package jntchina.entity; + +import java.io.Serializable; +import java.util.List; +import java.util.Objects; + +/** + * @Author Administrator + * @Description 报销单 + * @Date 2021/1/16 11:23 + */ +public class ReimbursementOrder implements Serializable { + + private static final long serialVersionUID = 1L; + + private String uuid; //主键 + private String pk_org; // 报销单位 JTSDCN0001 + private String total; // 报销金额 金额由表体相应字段汇总得出 + private String deptid; // 部门 传输编码 + private String djlxbm; // 单据类型编码 对私报销单:264X-Cxx-DSBXD 对公报销单:264X-Cxx-DGBXD + private String djrq; // 单据日期 yyyy-mm-dd hh:mm:ss + private String payflag; // 支付状态 + private String paytarget; // 受款对象 0=员工,1=供应商,2=客户 + private String hbbm; // 收款人(供应商) + private String receiver; // 收款人(员工) + private String skyhzh; //收款银行账户(员工) + private String custaccount; //收款银行账户(供应商) + private String jkbxr; // 借款报销人 传输编码 + private String operator; // 录入人 + private String jsfs; // 结算方式 3 网银 + private String fkyhzh; // 单位银行账户 传输编码 + private String jobid; // 项目 + private String zy; // 报销事由 + private String kjqj; // 会计期间 + private String kjnd; // 会计年度 + private String fjzs; // 附件张数 需业务人员在OA上传附件同时填写附件张数后传数据到NCC + private String zyx1; // OA单据号 OA传过来,用于联查单据 + private String zyx2; // 提交人 提交人姓名 + private String zyx3; // OA核销单号 + private String zyx5; // OARequestID + + private String zyx8; // 银行付款备注 + private String zyx9; // OA流程标题 + + + + private List er_busitem; + private List er_bxcontrast; + + public String getPk_org() { + return pk_org; + } + + public String getHbbm() { + return hbbm; + } + + public void setHbbm(String hbbm) { + this.hbbm = hbbm; + } + + public void setPk_org(String pk_org) { + this.pk_org = pk_org; + } + + public String getZyx9() { + return zyx9; + } + + public void setZyx9(String zyx9) { + this.zyx9 = zyx9; + } + + public String getZyx8() { + return zyx8; + } + public String getSkyhzh() { + return skyhzh; + } + + public void setSkyhzh(String skyhzh) { + this.skyhzh = skyhzh; + } + public String getCustaccount() { + return custaccount; + } + + public void setCustaccount(String custaccount) { + this.custaccount = custaccount; + } + + public String getUuid() { + return uuid; + } + + public void setUuid(String uuid) { + this.uuid = uuid; + } + + public void setZyx8(String zyx8) { + this.zyx8 = zyx8; + } + + public String getTotal() { + return total; + } + + public void setTotal(String total) { + this.total = total; + } + + public String getDeptid() { + return deptid; + } + + public void setDeptid(String deptid) { + this.deptid = deptid; + } + + public String getDjlxbm() { + return djlxbm; + } + + public void setDjlxbm(String djlxbm) { + this.djlxbm = djlxbm; + } + + public String getDjrq() { + return djrq; + } + + public void setDjrq(String djrq) { + this.djrq = djrq; + } + + public String getPayflag() { + return payflag; + } + + public void setPayflag(String payflag) { + this.payflag = payflag; + } + + public String getPaytarget() { + return paytarget; + } + + public void setPaytarget(String paytarget) { + this.paytarget = paytarget; + } + + public String getReceiver() { + return receiver; + } + + public void setReceiver(String receiver) { + this.receiver = receiver; + } + + public String getJkbxr() { + return jkbxr; + } + + public void setJkbxr(String jkbxr) { + this.jkbxr = jkbxr; + } + + public String getOperator() { + return operator; + } + + public void setOperator(String operator) { + this.operator = operator; + } + + public String getJsfs() { + return jsfs; + } + + public void setJsfs(String jsfs) { + this.jsfs = jsfs; + } + + public String getFkyhzh() { + return fkyhzh; + } + + public void setFkyhzh(String fkyhzh) { + this.fkyhzh = fkyhzh; + } + + public String getJobid() { + return jobid; + } + + public void setJobid(String jobid) { + this.jobid = jobid; + } + + public String getZy() { + return zy; + } + + public void setZy(String zy) { + this.zy = zy; + } + + public String getKjqj() { + return kjqj; + } + + public void setKjqj(String kjqj) { + this.kjqj = kjqj; + } + + public String getKjnd() { + return kjnd; + } + + public void setKjnd(String kjnd) { + this.kjnd = kjnd; + } + + public String getFjzs() { + return fjzs; + } + + public void setFjzs(String fjzs) { + this.fjzs = fjzs; + } + + public String getZyx1() { + return zyx1; + } + + public void setZyx1(String zyx1) { + this.zyx1 = zyx1; + } + + public String getZyx2() { + return zyx2; + } + + public void setZyx2(String zyx2) { + this.zyx2 = zyx2; + } + + public String getZyx3() { + return zyx3; + } + + public void setZyx3(String zyx3) { + this.zyx3 = zyx3; + } + + public String getZyx5() { + return zyx5; + } + + public void setZyx5(String zyx5) { + this.zyx5 = zyx5; + } + + public List getEr_busitem() { + return er_busitem; + } + + public void setEr_busitem(List er_busitem) { + this.er_busitem = er_busitem; + } + + public List getEr_bxcontrast() { + return er_bxcontrast; + } + + public void setEr_bxcontrast(List er_bxcontrast) { + this.er_bxcontrast = er_bxcontrast; + } + + @Override + public boolean equals(Object o) { + if (this == o) return true; + if (o == null || getClass() != o.getClass()) return false; + ReimbursementOrder that = (ReimbursementOrder) o; + return Objects.equals(pk_org, that.pk_org) && + Objects.equals(total, that.total) && + Objects.equals(deptid, that.deptid) && + Objects.equals(djlxbm, that.djlxbm) && + Objects.equals(djrq, that.djrq) && + Objects.equals(payflag, that.payflag) && + Objects.equals(paytarget, that.paytarget) && + Objects.equals(receiver, that.receiver) && + Objects.equals(jkbxr, that.jkbxr) && + Objects.equals(operator, that.operator) && + Objects.equals(jsfs, that.jsfs) && + Objects.equals(fkyhzh, that.fkyhzh) && + Objects.equals(jobid, that.jobid) && + Objects.equals(zy, that.zy) && + Objects.equals(kjqj, that.kjqj) && + Objects.equals(kjnd, that.kjnd) && + Objects.equals(fjzs, that.fjzs) && + Objects.equals(zyx1, that.zyx1) && + Objects.equals(zyx2, that.zyx2) && + Objects.equals(zyx3, that.zyx3) && + Objects.equals(zyx5, that.zyx5) && + Objects.equals(er_busitem, that.er_busitem); + } + + @Override + public int hashCode() { + return Objects.hash(pk_org, total, deptid, djlxbm, djrq, payflag, paytarget, receiver, jkbxr, operator, jsfs, fkyhzh, jobid, zy, kjqj, kjnd, fjzs, zyx1, zyx2, zyx3, zyx5, er_busitem); + } + +// @Override +// public String toString() { +// return "{" + +// "pk_org='" + pk_org + '\'' + +// ", total='" + total + '\'' + +// ", deptid='" + deptid + '\'' + +// ", djlxbm='" + djlxbm + '\'' + +// ", djrq='" + djrq + '\'' + +// ", payflag='" + payflag + '\'' + +// ", paytarget='" + paytarget + '\'' + +// ", receiver='" + receiver + '\'' + +// ", jkbxr='" + jkbxr + '\'' + +// ", operator='" + operator + '\'' + +// ", jsfs='" + jsfs + '\'' + +// ", fkyhzh='" + fkyhzh + '\'' + +// ", jobid='" + jobid + '\'' + +// ", zy='" + zy + '\'' + +// ", kjqj='" + kjqj + '\'' + +// ", kjnd='" + kjnd + '\'' + +// ", fjzs='" + fjzs + '\'' + +// ", zyx1='" + zyx1 + '\'' + +// ", zyx2='" + zyx2 + '\'' + +// ", zyx3='" + zyx3 + '\'' + +// ", zyx5='" + zyx5 + '\'' + +// ", er_busitem=" + er_busitem + +// '}'; +// } + + + @Override + public String toString() { + return "ReimbursementOrder{" + + "uuid='" + uuid + '\'' + + ", pk_org='" + pk_org + '\'' + + ", total='" + total + '\'' + + ", deptid='" + deptid + '\'' + + ", djlxbm='" + djlxbm + '\'' + + ", djrq='" + djrq + '\'' + + ", payflag='" + payflag + '\'' + + ", paytarget='" + paytarget + '\'' + + ", hbbm='" + hbbm + '\'' + + ", receiver='" + receiver + '\'' + + ", skyhzh='" + skyhzh + '\'' + + ", custaccount='" + custaccount + '\'' + + ", jkbxr='" + jkbxr + '\'' + + ", operator='" + operator + '\'' + + ", jsfs='" + jsfs + '\'' + + ", fkyhzh='" + fkyhzh + '\'' + + ", jobid='" + jobid + '\'' + + ", zy='" + zy + '\'' + + ", kjqj='" + kjqj + '\'' + + ", kjnd='" + kjnd + '\'' + + ", fjzs='" + fjzs + '\'' + + ", zyx1='" + zyx1 + '\'' + + ", zyx2='" + zyx2 + '\'' + + ", zyx3='" + zyx3 + '\'' + + ", zyx5='" + zyx5 + '\'' + + ", zyx8='" + zyx8 + '\'' + + ", zyx9='" + zyx9 + '\'' + + ", er_busitem=" + er_busitem + + ", er_bxcontrast=" + er_bxcontrast + + '}'; + } +} diff --git a/src/main/youhong_ai_jitu_src/jntchina/entity/ReimbursementOrderBody.java b/src/main/youhong_ai_jitu_src/jntchina/entity/ReimbursementOrderBody.java new file mode 100644 index 0000000..117c1d0 --- /dev/null +++ b/src/main/youhong_ai_jitu_src/jntchina/entity/ReimbursementOrderBody.java @@ -0,0 +1,238 @@ +package jntchina.entity; + +import java.io.Serializable; +import java.util.Objects; + +/** + * @Author Administrator + * @Description 报销单表体(明细表) + * @Date 2021/1/8 12:14 + */ +public class ReimbursementOrderBody implements Serializable { + + private static final long serialVersionUID = 1L; + + private String jobid; // 项目 + private String deptid; // 报销部门 + private String amount; // 含税金额 + private String tax_rate; // 税率 3% + private String tax_amount; // 税额 + private String tni_amount; // 无税金额 + private String defitem36; // 发票金额 + private String tablecode; // 默认固定值 arap_bxbusitem + private String rowno; + private String szxmid; // 收支项目 0101 汽车费用 + private String fpdm; //发票代码 + private String fphm; //发票号码 + private String fplxpk; //发票类型 + private String defitem46; // 网点(成本中心) + private String defitem45; // 国家 + private String defitem44; // 仓库 + private String defitem43; // 车牌号 + private String defitem42; // OA明细行ID + private String defitem48; // 分摊部门  + + public String getJobid() { + return jobid; + } + + public void setJobid(String jobid) { + this.jobid = jobid; + } + + public String getDeptid() { + return deptid; + } + + public void setDeptid(String deptid) { + this.deptid = deptid; + } + + public String getFplxpk() { + return fplxpk; + } + + public void setFplxpk(String fplxpk) { + this.fplxpk = fplxpk; + } + + public String getAmount() { + return amount; + } + + public void setAmount(String amount) { + this.amount = amount; + } + + public String getDefitem36() { + return defitem36; + } + + public void setDefitem36(String defitem36) { + this.defitem36 = defitem36; + } + + public String getTax_rate() { + return tax_rate; + } + + public void setTax_rate(String tax_rate) { + this.tax_rate = tax_rate; + } + + public String getTax_amount() { + return tax_amount; + } + + public void setTax_amount(String tax_amount) { + this.tax_amount = tax_amount; + } + + public String getTni_amount() { + return tni_amount; + } + + public void setTni_amount(String tni_amount) { + this.tni_amount = tni_amount; + } + + public String getTablecode() { + return tablecode; + } + + public void setTablecode(String tablecode) { + this.tablecode = tablecode; + } + + public String getRowno() { + return rowno; + } + + public void setRowno(String rowno) { + this.rowno = rowno; + } + + public String getSzxmid() { + return szxmid; + } + + public void setSzxmid(String szxmid) { + this.szxmid = szxmid; + } + + public String getDefitem46() { + return defitem46; + } + + public void setDefitem46(String defitem46) { + this.defitem46 = defitem46; + } + + public String getDefitem45() { + return defitem45; + } + + public void setDefitem45(String defitem45) { + this.defitem45 = defitem45; + } + + public String getDefitem44() { + return defitem44; + } + + public void setDefitem44(String defitem44) { + this.defitem44 = defitem44; + } + + public String getDefitem43() { + return defitem43; + } + + public void setDefitem43(String defitem43) { + this.defitem43 = defitem43; + } + + public String getDefitem42() { + return defitem42; + } + + public void setDefitem42(String defitem42) { + this.defitem42 = defitem42; + } + + public String getFpdm() { + return fpdm; + } + + public void setFpdm(String fpdm) { + this.fpdm = fpdm; + } + + public String getFphm() { + return fphm; + } + + public void setFphm(String fphm) { + this.fphm = fphm; + } + + public String getDefitem48() { + return defitem48; + } + + public void setDefitem48(String defitem48) { + this.defitem48 = defitem48; + } + + @Override + public boolean equals(Object o) { + if (this == o) return true; + if (o == null || getClass() != o.getClass()) return false; + ReimbursementOrderBody that = (ReimbursementOrderBody) o; + return Objects.equals(jobid, that.jobid) && + Objects.equals(deptid, that.deptid) && + Objects.equals(amount, that.amount) && + Objects.equals(tax_rate, that.tax_rate) && + Objects.equals(tax_amount, that.tax_amount) && + Objects.equals(tni_amount, that.tni_amount) && + Objects.equals(tablecode, that.tablecode) && + Objects.equals(rowno, that.rowno) && + Objects.equals(szxmid, that.szxmid) && + Objects.equals(fpdm, that.fpdm) && + Objects.equals(fphm, that.fphm) && + Objects.equals(defitem46, that.defitem46) && + Objects.equals(defitem45, that.defitem45) && + Objects.equals(defitem44, that.defitem44) && + Objects.equals(defitem43, that.defitem43) && + Objects.equals(defitem42, that.defitem42) && + Objects.equals(defitem48, that.defitem48); + } + + @Override + public int hashCode() { + return Objects.hash(jobid, deptid, amount, tax_rate, tax_amount, tni_amount, tablecode, rowno, szxmid, fpdm, fphm, defitem46, defitem45, defitem44, defitem43, defitem42, defitem48); + } + + @Override + public String toString() { + return "{" + + "jobid='" + jobid + '\'' + + ", deptid='" + deptid + '\'' + + ", amount='" + amount + '\'' + + ", tax_rate='" + tax_rate + '\'' + + ", tax_amount='" + tax_amount + '\'' + + ", tni_amount='" + tni_amount + '\'' + + ", tablecode='" + tablecode + '\'' + + ", rowno='" + rowno + '\'' + + ", szxmid='" + szxmid + '\'' + + ", fpdm='" + fpdm + '\'' + + ", fphm='" + fphm + '\'' + + ", defitem46='" + defitem46 + '\'' + + ", defitem45='" + defitem45 + '\'' + + ", defitem44='" + defitem44 + '\'' + + ", defitem43='" + defitem43 + '\'' + + ", defitem42='" + defitem42 + '\'' + + ", defitem48='" + defitem48 + '\'' + + '}'; + } +} diff --git a/src/main/youhong_ai_jitu_src/jntchina/entity/ReimbursementOrderBodyYY.java b/src/main/youhong_ai_jitu_src/jntchina/entity/ReimbursementOrderBodyYY.java new file mode 100644 index 0000000..06ef61c --- /dev/null +++ b/src/main/youhong_ai_jitu_src/jntchina/entity/ReimbursementOrderBodyYY.java @@ -0,0 +1,252 @@ +package jntchina.entity; + +import java.io.Serializable; +import java.util.Objects; + +/** + * @Author Administrator + * @Description 报销单表体(明细表) + * @Date 2021/1/8 12:14 + */ +public class ReimbursementOrderBodyYY implements Serializable { + + private static final long serialVersionUID = 1L; + + private String jobid; // 项目 + private String deptid; // 报销部门 + private String amount; // 含税金额 + private String tax_rate; // 税率 3% + private String tax_amount; // 税额 + private String tni_amount; // 无税金额 + private String defitem36; // 发票金额 + private String tablecode; // 默认固定值 arap_bxbusitem + private String rowno; + private String szxmid; // 收支项目 0101 汽车费用 + private String fpdm; //发票代码 + private String fphm; //发票号码 + private String fplxpk; //发票类型 + private String defitem46; // 网点(成本中心) + private String defitem45; // 国家 + private String defitem44; // 仓库 + private String defitem43; // 车牌号 + private String defitem42; // OA明细行ID + private String defitem48; // 分摊部门  + + @Override + public String toString() { + return "ReimbursementOrderBodyYY{" + + "jobid='" + jobid + '\'' + + ", deptid='" + deptid + '\'' + + ", amount='" + amount + '\'' + + ", tax_rate='" + tax_rate + '\'' + + ", tax_amount='" + tax_amount + '\'' + + ", tni_amount='" + tni_amount + '\'' + + ", defitem36='" + defitem36 + '\'' + + ", tablecode='" + tablecode + '\'' + + ", rowno='" + rowno + '\'' + + ", szxmid='" + szxmid + '\'' + + ", fpdm='" + fpdm + '\'' + + ", fphm='" + fphm + '\'' + + ", fplxpk='" + fplxpk + '\'' + + ", defitem46='" + defitem46 + '\'' + + ", defitem45='" + defitem45 + '\'' + + ", defitem44='" + defitem44 + '\'' + + ", defitem43='" + defitem43 + '\'' + + ", defitem42='" + defitem42 + '\'' + + ", defitem48='" + defitem48 + '\'' + + ", deptidIsNeedConvert='" + deptidIsNeedConvert + '\'' + + '}'; + } + + public String getDeptidIsNeedConvert() { + return deptidIsNeedConvert; + } + + public void setDeptidIsNeedConvert(String deptidIsNeedConvert) { + this.deptidIsNeedConvert = deptidIsNeedConvert; + } + + private String deptidIsNeedConvert ; + + public String getJobid() { + return jobid; + } + + public void setJobid(String jobid) { + this.jobid = jobid; + } + + public String getDeptid() { + return deptid; + } + + public void setDeptid(String deptid) { + this.deptid = deptid; + } + + public String getFplxpk() { + return fplxpk; + } + + public void setFplxpk(String fplxpk) { + this.fplxpk = fplxpk; + } + + public String getAmount() { + return amount; + } + + public void setAmount(String amount) { + this.amount = amount; + } + + public String getDefitem36() { + return defitem36; + } + + public void setDefitem36(String defitem36) { + this.defitem36 = defitem36; + } + + public String getTax_rate() { + return tax_rate; + } + + public void setTax_rate(String tax_rate) { + this.tax_rate = tax_rate; + } + + public String getTax_amount() { + return tax_amount; + } + + public void setTax_amount(String tax_amount) { + this.tax_amount = tax_amount; + } + + public String getTni_amount() { + return tni_amount; + } + + public void setTni_amount(String tni_amount) { + this.tni_amount = tni_amount; + } + + public String getTablecode() { + return tablecode; + } + + public void setTablecode(String tablecode) { + this.tablecode = tablecode; + } + + public String getRowno() { + return rowno; + } + + public void setRowno(String rowno) { + this.rowno = rowno; + } + + public String getSzxmid() { + return szxmid; + } + + public void setSzxmid(String szxmid) { + this.szxmid = szxmid; + } + + public String getDefitem46() { + return defitem46; + } + + public void setDefitem46(String defitem46) { + this.defitem46 = defitem46; + } + + public String getDefitem45() { + return defitem45; + } + + public void setDefitem45(String defitem45) { + this.defitem45 = defitem45; + } + + public String getDefitem44() { + return defitem44; + } + + public void setDefitem44(String defitem44) { + this.defitem44 = defitem44; + } + + public String getDefitem43() { + return defitem43; + } + + public void setDefitem43(String defitem43) { + this.defitem43 = defitem43; + } + + public String getDefitem42() { + return defitem42; + } + + public void setDefitem42(String defitem42) { + this.defitem42 = defitem42; + } + + public String getFpdm() { + return fpdm; + } + + public void setFpdm(String fpdm) { + this.fpdm = fpdm; + } + + public String getFphm() { + return fphm; + } + + public void setFphm(String fphm) { + this.fphm = fphm; + } + + public String getDefitem48() { + return defitem48; + } + + public void setDefitem48(String defitem48) { + this.defitem48 = defitem48; + } + + @Override + public boolean equals(Object o) { + if (this == o) return true; + if (o == null || getClass() != o.getClass()) return false; + ReimbursementOrderBodyYY that = (ReimbursementOrderBodyYY) o; + return Objects.equals(jobid, that.jobid) && + Objects.equals(deptid, that.deptid) && + Objects.equals(amount, that.amount) && + Objects.equals(tax_rate, that.tax_rate) && + Objects.equals(tax_amount, that.tax_amount) && + Objects.equals(tni_amount, that.tni_amount) && + Objects.equals(tablecode, that.tablecode) && + Objects.equals(rowno, that.rowno) && + Objects.equals(szxmid, that.szxmid) && + Objects.equals(fpdm, that.fpdm) && + Objects.equals(fphm, that.fphm) && + Objects.equals(defitem46, that.defitem46) && + Objects.equals(defitem45, that.defitem45) && + Objects.equals(defitem44, that.defitem44) && + Objects.equals(defitem43, that.defitem43) && + Objects.equals(defitem42, that.defitem42) && + Objects.equals(defitem48, that.defitem48); + } + + @Override + public int hashCode() { + return Objects.hash(jobid, deptid, amount, tax_rate, tax_amount, tni_amount, tablecode, rowno, szxmid, fpdm, fphm, defitem46, defitem45, defitem44, defitem43, defitem42, defitem48); + } + +} diff --git a/src/main/youhong_ai_jitu_src/jntchina/entity/ReimbursementOrderYY.java b/src/main/youhong_ai_jitu_src/jntchina/entity/ReimbursementOrderYY.java new file mode 100644 index 0000000..167aa79 --- /dev/null +++ b/src/main/youhong_ai_jitu_src/jntchina/entity/ReimbursementOrderYY.java @@ -0,0 +1,358 @@ +package jntchina.entity; + +import java.io.Serializable; +import java.util.List; +import java.util.Objects; + +/** + * @Author Administrator + * @Description 报销单 + * @Date 2021/1/16 11:23 + */ +public class ReimbursementOrderYY implements Serializable { + + private static final long serialVersionUID = 1L; + + private String uuid; //主键 + private String pk_org; // 报销单位 JTSDCN0001 + private String total; // 报销金额 金额由表体相应字段汇总得出 + private String deptid; // 部门 传输编码 + private String djlxbm; // 单据类型编码 对私报销单:264X-Cxx-DSBXD 对公报销单:264X-Cxx-DGBXD + private String djrq; // 单据日期 yyyy-mm-dd hh:mm:ss + private String payflag; // 支付状态 + private String paytarget; // 受款对象 0=员工,1=供应商,2=客户 + private String hbbm; // 收款人(供应商) + private String receiver; // 收款人(员工) + private String skyhzh; //收款银行账户(员工) + private String custaccount; //收款银行账户(供应商) + private String jkbxr; // 借款报销人 传输编码 + private String operator; // 录入人 + private String jsfs; // 结算方式 3 网银 + private String fkyhzh; // 单位银行账户 传输编码 + private String jobid; // 项目 + private String zy; // 报销事由 + private String kjqj; // 会计期间 + private String kjnd; // 会计年度 + private String fjzs; // 附件张数 需业务人员在OA上传附件同时填写附件张数后传数据到NCC + private String zyx1; // OA单据号 OA传过来,用于联查单据 + private String zyx2; // 提交人 提交人姓名 + private String zyx3; // OA核销单号 + private String zyx5; // OARequestID + + private String zyx8; // 银行付款备注 + private String zyx9; // OA流程标题 + private String deptidIsNeedConvert; + + + + private List er_busitem; + private List er_bxcontrast; + + public List getEr_bxcontrast() { + return er_bxcontrast; + } + + public void setEr_bxcontrast(List er_bxcontrast) { + this.er_bxcontrast = er_bxcontrast; + } + + public String getPk_org() { + return pk_org; + } + + @Override + public String toString() { + return "ReimbursementOrderYY{" + + "uuid='" + uuid + '\'' + + ", pk_org='" + pk_org + '\'' + + ", total='" + total + '\'' + + ", deptid='" + deptid + '\'' + + ", djlxbm='" + djlxbm + '\'' + + ", djrq='" + djrq + '\'' + + ", payflag='" + payflag + '\'' + + ", paytarget='" + paytarget + '\'' + + ", hbbm='" + hbbm + '\'' + + ", receiver='" + receiver + '\'' + + ", skyhzh='" + skyhzh + '\'' + + ", custaccount='" + custaccount + '\'' + + ", jkbxr='" + jkbxr + '\'' + + ", operator='" + operator + '\'' + + ", jsfs='" + jsfs + '\'' + + ", fkyhzh='" + fkyhzh + '\'' + + ", jobid='" + jobid + '\'' + + ", zy='" + zy + '\'' + + ", kjqj='" + kjqj + '\'' + + ", kjnd='" + kjnd + '\'' + + ", fjzs='" + fjzs + '\'' + + ", zyx1='" + zyx1 + '\'' + + ", zyx2='" + zyx2 + '\'' + + ", zyx3='" + zyx3 + '\'' + + ", zyx5='" + zyx5 + '\'' + + ", zyx8='" + zyx8 + '\'' + + ", zyx9='" + zyx9 + '\'' + + ", deptidIsNeedConvert='" + deptidIsNeedConvert + '\'' + + ", er_busitem=" + er_busitem + + '}'; + } + + public String getDeptidIsNeedConvert() { + return deptidIsNeedConvert; + } + + public void setDeptidIsNeedConvert(String deptidIsNeedConvert) { + this.deptidIsNeedConvert = deptidIsNeedConvert; + } + + public String getHbbm() { + return hbbm; + } + + public void setHbbm(String hbbm) { + this.hbbm = hbbm; + } + + public void setPk_org(String pk_org) { + this.pk_org = pk_org; + } + + public String getZyx9() { + return zyx9; + } + + public void setZyx9(String zyx9) { + this.zyx9 = zyx9; + } + + public String getZyx8() { + return zyx8; + } + public String getSkyhzh() { + return skyhzh; + } + + public void setSkyhzh(String skyhzh) { + this.skyhzh = skyhzh; + } + public String getCustaccount() { + return custaccount; + } + + public void setCustaccount(String custaccount) { + this.custaccount = custaccount; + } + + public String getUuid() { + return uuid; + } + + public void setUuid(String uuid) { + this.uuid = uuid; + } + + public void setZyx8(String zyx8) { + this.zyx8 = zyx8; + } + + public String getTotal() { + return total; + } + + public void setTotal(String total) { + this.total = total; + } + + public String getDeptid() { + return deptid; + } + + public void setDeptid(String deptid) { + this.deptid = deptid; + } + + public String getDjlxbm() { + return djlxbm; + } + + public void setDjlxbm(String djlxbm) { + this.djlxbm = djlxbm; + } + + public String getDjrq() { + return djrq; + } + + public void setDjrq(String djrq) { + this.djrq = djrq; + } + + public String getPayflag() { + return payflag; + } + + public void setPayflag(String payflag) { + this.payflag = payflag; + } + + public String getPaytarget() { + return paytarget; + } + + public void setPaytarget(String paytarget) { + this.paytarget = paytarget; + } + + public String getReceiver() { + return receiver; + } + + public void setReceiver(String receiver) { + this.receiver = receiver; + } + + public String getJkbxr() { + return jkbxr; + } + + public void setJkbxr(String jkbxr) { + this.jkbxr = jkbxr; + } + + public String getOperator() { + return operator; + } + + public void setOperator(String operator) { + this.operator = operator; + } + + public String getJsfs() { + return jsfs; + } + + public void setJsfs(String jsfs) { + this.jsfs = jsfs; + } + + public String getFkyhzh() { + return fkyhzh; + } + + public void setFkyhzh(String fkyhzh) { + this.fkyhzh = fkyhzh; + } + + public String getJobid() { + return jobid; + } + + public void setJobid(String jobid) { + this.jobid = jobid; + } + + public String getZy() { + return zy; + } + + public void setZy(String zy) { + this.zy = zy; + } + + public String getKjqj() { + return kjqj; + } + + public void setKjqj(String kjqj) { + this.kjqj = kjqj; + } + + public String getKjnd() { + return kjnd; + } + + public void setKjnd(String kjnd) { + this.kjnd = kjnd; + } + + public String getFjzs() { + return fjzs; + } + + public void setFjzs(String fjzs) { + this.fjzs = fjzs; + } + + public String getZyx1() { + return zyx1; + } + + public void setZyx1(String zyx1) { + this.zyx1 = zyx1; + } + + public String getZyx2() { + return zyx2; + } + + public void setZyx2(String zyx2) { + this.zyx2 = zyx2; + } + + public String getZyx3() { + return zyx3; + } + + public void setZyx3(String zyx3) { + this.zyx3 = zyx3; + } + + public String getZyx5() { + return zyx5; + } + + public void setZyx5(String zyx5) { + this.zyx5 = zyx5; + } + + public List getEr_busitem() { + return er_busitem; + } + + public void setEr_busitem(List er_busitem) { + this.er_busitem = er_busitem; + } + + @Override + public boolean equals(Object o) { + if (this == o) return true; + if (o == null || getClass() != o.getClass()) return false; + ReimbursementOrderYY that = (ReimbursementOrderYY) o; + return Objects.equals(pk_org, that.pk_org) && + Objects.equals(total, that.total) && + Objects.equals(deptid, that.deptid) && + Objects.equals(djlxbm, that.djlxbm) && + Objects.equals(djrq, that.djrq) && + Objects.equals(payflag, that.payflag) && + Objects.equals(paytarget, that.paytarget) && + Objects.equals(receiver, that.receiver) && + Objects.equals(jkbxr, that.jkbxr) && + Objects.equals(operator, that.operator) && + Objects.equals(jsfs, that.jsfs) && + Objects.equals(fkyhzh, that.fkyhzh) && + Objects.equals(jobid, that.jobid) && + Objects.equals(zy, that.zy) && + Objects.equals(kjqj, that.kjqj) && + Objects.equals(kjnd, that.kjnd) && + Objects.equals(fjzs, that.fjzs) && + Objects.equals(zyx1, that.zyx1) && + Objects.equals(zyx2, that.zyx2) && + Objects.equals(zyx3, that.zyx3) && + Objects.equals(zyx5, that.zyx5) && + Objects.equals(er_busitem, that.er_busitem); + } + + @Override + public int hashCode() { + return Objects.hash(pk_org, total, deptid, djlxbm, djrq, payflag, paytarget, receiver, jkbxr, operator, jsfs, fkyhzh, jobid, zy, kjqj, kjnd, fjzs, zyx1, zyx2, zyx3, zyx5, er_busitem); + } + +} diff --git a/src/main/youhong_ai_jitu_src/jntchina/schedule/JieKuanBuLu.java b/src/main/youhong_ai_jitu_src/jntchina/schedule/JieKuanBuLu.java new file mode 100644 index 0000000..abf2cf3 --- /dev/null +++ b/src/main/youhong_ai_jitu_src/jntchina/schedule/JieKuanBuLu.java @@ -0,0 +1,127 @@ +package jntchina.schedule; + +import selfdev.util.base.BaseUtil; +import selfdev.util.log.LogTool; +import weaver.conn.RecordSet; +import weaver.general.Util; +import weaver.interfaces.schedule.BaseCronJob; + +import java.util.ArrayList; +import java.util.List; + +/** + * 借款台账补录同步器 (仅同步主表) + * @title: JieKuanBuLu + * @Author LJL + * @Date: 2022/6/8 16:14 + * @Version 1.0 + */ +public class JieKuanBuLu extends BaseCronJob { + @Override + public void execute() { + try { + LogTool log = new LogTool("/log/schedule/", false); + String sql = ""; + log.writeLog("借款同步台账! START!"); + List lcbhArr = new ArrayList<>(); + RecordSet rs = new RecordSet(); + rs.execute("select lcbh from uf_jktz"); + while (rs.next()) { + lcbhArr.add(rs.getString("lcbh")); + } + rs.execute("select lcbh,yhkje,ycdje,whkje,jkje from uf_ygjktz_lsk"); + while (rs.next()) { + String lcbh = rs.getString("lcbh"); + String yhkje = Util.null2String(rs.getString("yhkje"));//已还款金额 + String ycdje = Util.null2String(rs.getString("ycdje"));//已冲抵金额 + String whkje = Util.null2String(rs.getString("whkje"));//未还款金额 + String jkje = Util.null2String(rs.getString("jkje"));//未还款金额 + + boolean contains = lcbhArr.contains(lcbh); + if (contains) { + continue; + } else { + String tablenem = BaseUtil.getBaseInfoByParm("TABLENAME", "workflow_bill", "1", "1", " and id in (select formid from workflow_base where id=(select WORKFLOWID from workflow_requestbase where REQUESTMARK='" + lcbh + "'))"); + if (tablenem.equals("")) { + RecordSet updateRs = new RecordSet(); + updateRs.executeUpdate("update uf_ygjktz_lsk set sjsfcggxzzsk = '1',gxzskstsxx = '未能通过流程编号找到对应表名,请检查编号是否正确' where lcbh = '" + lcbh + "'"); + continue; + } else { + RecordSet rs2 = new RecordSet(); + sql = "select t1.*,t2.REQUESTNAME from " + tablenem + " t1 left join workflow_requestbase t2 on t1.requestid = t2.requestid where lcbh = '" + lcbh + "'"; + rs2.execute(sql); + if (rs2.next()) { + String xm = rs2.getString("xm");//姓名 + String bm = rs2.getString("bm");//部门 + String cjrq = rs2.getString("cjrq");//申请日期 +// String jkje = rs2.getString("jkje");//借款金额 + String fb = rs2.getString("fb");//分部 + String xglc = rs2.getString("requestid");//相关流程 +// String yhkje = "0.00";//已还款金额 +// String ycdje = "0.00";//已冲抵金额 +// String whkje = rs2.getString("jkje");//未还款金额 + String yjhksj = rs2.getString("yjhkrq");//预计还款日期 + String gsmc = rs2.getString("gsmc");//付款公司名称 + String lcbt = rs2.getString("REQUESTNAME");//流程标题 + String nccjkdh = rs2.getString("nccfkdh");//NCC单号 + sql = "insert into uf_jktz(xm,lcbh,bm,cjrq,jkje,fb,xglc,yhkje,ycdje,whkje,yjhksj,gsmc,lcbt,nccjkdh,FORMMODEID) values(" + + "'" + xm + "'," + + "'" + lcbh + "'," + + "'" + bm + "'," + + "'" + cjrq + "'," + + "'" + jkje + "'," + + "'" + fb + "'," + + "'" + xglc + "'," + + "'" + yhkje + "'," + + "'" + ycdje + "'," + + "'" + whkje + "'," + + "'" + yjhksj + "'," + + "'" + gsmc + "'," + + "'" + lcbt + "'," + + "'" + nccjkdh + "'," + + "'" + 53001 + "'" + + ")"; + log.writeLog("insertMain sql:" + sql); + RecordSet insertRS = new RecordSet(); + boolean b = insertRS.executeUpdate(sql); + if (!b) { + log.writeLog("insert Error!"); + continue; + } + String mainId = BaseUtil.getBaseInfoByParm("id", "uf_jktz", "lcbh", lcbh, ""); + if(!ycdje.equals("")&&!ycdje.equals("0.00")){ + String insertDT = "insert into uf_jktz_dt1(mainid,hkje,bz) values(" + + "'" +mainId+"',"+ + "'" +ycdje+"',"+ + "'期初初始化导入')"; + boolean b1 = insertRS.executeUpdate(insertDT); + log.writeLog("借款明细插入"+insertDT+" "+b1); + } + if (!yhkje.equals("")&&!yhkje.equals("0.00")){ + String insertDT = "insert into uf_jktz_dt1(mainid,hkje,bz) values(" + + "'" +mainId+"',"+ + "'" +yhkje+"',"+ + "'期初初始化导入')"; + boolean b1 = insertRS.executeUpdate(insertDT); + log.writeLog("借款明细插入"+insertDT+" "+b1); + } + + + RecordSet updateRs = new RecordSet(); + updateRs.executeUpdate("update uf_ygjktz_lsk set sjsfcggxzzsk = '0',gxzskstsxx = '' where lcbh = '" + lcbh + "'"); + lcbhArr.add(lcbh); + } + + + } + } + + + } + }catch (Exception e){ + + } + + + } +} diff --git a/src/main/youhong_ai_jitu_src/jntchina/schedule/QianPianBuLu.java b/src/main/youhong_ai_jitu_src/jntchina/schedule/QianPianBuLu.java new file mode 100644 index 0000000..099a49f --- /dev/null +++ b/src/main/youhong_ai_jitu_src/jntchina/schedule/QianPianBuLu.java @@ -0,0 +1,168 @@ +package jntchina.schedule; + +import selfdev.util.base.BaseUtil; +import selfdev.util.log.LogTool; +import weaver.conn.RecordSet; +import weaver.general.Util; +import weaver.interfaces.schedule.BaseCronJob; + +import java.util.ArrayList; +import java.util.List; + +/** + * @title: QianPianBuLu + * @Author LJL + * @Date: 2022/6/8 16:17 + * @Version 1.0 + */ +public class QianPianBuLu extends BaseCronJob { + @Override + public void execute() { + LogTool log = new LogTool("/log/schedule/", false); + List lcbhArr = new ArrayList<>(); + String sql = ""; + try{ + RecordSet rs = new RecordSet(); + rs.execute("select lcbh from uf_fksqyfb"); + while (rs.next()) { + lcbhArr.add(rs.getString("lcbh")); + } + log.writeLog("流程编号总共有"+lcbhArr.size()); + rs.execute("select lcbh,yhxje,sywhxje from uf_gysqptz_lsk"); + while (rs.next()) { + String lcbh = rs.getString("lcbh"); + String yhxje = Util.null2String(rs.getString("yhxje"));//已核销金额 + String sywhxje = Util.null2String(rs.getString("sywhxje"));//剩余未核销金额 + + if(lcbhArr.contains(lcbh)){ + continue; + }else { + String tablenem = BaseUtil.getBaseInfoByParm("TABLENAME", "workflow_bill", "1", "1", " and id in (select formid from workflow_base where id=(select WORKFLOWID from workflow_requestbase where REQUESTMARK='" + lcbh + "'))"); + if (tablenem.equals("")) { + RecordSet updateRs = new RecordSet(); + updateRs.executeUpdate("update uf_gysqptz_lsk set sjsfcggxzzsk = '1',gxzskstsxx = '未能通过流程编号找到对应表名,请检查编号是否正确' where lcbh = '" + lcbh + "'"); + continue; + } else { + RecordSet rs2 = new RecordSet(); + sql = "select t1.*,t2.REQUESTNAME from " + tablenem + " t1 left join workflow_requestbase t2 on t1.requestid = t2.requestid where lcbh = '" + lcbh + "'"; + rs2.execute(sql); + if (rs2.next()) { + String mainid = rs2.getString("id");//主表id + RecordSet rs3 = new RecordSet(); + rs3.execute("select * from " + tablenem + "_dt2 where mainid = '" + mainid + "'"); + int counts = rs3.getCounts(); + + String sqrgh = BaseUtil.getBaseInfoByParm("workcode", "hrmresource", "id", rs2.getString("id"), "");//申请人工号 + String sqbmbm = rs2.getString("fygsbm");//申请部门编码 + String fkgsbm = rs2.getString("gsmc");//付款公司编码 + String gysbm = rs2.getString("gysmc");//供应商编码 + String fbbm = rs2.getString("zz");//分部编码 + String sqfb = rs2.getString("zz");//申请分部 + String ncclcdh = rs2.getString("nccfkdh");//NCC付款单号 + String fkje = rs2.getString("jshjje");//付款金额 + if (counts>1){ + yhxje = "0.00";//已核销金额 + sywhxje = rs2.getString("jshjje");//剩余未核销金额 + } + + String gsmc = rs2.getString("gsmc");//公司名称 + String gysmc = rs2.getString("gysmc");//供应商名称 + String sqbm = rs2.getString("fygsbm");//申请部门 + String qy = rs2.getString("qy");//区域 + String sqr = rs2.getString("xm");//申请人 + String bt = rs2.getString("REQUESTNAME");//标题 + String sqrq = rs2.getString("cjrq");//申请日期 + String qqid = rs2.getString("requestid");//相关流程 + String fksm = rs2.getString("fkxx");//付款说明 + sql = "insert into uf_fksqyfb(sqrgh,sqbmbm,fkgsbm,gysbm,fbbm,sqfb,ncclcdh,fkje,yhxje,sywhxje,gsmc,gysmc,sqbm,qy,lcbh,sqr,bt,sqrq,qqid,fksm,FORMMODEID) values(" + + "'" + sqrgh + "'," + + "'" + sqbmbm + "'," + + "'" + fkgsbm + "'," + + "'" + gysbm + "'," + + "'" + fbbm + "'," + + "'" + sqfb + "'," + + "'" + ncclcdh + "'," + + "'" + fkje + "'," + + "'" + yhxje + "'," + + "'" + sywhxje + "'," + + "'" + gsmc + "'," + + "'" + gysmc + "'," + + "'" + sqbm + "'," + + "'" + qy + "'," + + "'" + lcbh + "'," + + "'" + sqr + "'," + + "'" + bt + "'," + + "'" + sqrq + "'," + + "'" + qqid + "'," + + "'" + fksm + "'," + + "'" + 52501 + "'" + + ")"; + log.writeLog("insertMain sql:" + sql); + RecordSet insertRS = new RecordSet(); + boolean b = insertRS.executeUpdate(sql); + if (!b) { + log.writeLog("insert Error!"); + continue; + } + + + String mainId = BaseUtil.getBaseInfoByParm("id", "uf_fksqyfb", "lcbh", lcbh, ""); + while (rs3.next()) { + String fycdbm = rs3.getString("fycdbm");//费用承担部门 + String fylx = rs3.getString("fylx");//费用类型 + String fkje2 = rs3.getString("je");//预付款金额 + String bz = rs3.getString("bz");//备注 + String cph = rs3.getString("cph");//车牌号 + String cbzx = rs3.getString("wd");//成本中心 + String ck = rs3.getString("ck");//仓库 + String gj = rs3.getString("gj");//国家 + String oamxxid = rs3.getString("id");//明细行id + String xghxlc = rs3.getString("");//相关核销流程 + + String yhxje2 = yhxje;//已核销金额 + String sywhxje2 = sywhxje;//剩余未核销金额 + //如果明细行数超过1行 则不触发变更核销金额的逻辑 默认为0 + if (counts>1) { + yhxje2 = rs3.getString("0.00");//已核销金额 + sywhxje2 = rs3.getString("je");//剩余未核销金额 + } + + sql = "insert into uf_fksqyfb_dt1(mainid,fycdbm,fylx,fkje,bz,cph,cbzx,ck,gj,oamxxid,xghxlc,yhxje,sywhxje) values(" + + "'" + mainId + "'," + + "'" + fycdbm + "'," + + "'" + fylx + "'," + + "'" + fkje2 + "'," + + "'" + bz + "'," + + "'" + cph + "'," + + "'" + cbzx + "'," + + "'" + ck + "'," + + "'" + gj + "'," + + "'" + oamxxid + "'," + + "'" + xghxlc + "'," + + "'" + yhxje2 + "'," + + "'" + sywhxje2 + "'" + + ")"; + RecordSet insertDtRS = new RecordSet(); + log.writeLog("Insert DT sql:" + sql); + boolean b1 = insertDtRS.executeUpdate(sql); + if(!b1){ + log.writeLog("insert DT Error!"); + continue; + } + } + } + RecordSet updateRs = new RecordSet(); + updateRs.executeUpdate("update uf_gysqptz_lsk set sjsfcggxzzsk = '0',gxzskstsxx = '' where lcbh = '" + lcbh + "'"); + lcbhArr.add(lcbh); + } + + } + + } + + }catch (Exception e){ + log.writeLog("Error:"+e); + + } + } +} diff --git a/src/main/youhong_ai_jitu_src/jntchina/schedule/hrm/HRCompanySync.java b/src/main/youhong_ai_jitu_src/jntchina/schedule/hrm/HRCompanySync.java new file mode 100644 index 0000000..b912dbc --- /dev/null +++ b/src/main/youhong_ai_jitu_src/jntchina/schedule/hrm/HRCompanySync.java @@ -0,0 +1,14 @@ +package jntchina.schedule.hrm; + +import weaver.interfaces.schedule.BaseCronJob; + + +public class HRCompanySync extends BaseCronJob { + + @Override + public void execute() { + SyncHrmcompanyToOA hrmresource = new SyncHrmcompanyToOA(); + hrmresource.companySynJob(); + } + +} diff --git a/src/main/youhong_ai_jitu_src/jntchina/schedule/hrm/HRSynOc.java b/src/main/youhong_ai_jitu_src/jntchina/schedule/hrm/HRSynOc.java new file mode 100644 index 0000000..858f161 --- /dev/null +++ b/src/main/youhong_ai_jitu_src/jntchina/schedule/hrm/HRSynOc.java @@ -0,0 +1,43 @@ +package jntchina.schedule.hrm; + +import weaver.conn.RecordSet; +import weaver.interfaces.schedule.BaseCronJob; + +import java.time.LocalDate; +import java.time.LocalDateTime; +import java.time.LocalTime; +import java.time.format.DateTimeFormatter; + +/** + * 同步海外定时任务 + */ +public class HRSynOc extends BaseCronJob { + + + @Override + public void execute() { + LocalDateTime today_start = LocalDateTime.of(LocalDate.now(), LocalTime.MIN);//当天零点 + String today = today_start.format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")); + String allDay = "2022-03-21 00:00:00"; + SynHrmdepartmentToOAOc dept = new SynHrmdepartmentToOAOc(); + SyncHrmjobtitlesToOAOc job = new SyncHrmjobtitlesToOAOc(); + SyncHrmresourceToOAOc user = new SyncHrmresourceToOAOc(); + + + RecordSet rs = new RecordSet(); + rs.executeQuery("select * from controltask"); + if(!rs.next()){ + rs.executeUpdate("insert into controltask(task) values(?)",0); + } + rs.executeQuery("select * from controltask where task = ?",0); + if(rs.next()) { + rs.executeUpdate("update controltask set task = ?",1); + dept.execute(allDay); + job.execute(allDay); + user.execute(allDay); + rs.executeUpdate("update controltask set task = ?",0); + } + } + + +} diff --git a/src/main/youhong_ai_jitu_src/jntchina/schedule/hrm/HRSync.java b/src/main/youhong_ai_jitu_src/jntchina/schedule/hrm/HRSync.java new file mode 100644 index 0000000..87339c0 --- /dev/null +++ b/src/main/youhong_ai_jitu_src/jntchina/schedule/hrm/HRSync.java @@ -0,0 +1,78 @@ +package jntchina.schedule.hrm; + +import java.text.SimpleDateFormat; +import java.util.Date; + +import com.api.formmode.page.util.Util; + +import weaver.conn.RecordSet; +import weaver.interfaces.schedule.BaseCronJob; + +public class HRSync extends BaseCronJob { + + @Override + public void execute() { + SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd"); + //当天零点 + String today = sdf.format(new Date())+" 00:00:00"; + + // 取上次更新时间,默认值当天零点。 + String deptUpdateTime = today; + String postUpdateTime = today; + String employeeUpdateTime = today; + int size_dept=5000;//接口每页同步最大量 + int size_job=5000; + int size_user=5000; + RecordSet rs = new RecordSet(); + String jkbs="";//接口标识 + String jkm_dept="";//部门接口地址后缀 + String jkm_job="";//岗位接口地址后缀 + String jkm_user="";//人员接口地址后缀 + String sql = "select * from uf_HRRestDate"; + rs.executeQuery(sql); + while (rs.next()){ + + //接口标识 + jkbs=Util.null2String(rs.getString("jkbs")); + if("dept".equals(jkbs)){//同步部门 + deptUpdateTime = rs.getString("sctbsj"); + size_dept=rs.getInt("jkmyzdl"); + //接口地址后缀 + jkm_dept=Util.null2String(rs.getString("jkm")); + }else if("post".equals(jkbs)){//同步岗位 + postUpdateTime = rs.getString("sctbsj"); + size_job=rs.getInt("jkmyzdl"); + //接口地址后缀 + jkm_job=Util.null2String(rs.getString("jkm")); + }else if("user".equals(jkbs)){//同步员工 + employeeUpdateTime = rs.getString("sctbsj"); + size_user=rs.getInt("jkmyzdl"); + //接口地址后缀 + jkm_user=Util.null2String(rs.getString("jkm")); + } + } + //执行部门同步 + SyncHrmdepartmentToOA hrmdepartment = new SyncHrmdepartmentToOA(); + hrmdepartment.setSize(size_dept); + hrmdepartment.setJkhzurl(jkm_dept); + hrmdepartment.execute(deptUpdateTime); + + //执行岗位同步 + //SyncHrmjobtitlesToOA hrmjobtitles = new SyncHrmjobtitlesToOA(); + SyncHrmJobTitlesToOANew hrmjobtitles = new SyncHrmJobTitlesToOANew(); + hrmjobtitles.setSize(size_job); + hrmjobtitles.setJkhzurl(jkm_job); + hrmjobtitles.execute(postUpdateTime); + + //执行员工同步 + SyncHrmresourceToOA hrmresource = new SyncHrmresourceToOA(); + hrmresource.setJkhzurl(jkm_user); + hrmresource.setSize(size_user); + hrmresource.execute(employeeUpdateTime); + + //更新同步时间到中间表 + String sql1 = "update uf_HRRestDate set sctbsj ='"+today+"' "; + rs.execute(sql1); + } + +} diff --git a/src/main/youhong_ai_jitu_src/jntchina/schedule/hrm/HRSync1.java b/src/main/youhong_ai_jitu_src/jntchina/schedule/hrm/HRSync1.java new file mode 100644 index 0000000..d6ff0f2 --- /dev/null +++ b/src/main/youhong_ai_jitu_src/jntchina/schedule/hrm/HRSync1.java @@ -0,0 +1,23 @@ +package jntchina.schedule.hrm; + +import weaver.interfaces.schedule.BaseCronJob; + +import java.time.LocalDate; +import java.time.LocalDateTime; +import java.time.LocalTime; +import java.time.format.DateTimeFormatter; + +public class HRSync1 extends BaseCronJob { + + @Override + public void execute() { +// SyncHrmsubcompanyToOA hrmsubcompany = new SyncHrmsubcompanyToOA(); +// hrmsubcompany.execute(); + LocalDateTime today_start = LocalDateTime.of(LocalDate.now(), LocalTime.MIN);//当天零点 + String today = today_start.format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")); + SyncHrmdepartmentToOA hrmdepartment = new SyncHrmdepartmentToOA(); + String allDay = "2018-03-21 00:00:00"; + hrmdepartment.execute(allDay); + } + +} diff --git a/src/main/youhong_ai_jitu_src/jntchina/schedule/hrm/HRSync2.java b/src/main/youhong_ai_jitu_src/jntchina/schedule/hrm/HRSync2.java new file mode 100644 index 0000000..8c0aa45 --- /dev/null +++ b/src/main/youhong_ai_jitu_src/jntchina/schedule/hrm/HRSync2.java @@ -0,0 +1,21 @@ +package jntchina.schedule.hrm; + +import weaver.interfaces.schedule.BaseCronJob; + +import java.time.LocalDate; +import java.time.LocalDateTime; +import java.time.LocalTime; +import java.time.format.DateTimeFormatter; + +public class HRSync2 extends BaseCronJob { + + @Override + public void execute() { + LocalDateTime today_start = LocalDateTime.of(LocalDate.now(), LocalTime.MIN);//当天零点 + String today = today_start.format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")); + String allDay = "2018-03-21 00:00:00"; + SyncHrmresourceToOA hrmresource = new SyncHrmresourceToOA(); + hrmresource.execute(allDay); + } + +} diff --git a/src/main/youhong_ai_jitu_src/jntchina/schedule/hrm/HRSyncAll.java b/src/main/youhong_ai_jitu_src/jntchina/schedule/hrm/HRSyncAll.java new file mode 100644 index 0000000..fedb51f --- /dev/null +++ b/src/main/youhong_ai_jitu_src/jntchina/schedule/hrm/HRSyncAll.java @@ -0,0 +1,20 @@ +package jntchina.schedule.hrm; + +import weaver.interfaces.schedule.BaseCronJob; + +public class HRSyncAll extends BaseCronJob { + + @Override + public void execute() { + String allDay = "2018-03-21 00:00:00"; +// SyncHrmsubcompanyToOA hrmsubcompany = new SyncHrmsubcompanyToOA(); +// hrmsubcompany.execute(); + SyncHrmdepartmentToOA hrmdepartment = new SyncHrmdepartmentToOA(); + hrmdepartment.execute(allDay); + SyncHrmjobtitlesToOA hrmjobtitles = new SyncHrmjobtitlesToOA(); + hrmjobtitles.execute(allDay); + SyncHrmresourceToOA hrmresource = new SyncHrmresourceToOA(); + hrmresource.execute(allDay); + } + +} diff --git a/src/main/youhong_ai_jitu_src/jntchina/schedule/hrm/SynComGroupData.java b/src/main/youhong_ai_jitu_src/jntchina/schedule/hrm/SynComGroupData.java new file mode 100644 index 0000000..b8ed678 --- /dev/null +++ b/src/main/youhong_ai_jitu_src/jntchina/schedule/hrm/SynComGroupData.java @@ -0,0 +1,207 @@ +package jntchina.schedule.hrm; + + +import com.alibaba.fastjson.JSONArray; +import com.alibaba.fastjson.JSONObject; +import jntchina.schedule.hrm.entity.ResoutDate; + +import jntchina.util.HttpClientToJT; +import selfdev.util.log.LogTool; +import weaver.conn.RecordSet; +import weaver.file.Prop; +import weaver.general.TimeUtil; +import weaver.general.Util; +import weaver.interfaces.schedule.BaseCronJob; + + +import java.util.*; + + +/** + * @title: 同步Hr薪酬组到建模表 + * @Author ycf + * @Date: 2021/9/28 10:20 + * @Version 1.0 + */ +public class SynComGroupData extends BaseCronJob { + + private final LogTool log = new LogTool("/log/hrm/xinchouzu/", false); + + @Override + public void execute() { + this.getConversionValue(); + + } + + /** + * 获取所有公司的code + * + * @return List + * @hidden 从hr公司表uf_hrmcompany中获取所有公司信息 + */ + + public List getCompanyList() { + List list = new ArrayList<>(); + RecordSet recordSet = new RecordSet(); + recordSet.executeQuery("select company_code from uf_hrmcompany"); + while (recordSet.next()) { + list.add(recordSet.getString("company_code")); + } + log.writeLog("listSize:"+list.size()); + //日志 + + return list; + } + + /** + * 获取资源表 + * + * @return list + */ + + public List getField() { + + List list = new ArrayList<>(); + RecordSet recordSet = new RecordSet(); + recordSet.executeQuery("select FIELDNAME from uf_fieldname_glgs"); + while (recordSet.next()) { + list.add(recordSet.getString("FIELDNAME")); + } + + return list; + } + + + /** + * 请求url 获取资源组,保存到中台HR字段转换值(关联公司)uf_fieldvalue_glgs + */ + public void getConversionValue() { + //hr字段表,uf_fieldname_glgs + List field = this.getField(); + log.writeLog("field资源表长度:" + field.size()); + + String token = HttpClientToJT.getToken(); + //获取token +// String token = "DbS4EAxWjsseV14AqnepwzYkaBPhHXlpwQg8TQrM3jIrIByV6g6Yvw=="; + log.writeLog("获取的token为:" + token); + //所有的字段数据 + List resoutDates = new ArrayList<>(); + String mode = Prop.getPropValue("DevToDC_jntchina", "mode"); + // 服务器ip:port + String baseUrl = Prop.getPropValue("DevToDC_jntchina", mode + "_baseUrl"); + String url = baseUrl+"/dcoaapi/hr/translateValue"; + + + for (String s : field) { + + RecordSet recordSet = new RecordSet(); + recordSet.execute("select id from modeinfo where formid = (select id from workflow_bill where tablename = 'uf_fieldvalue_glgs')"); + recordSet.next(); + + String FORMMODEID = recordSet.getString("ID"); + log.writeLog("FORMMODEID:"+FORMMODEID); + + + List companyList = this.getCompanyList(); + log.writeLog("companyList的长度:" + companyList.size()); + + for (String assetGroup : companyList) { + log.writeLog("公司code:"+assetGroup); + //设置参数 + + String param = "{\"LANGUAGE_CD\":\"ZHS\",\"FIELDNAME\":\"" + s + "_" + assetGroup + "\"}"; + log.writeLog("请求的json:" + param); + log.writeLog("请求的url:" + url); + //获取请求返回的数据 + String rDate = HttpClientToJT.sendPost(url, token, param); + log.writeLog("请求结果" + rDate); + + log.writeLog("请求的url返回的code" + JSONObject.parseObject(rDate).getString("code")); + + //判断是否请求成功 + if ("1".equals(JSONObject.parseObject(rDate).getString("code"))) { + log.writeLog("请求成功"); + JSONObject json = JSONObject.parseObject(rDate); + //获取json数组 + JSONArray array = json.getJSONArray("data"); + log.writeLog("请求的数组长度" + array.size()); + for (int i = 0; i < array.size(); i++) { + //把从url中获取到的json字符串解析,保存到List中, + JSONObject jo = array.getJSONObject(i); + jo.getString("media_id"); + ResoutDate resoutDate = new ResoutDate(); + resoutDate.setFIELDVALUE(Util.null2String(jo.getString("FIELDVALUE"))); + resoutDate.setXlADLONGNAME(Util.null2String(jo.getString("XlADLONGNAME"))); + resoutDate.setFIELDNAME(Util.null2String(s)); + resoutDate.setXLADSHORTNAME(Util.null2String(jo.getString("XLADSHORTNAME"))); + resoutDate.setGs(Util.null2String(assetGroup)); + log.writeLog(resoutDate.toString()); + resoutDates.add(resoutDate); + } + } else { + log.writeLog("请求的错误信息:" + JSONObject.parseObject(rDate).getString("msg")); + } + } + + + log.writeLog("字段数据的长度:" + resoutDates.size()); + for (ResoutDate resoutDate : resoutDates) { + //数据库中查询转换值是否存在, 条件为公司名和字段 + + recordSet.execute("select count(*) from uf_fieldvalue_glgs where FIELDNAME = '" + resoutDate.getFIELDNAME() + "' and gs = '" + resoutDate.getGs() + "' and FIELDVALUE = '"+resoutDate.getFIELDVALUE()+"'"); + log.writeLog("select count(*) from uf_fieldvalue_glgs where FIELDNAME = '" + resoutDate.getFIELDNAME() + "' and gs = '" + resoutDate.getGs() + "' and FIELDVALUE = '"+resoutDate.getFIELDVALUE()+"'"); + int a = 0; + /* + 获取符合条件的行数 + 当数据存在时 recordSet.getInt(1)的值大于0行, + 当数据不存在时 recordSet.getInt(1)=0 + */ + while (recordSet.next()) { + a = recordSet.getInt(1); + } + //数据不存在时,执行插入数据操作 + if (a == 0) { + String sql = "insert into uf_fieldvalue_glgs " + + "(FIELDVALUE,XlADLONGNAME,XLADSHORTNAME,FIELDNAME,gs,FORMMODEID,MODEDATACREATEDATE,MODEDATACREATETIME) VALUES ('" + resoutDate.getFIELDVALUE() + "'," + + "'" + resoutDate.getXlADLONGNAME() + "','" + resoutDate.getXLADSHORTNAME() + "" + + "','" + resoutDate.getFIELDNAME() + "','" + resoutDate.getGs() + "','" + FORMMODEID + "','" + TimeUtil.getDateString(new Date()) + "','" + TimeUtil.getOnlyCurrentTimeString() + "')"; + + boolean i = recordSet.executeUpdate(sql); + if (i) { + log.writeLog("插入成功" + sql); + } else { + log.writeLog("插入失败" + sql); + } + } else { + //如果存在时,判断长描述和短描述是否一致,不一致就更新 + String sql = "select count(*) nums from uf_fieldvalue_glgs " + + "where FIELDNAME = '" + resoutDate.getFIELDNAME() + "' " + + "and gs = '" + resoutDate.getGs() + "' " + + "and FIELDVALUE = '"+resoutDate.getFIELDVALUE()+"' " + + "and XlADLONGNAME = '"+resoutDate.getXlADLONGNAME()+"' " + + "and XLADSHORTNAME = '"+resoutDate.getXLADSHORTNAME()+"' "; + recordSet.execute(sql); + + int b = 0; + while (recordSet.next()) { + b = recordSet.getInt(1); + } + //数据不存在时,执行更新数据操作 + if (b == 0) { + sql = "update uf_fieldvalue_glgs " + + "set XlADLONGNAME = '"+resoutDate.getXlADLONGNAME()+"' " + + ",XLADSHORTNAME = '"+resoutDate.getXLADSHORTNAME()+"' " + + "where FIELDNAME = '" + resoutDate.getFIELDNAME() + "' " + + "and gs = '" + resoutDate.getGs() + "' " + + "and FIELDVALUE = '"+resoutDate.getFIELDVALUE()+"' " ; + recordSet.execute(sql); + log.writeLog("长描述和端描述有更改,执行更新操作:"+sql); + + } + + + } + } + } + } +} \ No newline at end of file diff --git a/src/main/youhong_ai_jitu_src/jntchina/schedule/hrm/SynGjjAndSbToOA.java b/src/main/youhong_ai_jitu_src/jntchina/schedule/hrm/SynGjjAndSbToOA.java new file mode 100644 index 0000000..c534690 --- /dev/null +++ b/src/main/youhong_ai_jitu_src/jntchina/schedule/hrm/SynGjjAndSbToOA.java @@ -0,0 +1,168 @@ +package jntchina.schedule.hrm; + +import com.alibaba.fastjson.JSONArray; +import com.alibaba.fastjson.JSONObject; +import jntchina.util.HttpClientToJT; +import selfdev.util.log.LogTool; +import weaver.conn.RecordSet; +import weaver.file.Prop; +import weaver.general.Util; +import weaver.interfaces.schedule.BaseCronJob; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +/** + * @title: 同步公积金和社保到OA + * @Author ycf + * @Date: 2021/12/29 13:29 + * @Version 1.0 + */ +public class SynGjjAndSbToOA extends BaseCronJob { + private final LogTool log = new LogTool("/log/hrm/shebao/", false); + + + + @Override + public void execute() { + + List list = this.getAddressByGs(); + synGjjAndSbByAddress("C_SB_RULE_ID",list); + log.writeLog("---------------------社保同步完-----------------------"); + synGjjAndSbByAddress("C_GJJ_RULE_ID",list); + log.writeLog("------------------公积金同步完成-----------------"); + } + + /** + * 同步公积金和社保 + * @param ruleField 规则字段 + */ + public void synGjjAndSbByAddress(String ruleField,List list) { + + //记录插入长度 + int size = 0; + int size2 = 0; + ArrayList> maps = new ArrayList<>(); + log.writeLog("获取社保缴纳地的长度:"+list.size()); + //获取的token + String token = HttpClientToJT.getToken(); + //获取的url + String mode = Prop.getPropValue("DevToDC_jntchina", "mode"); + String baseUrl = Prop.getPropValue("DevToDC_jntchina", mode + "_baseUrl"); + String url = baseUrl + "/dcoaapi/hr/translateValue"; + + //获取的模块id + RecordSet recordSet = new RecordSet(); + recordSet.execute("select id from modeinfo where formid = (select id from workflow_bill where tablename = 'uf_sbandgjj')"); + recordSet.next(); + String modelId = recordSet.getString("ID"); + + log.writeLog("开始请求:"); + log.writeLog("请求的url:"+url); + log.writeLog("请求的token:"+token); + + + for (String dq : list) { + //发请求 + String param = "{\"LANGUAGE_CD\":\"ZHS\",\"FIELDNAME\":\""+ ruleField +"_"+ dq + "\"}"; + log.writeLog("获取规则的参数:"+param); + + String json = HttpClientToJT.sendPost(url, token, param); + log.writeLog("获取规则返回的json:"+json); + //取出json的值 + JSONArray data = JSONObject.parseObject(json).getJSONArray("data"); + for (int i = 0; i < data.size(); i++) { + JSONObject jsoni = data.getJSONObject(i); + log.writeLog("jsoni:"+jsoni); + + Map map = new HashMap<>(); + map.put("FIELDVALUE",jsoni.getString("FIELDVALUE")); + map.put("XlADLONGNAME",jsoni.getString("XlADLONGNAME")); + map.put("FIELDNAME",jsoni.getString("FIELDNAME")); + map.put("XLADSHORTNAME",jsoni.getString("XLADSHORTNAME")); + map.put("DESCR1",jsoni.getString("DESCR1")); + map.put("DESCR2",jsoni.getString("DESCR2")); + map.put("DESCR3",jsoni.getString("DESCR3")); + map.put("DESCR4",jsoni.getString("DESCR4")); + map.put("DESCR5",jsoni.getString("DESCR5")); + map.put("DESCR6",jsoni.getString("DESCR6")); + + maps.add(map); + } + } + log.writeLog("值的长度:"+maps); + + + String sql = ""; + + + //所有集合存在list中,用于判断值是否存在 + sql = "select * from uf_sbandgjj "; + ArrayList> arrayList = new ArrayList<>(); + recordSet.execute(sql); + while (recordSet.next()) { + HashMap map1 = new HashMap<>(); + for (String s : recordSet.getColumnName()) { + map1.put(s, recordSet.getString(s)); + } + arrayList.add(map1); + } + log.writeLog("arrayList.size:"+arrayList.size()); + + for (Map map : maps) { + String jnd = (map.get("FIELDNAME")).replace(ruleField,"").replace("_",""); + + sql = "select count(*) num from uf_sbandgjj " + + "where FIELDVALUE = '"+Util.null2String(map.get("FIELDVALUE"))+"' " + + "and XlADLONGNAME = '"+Util.null2String(map.get("XlADLONGNAME"))+"' " + + "and XLADSHORTNAME = '"+Util.null2String(map.get("XLADSHORTNAME"))+"' " + + "and FIELDNAME = '"+ ruleField +"' " + + "and jnd = '"+jnd+"' "; + log.writeLog("找到当前值是否存在:"+sql); + + recordSet.execute(sql); + recordSet.next(); + + if (recordSet.getString("num").equals("0")) { + //直接插入 + sql = "insert into uf_sbandgjj (FIELDVALUE,XlADLONGNAME,XLADSHORTNAME,FIELDNAME,DESCR1,DESCR2,DESCR3," + + "DESCR4,DESCR5,DESCR6,FORMMODEID,jnd) values ('" + map.get("FIELDVALUE") + "','" + map.get("XlADLONGNAME") + "'," + + "'" + map.get("XLADSHORTNAME") + "','" + ruleField + "'," + + "'" + map.get("DESCR1") + "','" + map.get("DESCR2") + "','" + map.get("DESCR3") + "'," + + "'" + map.get("DESCR4") + "','" + map.get("DESCR5") + "','" + map.get("DESCR6") + "'," + modelId + " ,'"+jnd+"')"; + size++; + log.writeLog("1插入sql:" + sql); + boolean b = recordSet.executeUpdate(sql); + size2 = b ? size2 + 1 : size2; + log.writeLog("1插入SQL:" + (b ? "成功" : "失败")); + } + + + } + log.writeLog("本次插入条数:"+size); + log.writeLog("本次成功插入条数:"+size2); + + } + + + + /** + * 通过公司获取 社保缴纳地 + * @return list->地区(string) + */ + public List getAddressByGs() { + + //社保缴纳地 + ArrayList addressList = new ArrayList<>(); + RecordSet recordSet = new RecordSet(); + recordSet.execute("select FIELDVALUE from uf_fieldvalue_glgs where FIELDNAME = 'C_SB_LOC_ID' "); + while (recordSet.next()) { + addressList.add(Util.null2String(recordSet.getString("FIELDVALUE"))); + } + log.writeLog("通过公司获取 社保缴纳地的长度:"+addressList.size()); + return addressList; + } + +} diff --git a/src/main/youhong_ai_jitu_src/jntchina/schedule/hrm/SynHrmdepartmentToOAOc.java b/src/main/youhong_ai_jitu_src/jntchina/schedule/hrm/SynHrmdepartmentToOAOc.java new file mode 100644 index 0000000..795d978 --- /dev/null +++ b/src/main/youhong_ai_jitu_src/jntchina/schedule/hrm/SynHrmdepartmentToOAOc.java @@ -0,0 +1,767 @@ +package jntchina.schedule.hrm; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.JSONArray; +import com.alibaba.fastjson.JSONObject; +import com.api.integration.util.JavaUtil; +import jntchina.schedule.hrm.entity.DepartmentDto; +import jntchina.schedule.hrm.util.OrganizationUtil; +import jntchina.util.HttpClientToJT; +import selfdev.util.base.TimeCommonUtil; +import selfdev.util.log.LogTool; +import weaver.conn.RecordSet; +import weaver.general.Util; +import weaver.hrm.company.DepartmentComInfo; +import weaver.matrix.MatrixUtil; + +import java.io.BufferedWriter; +import java.io.FileWriter; +import java.io.IOException; +import java.util.*; +import java.util.stream.Collectors; + +public class SynHrmdepartmentToOAOc { + + Map deptMap = new HashMap<>(); + + + //分页接口参数 + String maxPoint = "1"; + //接口是否有下一页 默认为有 + boolean ifPage = true; + + + //部门编码和id map + Map map_dept_code_id = new HashMap<>(); + private final LogTool log = new LogTool("/log/hrm/deptOc/", false); + + //60里面是否还有分部 + boolean ifExistenceSub = true; + + /** + * 所有 organizationClass = 10 的组织上级编码存储List集合 + */ + List subList = new ArrayList<>(); + + + //存放60分部 + /** + * 存放60 + */ + List list60 = new ArrayList<>(); + + /** + * + * 对 organizationClass = 60 的记录进行分析 + * @param supSubMap <组织编码,上级组织编码> organizationClass = 60 组织记录信息集合 + * @param oaSubCompanyMap <分部编码,分部ID> 当前OA库中已存在的分部 + */ + public void ScreenSub(Map supSubMap,Map oaSubCompanyMap) { + try { + boolean ifSub = false; + Set keySet = supSubMap.keySet(); + for (String deptCode : keySet) { + //获取上级组织编码 + String supDeptCode = supSubMap.get(deptCode); + + //60的key + if (subList.contains(supDeptCode) || oaSubCompanyMap.containsKey(supDeptCode) || oaSubCompanyMap.containsKey(deptCode)) { + ifSub = true; + + list60.add(deptCode); + subList.add(supDeptCode); + supSubMap.remove(deptCode); + } + } + ifExistenceSub = ifSub; + } catch (Exception e) { + e.printStackTrace(); + } + } + + + /** + * 同步分部、部门数据 + * 注:对方整个组织数不区分部门和分部,全部用部门接口数据,用类型区分 + */ + @SuppressWarnings("unchecked") + public Map> execute(String date) { + log.writeLog("-----------------execute"); + log.writeLog("-----------------date:" + date); + Map> rtMap = new HashMap<>(); + try { + + String now = TimeCommonUtil.obtainDate(0); + log.writeLog("-----------------now:" + now); + //匹配部门id,关联的上级部门,所属分部 map + Map> map_dept_id_data = new HashMap<>(); + map_dept_id_data = getDeptDataMap(); + map_dept_code_id = getDepartmentCodeIdMap(); + SyncHrmsubcompanyToOAOC syncHrmsubcompanyToOAOC = new SyncHrmsubcompanyToOAOC(); + SyncHrmresourceToOA hrmresource = new SyncHrmresourceToOA(); + //人员map,用于匹配上级领导 + Map map_user_code_id = hrmresource.getUserCodeIdMap(); + //拆分数据、organizationClass 10类型是组织,其他类型当部门,【代理区】在对方那是虚拟部门,特殊处理划分为OA 分部 + //JSONArray data = getDepartments(date); + //JSONArray ocData = getOcDepartments(date); + + //获取当前OA中已存在的分部信息 + Map oaSubCompanyMap = OrganizationUtil.getEffectiveSubCompanyCodeIdMap(); + + log.writeLog("-----------------apiSta"); + JSONArray ocData = new JSONArray(); + while (ifPage) { + ocData.addAll(getOcDepartments(date, maxPoint)); + } + log.writeLog("-----------------apiEnd"); + log.writeLog("-----------------size:" + ocData.size()); + + //key为60自己,value为上级 + Map supSubMap = new HashMap<>(); + + Object directSales = ocData.stream().filter(item -> { + JSONObject itemJson = JSONObject.parseObject(JSON.toJSONString(item)); + if ("10".equals(itemJson.getString("organizationClass"))) { + subList.add(itemJson.getString("superiorDepartment")); + } + if ("60".equals(itemJson.getString("organizationClass"))) { + //key为60自己,value为上级 + supSubMap.put(itemJson.getString("departmentCode"), itemJson.getString("superiorDepartment")); + } + return !"10".equals(itemJson.getString("organizationClass")); + }).collect(Collectors.toList()); + + //对 organizationClass = 60 的组织进行分析 + ScreenSub(supSubMap,oaSubCompanyMap); + + + List dataList = JSONArray.parseArray(ocData.toJSONString(), DepartmentDto.class); + log.writeLog("-----------------全部长度:" + dataList.size()); + + //分部数据 + List subcompanys = dataList.stream().filter(item -> { + return "10".equals(item.getOrganizationClass()) || "60".equals(item.getOrganizationClass()); + // return "10".equals(item.getOrganizationClass()) || ("60".equals(item.getOrganizationClass()) && list60.contains(item.getDepartmentCode())); + }).collect(Collectors.toList()); + //部门数据 注意:10000300代理区编码 + List departments = dataList.stream().filter(item -> { + return "20".equals(item.getOrganizationClass()) + || "30".equals(item.getOrganizationClass()) + || "40".equals(item.getOrganizationClass()) + || "50".equals(item.getOrganizationClass()); + // || ("60".equals(item.getOrganizationClass()) && !list60.contains(item.getDepartmentCode())); + }).collect(Collectors.toList()); + log.writeLog("-----------------分部长度:" + subcompanys.size()); + log.writeLog("-----------------部门长度:" + departments.size()); + //处理分部同步逻辑 + List execute = syncHrmsubcompanyToOAOC.execute(subcompanys, departments); + rtMap.put("department", departments); + //rtMap.put("subcompany",subcompanys); + //departments = execute; + //Map map_subcompany_code_id = hrmsubcompany.getSubCodeIdMap(); + + + + //处理部门同步逻辑 + RecordSet rs = new RecordSet(); + int skipNum = 0, insertNum = 0, updateNum = 0; + List skipList = new ArrayList<>(); + log.writeLog("----------开始同步部门,条数:" + departments.size()); + //log.writeLog("----------同步部门源数据:" + JSON.toJSONString(departments)); + // 处理部门同步逻辑 1.未匹配到分部,不新增, + for (int i = 0; i < departments.size(); i++) { + DepartmentDto row = departments.get(i); + String countryCode = Util.null2String(row.getCountryCode());//国家 + String departmentCode = Util.null2String(row.getDepartmentCode());//部门编码 + String departmentName = Util.null2String(row.getDepartmentName());//部门全称 + String shortName = Util.null2String(row.getDepartmentAbbreviation());//部门简称 + String superiorDepartment = Util.null2String(row.getSuperiorDepartment());//上级部门编码 + String departmentOrder = Util.null2String(row.getDepartmentOrder());//排序 + String deptManager = Util.null2String(row.getDeptManager());//部门负责人code + String brchLeader = Util.null2String(row.getBrchLeader());//分管领导code + Integer canceled = Util.null2String(row.getStatus()).equals("3") ? 1 : null;//1 新增 2 修改 3作废 + String companyCode = Util.null2String(row.getCompanyCode());// 公司 +// String companyName = Util.null2String(row.getCompanyName());//公司名称 + if ("".equals(superiorDepartment)) { + skipList.add(row); + log.writeLog("cylnb superiorDepartment is null:" + superiorDepartment); + skipNum++; + deptMap.put(departmentCode, superiorDepartment); + // continue; + } + //各种code转id + String bmfzr = Util.null2String(map_user_code_id.get(deptManager));//部门负责人 + String bmfgld = Util.null2String(map_user_code_id.get(brchLeader));//分管领导 + String subcompanyid1 = Util.null2String(oaSubCompanyMap.get(superiorDepartment));//分部ID + String supdepid = Util.null2String(map_dept_code_id.get(superiorDepartment));//获取上级ID + log.writeLog("------------subcompanyid1:" + subcompanyid1 + "-----deptCode:" + departmentCode + ",status:" + row.getStatus() + ",canceled:" + canceled + "-------"); + log.writeLog("------------supdepid:" + supdepid + "----deptCode:" + departmentCode + ",status:" + row.getStatus() + ",canceled:" + canceled + "--------"); + //如果上级编码为空、所属分部,上级部门都找不到,不作处理 + if ("".equals(superiorDepartment) || ("".equals(subcompanyid1) && "".equals(supdepid))) { + skipList.add(row); + skipNum++; + log.writeLog("cylnb 上级编码为空、所属分部,上级部门都找不到,不作处理deptcode:" + departmentCode + ";supcode:" + superiorDepartment); + deptMap.put(departmentCode, superiorDepartment); + //continue; + } + String sql = ""; + //判断HR部门ID是否已经存在 + + // 、 • 7中°~^8英文、心‘9繁体、• ~‘14 越南°~17泰国°~‘21 葡萄牙‘~‘22 印尼 + log.writeLog("第" + (i + 1) + "条,取数据完成!"); + + String status = row.getStatus(); + + if (!"3".equals(status)) { + log.writeLog("---------------国家:" + countryCode); + departmentName = getDepartmentName(date, countryCode, departmentCode, departmentName); + } else { + log.writeLog("----------------状态为3"); + } + + if ("".equals(departmentName)) { + log.writeLog("----------------多语言为空"); + departmentName = row.getDepartmentName(); + } + + log.writeLog("-----------------countryCode:" + countryCode); + log.writeLog("-----------------departmentName:" + departmentName); + // departmentName = "~`~`7 " + departmentName + "`~`8 " + engDepartmentName + "`~`13 5`~`~"; + if (!map_dept_code_id.containsKey(departmentCode)) {//部门不存在则插入生成新部门 + rs.executeQuery("select id from hrmdepartment where outkey = ?", departmentCode); + if (rs.next()) { + String id = rs.getString("id"); + //如果找到subcompanyid1不为空,说明是顶级部门, + //String deptid = Util.null2String(map_dept_code_id.get(departmentCode));//OA部门ID + String deptid = id;//OA部门ID + if ("".equals(deptid)) { + skipNum++; + log.writeLog("cylnb deptid is null"); + deptMap.put(departmentCode, superiorDepartment); + //continue; + } + if (!"".equals(subcompanyid1)) { + supdepid = "0"; + } + if (!"".equals(supdepid) && "".equals(subcompanyid1)) { + log.writeLog("开始取部门" + departmentCode + "上级分部id:" + supdepid + "。"); + subcompanyid1 = getSubId(map_dept_id_data, supdepid); + log.writeLog("结束取部门" + departmentCode + "上级分部id:" + supdepid + "。取到的分部id:" + subcompanyid1); + if ("".equals(subcompanyid1)) { + log.writeLog("----------------分部id找不到"); + deptMap.put(departmentCode, superiorDepartment); + } + } + String updateStr = ""; + //只有有值才覆盖 + updateStr += !"".equals(subcompanyid1) ? "subcompanyid1 = '" + subcompanyid1 + "', " : ""; + updateStr += !"".equals(supdepid) ? "supdepid = '" + supdepid + "', " : ""; + updateStr += !"".equals(bmfzr) ? "bmfzr = '" + bmfzr + "', " : ""; + updateStr += !"".equals(bmfgld) ? "bmfgld = '" + bmfgld + "', " : ""; + sql = "update HrmDepartment set " + + "departmentname = '" + departmentName + "', " + + "departmentmark = '" + departmentName + "', " + + updateStr + + "canceled = " + canceled + ", " + + "modified = to_date('" + now + "','yyyy-mm-dd hh24:mi:ss'), " + + "modifier = '1', " + + "showorder = '" + departmentOrder + "' " + + "where id= '" + deptid + "'"; + log.writeLog("更新部门表中数据sql--------->" + sql); + boolean b1 = rs.executeUpdate(sql); + log.writeLog("deptid " + deptid + " ---------是否成功:" + b1); + updateNum++; + //处理部门矩阵 + sql = "select deptid,bmfzr,bmfgld,sfzy from HrmDepartmentDefined where deptid ='" + deptid + "'"; + rs.executeQuery(sql); + if (rs.next()) { + bmfzr = !"".equals(bmfzr) ? bmfzr : Util.null2String(rs.getString("bmfzr")); + bmfgld = !"".equals(bmfgld) ? bmfgld : Util.null2String(rs.getString("bmfgld")); + sql = "update HrmDepartmentDefined set " + + "bmfzr = '" + bmfzr + "' " + + ",sfzy = '" + row.getIsDirectSales() + "' " + + ",frgs= '" + companyCode + "'" + + ",bmfgld= '" + bmfgld + "'" + + ",guojia = '" + countryCode + "' " + + " where deptid = '" + deptid + "'"; + boolean b = rs.executeUpdate(sql); + log.writeLog("更新部门自定义表中数据sql--------->" + sql); + log.writeLog("deptid " + deptid + " ---------是否成功:" + b); + } else { + sql = "insert into HrmDepartmentDefined(deptid,sfzy,frgs,bmfzr,bmfgld,guojia) " + + "values('" + deptid + "'," + + "'" + row.getIsDirectSales() + "'," + + "'" + companyCode + "'," + + "'" + bmfzr + "'," + + "'" + bmfgld + "'," + + "'" + countryCode + "')"; + boolean b = rs.executeUpdate(sql); + log.writeLog("插入部门自定义表中数据sql--------->" + sql); + log.writeLog("deptid " + deptid + " ---------是否成功:" + b); + } + //同步部门矩阵信息 + MatrixUtil.updateDepartmentData(deptid); + continue; + } + + //如果找到subcompanyid1不为空,说明是顶级部门, + if (!"".equals(subcompanyid1)) { + supdepid = "0"; + } + if (!"".equals(supdepid) && "".equals(subcompanyid1)) { + log.writeLog("开始取部门:" + departmentCode + ",上级分部id:" + supdepid + "。" + "部门负责人code:" + deptManager + "部门负责人ID:" + bmfzr); + subcompanyid1 = getSubId(map_dept_id_data, supdepid); + log.writeLog("结束取部门:" + departmentCode + ",上级分部id:" + supdepid + ",取到的分部id:" + subcompanyid1); + if ("".equals(subcompanyid1)) { + log.writeLog("---------------分部id找不到:"); + deptMap.put(departmentCode, superiorDepartment); + } + } + sql = "insert into HrmDepartment (departmentname,departmentcode,departmentmark,outkey," + + "supdepid,canceled,created,creater,modified,modifier," + + "showorder,subcompanyid1,bmfzr,bmfgld) values(" + + "'" + departmentName + "'," + + "'" + departmentCode + "'," + + "'" + departmentName + "'," + + "'" + departmentCode + "'," + + "'" + supdepid + "'," + + "" + canceled + "," + + "to_date('" + now + "','yyyy-mm-dd hh24:mi:ss')," + + "'1'," + + "to_date('" + now + "','yyyy-mm-dd hh24:mi:ss')," + + "'1'," + + "'" + departmentOrder + "'," + + "'" + subcompanyid1 + "', " + + "'" + bmfzr + "', " + + "'" + bmfgld + "')"; + log.writeLog("插入部门表生成新数据sql--------->" + sql); + rs.executeUpdate(sql); + insertNum++; + rs.executeQuery("select id from HrmDepartment where departmentcode = ?", departmentCode); + int maxDeptID = 0;//新插入数据的部门ID + if (rs.next()) { + maxDeptID = rs.getInt("id"); + //将新增加的部门加入至MAP中 + map_dept_code_id.put(departmentCode, maxDeptID + ""); + Map map1 = new HashMap<>(); + map1.put("outkey", departmentCode); + map1.put("supdepid", supdepid); + map1.put("subcompanyid1", subcompanyid1); + log.writeLog("maxDeptID--------->" + maxDeptID + ",size:" + map_dept_id_data.size()); + map_dept_id_data.put(maxDeptID + "", map1); + } + //新增数据,插入到部门自定义表HrmDepartmentDefined中 + sql = "insert into HrmDepartmentDefined(deptid,sfzy,frgs,bmfzr,bmfgld,guojia) " + + "values('" + maxDeptID + "'," + + "'" + row.getIsDirectSales() + "'," + + "'" + companyCode + "'," + + "'" + bmfzr + "'," + + "'" + bmfgld + "'," + + "'" + countryCode + "')"; + boolean b = rs.executeUpdate(sql); + log.writeLog("插入部门自定义表中数据sql--------->" + sql); + log.writeLog("deptid " + maxDeptID + " ---------是否成功:" + b); + //同步部门矩阵信息 + MatrixUtil.updateDepartmentData(maxDeptID + ""); +// //将新增加的人员自定义信息加入至MAP中 +// map_dept_id_defined.put(maxDeptID + "", maxDeptID + ""); +// //将部门与所属分部对应关系放到map中 +// map_deptid_subcompanyid.put(maxDeptID + "", subcompanyid1); + } else {//部门存在则更新 + //如果找到subcompanyid1不为空,说明是顶级部门, + String deptid = Util.null2String(map_dept_code_id.get(departmentCode));//OA部门ID + if ("".equals(deptid)) { + skipNum++; + log.writeLog("cylnb deptid is null"); + deptMap.put(departmentCode, superiorDepartment); + //continue; + } + if (!"".equals(subcompanyid1)) { + supdepid = "0"; + } + if (!"".equals(supdepid) && "".equals(subcompanyid1)) { + log.writeLog("开始取部门" + departmentCode + "上级分部id:" + supdepid + "。"); + subcompanyid1 = getSubId(map_dept_id_data, supdepid); + log.writeLog("结束取部门" + departmentCode + "上级分部id:" + supdepid + "。取到的分部id:" + subcompanyid1); + if ("".equals(subcompanyid1)) { + log.writeLog("----------------分部id找不到"); + deptMap.put(departmentCode, superiorDepartment); + } + } + String updateStr = ""; + //只有有值才覆盖 + updateStr += !"".equals(subcompanyid1) ? "subcompanyid1 = '" + subcompanyid1 + "', " : ""; + updateStr += !"".equals(supdepid) ? "supdepid = '" + supdepid + "', " : ""; + updateStr += !"".equals(bmfzr) ? "bmfzr = '" + bmfzr + "', " : ""; + updateStr += !"".equals(bmfgld) ? "bmfgld = '" + bmfgld + "', " : ""; + sql = "update HrmDepartment set " + + "departmentname = '" + departmentName + "', " + + "departmentmark = '" + departmentName + "', " + + updateStr + + "canceled = " + canceled + ", " + + "modified = to_date('" + now + "','yyyy-mm-dd hh24:mi:ss'), " + + "modifier = '1', " + + "showorder = '" + departmentOrder + "' " + + "where id= '" + deptid + "'"; + log.writeLog("更新部门表中数据sql--------->" + sql); + boolean b1 = rs.executeUpdate(sql); + log.writeLog("deptid " + deptid + " ---------是否成功:" + b1); + updateNum++; + //处理部门矩阵 + sql = "select deptid,bmfzr,bmfgld,sfzy from HrmDepartmentDefined where deptid ='" + deptid + "'"; + rs.executeQuery(sql); + if (rs.next()) { + bmfzr = !"".equals(bmfzr) ? bmfzr : Util.null2String(rs.getString("bmfzr")); + bmfgld = !"".equals(bmfgld) ? bmfgld : Util.null2String(rs.getString("bmfgld")); + sql = "update HrmDepartmentDefined set " + + "bmfzr = '" + bmfzr + "' " + + ",sfzy = '" + row.getIsDirectSales() + "' " + + ",frgs= '" + companyCode + "'" + + ",bmfgld= '" + bmfgld + "'" + + ",guojia = '" + countryCode + "' " + + " where deptid = '" + deptid + "'"; + boolean b = rs.executeUpdate(sql); + log.writeLog("更新部门自定义表中数据sql--------->" + sql); + log.writeLog("deptid " + deptid + " ---------是否成功:" + b); + } else { + sql = "insert into HrmDepartmentDefined(deptid,sfzy,frgs,bmfzr,bmfgld,guojia) " + + "values('" + deptid + "'," + + "'" + row.getIsDirectSales() + "'," + + "'" + companyCode + "'," + + "'" + bmfzr + "'," + + "'" + bmfgld + ",'" + + "'" + countryCode + "')"; + boolean b = rs.executeUpdate(sql); + log.writeLog("插入部门自定义表中数据sql--------->" + sql); + log.writeLog("deptid " + deptid + " ---------是否成功:" + b); + } + //人员信息伴随部门信息变化 + if (!"".equals(subcompanyid1) && !"".equals(deptid)) { + sql = "update hrmResource set subCompanyId1='" + subcompanyid1 + "' where departmentId = '" + deptid + "' "; + rs.executeUpdate(sql); + } + //同步部门矩阵信息 + MatrixUtil.updateDepartmentData(deptid); + } + } + + +// for (int i = 0; i < departments.size(); i++) { +// DepartmentDto row = departments.get(i); +// String departmentCode = Util.null2String(row.getDepartmentCode());//部门编码 +// String superiorDepartment = Util.null2String(row.getSuperiorDepartment());//上级部门编码 +// String parId = ""; +// rs.executeQuery("select * from HRMDEPARTMENT where outkey = ?",superiorDepartment); +// if(rs.next()){ +// parId = rs.getString("id"); +// } +// rs.executeUpdate("update HRMDEPARTMENT set supdepid = ? where outkey = ?",parId,departmentCode); +// } + + log.writeLog("此次同步部门总数为:" + departments.size() + ",新增部门数为:" + insertNum + + ",更新部门数为:" + updateNum + ",跳出处理部门数为:" + skipNum); + log.writeLog("此次同步部门跳过是数据为:" + JSON.toJSONString(skipList)); + + + log.writeLog("----sta:" + deptMap.size()); + + int size = deptMap.size(); + int lastCount = deptMap.size(); + for (int i = 0; i < size; i++) { + if (deptMap.size() == 0) { + break; + } + log.writeLog("---------------当前正在执行第" + i + "次,本次剩余" + deptMap.size() + "条部门待处理"); + setSup(); + if (lastCount <= deptMap.size()) { + log.writeLog("---------------异常,有" + deptMap.size() + "条部门无分部的数据异常"); + break; + } else { + lastCount = deptMap.size(); + } + } + log.writeLog("----end"); + + + //更新部门缓存 + DepartmentComInfo dci = new DepartmentComInfo(); + dci.removeCompanyCache(); + + //释放map内存 + map_dept_id_data.clear(); + map_dept_code_id.clear(); + map_user_code_id.clear(); + + //更新同步时间到中间表 + String sql1 = "update uf_HRRestDate set sctbsj ='" + now + "' where jkm = '/dcopenedi/hrDept/pageByUpdateTime'"; + rs.executeUpdate(sql1); + + } catch (Exception e) { + log.writeLog("--------------------Exception:" + JavaUtil.getExceptionDetail(e)); + e.printStackTrace(); + } + return rtMap; + } + + + public void setSup() { + RecordSet rss = new RecordSet(); + Set keySet = deptMap.keySet(); + Iterator it = keySet.iterator(); + while (it.hasNext()) { + try { + String deptCode = (String) it.next(); + String supCode = String.valueOf(deptMap.get(deptCode)); + String SUPDEPID = ""; + String SUBCOMPANYID1 = ""; + rss.executeQuery("select * from hrmdepartment where departmentcode = ?", supCode); + if (rss.next()) { + SUPDEPID = rss.getString("id"); + SUBCOMPANYID1 = rss.getString("SUBCOMPANYID1"); + if (SUBCOMPANYID1 != null && !"".equals(SUBCOMPANYID1)) { + rss.executeUpdate("update hrmdepartment set SUPDEPID = ? ,SUBCOMPANYID1 = ? where departmentcode = ? ", SUPDEPID, SUBCOMPANYID1, deptCode); + it.remove(); + } + log.writeLog("-----------------已补处理部门code:" + deptCode + ",分部id:" + SUBCOMPANYID1); + } + } catch (Exception e) { + log.writeLog("--------------------Exception:" + JavaUtil.getExceptionDetail(e)); + } + } + + } + + + /** + * 匹配部门id,关联的上级部门,所属分部 map + * + * @return + */ + private Map> getDeptDataMap() { + RecordSet rs = new RecordSet(); + Map> map = new HashMap<>(); + rs.executeQuery("select id, outkey,supdepid,subcompanyid1 from HrmDepartment where (CANCELED!=1 or CANCELED is null)"); + while (rs.next()) { + Map map1 = new HashMap<>(); + map1.put("outkey", rs.getString("outkey")); + map1.put("supdepid", rs.getString("supdepid")); + map1.put("subcompanyid1", rs.getString("subcompanyid1")); + map.put(rs.getString("id"), map1); + } + return map; + } + + /** + * 根据部门id匹配所属分部 + * + * @return + */ + public String getSubId(Map> map_dept_id_data, String deptId) { + String subcompanyid = ""; + if (!map_dept_id_data.containsKey(deptId)) { + return ""; + } + Map map = map_dept_id_data.get(deptId); + subcompanyid = map.get("subcompanyid1"); + return subcompanyid; + } + + public Map getDepartmentCodeIdMap() { + RecordSet rs = new RecordSet(); + Map map = new HashMap<>(); + rs.executeQuery("select departmentcode,outkey,id from HrmDepartment where outkey is not null and (CANCELED!=1 or CANCELED is null)"); + while (rs.next()) { + map.put(rs.getString("outkey"), rs.getString("id")); + } + return map; + } + + + /** + * 获取海外部门数据 + * + * @param date 时间 + * @param point + * @return + */ + public JSONArray getOcDepartments(String date, String point) { + log.writeLog("--------------getOcDepartments"); + int current = 1, size = 5000, pages = 2; + String url = HttpClientToJT.baseUrl + "/dcopenedi/hrDept/pageNewHrDeptByUpdateTime"; + String token = HttpClientToJT.getToken(); + log.writeLog("-------token--------->" + token); + Map params = new HashMap<>(); + List list1 = new ArrayList(); + list1.add("ZHS"); + params.put("languageCds", list1); + params.put("updateTime", date); + params.put("point", point); + params.put("size", size); + log.writeLog("传入JSON--------------->" + JSON.toJSONString(params)); + String s = HttpClientToJT.sendPost(url, token, JSONObject.toJSONString(params)); + JSONObject jsonObject = JSONObject.parseObject(s); + JSONArray jsonArray = new JSONArray(); + + String code = Util.null2String(jsonObject.getString("code")); + log.writeLog("code------>" + code); + if ("1".equals(code)) { + JSONObject result = jsonObject.getJSONObject("data"); + JSONArray records = result.getJSONArray("records"); + Object hasNextPage = result.get("hasNextPage"); + jsonArray.addAll(records); + //下次继续传 + maxPoint = result.get("maxPoint").toString(); + if ("false".equals(hasNextPage.toString())) { + ifPage = false; + } + + Object directSales = jsonArray.stream().filter(item -> { + JSONObject itemJson = JSONObject.parseObject(JSON.toJSONString(item)); + return !"CHN".equals(itemJson.getString("countryCode")) && !"IDN".equals(itemJson.getString("countryCode")); + }).collect(Collectors.toList()); + jsonArray = JSONArray.parseArray(JSON.toJSONString(directSales)); + } + + return jsonArray; + } + + + /** + * 获取海外某个部门对应国家语言的数据 + * + * @param date 时间 + * @param point 页码 + * @return 返回接口返回信息 + */ + public JSONArray getOcDepartmentsGUOJIA(String date, String point, String guojia, String departmentCode) { + int size = 5000; + String url = HttpClientToJT.baseUrl + "/dcopenedi/hrDept/pageNewHrDeptByUpdateTime"; + String token = HttpClientToJT.getToken(); + log.writeLog("-------token--------->" + token); + Map params = new HashMap<>(); + List list1 = new ArrayList<>(); + list1.add(guojia); + params.put("languageCds", list1); + params.put("updateTime", date); + params.put("point", point); + params.put("size", size); + params.put("deptCode", departmentCode); + log.writeLog("传入JSON--------------->" + JSON.toJSONString(params)); + String s = HttpClientToJT.sendPost(url, token, JSONObject.toJSONString(params)); + JSONObject jsonObject = JSONObject.parseObject(s); + JSONArray jsonArray = new JSONArray(); + + String code = Util.null2String(jsonObject.getString("code")); + log.writeLog("code------>" + code); + if ("1".equals(code)) { + JSONObject result = jsonObject.getJSONObject("data"); + JSONArray records = result.getJSONArray("records"); + Object hasNextPage = result.get("hasNextPage"); + jsonArray.addAll(records); +// //下次继续传 +// maxPoint = result.get("maxPoint").toString(); +// if ("false".equals(hasNextPage.toString())) { +// ifPage = false; +// } + + Object directSales = jsonArray.stream().filter(item -> { + JSONObject itemJson = JSONObject.parseObject(JSON.toJSONString(item)); + return !"CHN".equals(itemJson.getString("countryCode")); + }).collect(Collectors.toList()); + jsonArray = JSONArray.parseArray(JSON.toJSONString(directSales)); + } + + return jsonArray; + } + + + private void writeFile(JSONArray jsonArray) { + BufferedWriter bw = null; + try { + bw = new BufferedWriter(new FileWriter("D:\\2.txt")); + //一次写一行 + bw.write(jsonArray.toJSONString()); + bw.newLine(); //换行用 + //关闭流 + bw.close(); + } catch (IOException e) { + e.printStackTrace(); + } + System.out.println("写入成功"); + } + + + /** + * 获取多语言 + * + * @param date 时间 + * @param countryCode 国家code + * @param departmentCode 部门code + * @param deptName 部门中文名称 + * @return 多语言名称 + */ + public String getDepartmentName(String date, String countryCode, String departmentCode, String deptName) { + String retName = ""; + boolean existence = true; + String language = ""; + String cdIndex = ""; + try { + if ("CHN".equals(countryCode)) { + language = "ZHS"; + } + if ("BRA".equals(countryCode)) { + language = "POR"; + cdIndex = "21"; + } + if ("SAU".equals(countryCode) || "ARE".equals(countryCode) + || "EGY".equals(countryCode) + || "MEX".equals(countryCode) + || "SGP".equals(countryCode) + || "PHL".equals(countryCode) + || "MYS".equals(countryCode) + || "KHM".equals(countryCode) + ) { + existence = false; + language = "ENG"; + } + // 、 • 7中°~^8英文、心‘9繁体、• ~‘14 越南°~17泰国°~‘21 葡萄牙‘~‘22 印尼 + if ("IDN".equals(countryCode)) { + language = "IDN"; + cdIndex = "22"; + } + if ("THA".equals(countryCode)) { + //language = "THA"; + language = "ENG"; + cdIndex = "17"; + } + if ("VNM".equals(countryCode)) { + language = "VIE"; + cdIndex = "14"; + } + + String country = ""; + // 日期 位置 国家 部门code + JSONArray ocDepartmentsGUOJIA = getOcDepartmentsGUOJIA(date, "1", language, departmentCode); + log.writeLog("--------------多语言是否拿到数据:" + ocDepartmentsGUOJIA.size()); + List countryList = JSONArray.parseArray(ocDepartmentsGUOJIA.toJSONString(), DepartmentDto.class); + DepartmentDto countryDto = countryList.get(0); + //对应国家的语言名称(对应国家标签里面) + String countryDepartmentName = countryDto.getDepartmentName(); + log.writeLog("---------------对应国家语言名称:" + countryDepartmentName); + + //departmentName = + if (existence) { + //需要3个标签 + retName = "~`~`7 " + deptName + "`~`8 " + countryDepartmentName + "`~`" + cdIndex + " " + countryDepartmentName + "`~`~"; + } else { + //只需要中文和英文 + retName = "~`~`7 " + deptName + "`~`8 " + countryDepartmentName + "`~`~"; + } + + log.writeLog("---------------多语言名称:" + retName); + } catch (Exception e) { + e.printStackTrace(); + } + return retName; + } +} diff --git a/src/main/youhong_ai_jitu_src/jntchina/schedule/hrm/SynHrmdepartmentToOAOcOld.java b/src/main/youhong_ai_jitu_src/jntchina/schedule/hrm/SynHrmdepartmentToOAOcOld.java new file mode 100644 index 0000000..022595c --- /dev/null +++ b/src/main/youhong_ai_jitu_src/jntchina/schedule/hrm/SynHrmdepartmentToOAOcOld.java @@ -0,0 +1,791 @@ +package jntchina.schedule.hrm; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.JSONArray; +import com.alibaba.fastjson.JSONObject; +import com.api.integration.util.JavaUtil; +import jntchina.schedule.hrm.entity.DepartmentDto; +import jntchina.util.HttpClientToJT; +import selfdev.util.base.TimeCommonUtil; +import selfdev.util.log.LogTool; +import weaver.conn.RecordSet; +import weaver.general.Util; +import weaver.hrm.company.DepartmentComInfo; +import weaver.matrix.MatrixUtil; + +import java.io.BufferedWriter; +import java.io.FileWriter; +import java.io.IOException; +import java.util.*; +import java.util.stream.Collectors; + +public class SynHrmdepartmentToOAOcOld { + + Map deptMap = new HashMap<>(); + + + //分页接口参数 + String maxPoint = "1"; + //接口是否有下一页 默认为有 + boolean ifPage = true; + + + //部门编码和id map + Map map_dept_code_id = new HashMap(); + private LogTool log = new LogTool("/log/hrm/deptOc/", false); + + //60里面是否还有分部 + boolean ifExistenceSub = true; + + //所有10分部的上级 + List subList = new ArrayList(); + + + //存放60分部 + List list60 = new ArrayList(); + + + public void ScreenSub(Map supSubMap) { + try { + boolean ifSub = false; + Set keySet = supSubMap.keySet(); + Iterator it = keySet.iterator(); + while (it.hasNext()) { + //60的key + String deptCode = (String) it.next(); + if (subList.contains(deptCode)) { + ifSub = true; + String supDeptCode = String.valueOf(supSubMap.get(deptCode)); + //60的value + list60.add(deptCode); + subList.add(supDeptCode); + supSubMap.remove(deptCode); + } + } + ifExistenceSub = ifSub; + } catch (Exception e) { + e.printStackTrace(); + } + } + + + /** + * 同步分部、部门数据 + * 注:对方整个组织数不区分部门和分部,全部用部门接口数据,用类型区分 + */ + public Map> execute(String date) { + log.writeLog("-----------------execute"); + log.writeLog("-----------------date:" + date); + Map> rtMap = new HashMap<>(); + try { + + String now = TimeCommonUtil.obtainDate(0); + log.writeLog("-----------------now:" + now); + //匹配部门id,关联的上级部门,所属分部 map + Map> map_dept_id_data = new HashMap<>(); + map_dept_id_data = getDeptDataMap(); +// log.writeLog("字典:"+JSON.toJSONString(map_dept_id_data)); + map_dept_code_id = getDepartmentCodeIdMap(); + SyncHrmsubcompanyToOAOC hrmsubcompany = new SyncHrmsubcompanyToOAOC(); + SyncHrmresourceToOA hrmresource = new SyncHrmresourceToOA(); + //人员map,用于匹配上级领导 + Map map_user_code_id = hrmresource.getUserCodeIdMap(); + //拆分数据、organizationClass 10类型是组织,其他类型当部门,【代理区】在对方那是虚拟部门,特殊处理划分为OA 分部 + //JSONArray data = getDepartments(date); + //JSONArray ocData = getOcDepartments(date); + + log.writeLog("-----------------apiSta"); + JSONArray ocData = new JSONArray(); + while (ifPage) { + ocData.addAll(getOcDepartments(date, maxPoint)); + } + log.writeLog("-----------------apiEnd"); + log.writeLog("-----------------size:" + ocData.size()); + + //key为60自己,value为上级 + Map supSubMap = new HashMap<>(); + + Object directSales = ocData.stream().filter(item -> { + JSONObject itemJson = JSONObject.parseObject(JSON.toJSONString(item)); + if ("10".equals(itemJson.getString("organizationClass"))) { + subList.add(itemJson.getString("superiorDepartment")); + } + if ("60".equals(itemJson.getString("organizationClass"))) { + //key为60自己,value为上级 + supSubMap.put(itemJson.getString("departmentCode"), itemJson.getString("superiorDepartment")); + } + return !"10".equals(itemJson.getString("organizationClass")); + }).collect(Collectors.toList()); + + while (ifExistenceSub) { + ScreenSub(supSubMap); + } + + List dataList = JSONArray.parseArray(ocData.toJSONString(), DepartmentDto.class); + log.writeLog("-----------------全部长度:" + dataList.size()); + + //分部数据 + List subcompanys = dataList.stream().filter(item -> { + //return "10".equals(item.getOrganizationClass()) || "60".equals(item.getOrganizationClass()); + return "10".equals(item.getOrganizationClass()) || ("60".equals(item.getOrganizationClass()) && list60.contains(item.getDepartmentCode())); + }).collect(Collectors.toList()); + //部门数据 注意:10000300代理区编码 + List departments = dataList.stream().filter(item -> { + return "20".equals(item.getOrganizationClass()) + || "30".equals(item.getOrganizationClass()) + || "40".equals(item.getOrganizationClass()) + || "50".equals(item.getOrganizationClass()) + || ("60".equals(item.getOrganizationClass()) && !list60.contains(item.getDepartmentCode())); + }).collect(Collectors.toList()); + log.writeLog("-----------------分部长度:" + subcompanys.size()); + log.writeLog("-----------------部门长度:" + departments.size()); + //处理分部同步逻辑 + List execute = hrmsubcompany.execute(subcompanys, departments); + rtMap.put("department", departments); + //rtMap.put("subcompany",subcompanys); + //departments = execute; + Map map_subcompany_code_id = hrmsubcompany.getSubCodeIdMap(); + //处理部门同步逻辑 + RecordSet rs = new RecordSet(); + int skipNum = 0, insertNum = 0, updateNum = 0; + List skipList = new ArrayList<>(); + log.writeLog("----------开始同步部门,条数:" + departments.size()); + //log.writeLog("----------同步部门源数据:" + JSON.toJSONString(departments)); + // 处理部门同步逻辑 1.未匹配到分部,不新增, + for (int i = 0; i < departments.size(); i++) { + DepartmentDto row = departments.get(i); + String countryCode = Util.null2String(row.getCountryCode());//国家 + String departmentCode = Util.null2String(row.getDepartmentCode());//部门编码 + String departmentName = Util.null2String(row.getDepartmentName());//部门全称 + String shortName = Util.null2String(row.getDepartmentAbbreviation());//部门简称 + String superiorDepartment = Util.null2String(row.getSuperiorDepartment());//上级部门编码 + String departmentOrder = Util.null2String(row.getDepartmentOrder());//排序 + String deptManager = Util.null2String(row.getDeptManager());//部门负责人code + String brchLeader = Util.null2String(row.getBrchLeader());//分管领导code + Integer canceled = Util.null2String(row.getStatus()).equals("3") ? 1 : null;//1 新增 2 修改 3作废 + String companyCode = Util.null2String(row.getCompanyCode());// 公司 +// String companyName = Util.null2String(row.getCompanyName());//公司名称 + if ("".equals(superiorDepartment)) { + skipList.add(row); + log.writeLog("cylnb superiorDepartment is null:" + superiorDepartment); + skipNum++; + deptMap.put(departmentCode, superiorDepartment); + // continue; + } + //各种code转id + String bmfzr = Util.null2String(map_user_code_id.get(deptManager));//部门负责人 + String bmfgld = Util.null2String(map_user_code_id.get(brchLeader));//分管领导 + String subcompanyid1 = Util.null2String(map_subcompany_code_id.get(superiorDepartment));//分部ID + String supdepid = Util.null2String(map_dept_code_id.get(superiorDepartment));//获取上级ID + log.writeLog("------------subcompanyid1:" + subcompanyid1 + "-----deptCode:" + departmentCode + ",status:" + row.getStatus() + ",canceled:" + canceled + "-------"); + log.writeLog("------------supdepid:" + supdepid + "----deptCode:" + departmentCode + ",status:" + row.getStatus() + ",canceled:" + canceled + "--------"); + //如果上级编码为空、所属分部,上级部门都找不到,不作处理 + if ("".equals(superiorDepartment) || ("".equals(subcompanyid1) && "".equals(supdepid))) { + skipList.add(row); + skipNum++; + log.writeLog("cylnb 上级编码为空、所属分部,上级部门都找不到,不作处理deptcode:" + departmentCode + ";supcode:" + superiorDepartment); + deptMap.put(departmentCode, superiorDepartment); + //continue; + } + String sql = ""; + //判断HR部门ID是否已经存在 + + // 、 • 7中°~^8英文、心‘9繁体、• ~‘14 越南°~17泰国°~‘21 葡萄牙‘~‘22 印尼 + + log.writeLog("第" + (i + 1) + "条,取数据完成!"); + + String status = row.getStatus(); + + if (!"3".equals(status)) { + log.writeLog("---------------国家:" + countryCode); + departmentName = getDepartmentName(date, countryCode, departmentCode, departmentName); + } else { + log.writeLog("----------------状态为3"); + } + + if ("".equals(departmentName)) { + log.writeLog("----------------多语言为空"); + departmentName = row.getDepartmentName(); + } + + log.writeLog("-----------------countryCode:" + countryCode); + log.writeLog("-----------------departmentName:" + departmentName); + // departmentName = "~`~`7 " + departmentName + "`~`8 " + engDepartmentName + "`~`13 5`~`~"; + if (!map_dept_code_id.containsKey(departmentCode)) {//部门不存在则插入生成新部门 + rs.executeQuery("select id from hrmdepartment where outkey = ?", departmentCode); + if (rs.next()) { + String id = rs.getString("id"); + //如果找到subcompanyid1不为空,说明是顶级部门, + //String deptid = Util.null2String(map_dept_code_id.get(departmentCode));//OA部门ID + String deptid = id;//OA部门ID + if ("".equals(deptid)) { + skipNum++; + log.writeLog("cylnb deptid is null"); + deptMap.put(departmentCode, superiorDepartment); + //continue; + } + if (!"".equals(subcompanyid1)) { + supdepid = "0"; + } + if (!"".equals(supdepid) && "".equals(subcompanyid1)) { + log.writeLog("开始取部门" + departmentCode + "上级分部id:" + supdepid + "。"); + subcompanyid1 = getSubId(map_dept_id_data, supdepid); + log.writeLog("结束取部门" + departmentCode + "上级分部id:" + supdepid + "。取到的分部id:" + subcompanyid1); + if ("".equals(subcompanyid1)) { + log.writeLog("----------------分部id找不到"); + deptMap.put(departmentCode, superiorDepartment); + } + } + String updateStr = ""; + //只有有值才覆盖 + updateStr += !"".equals(subcompanyid1) ? "subcompanyid1 = '" + subcompanyid1 + "', " : ""; + updateStr += !"".equals(supdepid) ? "supdepid = '" + supdepid + "', " : ""; + updateStr += !"".equals(bmfzr) ? "bmfzr = '" + bmfzr + "', " : ""; + updateStr += !"".equals(bmfgld) ? "bmfgld = '" + bmfgld + "', " : ""; + sql = "update HrmDepartment set " + + "departmentname = '" + departmentName + "', " + + "departmentmark = '" + departmentName + "', " + + updateStr + + "canceled = " + canceled + ", " + + "modified = to_date('" + now + "','yyyy-mm-dd hh24:mi:ss'), " + + "modifier = '1', " + + "showorder = '" + departmentOrder + "' " + + "where id= '" + deptid + "'"; + log.writeLog("更新部门表中数据sql--------->" + sql); + boolean b1 = rs.executeUpdate(sql); + log.writeLog("deptid " + deptid + " ---------是否成功:" + b1); + updateNum++; + //处理部门矩阵 + sql = "select deptid,bmfzr,bmfgld,sfzy from HrmDepartmentDefined where deptid ='" + deptid + "'"; + rs.executeQuery(sql); + if (rs.next()) { + bmfzr = !"".equals(bmfzr) ? bmfzr : Util.null2String(rs.getString("bmfzr")); + bmfgld = !"".equals(bmfgld) ? bmfgld : Util.null2String(rs.getString("bmfgld")); + sql = "update HrmDepartmentDefined set " + + "bmfzr = '" + bmfzr + "' " + + ",sfzy = '" + row.getIsDirectSales() + "' " + + ",frgs= '" + companyCode + "'" + + ",bmfgld= '" + bmfgld + "'" + + ",guojia = '" + countryCode + "' " + + " where deptid = '" + deptid + "'"; + boolean b = rs.executeUpdate(sql); + log.writeLog("更新部门自定义表中数据sql--------->" + sql); + log.writeLog("deptid " + deptid + " ---------是否成功:" + b); + } else { + sql = "insert into HrmDepartmentDefined(deptid,sfzy,frgs,bmfzr,bmfgld,guojia) " + + "values('" + deptid + "'," + + "'" + row.getIsDirectSales() + "'," + + "'" + companyCode + "'," + + "'" + bmfzr + "'," + + "'" + bmfgld + "'," + + "'" + countryCode + "')"; + boolean b = rs.executeUpdate(sql); + log.writeLog("插入部门自定义表中数据sql--------->" + sql); + log.writeLog("deptid " + deptid + " ---------是否成功:" + b); + } + //同步部门矩阵信息 + MatrixUtil.updateDepartmentData(deptid); + continue; + } + + //如果找到subcompanyid1不为空,说明是顶级部门, + if (!"".equals(subcompanyid1)) { + supdepid = "0"; + } + if (!"".equals(supdepid) && "".equals(subcompanyid1)) { + log.writeLog("开始取部门:" + departmentCode + ",上级分部id:" + supdepid + "。" + "部门负责人code:" + deptManager + "部门负责人ID:" + bmfzr); + subcompanyid1 = getSubId(map_dept_id_data, supdepid); + log.writeLog("结束取部门:" + departmentCode + ",上级分部id:" + supdepid + ",取到的分部id:" + subcompanyid1); + if ("".equals(subcompanyid1)) { + log.writeLog("---------------分部id找不到:"); + deptMap.put(departmentCode, superiorDepartment); + } + } + sql = "insert into HrmDepartment (departmentname,departmentcode,departmentmark,outkey," + + "supdepid,canceled,created,creater,modified,modifier," + + "showorder,subcompanyid1,bmfzr,bmfgld) values(" + + "'" + departmentName + "'," + + "'" + departmentCode + "'," + + "'" + departmentName + "'," + + "'" + departmentCode + "'," + + "'" + supdepid + "'," + + "" + canceled + "," + + "to_date('" + now + "','yyyy-mm-dd hh24:mi:ss')," + + "'1'," + + "to_date('" + now + "','yyyy-mm-dd hh24:mi:ss')," + + "'1'," + + "'" + departmentOrder + "'," + + "'" + subcompanyid1 + "', " + + "'" + bmfzr + "', " + + "'" + bmfgld + "')"; + log.writeLog("插入部门表生成新数据sql--------->" + sql); + rs.executeUpdate(sql); + insertNum++; + rs.executeQuery("select id from HrmDepartment where departmentcode = ?", departmentCode); + int maxDeptID = 0;//新插入数据的部门ID + if (rs.next()) { + maxDeptID = rs.getInt("id"); + //将新增加的部门加入至MAP中 + map_dept_code_id.put(departmentCode, maxDeptID + ""); + Map map1 = new HashMap<>(); + map1.put("outkey", departmentCode); + map1.put("supdepid", supdepid); + map1.put("subcompanyid1", subcompanyid1); + log.writeLog("maxDeptID--------->" + maxDeptID + ",size:" + map_dept_id_data.size()); + map_dept_id_data.put(maxDeptID + "", map1); + } + //新增数据,插入到部门自定义表HrmDepartmentDefined中 + sql = "insert into HrmDepartmentDefined(deptid,sfzy,frgs,bmfzr,bmfgld,guojia) " + + "values('" + maxDeptID + "'," + + "'" + row.getIsDirectSales() + "'," + + "'" + companyCode + "'," + + "'" + bmfzr + "'," + + "'" + bmfgld + "'," + + "'" + countryCode + "')"; + boolean b = rs.executeUpdate(sql); + log.writeLog("插入部门自定义表中数据sql--------->" + sql); + log.writeLog("deptid " + maxDeptID + " ---------是否成功:" + b); + //同步部门矩阵信息 + MatrixUtil.updateDepartmentData(maxDeptID + ""); +// //将新增加的人员自定义信息加入至MAP中 +// map_dept_id_defined.put(maxDeptID + "", maxDeptID + ""); +// //将部门与所属分部对应关系放到map中 +// map_deptid_subcompanyid.put(maxDeptID + "", subcompanyid1); + } else {//部门存在则更新 + //如果找到subcompanyid1不为空,说明是顶级部门, + String deptid = Util.null2String(map_dept_code_id.get(departmentCode));//OA部门ID + if ("".equals(deptid)) { + skipNum++; + log.writeLog("cylnb deptid is null"); + deptMap.put(departmentCode, superiorDepartment); + //continue; + } + if (!"".equals(subcompanyid1)) { + supdepid = "0"; + } + if (!"".equals(supdepid) && "".equals(subcompanyid1)) { + log.writeLog("开始取部门" + departmentCode + "上级分部id:" + supdepid + "。"); + subcompanyid1 = getSubId(map_dept_id_data, supdepid); + log.writeLog("结束取部门" + departmentCode + "上级分部id:" + supdepid + "。取到的分部id:" + subcompanyid1); + if ("".equals(subcompanyid1)) { + log.writeLog("----------------分部id找不到"); + deptMap.put(departmentCode, superiorDepartment); + } + } + String updateStr = ""; + //只有有值才覆盖 + updateStr += !"".equals(subcompanyid1) ? "subcompanyid1 = '" + subcompanyid1 + "', " : ""; + updateStr += !"".equals(supdepid) ? "supdepid = '" + supdepid + "', " : ""; + updateStr += !"".equals(bmfzr) ? "bmfzr = '" + bmfzr + "', " : ""; + updateStr += !"".equals(bmfgld) ? "bmfgld = '" + bmfgld + "', " : ""; + sql = "update HrmDepartment set " + + "departmentname = '" + departmentName + "', " + + "departmentmark = '" + departmentName + "', " + + updateStr + + "canceled = " + canceled + ", " + + "modified = to_date('" + now + "','yyyy-mm-dd hh24:mi:ss'), " + + "modifier = '1', " + + "showorder = '" + departmentOrder + "' " + + "where id= '" + deptid + "'"; + log.writeLog("更新部门表中数据sql--------->" + sql); + boolean b1 = rs.executeUpdate(sql); + log.writeLog("deptid " + deptid + " ---------是否成功:" + b1); + updateNum++; + //处理部门矩阵 + sql = "select deptid,bmfzr,bmfgld,sfzy from HrmDepartmentDefined where deptid ='" + deptid + "'"; + rs.executeQuery(sql); + if (rs.next()) { + bmfzr = !"".equals(bmfzr) ? bmfzr : Util.null2String(rs.getString("bmfzr")); + bmfgld = !"".equals(bmfgld) ? bmfgld : Util.null2String(rs.getString("bmfgld")); + sql = "update HrmDepartmentDefined set " + + "bmfzr = '" + bmfzr + "' " + + ",sfzy = '" + row.getIsDirectSales() + "' " + + ",frgs= '" + companyCode + "'" + + ",bmfgld= '" + bmfgld + "'" + + ",guojia = '" + countryCode + "' " + + " where deptid = '" + deptid + "'"; + boolean b = rs.executeUpdate(sql); + log.writeLog("更新部门自定义表中数据sql--------->" + sql); + log.writeLog("deptid " + deptid + " ---------是否成功:" + b); + } else { + sql = "insert into HrmDepartmentDefined(deptid,sfzy,frgs,bmfzr,bmfgld,guojia) " + + "values('" + deptid + "'," + + "'" + row.getIsDirectSales() + "'," + + "'" + companyCode + "'," + + "'" + bmfzr + "'," + + "'" + bmfgld + ",'" + + "'" + countryCode + "')"; + boolean b = rs.executeUpdate(sql); + log.writeLog("插入部门自定义表中数据sql--------->" + sql); + log.writeLog("deptid " + deptid + " ---------是否成功:" + b); + } + //人员信息伴随部门信息变化 + if (!"".equals(subcompanyid1) && !"".equals(deptid)) { + sql = "update hrmResource set subCompanyId1='" + subcompanyid1 + "' where departmentId = '" + deptid + "' "; + rs.executeUpdate(sql); + } + //同步部门矩阵信息 + MatrixUtil.updateDepartmentData(deptid); + } + } + + +// for (int i = 0; i < departments.size(); i++) { +// DepartmentDto row = departments.get(i); +// String departmentCode = Util.null2String(row.getDepartmentCode());//部门编码 +// String superiorDepartment = Util.null2String(row.getSuperiorDepartment());//上级部门编码 +// String parId = ""; +// rs.executeQuery("select * from HRMDEPARTMENT where outkey = ?",superiorDepartment); +// if(rs.next()){ +// parId = rs.getString("id"); +// } +// rs.executeUpdate("update HRMDEPARTMENT set supdepid = ? where outkey = ?",parId,departmentCode); +// } + + log.writeLog("此次同步部门总数为:" + departments.size() + ",新增部门数为:" + insertNum + + ",更新部门数为:" + updateNum + ",跳出处理部门数为:" + skipNum); + log.writeLog("此次同步部门跳过是数据为:" + JSON.toJSONString(skipList)); + + + log.writeLog("----sta:" + deptMap.size()); + + int size = deptMap.size(); + int lastCount = deptMap.size(); + for (int i = 0; i < size; i++) { + if (deptMap.size() == 0) { + break; + } + log.writeLog("---------------当前正在执行第" + i + "次,本次剩余" + deptMap.size() + "条部门待处理"); + setSup(); + if (lastCount <= deptMap.size()) { + log.writeLog("---------------异常,有" + deptMap.size() + "条部门无分部的数据异常"); + break; + } else { + lastCount = deptMap.size(); + } + } + log.writeLog("----end"); + + + //更新部门缓存 + DepartmentComInfo dci = new DepartmentComInfo(); + dci.removeCompanyCache(); + + //释放map内存 + map_dept_id_data.clear(); + map_dept_id_data = null; + map_dept_code_id.clear(); + map_dept_code_id = null; + map_user_code_id.clear(); + map_user_code_id = null; + + //更新同步时间到中间表 + String sql1 = "update uf_HRRestDate set sctbsj ='" + now + "' where jkm = '/dcopenedi/hrDept/pageByUpdateTime'"; + rs.executeUpdate(sql1); + + } catch (Exception e) { + log.writeLog("--------------------Exception:" + JavaUtil.getExceptionDetail(e)); + e.printStackTrace(); + } + return rtMap; + } + + + public void setSup() { + RecordSet rss = new RecordSet(); + Set keySet = deptMap.keySet(); + Iterator it = keySet.iterator(); + while (it.hasNext()) { + try { + String deptCode = (String) it.next(); + String supCode = String.valueOf(deptMap.get(deptCode)); + String SUPDEPID = ""; + String SUBCOMPANYID1 = ""; + rss.executeQuery("select * from hrmdepartment where departmentcode = ?", supCode); + if (rss.next()) { + SUPDEPID = rss.getString("id"); + SUBCOMPANYID1 = rss.getString("SUBCOMPANYID1"); + if (SUBCOMPANYID1 != null && !"".equals(SUBCOMPANYID1)) { + rss.executeUpdate("update hrmdepartment set SUPDEPID = ? ,SUBCOMPANYID1 = ? where departmentcode = ? ", SUPDEPID, SUBCOMPANYID1, deptCode); + it.remove(); + } + log.writeLog("-----------------已补处理部门code:" + deptCode + ",分部id:" + SUBCOMPANYID1); + } + } catch (Exception e) { + log.writeLog("--------------------Exception:" + JavaUtil.getExceptionDetail(e)); + } + } + + } + + + /** + * 匹配部门id,关联的上级部门,所属分部 map + * + * @return + */ + private Map> getDeptDataMap() { + RecordSet rs = new RecordSet(); + Map> map = new HashMap<>(); + rs.executeQuery("select id, outkey,supdepid,subcompanyid1 from HrmDepartment where (CANCELED!=1 or CANCELED is null)"); + while (rs.next()) { + Map map1 = new HashMap<>(); + map1.put("outkey", rs.getString("outkey")); + map1.put("supdepid", rs.getString("supdepid")); + map1.put("subcompanyid1", rs.getString("subcompanyid1")); + map.put(rs.getString("id"), map1); + } + return map; + } + + /** + * 根据部门id匹配所属分部 + * + * @return + */ + public String getSubId(Map> map_dept_id_data, String deptId) { + String subcompanyid = ""; + if (!map_dept_id_data.containsKey(deptId)) { + return ""; + } + Map map = map_dept_id_data.get(deptId); + subcompanyid = map.get("subcompanyid1"); + return subcompanyid; + } +// /** +// * 获取部门编码和上级分部的集合 +// * +// * @return +// */ +// public Map getDeptComMap() { +// RecordSet rs = new RecordSet(); +// Map map = new HashMap<>(); +// rs.executeQuery("select outkey,supdepid from HrmDepartment where outkey is not null and (CANCELED!=1 or CANCELED is null)"); +// while (rs.next()) { +// map.put(rs.getString("outkey"), rs.getString("supdepid")); +// } +// return map; +// } + + public Map getDepartmentCodeIdMap() { + RecordSet rs = new RecordSet(); + Map map = new HashMap<>(); + rs.executeQuery("select departmentcode,outkey,id from HrmDepartment where outkey is not null and (CANCELED!=1 or CANCELED is null)"); + while (rs.next()) { + map.put(rs.getString("outkey"), rs.getString("id")); + } + return map; + } + + + /** + * 获取海外部门数据 + * + * @param date 时间 + * @param point + * @return + */ + public JSONArray getOcDepartments(String date, String point) { + log.writeLog("--------------getOcDepartments"); + int current = 1, size = 5000, pages = 2; + String url = HttpClientToJT.baseUrl + "/dcopenedi/hrDept/pageNewHrDeptByUpdateTime"; + String token = HttpClientToJT.getToken(); + log.writeLog("-------token--------->" + token); + Map params = new HashMap<>(); + List list1 = new ArrayList(); + list1.add("ZHS"); + params.put("languageCds", list1); + params.put("updateTime", date); + params.put("point", point); + params.put("size", size); + log.writeLog("传入JSON--------------->" + JSON.toJSONString(params)); + String s = HttpClientToJT.sendPost(url, token, JSONObject.toJSONString(params)); + JSONObject jsonObject = JSONObject.parseObject(s); + JSONArray jsonArray = new JSONArray(); + + String code = Util.null2String(jsonObject.getString("code")); + log.writeLog("code------>" + code); + if ("1".equals(code)) { + JSONObject result = jsonObject.getJSONObject("data"); + JSONArray records = result.getJSONArray("records"); + Object hasNextPage = result.get("hasNextPage"); + jsonArray.addAll(records); + //下次继续传 + maxPoint = result.get("maxPoint").toString(); + if ("false".equals(hasNextPage.toString())) { + ifPage = false; + } + + Object directSales = jsonArray.stream().filter(item -> { + JSONObject itemJson = JSONObject.parseObject(JSON.toJSONString(item)); + return !"CHN".equals(itemJson.getString("countryCode")) && !"IDN".equals(itemJson.getString("countryCode")); + }).collect(Collectors.toList()); + jsonArray = JSONArray.parseArray(JSON.toJSONString(directSales)); + } + + return jsonArray; + } + + + /** + * 获取海外部门国家数据 + * + * @param date 时间 + * @param point + * @return + */ + public JSONArray getOcDepartmentsGUOJIA(String date, String point, String guojia, String departmentCode) { + int current = 1, size = 5000, pages = 2; + String url = HttpClientToJT.baseUrl + "/dcopenedi/hrDept/pageNewHrDeptByUpdateTime"; + String token = HttpClientToJT.getToken(); + log.writeLog("-------token--------->" + token); + Map params = new HashMap<>(); + List list1 = new ArrayList(); + list1.add(guojia); + params.put("languageCds", list1); + params.put("updateTime", date); + params.put("point", point); + params.put("size", size); + params.put("deptCode", departmentCode); + log.writeLog("传入JSON--------------->" + JSON.toJSONString(params)); + String s = HttpClientToJT.sendPost(url, token, JSONObject.toJSONString(params)); + JSONObject jsonObject = JSONObject.parseObject(s); + JSONArray jsonArray = new JSONArray(); + + String code = Util.null2String(jsonObject.getString("code")); + log.writeLog("code------>" + code); + if ("1".equals(code)) { + JSONObject result = jsonObject.getJSONObject("data"); + JSONArray records = result.getJSONArray("records"); + Object hasNextPage = result.get("hasNextPage"); + jsonArray.addAll(records); +// //下次继续传 +// maxPoint = result.get("maxPoint").toString(); +// if ("false".equals(hasNextPage.toString())) { +// ifPage = false; +// } + + Object directSales = jsonArray.stream().filter(item -> { + JSONObject itemJson = JSONObject.parseObject(JSON.toJSONString(item)); + return !"CHN".equals(itemJson.getString("countryCode")); + }).collect(Collectors.toList()); + jsonArray = JSONArray.parseArray(JSON.toJSONString(directSales)); + } + + return jsonArray; + } + + + private void writeFile(JSONArray jsonArray) { + BufferedWriter bw = null; + try { + bw = new BufferedWriter(new FileWriter("D:\\2.txt")); + //一次写一行 + bw.write(jsonArray.toJSONString()); + bw.newLine(); //换行用 + //关闭流 + bw.close(); + } catch (IOException e) { + e.printStackTrace(); + } + System.out.println("写入成功"); + } + + + /** + * 获取多语言 + * + * @param date 时间 + * @param countryCode 国家code + * @param departmentCode 部门code + * @param deptName 部门中文名称 + * @return 多语言名称 + */ + public String getDepartmentName(String date, String countryCode, String departmentCode, String deptName) { + String retName = ""; + boolean existence = true; + String language = ""; + String cdIndex = ""; + try { + if ("CHN".equals(countryCode)) { + language = "ZHS"; + } + if ("BRA".equals(countryCode)) { + language = "POR"; + cdIndex = "21"; + } + if ("SAU".equals(countryCode) || "ARE".equals(countryCode) + || "EGY".equals(countryCode) + || "MEX".equals(countryCode) + || "SGP".equals(countryCode) + || "PHL".equals(countryCode) + || "MYS".equals(countryCode) + || "KHM".equals(countryCode) + ) { + existence = false; + language = "ENG"; + } + // 、 • 7中°~^8英文、心‘9繁体、• ~‘14 越南°~17泰国°~‘21 葡萄牙‘~‘22 印尼 + if ("IDN".equals(countryCode)) { + language = "IDN"; + cdIndex = "22"; + } + if ("THA".equals(countryCode)) { + //language = "THA"; + language = "ENG"; + cdIndex = "17"; + } + if ("VNM".equals(countryCode)) { + language = "VIE"; + cdIndex = "14"; + } + + String country = ""; + // 日期 位置 国家 部门code + JSONArray ocDepartmentsGUOJIA = getOcDepartmentsGUOJIA(date, "1", language, departmentCode); + log.writeLog("--------------多语言是否拿到数据:" + ocDepartmentsGUOJIA.size()); + List countryList = JSONArray.parseArray(ocDepartmentsGUOJIA.toJSONString(), DepartmentDto.class); + DepartmentDto countryDto = countryList.get(0); + //对应国家的语言名称(对应国家标签里面) + String countryDepartmentName = countryDto.getDepartmentName(); + log.writeLog("---------------对应国家语言名称:" + countryDepartmentName); + + //departmentName = + if (existence) { + //需要3个标签 + retName = "~`~`7 " + deptName + "`~`8 " + countryDepartmentName + "`~`" + cdIndex + " " + countryDepartmentName + "`~`~"; + } else { + //只需要中文和英文 + retName = "~`~`7 " + deptName + "`~`8 " + countryDepartmentName + "`~`~"; + } + + log.writeLog("---------------多语言名称:" + retName); + } catch (Exception e) { + e.printStackTrace(); + } + return retName; + } + + + public static void main(String[] args) { +// String token = HttpClientToJT.getToken(); +// SyncHrmsubcompanyToOA hrmsubcompany = new SyncHrmsubcompanyToOA(); +// hrmsubcompany.getSubcompanys(); + SyncHrmdepartmentToOA hrmdepartment = new SyncHrmdepartmentToOA(); + JSONArray data = hrmdepartment.getDepartments("2018-08-01 00:00:00"); + // hrmdepartment.writeFile(data); +// List dataList = JSONArray.parseArray(data.toJSONString(), DepartmentDto.class); +// System.out.println(JSON.toJSONString(dataList)); +// SyncHrmjobtitlesToOA hrmjobtitles = new SyncHrmjobtitlesToOA(); +// hrmjobtitles.getJobtitles(); +// SyncHrmresourceToOA hrmresource = new SyncHrmresourceToOA(); +// JSONArray users = hrmresource.getUsers(); +// System.out.println(users); +// System.out.println(JSON.toJSONString(users)); +// JSONObject row =new JSONObject(); +// Integer status = Util.null2String(row.getInteger("status"))== "3" ? 1 : null; +// System.out.println(status); + } + + +} diff --git a/src/main/youhong_ai_jitu_src/jntchina/schedule/hrm/SynShangBiao.java b/src/main/youhong_ai_jitu_src/jntchina/schedule/hrm/SynShangBiao.java new file mode 100644 index 0000000..d24b22d --- /dev/null +++ b/src/main/youhong_ai_jitu_src/jntchina/schedule/hrm/SynShangBiao.java @@ -0,0 +1,80 @@ +package jntchina.schedule.hrm; + +import jntchina.service.oa.ShangbiaoTemplate; + +import selfdev.util.log.LogTool; +import weaver.conn.RecordSet; +import weaver.docs.webservices.DocAttachment; +import weaver.docs.webservices.DocInfo; +import weaver.docs.webservices.DocServiceImpl; +import weaver.hrm.User; +import weaver.interfaces.schedule.BaseCronJob; + +/** + * @title: 同步商标 + * @Author ycf + * @Date: 2022/1/4 14:27 + * @Version 1.0 + */ +public class SynShangBiao extends BaseCronJob { + private final LogTool log = new LogTool("/log/api/shangB/", false); + + @Override + public void execute() { + RecordSet recordSet = new RecordSet(); + String sql = "select id,by1 ,sbmc from uf_shangbiao where BY1 is null "; + recordSet.execute(sql); + log.writeLog("sql:" + sql); + while (recordSet.next()) { + log.writeLog("商标名称:" + recordSet.getString("sbmc")); + + String id = recordSet.getString("id"); + String sbmc = recordSet.getString("sbmc"); + + this.createDoc(sbmc,id); + } + } + + public void createDoc(String sbmc,String id) { + log.writeLog("商标名称:"+sbmc); + log.writeLog("id:"+id); + + RecordSet recordSet = new RecordSet(); + + DocServiceImpl docService = new DocServiceImpl();//OA知识接口 + DocInfo docInfo = new DocInfo(); //知识文档实体bean + docInfo.setMaincategory(0);//文档主目录 + docInfo.setSubcategory(0);//文档分目录 + recordSet.execute("select id from docseccategory where CATEGORYNAME= '标样'"); + recordSet.next(); + docInfo.setSeccategory(recordSet.getInt("ID")); + docInfo.setDocSubject(sbmc + "商标");//文档标题 + //附件(一个附件创建一篇文档) + DocAttachment[] da = new DocAttachment[1]; + da[0] = new DocAttachment(); + da[0].setDocid(0); + da[0].setImagefileid(0); + recordSet.execute("select needzip,needzipencrypt from systemset"); + while (recordSet.next()) { + da[0].setIszip(recordSet.getInt("NEEDZIP"));//是否压缩 + da[0].setIsencrype(recordSet.getInt("NEEDZIPENCRYPT"));//是否加密 + log.writeLog("是否压缩:" + recordSet.getInt("NEEDZIP")); + log.writeLog("是否加密:" + recordSet.getInt("NEEDZIPENCRYPT")); + } + da[0].setFilename(sbmc + ".jpeg");//附件名 + da[0].setFilecontent(new ShangbiaoTemplate().getBase64(sbmc)); + //将附件添加到文档中 + docInfo.setAttachments(da); + User localUser = User.getUser(1, 0); + //创建文档 + int docid = 0; + try { + docid = docService.createDocByUser(docInfo, localUser); + } catch (Exception e) { + e.printStackTrace(); + } + String sql2 = "update uf_shangbiao set by1 = " + docid + " where id = " + id; + log.writeLog("sql2:" + sql2); + recordSet.execute(sql2); + } +} diff --git a/src/main/youhong_ai_jitu_src/jntchina/schedule/hrm/SyncHRBaseData.java b/src/main/youhong_ai_jitu_src/jntchina/schedule/hrm/SyncHRBaseData.java new file mode 100644 index 0000000..6e19be8 --- /dev/null +++ b/src/main/youhong_ai_jitu_src/jntchina/schedule/hrm/SyncHRBaseData.java @@ -0,0 +1,17 @@ +package jntchina.schedule.hrm; + +import weaver.interfaces.schedule.BaseCronJob; + +public class SyncHRBaseData extends BaseCronJob { + + @Override + public void execute() { + //基础数据 HR转换值 + SyncJTBaseData syncJTBaseData = new SyncJTBaseData(); + syncJTBaseData.syncBaseData(); + //公司数据 + SyncHrmcompanyToOA xx = new SyncHrmcompanyToOA(); + xx.getCompanys(); + } + +} diff --git a/src/main/youhong_ai_jitu_src/jntchina/schedule/hrm/SyncHrmJobTitlesToOANew.java b/src/main/youhong_ai_jitu_src/jntchina/schedule/hrm/SyncHrmJobTitlesToOANew.java new file mode 100644 index 0000000..73e68ac --- /dev/null +++ b/src/main/youhong_ai_jitu_src/jntchina/schedule/hrm/SyncHrmJobTitlesToOANew.java @@ -0,0 +1,491 @@ +package jntchina.schedule.hrm; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.JSONArray; +import com.alibaba.fastjson.JSONObject; +import com.alibaba.fastjson.serializer.SerializerFeature; +import jntchina.schedule.hrm.util.OrganizationUtil; +import jntchina.util.HttpClientToJT; +import org.apache.commons.lang3.StringUtils; +import selfdev.util.base.TimeCommonUtil; +import selfdev.util.log.LogTool; +import weaver.conn.RecordSet; +import weaver.general.Util; +import weaver.hrm.job.JobTitlesComInfo; + +import java.io.BufferedWriter; +import java.io.FileWriter; +import java.io.IOException; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.stream.Collectors; + +/** + * 定时同步岗位到OA中 + * @author Cyq + *

日期 2021年6月17日 02:01:51

+ * @version 2.0 Modify by bleach 修复内存溢出的问题 + */ +public class SyncHrmJobTitlesToOANew { + + //岗位编码和id map + //Map map_jobtitle_code_id = new HashMap<>(); + + private final LogTool log = new LogTool("/log/hrm/job/", false); + public int size;//接口同步每页数量 + public boolean hasNextPage;//是否有下一页 + public String point;//页标 + public String jkhzurl;//接口URL后缀 + public void execute(String today){ + String now = TimeCommonUtil.obtainDate(0); + log.writeLog("--------------------同步岗位 start["+now+"]----------------------"); + + //为空时默认每页1000条数据 + if("null".equals(String.valueOf(size))||"0".equals(String.valueOf(size))||size<=0){ + setSize(1000); + } + //设置同步HR数据时是否有下一页为是 + setHasNextPage(true); + setPoint("1"); + + SyncHrmdepartmentToOA hrmdepartment = new SyncHrmdepartmentToOA(); + Map map_dept_code_id = hrmdepartment.getDepartmentCodeIdMap(); + //岗位自定义建模表中的ID和编码 map + //Map map_jobtitledefined_id_code = BaseUtil.getMapKeyValueInfoByParm("uf_jobtitledefined", "", "positionid", "positioncode"); + //map_jobtitle_code_id = getJobtitleCodeIdMap(); + RecordSet rs = new RecordSet(); + log.writeLog("----------开始同步岗位-------"); + int count = 0; + int skipNum = 0,insertNum=0,updateNum = 0; +// int page = getPages(date); + int page = 5000;//默认为1万页 + log.writeLog("size---------------------->"+size); + //查询条件 + Map map_parm= new HashMap<>(); + map_parm.put("beginTime", today);//时间戳 + map_parm.put("size", size);//每页数量 + + //获取所有的岗位编码,同时将岗位编码存入List中 + List codeList = new ArrayList<>(); + //当前库中已存在的记录集合 -- 系统岗位表 + Map sysExistMap = new HashMap<>(); + //当前库中已存在的记录集合 -- 自定义岗位表 + Map definedExistMap = new HashMap<>(); + + for (int k = 1; k <= page; k++) { + if (!hasNextPage) { + log.writeLog("------------第【" + k + "】次循环获取数据不存在,跳出"); + break; + } + map_parm.put("point", getPoint());//起始位置,第一次 + //JSONArray jobtitles = getJobsByPage(k,date); + //调用接口获取数据 + JSONArray jobtitles = getJobsByPoint_New(map_parm); + //未获取到数据,跳出循环 + if(jobtitles==null||jobtitles.isEmpty()){ + log.writeLog("------------第【" + k + "】调用接口未获取到数据,可能是语言languageCd!=ZHS,跳出本次循环,继续下次循环"); + continue; + } + + codeList.clear(); + sysExistMap.clear(); + definedExistMap.clear(); + for(int m = 0 ; m < jobtitles.size();m++){ + JSONObject row = jobtitles.getJSONObject(m); + String positionCode = Util.null2String(row.getString("positionCode"));//岗位编码 + if(!"".equals(positionCode)){ + codeList.add(positionCode); + } + } + + if(codeList.size() > 0){ + sysExistMap = OrganizationUtil.getExitsData(codeList,0); + definedExistMap = OrganizationUtil.getExitsData(codeList,1); + } + + + count = count + jobtitles.size(); + log.writeLog("----------同步岗位第" + k + "页,条数:" + jobtitles.size()); + for (int i = 0; i < jobtitles.size(); i++) { + JSONObject row = jobtitles.getJSONObject(i); + String positionCode = Util.null2String(row.getString("positionCode"));//岗位编码 + String positionName = Util.null2String(row.getString("positionName"));//岗位名称 + Integer canceled = "3".equals(Util.null2String(row.getString("status"))) ? 1 : null;//1 新增 2 修改 3作废 + String deptCode = Util.null2String(row.getString("deptCode"));//部门编码 + String jobdepartmentid = Util.null2String(map_dept_code_id.get(deptCode));//所属部门ID + String jobtitleid = Util.null2String(sysExistMap.get(positionCode));//OA岗位ID +// String jobactivityid ="1545";//默认职务ID + String positionabbreviation = Util.null2String(row.getString("positionAbbreviation"));//岗位简称 + String positiontype = Util.null2String(row.getString("positionType"));//岗位类别 + String positiontypehighest = Util.null2String(row.getString("positionTypeHighest"));//岗位类别最高 + String positiontypelowest = Util.null2String(row.getString("positionTypeLowest"));//岗位类别最低 + String positionpropecode = Util.null2String(row.getString("positionPropeCode"));//岗位属性编码 + String positionpropename = Util.null2String(row.getString("positionPropeName"));//岗位属性名称 + String companycode = Util.null2String(row.getString("companyCode"));//公司编码 + String companyname = Util.null2String(row.getString("companyName"));//公司名称 + String deptname = Util.null2String(row.getString("deptName"));//部门名称 + String locationcode = Util.null2String(row.getString("locationCode"));//地点编码 + String locationname = Util.null2String(row.getString("locationName"));//地点描述 + String stdpositioncode = Util.null2String(row.getString("stdPositionCode"));//标准岗位编码 + String stdpositionname = Util.null2String(row.getString("stdPositionName"));//标准岗位名称 + String postcode = Util.null2String(row.getString("postCode"));//岗编码 + String postname = Util.null2String(row.getString("postName"));//岗名称 + String sequencecode = Util.null2String(row.getString("sequenceCode"));//序列编码 + String sequencename = Util.null2String(row.getString("sequenceName"));//序列名称 + String positiongroupcode = Util.null2String(row.getString("positionGroupCode"));//岗族编码 + String positiongroupname = Util.null2String(row.getString("positionGroupName"));//岗族名称 + String ethnicgroupcode = Util.null2String(row.getString("ethnicGroupCode"));//族群编码 + String ethnicgroupname = Util.null2String(row.getString("ethnicGroupName"));//族群名称 + + String sql; + //判断HR岗位ID是否已经存在 + if("".equals(jobdepartmentid)){ + skipNum++; + continue; + } + + if ("".equals(Util.null2String(jobtitleid))) {//岗位不存在则插入生成新岗位 + //新增数据,插入到hrmjobtitles表中 + sql = "insert into hrmjobtitles (jobtitlename,jobtitlemark,outkey,jobdepartmentid," + + "canceled,created,creater,modified,modifier) values(" + + "'" + positionName + "'," + + "'" + positionName + "'," + + "'" + positionCode + "'," + + "'" + jobdepartmentid + "'," + + "" + canceled + "," + + "to_date('" + now + "','yyyy-mm-dd hh24:mi:ss')," + + "'1'," + + "to_date('" + now + "','yyyy-mm-dd hh24:mi:ss')," + + "'1')"; + log.writeLog("插入岗位表生成新数据sql--------->" + sql); + if(rs.execute(sql)) { + insertNum++; + rs.execute("select max(id) from hrmjobtitles"); + int maxJobid = 0;//新插入数据的岗位ID + if (rs.next()) { + maxJobid = rs.getInt(1); + //将新增加的岗位加入至MAP中 + //map_jobtitle_code_id.put(positionCode, maxJobid + ""); + sysExistMap.put(positionCode, maxJobid + "");//防止同一批记录中存在重复数据 + } + //新增数据,插入到hrmjobtitles表中 + sql = "insert into uf_jobtitledefined (formmodeid,modedatacreater,modedatacreatertype,modedatacreatedate,modedatacreatetime," + + "positionid,positioncode,positionname,positionabbreviation,positiontype,positiontypehighest,positiontypelowest," + + "positionpropecode,positionpropename,companycode,companyname,deptcode,deptname,locationcode,locationname,stdpositioncode," + + "stdpositionname,postcode,postname,sequencecode,sequencename,positiongroupcode,positiongroupname,ethnicgroupcode,ethnicgroupname) values" + + "(32501,1,0,to_char(sysdate, 'yyyy-MM-dd'),to_char(sysdate, 'HH24:mi:ss'),'" + maxJobid + "','" + positionCode + "','" + positionName + "'," + + "'" + positionabbreviation + "','" + positiontype + "','" + positiontypehighest + "','" + positiontypelowest + "','" + positionpropecode + "'," + + "'" + positionpropename + "','" + companycode + "','" + companyname + "','" + deptCode + "','" + deptname + "','" + locationcode + "'" + "," + + "'" + locationname + "','" + stdpositioncode + "','" + stdpositionname + "','" + postcode + "','" + postname + "','" + sequencecode + "','" + sequencename + "'," + + "'" + positiongroupcode + "','" + positiongroupname + "','" + ethnicgroupcode + "','" + ethnicgroupname + "')"; + log.writeLog("插入岗位建模自定义表生成新数据sql--------->" + sql); + rs.execute(sql); + //将新增加的岗位加入至MAP中 + definedExistMap.put(maxJobid + "", positionCode); + }else{ + log.writeLog("该岗位信息写入失败!"); + } + + } else {//岗位存在则更新 + sql = "update hrmjobtitles set " + + "jobtitlename = '" + positionName + "', " + + "jobtitlemark = '" + positionName + "', " + + "jobtitlecode = '" + positionCode + "', " + + "jobdepartmentid = '" + jobdepartmentid + "', " + + "modified = to_date('" + now + "','yyyy-mm-dd hh24:mi:ss')," + + "modifier = '1', " + + "canceled = " + canceled + " " + + "where id= '" + jobtitleid + "'"; + log.writeLog("更新岗位表中数据sql--------->" + sql); + rs.execute(sql); + updateNum++; + log.writeLog("更新岗位表---成功------>"); + + + if(definedExistMap.containsKey(jobtitleid)){//存在则更新岗位自定义表 + sql = "update uf_jobtitledefined set " + + "positionName = '" + positionName + "', " + + "positionabbreviation = '" + positionabbreviation + "', " + + "positiontype = '" + positiontype + "', " + + "positiontypehighest = '" + positiontypehighest + "', " + + "positiontypelowest = '" + positiontypelowest + "', " + + "positionpropecode = '" + positionpropecode + "', " + + "positionpropename = '" + positionpropename + "', " + + "companycode = '" + companycode + "', " + + "companyname = '" + companyname + "', " + + "deptCode = '" + deptCode + "', " + + "deptname = '" + deptname + "', " + + "locationcode = '" + locationcode + "', " + + "locationname = '" + locationname + "', " + + "stdpositioncode = '" + stdpositioncode + "', " + + "stdpositionname = '" + stdpositionname + "', " + + "postcode = '" + postcode + "', " + + "postname = '" + postname + "', " + + "sequencecode = '" + sequencecode + "', " + + "sequencename = '" + sequencename + "', " + + "positiongroupcode = '" + positiongroupcode + "', " + + "positiongroupname = '" + positiongroupname + "', " + + "ethnicgroupcode = '" + ethnicgroupcode + "', " + + "ethnicgroupname = '" + ethnicgroupname + "' " + + "where positionid= '" + jobtitleid + "'"; + log.writeLog("更新岗位建模自定义表中数据sql--------->" + sql); + rs.execute(sql); + + }else{//不存在则插入岗位自定义表 + //新增数据,插入到hrmjobtitles表中 + sql = "insert into uf_jobtitledefined (formmodeid,modedatacreater,modedatacreatertype,modedatacreatedate,modedatacreatetime," + + "positionid,positioncode,positionname,positionabbreviation,positiontype,positiontypehighest,positiontypelowest," + + "positionpropecode,positionpropename,companycode,companyname,deptcode,deptname,locationcode,locationname,stdpositioncode," + + "stdpositionname,postcode,postname,sequencecode,sequencename,positiongroupcode,positiongroupname,ethnicgroupcode,ethnicgroupname) values" + + "(32501,1,0,to_char(sysdate, 'yyyy-MM-dd'),to_char(sysdate, 'HH24:mi:ss'),'"+jobtitleid+"','"+positionCode+"','"+positionName+"'," + + "'"+positionabbreviation+"','"+positiontype+"','"+positiontypehighest+"','"+positiontypelowest+"','"+positionpropecode+"'," + + "'"+positionpropename+"','"+companycode+"','"+companyname+"','"+deptCode+"','"+deptname+"','"+locationcode+"'"+ "," + + "'"+locationname+"','"+stdpositioncode+"','"+stdpositionname+"','"+postcode+"','"+postname+"','"+sequencecode+"','"+sequencename+"'," + + "'"+positiongroupcode+"','"+positiongroupname+"','"+ethnicgroupcode+"','"+ethnicgroupname+"')"; + log.writeLog("插入岗位建模自定义表生成新数据sql--------->" + sql); + rs.execute(sql); + //将新增加的岗位加入至MAP中 + //map_jobtitledefined_id_code.put(jobtitleid + "",positionCode); + definedExistMap.put(jobtitleid,positionCode); + } + } + } + log.writeLog("----------同步结束岗位,第" + k + "页:"+count+ + ",新增岗位数为:"+insertNum+" ,更新岗位数为:"+updateNum+",跳出处理岗位数为:"+skipNum+"------------"); + skipNum = 0;insertNum=0;updateNum = 0; + } + log.writeLog("----------同步结束岗位总数:"+count+"------------"); + //更新岗位缓存 + JobTitlesComInfo jtci = new JobTitlesComInfo(); + jtci.removeJobTitlesCache(); + + //释放map占用的内存 + //map_jobtitledefined_id_code.clear(); + map_dept_code_id.clear(); + //map_jobtitle_code_id.clear(); + //map_jobtitle_code_id=null; + + //更新同步时间到中间表 + String sql1 = "update uf_HRRestDate set sctbsj ='"+now+"' where jkbs = 'post'"; + rs.execute(sql1); + + } + /** + * 获取当前库的岗位信息 + * @deprecated 暂不使用 + * @return 岗位信息集合 + */ + public Map getJobtitleCodeIdMap() { + RecordSet rs = new RecordSet(); + Map map = new HashMap<>(); + rs.executeQuery("select jobtitlecode,outkey,id from hrmjobtitles where outkey is not null and (CANCELED!=1 or CANCELED is null)"); + while (rs.next()) { + map.put(rs.getString("outkey"), rs.getString("id")); + } + return map; + } + + /** + * 获取岗位信息(新方法) + * @param map 查询条件 + * @return 返回岗位信息 + */ + @SuppressWarnings("unchecked") + public JSONArray getJobsByPoint_New(Map map) { + //新接口URL + String url = HttpClientToJT.baseUrl + getJkhzurl(); + log.writeLog("获取岗位数据url-------->"+url); + LogTool log2 = new LogTool("/log/hrm/job/detail", false); + //获取token + String token = HttpClientToJT.getToken(); + //将map转成字符串 + String param=JSONObject.toJSONString(map, SerializerFeature.DisableCircularReferenceDetect); + log.writeLog("获取岗位数据传入参数param------------>"+param); + log2.writeLog("获取岗位数据传入参数param------------>"+param); + String s = HttpClientToJT.sendPost(url, token, param); + log2.writeLog("岗位数据返回结果------------>"+s); + + JSONObject jsonObject = JSONObject.parseObject(s); + JSONArray jsonArray = new JSONArray(); + String code=Util.null2String(jsonObject.getString("code")); + if ("1".equals(code)) { + JSONObject result = jsonObject.getJSONObject("data"); + //是否有下一页 + boolean sfyxyy=result.getBoolean("hasNextPage");//是否有下一页 + String maxPoint=result.getString("maxPoint");//下一页开始 + this.setHasNextPage(sfyxyy); + this.setPoint(maxPoint); + JSONArray records = result.getJSONArray("records"); + //过滤未获取到数据 + if(records!=null){ + jsonArray.addAll(records); + Object directSales = jsonArray.stream().filter(item -> { + JSONObject itemJson = JSONObject.parseObject(JSON.toJSONString(item)); + return "ZHS".equals(itemJson.getString("languageCd")); + }).collect(Collectors.toList()); + jsonArray = JSONArray.parseArray(JSON.toJSONString(directSales)); + } + }else{ + this.setHasNextPage(false); + } + + + return jsonArray; + } + + /** + * @deprecated 未使用到 + * @param date 日期 + * @return 整数 + */ + public int getPages(String date) { + int current = 1,pages=1; + String url = HttpClientToJT.baseUrl+"/dcopenedi/hrPost/pageByUpdateTime"; + String token = HttpClientToJT.getToken(); + Map params = new HashMap<>(); + params.put("updateTime",date); + params.put("current",current); + params.put("size",size); + String s = HttpClientToJT.sendGet(url, token, params); + JSONObject jsonObject = JSONObject.parseObject(s); + String code=Util.null2String(jsonObject.getString("code")); + log.writeLog("code------>"+code); + if ("1".equals(code)) { + JSONObject result = jsonObject.getJSONObject("data"); + pages = result.getInteger("pages"); + }else{ + log.writeLog("获取页数返回结果------>"+s); + } + return pages; + } + + /** + * @deprecated 未使用到 + * @param pages 页数 + * @param date 日期 + * @return 岗位信息 + */ + @SuppressWarnings("unchecked") + public JSONArray getJobsByPage(int pages,String date) { + String url = HttpClientToJT.baseUrl+"/dcopenedi/hrPost/pageByUpdateTime"; + String token = HttpClientToJT.getToken(); + Map params = new HashMap<>(); + params.put("updateTime",date); + params.put("current",pages); + params.put("size",size); + String s = HttpClientToJT.sendGet(url, token, params); + JSONObject jsonObject = JSONObject.parseObject(s); + JSONArray jsonArray = new JSONArray(); + String code=Util.null2String(jsonObject.getString("code")); + if ("1".equals(code)) { + JSONObject result = jsonObject.getJSONObject("data"); + JSONArray records = result.getJSONArray("records"); + jsonArray.addAll(records); + } + Object directSales = jsonArray.stream().filter(item -> { + JSONObject itemJson = JSONObject.parseObject(JSON.toJSONString(item)); + return "ZHS".equals(itemJson.getString("languageCd")); + }).collect(Collectors.toList()); + jsonArray = JSONArray.parseArray(JSON.toJSONString(directSales)); + return jsonArray; + } + + /** + * 获取岗位信息 + * @return JSONArray + */ + @SuppressWarnings("unchecked") + public JSONArray getJobtitles() { + int current = 1,pages; + String url = HttpClientToJT.baseUrl+"/dcopenedi/hrPost/pageByUpdateTime"; + String token = HttpClientToJT.getToken(); + Map params = new HashMap<>(); + params.put("updateTime", "2021-03-21 00:00:00"); + params.put("current",current); + params.put("size",size); + String s = HttpClientToJT.sendGet(url, token, params); + JSONObject jsonObject = JSONObject.parseObject(s); + JSONArray jsonArray = new JSONArray(); + String code=Util.null2String(jsonObject.getString("code")); + if ("1".equals(code)) { + JSONObject result = jsonObject.getJSONObject("data"); + pages = result.getInteger("pages"); + JSONArray records = result.getJSONArray("records"); + jsonArray.addAll(records); + for (int i = 2; i <= pages; i++) { + System.out.println(i); + params.put("current", i); + String str = HttpClientToJT.sendGet(url, token, params); + JSONObject jsonObject1 = JSONObject.parseObject(str); + JSONObject jsonResult = jsonObject1.getJSONObject("data"); + JSONArray records1 = jsonResult.getJSONArray("records"); + jsonArray.addAll(records1); + } + Object directSales = jsonArray.stream().filter(item -> { + JSONObject itemJson = JSONObject.parseObject(JSON.toJSONString(item)); + return "ZHS".equals(itemJson.getString("languageCd")); + }).collect(Collectors.toList()); + jsonArray = JSONArray.parseArray(JSON.toJSONString(directSales)); + } +// System.out.println(jsonArray.toJSONString()); +// System.out.println(s); + //将写入转化为流的形式 + writeFile(jsonArray); + return jsonArray; + } + + private void writeFile(JSONArray jsonArray) { + BufferedWriter bw; + try { + bw = new BufferedWriter(new FileWriter("E:\\3.txt")); + //一次写一行 + bw.write(jsonArray.toJSONString()); + bw.newLine(); //换行用 + //关闭流 + bw.close(); + } catch (IOException e) { + e.printStackTrace(); + } + System.out.println("写入成功"); + } + + public static void main(String[] args) { + SyncHrmJobTitlesToOANew job = new SyncHrmJobTitlesToOANew(); + JSONArray array = job.getJobtitles(); + System.out.println(array.toJSONString()); + } + + public int getSize() { + return size; + } + + public void setSize(int size) { + this.size = size; + } + + public boolean isHasNextPage() { + return hasNextPage; + } + + public void setHasNextPage(boolean hasNextPage) { + this.hasNextPage = hasNextPage; + } + + public String getPoint() { + return point; + } + + public String getJkhzurl() { + return jkhzurl; + } + + public void setJkhzurl(String jkhzurl) { + this.jkhzurl = jkhzurl; + } + + public void setPoint(String point) { + this.point = point; + } +} diff --git a/src/main/youhong_ai_jitu_src/jntchina/schedule/hrm/SyncHrmcompanyToOA.java b/src/main/youhong_ai_jitu_src/jntchina/schedule/hrm/SyncHrmcompanyToOA.java new file mode 100644 index 0000000..e512111 --- /dev/null +++ b/src/main/youhong_ai_jitu_src/jntchina/schedule/hrm/SyncHrmcompanyToOA.java @@ -0,0 +1,187 @@ +package jntchina.schedule.hrm; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.JSONArray; +import com.alibaba.fastjson.JSONObject; +import com.weaver.formmodel.util.DateHelper; +import jntchina.schedule.hrm.entity.CompanyDto; +import jntchina.util.HttpClientToJT; +import selfdev.util.log.LogTool; +import weaver.conn.RecordSet; +import weaver.file.Prop; +import weaver.formmode.data.ModeDataIdUpdate; +import weaver.formmode.setup.ModeRightInfo; +import weaver.general.Util; + +import java.io.BufferedWriter; +import java.io.FileWriter; +import java.io.IOException; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.stream.Collectors; + +/** + * @author Cyq + * @date 2021年6月17日 02:01:51 + */ +@SuppressWarnings("all") +public class SyncHrmcompanyToOA { + + // 分部编码和id map + Map map_company_code_id = new HashMap(); + private LogTool log = new LogTool("/log/hrm/company/", false); + + /** + * 同步HR的公司数据到uf_hrmcompany建模表,注意不是对应OA组织架构hrmsubcompany数据,仅为流程集成时使用 + */ + public void companySynJob() { + // 获取中台所有公司数据 + JSONArray subcompanys = getCompanys(); + // 已有公司数据map + map_company_code_id = getAllCompanys(); + List companyDtos = JSONArray.parseArray(subcompanys.toJSONString(), CompanyDto.class); + RecordSet rs = new RecordSet(); + RecordSet rs2 = new RecordSet(); + String sql = ""; + // 建模表表名 + String tablename = "uf_hrmcompany"; + String mode = Prop.getPropValue("DevToHR_jntchina", "mode"); + // 建模ID + String formmodeId_p = Prop.getPropValue("DevToHR_jntchina", mode + "_" + tablename + "_formmodeId"); + log.writeLog("formmodeId_p---------->" + formmodeId_p); + // 建模ID + int modelId = Integer.parseInt(formmodeId_p); + // TODO 同步进表 + log.writeLog("-----------同步HR公司开始----------"); + for (int i = 0; i < companyDtos.size(); i++) { + CompanyDto companyDto = companyDtos.get(i); + // 不存在新增 + if (!map_company_code_id.containsKey(companyDto.getCompanyCode())) { + String modeid_2 = ""; + // 为解决同时手工执行点击了2次同步时多线程产生的问题,故还需要再次查询一遍数据库中是否已存在 + rs2.execute("select * from " + tablename + " where company_code='" + companyDto.getCompanyCode() + "'"); + while (rs2.next()) { + modeid_2 = Util.null2String(rs2.getString("id")); + } + // 若不存在则插入,若已存在则不做其他操作 + if (!"".equals(modeid_2)) { + map_company_code_id.put(companyDto.getCompanyCode(), modeid_2); + continue; + } + // 建模插入数据 + int id = ModeDataIdUpdate.getInstance().getModeDataNewIdByUUID(tablename, modelId, 1, 1, DateHelper.getCurrentDate(), DateHelper.getCurrentTime()); + log.writeLog("-----------公司建模数据id----------" + id); + ModeRightInfo ModeRightInfo = new ModeRightInfo(); + ModeRightInfo.setNewRight(true); + // 新建的时候添加共享 + ModeRightInfo.editModeDataShare(1, modelId, id); + // 新建的时候添加文档共享 + ModeRightInfo.addDocShare(1, modelId, id); + sql = "update " + tablename + " set " + + "language_cd = '" + companyDto.getLanguageCd() + "', " + + "company_code = '" + companyDto.getCompanyCode() + "', " + + "company_name = '" + companyDto.getCompanyName() + "', " + + "company_abbreviation = '" + companyDto.getCompanyAbbreviation() + "', " + + "country_code = '" + companyDto.getCountryCode() + "', " + + "country_name = '" + companyDto.getCountryName() + "', " + + "company_level_code = '" + companyDto.getCompanyLevelCode() + "', " + + "company_level_name = '" + companyDto.getCompanyLevelName() + "', " + + "is_direct_sales = '" + companyDto.getIsDirectSales() + "', " + + "unify_social_credit_code = '" + companyDto.getUnifySocialCreditCode() + "', " + + "status = '" + companyDto.getStatus() + "' " + + "where id = " + id; + log.writeLog("-----------公司新增sql:" + sql); + rs.executeUpdate(sql); + map_company_code_id.put(companyDto.getCompanyCode(), id + ""); + } else {// 存在修改 + sql = "update " + tablename + " set " + + "company_name = '" + companyDto.getCompanyName() + "', " + + "company_abbreviation = '" + companyDto.getCompanyAbbreviation() + "', " + + "company_level_code = '" + companyDto.getCompanyLevelCode() + "', " + + "company_level_name = '" + companyDto.getCompanyLevelName() + "', " + + "unify_social_credit_code = '" + companyDto.getUnifySocialCreditCode() + "', " + + "is_direct_sales = '" + companyDto.getIsDirectSales() + "', " + + "status = '" + companyDto.getStatus() + "' " + + "where company_code = '" + companyDto.getCompanyCode() + "'"; + log.writeLog("-----------公司更新sql:" + sql); + rs.executeUpdate(sql); + } + + } + log.writeLog("-----------公司同步结束----------"); + } + + public Map getAllCompanys() { + RecordSet rs = new RecordSet(); + Map map = new HashMap<>(); + String sql = "select company_code,id from uf_hrmcompany"; + rs.executeQuery(sql); + while (rs.next()) { + map.put(rs.getString("company_code"), rs.getString("id")); + } + return map; + + } + + public JSONArray getCompanys() { + int current = 1, size = 10000, pages = 2; + String url = HttpClientToJT.baseUrl + "/dcopenedi/hrCompany/pageByUpdateTime"; + System.out.println(url); + String token = HttpClientToJT.getToken(); + Map params = new HashMap<>(); +// LocalDateTime today_start = LocalDateTime.of(LocalDate.now(), LocalTime.MIN);//当天零点 +// String td_st_str = today_start.format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")); +// params.put("updateTime", td_st_str); + params.put("updateTime", "2018-03-21 00:00:00"); + params.put("current", current); + params.put("size", size); + String s = HttpClientToJT.sendGet(url, token, params); + JSONObject jsonObject = JSONObject.parseObject(s); + JSONArray jsonArray = new JSONArray(); + if (jsonObject.getInteger("code").equals(1)) { + JSONObject result = jsonObject.getJSONObject("data"); + pages = result.getInteger("pages"); + JSONArray records = result.getJSONArray("records"); + jsonArray.addAll(records); + for (int i = 2; i <= pages; i++) { + params.put("current", i); + String str = HttpClientToJT.sendGet(url, token, params); + JSONObject jsonObject1 = JSONObject.parseObject(str); + JSONObject jsonResult = jsonObject1.getJSONObject("data"); + JSONArray records1 = jsonResult.getJSONArray("records"); + jsonArray.addAll(records1); + } + Object directSales = jsonArray.stream().filter(item -> { + JSONObject itemJson = JSONObject.parseObject(JSON.toJSONString(item)); + return "CHN".equals(itemJson.getString("countryCode")) && "ZHS".equals(itemJson.getString("languageCd")); + // return "ZHS".equals(itemJson.getString("languageCd")); + }).collect(Collectors.toList()); + jsonArray = JSONArray.parseArray(JSON.toJSONString(directSales)); + } + System.out.println(jsonArray.toJSONString()); + // 将写入转化为流的形式 +// writeFile(jsonArray); + return jsonArray; + } + + private void writeFile(JSONArray jsonArray) { + BufferedWriter bw = null; + try { + bw = new BufferedWriter(new FileWriter("E:\\1.txt")); + // 一次写一行 + bw.write(jsonArray.toJSONString()); + bw.newLine(); // 换行用 + // 关闭流 + bw.close(); + } catch (IOException e) { + e.printStackTrace(); + } + System.out.println("写入成功"); + } + + public static void main(String[] args) { + SyncHrmcompanyToOA xx = new SyncHrmcompanyToOA(); + xx.getCompanys(); + } +} diff --git a/src/main/youhong_ai_jitu_src/jntchina/schedule/hrm/SyncHrmdepartmentToOA.java b/src/main/youhong_ai_jitu_src/jntchina/schedule/hrm/SyncHrmdepartmentToOA.java new file mode 100644 index 0000000..e221a57 --- /dev/null +++ b/src/main/youhong_ai_jitu_src/jntchina/schedule/hrm/SyncHrmdepartmentToOA.java @@ -0,0 +1,702 @@ +package jntchina.schedule.hrm; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.JSONArray; +import com.alibaba.fastjson.JSONObject; +import com.alibaba.fastjson.serializer.SerializerFeature; +import com.api.integration.util.JavaUtil; +import jntchina.schedule.hrm.entity.DepartmentDto; +import jntchina.util.HttpClientToJT; +import selfdev.util.base.TimeCommonUtil; +import selfdev.util.log.LogTool; +import weaver.conn.RecordSet; +import weaver.general.Util; +import weaver.hrm.company.DepartmentComInfo; +import weaver.matrix.MatrixUtil; + +import java.io.BufferedWriter; +import java.io.FileWriter; +import java.io.IOException; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.stream.Collectors; + +/** + * 定时将HR系统中的组织同步至OA的部门中 + * + * @author Cyq + * @date 2021年6月17日 02:01:51 + */ +public class SyncHrmdepartmentToOA { + + //部门编码和id map + Map map_dept_code_id = new HashMap(); + private LogTool log = new LogTool("/log/hrm/dept/", false); + public int size;//接口同步每页数量 + public boolean hasNextPage;//是否有下一页 + public String point;//页标 + public String jkhzurl = "/dcopenedi/hrDept/pageNewHrDeptByUpdateTime";//接口URL后缀 + + /** + * 同步分部、部门数据 + * 注:对方整个组织数不区分部门和分部,全部用部门接口数据,用类型区分 + */ + public void execute(String today) { + String now = TimeCommonUtil.obtainDate(0); + log.writeLog("--------------------同步组织 start[" + now + "]----------------------"); + //为空时默认每页1000条数据 + if ("null".equals(String.valueOf(size)) || "0".equals(String.valueOf(size)) || size <= 0) { + setSize(1000); + } + //设置同步HR数据时是否有下一页为是 + setHasNextPage(true); + setPoint("1"); + RecordSet rs = new RecordSet(); + //处理部门同步逻辑 + RecordSet rs2 = new RecordSet(); + //匹配部门id,关联的上级部门,所属分部 map + Map> map_dept_id_data = new HashMap<>(); + map_dept_id_data = getDeptDataMap(); + map_dept_code_id = getDepartmentCodeIdMap(); + SyncHrmsubcompanyToOA hrmsubcompany = new SyncHrmsubcompanyToOA(); + SyncHrmresourceToOA hrmresource = new SyncHrmresourceToOA(); + //人员map,用于匹配上级领导 + Map map_user_code_id = hrmresource.getUserCodeIdMap(); + //分部List + List subcompanys = new ArrayList(); + //部门List + List departments = new ArrayList(); + log.writeLog("size---------------------->" + size); + //查询条件 + Map map_parm = new HashMap(); + map_parm.put("updateTime", today);//时间戳 + map_parm.put("size", size);//每页数量 +// List languageCds_list=new ArrayList(); +// languageCds_list.add("ZHS");//语言默认为中文 +// map_parm.put("languageCds", languageCds_list);//支持多语言 + log.writeLog("----------hasNextPage------------>" + hasNextPage); + List skipList = new ArrayList<>(); + int skipNum = 0, insertNum = 0, updateNum = 0; + int page = 10000;//默认为1万页 + for (int k = 1; k <= page; k++) { + if (!hasNextPage) { + log.writeLog("------------第【" + k + "】次循环获取数据不存在,跳出"); + break; + } + map_parm.put("point", getPoint());//起始位置,第一次 + //拆分数据、organizationClass 10类型是组织,其他类型当部门,【代理区】在对方那是虚拟部门,特殊处理划分为OA 分部 + //JSONArray data = getDepartments(date); + //调用新接口获取组织数据 + JSONArray data = getDepartmentsByPoint_New(map_parm); + //接口未获取到数据时,跳过当前循环,进入下一次 + if (data == null || data.isEmpty()) { + log.writeLog("------------第【" + k + "】调用接口未获取到数据,可能是语言languageCd!=ZHS,或者部门国家!=CHN,跳出本次循环,继续下次循环"); + continue; + } + List dataList = JSONArray.parseArray(data.toJSONString(), DepartmentDto.class); + //分部数据 + List subcompanys_dt = dataList.stream().filter(item -> { + return "10".equals(item.getOrganizationClass()) || "代理区".equals(item.getDepartmentName()) + || "加盟商".equals(item.getDepartmentName()) || "中国J&T".equals(item.getDepartmentName()) + || "纭毅".equals(item.getDepartmentName()) || "云路科技".equals(item.getDepartmentName())||"区域管理".equals(item.getDepartmentName()); + }).collect(Collectors.toList()); + //部门数据 注意:10000300代理区编码 + List departments_dt = dataList.stream().filter(item -> { + return !"10".equals(item.getOrganizationClass()) && !"中国J&T".equals(item.getDepartmentName()) + && !"代理区".equals(item.getDepartmentName()) && !"加盟商".equals(item.getDepartmentName()) + && !"纭毅".equals(item.getDepartmentName()) && !"云路科技".equals(item.getDepartmentName())&&!"区域管理".equals(item.getDepartmentName()) + && !"10000300".equals(item.getSuperiorDepartment()); + }).collect(Collectors.toList()); + log.writeLog("----------同步分部第" + k + "页,条数:" + subcompanys_dt.size()); + log.writeLog("----------同步分部第" + k + "页,具体数据:" + JSON.toJSONString(subcompanys_dt, SerializerFeature.DisableCircularReferenceDetect)); + log.writeLog("----------同步部门第" + k + "页,条数:" + departments_dt.size()); + log.writeLog("----------同步部门第" + k + "页,具体数据:" + JSON.toJSONString(departments_dt, SerializerFeature.DisableCircularReferenceDetect)); + + //将数据add到list中 + subcompanys.addAll(subcompanys_dt); + departments.addAll(departments_dt); + } + + + //同步分部 + hrmsubcompany.execute(subcompanys); + //获取分部code与ID的MAP映射关系 + Map map_subcompany_code_id = hrmsubcompany.getSubCodeIdMap(); + + // 处理部门同步逻辑 1.未匹配到分部,不新增, + for (int i = 0; i < departments.size(); i++) { + DepartmentDto row = departments.get(i); + String countryCode = Util.null2String(row.getCountryCode());//国家编码 + String departmentCode = Util.null2String(row.getDepartmentCode());//部门编码 + String departmentName = Util.null2String(row.getDepartmentName());//部门全称 +// String shortName = Util.null2String(row.getDepartmentAbbreviation());//部门简称 + String superiorDepartment = Util.null2String(row.getSuperiorDepartment());//上级部门编码 + String departmentOrder = Util.null2String(row.getDepartmentOrder());//排序 + String deptManager = Util.null2String(row.getDeptManager());//部门负责人code + String brchLeader = Util.null2String(row.getBrchLeader());//分管领导code + Integer canceled = Util.null2String(row.getStatus()).equals("3") ? 1 : null;//1 新增 2 修改 3作废 + String companyCode = Util.null2String(row.getCompanyCode());// 公司 +// String companyName = Util.null2String(row.getCompanyName());//公司名称 + if ("".equals(superiorDepartment)) {//上级部门为空时,则跳过同步 + skipList.add(row); + skipNum++; + log.writeLog("----------部门编码【" + departmentCode + "】、部门名称【" + departmentName + "】的上级部门为空,跳过同步----------"); + continue; + } + //各种code转id + String bmfzr = Util.null2String(map_user_code_id.get(deptManager));//部门负责人 + String bmfgld = Util.null2String(map_user_code_id.get(brchLeader));//分管领导 + String subcompanyid1 = Util.null2String(map_subcompany_code_id.get(superiorDepartment));//分部ID + String supdepid = Util.null2String(map_dept_code_id.get(superiorDepartment));//获取上级ID + log.writeLog("------------subcompanyid1:" + subcompanyid1 + "-----deptCode:" + departmentCode + ",status:" + row.getStatus() + ",canceled:" + canceled + "-------"); + log.writeLog("------------supdepid:" + supdepid + "----deptCode:" + departmentCode + ",status:" + row.getStatus() + ",canceled:" + canceled + "--------"); + //如果上级编码为空、所属分部,上级部门都找不到,不作处理 + if ("".equals(superiorDepartment) || ("".equals(subcompanyid1) && "".equals(supdepid))) { + skipList.add(row); + skipNum++; + log.writeLog("----------部门编码【" + departmentCode + "】、部门名称【" + departmentName + "】、上级部门编码【" + superiorDepartment + "】在OA中为匹配上上级部门,或者未找到所属分部,跳过同步----------"); + continue; + } + String sql = ""; + //判断HR部门ID是否已经存在 + +// //多语言 +// departmentName = getDepartmentName(today,departmentCode,departmentName); +// if("".equals(departmentName)){ +// log.writeLog("--------------多语言为空code:"+departmentCode); +// departmentName = row.getDepartmentName(); +// } + + //只需要中文和英文 + departmentName = "~`~`7 " + departmentName + "`~`8 `~`~"; + log.writeLog("-------------英语刷为空:" + departmentName); + + log.writeLog("第" + (i + 1) + "条,取数据完成!"); + if (!map_dept_code_id.containsKey(departmentCode)) {//部门不存在则插入生成新部门 + //如果找到subcompanyid1不为空,说明是顶级部门, + if (!"".equals(subcompanyid1)) { + supdepid = "0"; + } + if (!"".equals(supdepid) && "".equals(subcompanyid1)) { + log.writeLog("开始取部门:" + departmentCode + ",上级分部id:" + supdepid + "。"); + subcompanyid1 = getSubId(map_dept_id_data, supdepid); + log.writeLog("结束取部门:" + departmentCode + ",上级分部id:" + supdepid + ",取到的分部id:" + subcompanyid1); + } + String deptid_2 = ""; + //为解决同时手工执行点击了2次同步时多线程产生的问题,故还需要再次查询一遍数据库中是否已存在 + rs2.execute("select id from HrmDepartment where outkey='" + departmentCode + "'"); + while (rs2.next()) { + deptid_2 = Util.null2String(rs2.getString("id")); + } + //若不存在则插入,若已存在则不做其他操作 + if (!"".equals(deptid_2)) { + log.writeLog("部门ID【" + deptid_2 + "】、部门编码【" + departmentCode + "】、部门outkey【" + departmentCode + "】已存在,当前跳过,进入下一次循环"); + map_dept_code_id.put(departmentCode, deptid_2); + skipNum++; + continue; + } + sql = "insert into HrmDepartment (departmentname,departmentcode,departmentmark,outkey," + + "supdepid,canceled,created,creater,modified,modifier," + + "showorder,subcompanyid1,bmfzr,bmfgld) values(" + + "'" + departmentName + "'," + + "'" + departmentCode + "'," + + "'" + departmentName + "'," + + "'" + departmentCode + "'," + + "'" + supdepid + "'," + + "" + canceled + "," + + "to_date('" + now + "','yyyy-mm-dd hh24:mi:ss')," + + "'1'," + + "to_date('" + now + "','yyyy-mm-dd hh24:mi:ss')," + + "'1'," + + "'" + departmentOrder + "'," + + "'" + subcompanyid1 + "', " + + "'" + bmfzr + "', " + + "'" + bmfgld + "')"; + log.writeLog("插入部门表生成新数据sql--------->" + sql); + rs.execute(sql); + insertNum++; + rs.execute("select max(id) from HrmDepartment"); + int maxDeptID = 0;//新插入数据的部门ID + if (rs.next()) { + maxDeptID = rs.getInt(1); + //将新增加的部门加入至MAP中 + map_dept_code_id.put(departmentCode, maxDeptID + ""); + //将数据加入到MAP中 + Map map2 = new HashMap(); + map2.put("outkey", departmentCode); + map2.put("subdepid", supdepid); + map2.put("subcompanyid1", subcompanyid1); + map_dept_id_data.put(maxDeptID + "", map2); + } + //新增数据,插入到部门自定义表HrmDepartmentDefined中 + sql = "insert into HrmDepartmentDefined(deptid,sfzy,frgs,bmfzr,guojia,bmfgld) " + + "values('" + maxDeptID + "'," + + "'" + row.getIsDirectSales() + "'," + + "'" + companyCode + "'," + + "'" + bmfzr + "'," + + "'" + countryCode + "'," + + "'" + bmfgld + "')"; + rs.execute(sql); + log.writeLog("插入部门自定义表中数据sql--------->" + sql); +// //将新增加的人员自定义信息加入至MAP中 +// map_dept_id_defined.put(maxDeptID + "", maxDeptID + ""); +// //将部门与所属分部对应关系放到map中 +// map_deptid_subcompanyid.put(maxDeptID + "", subcompanyid1); + //同步部门矩阵信息 + MatrixUtil.updateDepartmentData(maxDeptID + ""); + } else {//部门存在则更新 + //如果找到subcompanyid1不为空,说明是顶级部门, + String deptid = Util.null2String(map_dept_code_id.get(departmentCode));//OA部门ID + if ("".equals(deptid)) { + skipNum++; + continue; + } + if (!"".equals(subcompanyid1)) { + supdepid = "0"; + } + if (!"".equals(supdepid) && "".equals(subcompanyid1)) { + log.writeLog("开始取部门" + departmentCode + "上级分部id:" + supdepid + "。"); + subcompanyid1 = getSubId(map_dept_id_data, supdepid); + log.writeLog("结束取部门" + departmentCode + "上级分部id:" + supdepid + "。取到的分部id:" + subcompanyid1); + } + String updateStr = ""; + //只有有值才覆盖 + updateStr += !"".equals(subcompanyid1) ? "subcompanyid1 = '" + subcompanyid1 + "', " : ""; + updateStr += !"".equals(supdepid) ? "supdepid = '" + supdepid + "', " : ""; + updateStr += !"".equals(bmfzr) ? "bmfzr = '" + bmfzr + "', " : ""; + updateStr += !"".equals(bmfgld) ? "bmfgld = '" + bmfgld + "', " : ""; + sql = "update HrmDepartment set " + + "departmentname = '" + departmentName + "', " + + "departmentmark = '" + departmentName + "', " + + updateStr + + "canceled = " + canceled + ", " + + "modified = to_date('" + now + "','yyyy-mm-dd hh24:mi:ss'), " + + "modifier = '1', " + + "showorder = '" + departmentOrder + "' " + + "where id= '" + deptid + "'"; + log.writeLog("更新部门表中数据sql--------->" + sql); + rs.execute(sql); + updateNum++; + //处理部门矩阵 + sql = "select deptid,bmfzr,bmfgld,sfzy from HrmDepartmentDefined where deptid ='" + deptid + "'"; + rs.executeQuery(sql); + if (rs.next()) { + bmfzr = !"".equals(bmfzr) ? bmfzr : Util.null2String(rs.getString("bmfzr")); + bmfgld = !"".equals(bmfgld) ? bmfgld : Util.null2String(rs.getString("bmfgld")); + sql = "update HrmDepartmentDefined set " + + "bmfzr = '" + bmfzr + "' " + + ",guojia = '" + countryCode + "' " + + ",sfzy = '" + row.getIsDirectSales() + "' " + + ",frgs= '" + companyCode + "'" + + ",bmfgld= '" + bmfgld + "'" + + "where deptid = '" + deptid + "'"; + rs.execute(sql); + log.writeLog("更新部门自定义表中数据sql--------->" + sql); + } else { + sql = "insert into HrmDepartmentDefined(deptid,sfzy,frgs,bmfzr,guojia,bmfgld) " + + "values('" + deptid + "'," + + "'" + row.getIsDirectSales() + "'," + + "'" + companyCode + "'," + + "'" + bmfzr + "'," + + "'" + countryCode + "'," + + "'" + bmfgld + "')"; + rs.execute(sql); + log.writeLog("插入部门自定义表中数据sql--------->" + sql); + } + //人员信息伴随部门信息变化 + if (!"".equals(subcompanyid1)) { + sql = "update hrmResource set subCompanyId1='" + subcompanyid1 + "' where departmentId = '" + deptid + "' "; + rs.executeUpdate(sql); + + //更新该部门的所有下级部门的所属分部 + sql = "update hrmdepartment set subCompanyId1 = '" + subcompanyid1 + "' where exists ( \n" + + " select 1 from (" + + " select id from hrmdepartment start with id = " + deptid + " connect by supdepid = prior id \n" + + " ) s where s.id = hrmdepartment.id \n" + + ")"; + + rs.executeUpdate(sql); + } + //同步部门矩阵信息 + MatrixUtil.updateDepartmentData(deptid); + } + } + log.writeLog("此次同步部门总数为:" + departments.size() + ",新增部门数为:" + insertNum + + ",更新部门数为:" + updateNum + ",跳出处理部门数为:" + skipNum); + log.writeLog("此次同步部门跳过是数据为:" + JSON.toJSONString(skipList)); + //更新部门缓存 + DepartmentComInfo dci = new DepartmentComInfo(); + dci.removeCompanyCache(); + //释放map内存 + map_dept_id_data.clear(); + map_dept_id_data = null; + map_dept_code_id.clear(); + map_dept_code_id = null; + map_user_code_id.clear(); + map_user_code_id = null; + + //将部门矩阵信息同步至矩阵表(20220118取消矩阵全量同步) + //MatrixUtil.sysDepartmentData(); + //MatrixUtil.updateSubcompayData("");//同步分部矩阵数据 + //更新同步时间到中间表 + String sql1 = "update uf_HRRestDate set sctbsj ='" + now + "' where jkbs = 'dept'"; + rs.execute(sql1); + } + + + /** + * 匹配部门id,关联的上级部门,所属分部 map + * + * @return + */ + private Map> getDeptDataMap() { + RecordSet rs = new RecordSet(); + Map> map = new HashMap<>(); + //rs.executeQuery("select id, outkey,supdepid,subcompanyid1 from HrmDepartment where (CANCELED!=1 or CANCELED is null)"); + rs.executeQuery("select id, outkey,supdepid,subcompanyid1 from HrmDepartment where outkey is not null"); + while (rs.next()) { + Map map1 = new HashMap<>(); + map1.put("outkey", rs.getString("outkey")); + map1.put("supdepid", rs.getString("supdepid")); + map1.put("subcompanyid1", rs.getString("subcompanyid1")); + map.put(rs.getString("id"), map1); + } + return map; + } + + /** + * 根据部门id匹配所属分部 + * + * @return + */ + public String getSubId(Map> map_dept_id_data, String deptId) { + String subcompanyid = ""; + if (!map_dept_id_data.containsKey(deptId)) { + return ""; + } + Map map = map_dept_id_data.get(deptId); + subcompanyid = map.get("subcompanyid1"); + return subcompanyid; + } +// /** +// * 获取部门编码和上级分部的集合 +// * +// * @return +// */ +// public Map getDeptComMap() { +// RecordSet rs = new RecordSet(); +// Map map = new HashMap<>(); +// rs.executeQuery("select outkey,supdepid from HrmDepartment where outkey is not null and (CANCELED!=1 or CANCELED is null)"); +// while (rs.next()) { +// map.put(rs.getString("outkey"), rs.getString("supdepid")); +// } +// return map; +// } + + public Map getDepartmentCodeIdMap() { + RecordSet rs = new RecordSet(); + Map map = new HashMap<>(); + //rs.executeQuery("select departmentcode,outkey,id from HrmDepartment where outkey is not null and (CANCELED!=1 or CANCELED is null)"); + rs.executeQuery("select departmentcode,outkey,id from HrmDepartment where outkey is not null "); + while (rs.next()) { + map.put(rs.getString("outkey"), rs.getString("id")); + } + return map; + } + + + /** + * 获取组织信息(新方法) + * + * @param map 查询条件 + * @return + */ + public JSONArray getDepartmentsByPoint_New(Map map) { + //新接口URL + String url = HttpClientToJT.baseUrl + getJkhzurl(); + log.writeLog("获取部门数据url-------->" + url); + LogTool log2 = new LogTool("/log/hrm/dept/detail", false); + JSONArray jsonArray = new JSONArray(); + try { + //获取token + String token = HttpClientToJT.getToken(); + //将map转成字符串 + String param = JSONObject.toJSONString(map, SerializerFeature.DisableCircularReferenceDetect); + log.writeLog("获取组织数据传入参数param------------>" + param); + log2.writeLog("获取组织数据传入参数param------------>" + param); + String s = HttpClientToJT.sendPost(url, token, param); + log2.writeLog("组织数据返回结果------------>" + s); + JSONObject jsonObject = JSONObject.parseObject(s); + String code = Util.null2String(jsonObject.getString("code")); + log2.writeLog("code------------>" + code); + if ("1".equals(code)) { + JSONObject result = jsonObject.getJSONObject("data"); + //是否有下一页 + boolean sfyxyy = result.getBoolean("hasNextPage");//是否有下一页 + log2.writeLog("sfyxyy------------>" + sfyxyy); + String maxPoint = Util.null2String(result.getString("maxPoint"));//下一页开始 + log2.writeLog("maxPoint------------>" + maxPoint); + this.setHasNextPage(sfyxyy); + this.setPoint(maxPoint); + JSONArray records = result.getJSONArray("records"); + //判断不为空 + if (records != null) { + jsonArray.addAll(records); + Object directSales = jsonArray.stream().filter(item -> { + JSONObject itemJson = JSONObject.parseObject(JSON.toJSONString(item)); + return "CHN".equals(itemJson.getString("countryCode")) && "ZHS".equals(itemJson.getString("languageCd")); + }).collect(Collectors.toList()); + jsonArray = JSONArray.parseArray(JSON.toJSONString(directSales)); + } + } else { + this.setHasNextPage(false); + } + } catch (Exception e) { + log2.writeLog("获取组织接口报错,错误信息:" + e.toString()); + } + return jsonArray; + } + + + public JSONArray getDepartments(String date) { + int current = 1, pages = 2; + String url = HttpClientToJT.baseUrl + "/dcopenedi/hrDept/pageByUpdateTime"; +// String token = "sBRQZP+HogxLDE0J3vlDRLZHNG5CBxmqT4w8QG/NFr5ejXb6D6la1w=="; + String token = HttpClientToJT.getToken(); + log.writeLog("-------token--------->" + token); +// String updateTime = DateUtil.formatDate(DateUtil.getCurrentDate(),DateUtil.FORMAT_FULL); + Map params = new HashMap<>(); + + params.put("updateTime", date); +// params.put("updateTime", "2018-03-21 00:00:00"); + params.put("current", current); + params.put("size", size); + log.writeLog("传入JSON--------------->" + JSON.toJSONString(params)); + String s = HttpClientToJT.sendGet(url, token, params); + JSONObject jsonObject = JSONObject.parseObject(s); + JSONArray jsonArray = new JSONArray(); + String code = Util.null2String(jsonObject.getString("code")); + log.writeLog("code------>" + code); + if ("1".equals(code)) { + JSONObject result = jsonObject.getJSONObject("data"); + pages = result.getInteger("pages"); + JSONArray records = result.getJSONArray("records"); + jsonArray.addAll(records); + for (int i = 2; i <= pages; i++) { + params.put("current", i); + String str = HttpClientToJT.sendGet(url, token, params); + JSONObject jsonObject1 = JSONObject.parseObject(str); + JSONObject jsonResult = jsonObject1.getJSONObject("data"); + JSONArray records1 = jsonResult.getJSONArray("records"); + jsonArray.addAll(records1); + } + Object directSales = jsonArray.stream().filter(item -> { + JSONObject itemJson = JSONObject.parseObject(JSON.toJSONString(item)); +// "Y".equals(itemJson.getString("isDirectSales")) + return "CHN".equals(itemJson.getString("countryCode")) && "ZHS".equals(itemJson.getString("languageCd")); + //return "ZHS".equals(itemJson.getString("languageCd")) ; + }).collect(Collectors.toList()); + jsonArray = JSONArray.parseArray(JSON.toJSONString(directSales)); + } else { + log.writeLog("获取页数返回结果------>" + s); + } +// System.out.println(jsonArray.toJSONString()); +// System.out.println(s); + //将写入转化为流的形式 +// writeFile(jsonArray); + return jsonArray; + } + + private void writeFile(JSONArray jsonArray) { + BufferedWriter bw = null; + try { + bw = new BufferedWriter(new FileWriter("D:\\2.txt")); + //一次写一行 + bw.write(jsonArray.toJSONString()); + bw.newLine(); //换行用 + //关闭流 + bw.close(); + } catch (IOException e) { + e.printStackTrace(); + } + System.out.println("写入成功"); + } + + + public static void main(String[] args) { +// String token = HttpClientToJT.getToken(); +// SyncHrmsubcompanyToOA hrmsubcompany = new SyncHrmsubcompanyToOA(); +// hrmsubcompany.getSubcompanys(); + SyncHrmdepartmentToOA hrmdepartment = new SyncHrmdepartmentToOA(); +// JSONArray data = hrmdepartment.getDepartments("2018-08-01 00:00:00"); +// hrmdepartment.writeFile(data); + + JSONArray jsonArray = new JSONArray(); + + String s1="{\"size\":5000,\"updateTime\":\"2022-09-06 00:00:00\",\"point\":\"434632472047648783\"}"; + String s = HttpClientToJT.sendPost("https://jtdcapi.jtexpress.com.cn/dcopenedi/hrDept/pageNewHrDeptByUpdateTime", "oRGUaD6svUYS6LR8q1XcrJnhkiPbNReg5Gn+WxbODT1cNwNsJg9PjA==", s1); + + JSONObject jsonObject = JSONObject.parseObject(s); + String code = Util.null2String(jsonObject.getString("code")); + if ("1".equals(code)) { + JSONObject result = jsonObject.getJSONObject("data"); + //是否有下一页 + boolean sfyxyy = result.getBoolean("hasNextPage");//是否有下一页 + String maxPoint = Util.null2String(result.getString("maxPoint"));//下一页开始 + hrmdepartment.setHasNextPage(sfyxyy); + hrmdepartment.setPoint(maxPoint); + JSONArray records = result.getJSONArray("records"); + //判断不为空 + if (records != null) { + jsonArray.addAll(records); + Object directSales = jsonArray.stream().filter(item -> { + JSONObject itemJson = JSONObject.parseObject(JSON.toJSONString(item)); + return "CHN".equals(itemJson.getString("countryCode")) && "ZHS".equals(itemJson.getString("languageCd")); + }).collect(Collectors.toList()); + jsonArray = JSONArray.parseArray(JSON.toJSONString(directSales)); + } + } else { + hrmdepartment.setHasNextPage(false); + } + System.out.println(jsonArray); + List dataList = JSONArray.parseArray(jsonArray.toJSONString(), DepartmentDto.class); + //分部数据 + List subcompanys_dt = dataList.stream().filter(item -> { + return "10".equals(item.getOrganizationClass()) || "代理区".equals(item.getDepartmentName()) + || "加盟商".equals(item.getDepartmentName()) || "中国J&T".equals(item.getDepartmentName()) + || "纭毅".equals(item.getDepartmentName()) || "云路科技".equals(item.getDepartmentName())||"区域管理部".equals(item.getDepartmentName()); + }).collect(Collectors.toList()); + //部门数据 注意:10000300代理区编码 + List departments_dt = dataList.stream().filter(item -> { + return !"10".equals(item.getOrganizationClass()) && !"中国J&T".equals(item.getDepartmentName()) + && !"代理区".equals(item.getDepartmentName()) && !"加盟商".equals(item.getDepartmentName()) + && !"纭毅".equals(item.getDepartmentName()) && !"云路科技".equals(item.getDepartmentName())&&!"区域管理部".equals(item.getDepartmentName()) + && !"10000300".equals(item.getSuperiorDepartment()); + }).collect(Collectors.toList()); + System.out.println(); + System.out.println("----------同步分部,具体数据:" + JSON.toJSONString(subcompanys_dt, SerializerFeature.DisableCircularReferenceDetect)); + System.out.println("----------同步部门,具体数据:" + JSON.toJSONString(departments_dt, SerializerFeature.DisableCircularReferenceDetect)); + +// List dataList = JSONArray.parseArray(data.toJSONString(), DepartmentDto.class); +// System.out.println(JSON.toJSONString(dataList)); +// SyncHrmjobtitlesToOA hrmjobtitles = new SyncHrmjobtitlesToOA(); +// hrmjobtitles.getJobtitles(); +// SyncHrmresourceToOA hrmresource = new SyncHrmresourceToOA(); +// JSONArray users = hrmresource.getUsers(); +// System.out.println(users); +// System.out.println(JSON.toJSONString(users)); +// JSONObject row =new JSONObject(); +// Integer status = Util.null2String(row.getInteger("status"))== "3" ? 1 : null; +// System.out.println(status); + } + + + /** + * 获取多语言 + * + * @param date 时间 + * @param departmentCode 部门code + * @param deptName 部门中文名称 + * @return 多语言名称 + */ + public String getDepartmentName(String date, String departmentCode, String deptName) { + String retName = ""; + boolean existence = true; + String language = "ENG"; + String cdIndex = ""; + try { + String country = ""; + // 日期 位置 国家 部门code + JSONArray ocDepartmentsGUOJIA = getOcDepartmentsGUOJIA(date, "1", language, departmentCode); + log.writeLog("--------------多语言是否拿到数据:" + ocDepartmentsGUOJIA.size()); + List countryList = JSONArray.parseArray(ocDepartmentsGUOJIA.toJSONString(), DepartmentDto.class); + DepartmentDto countryDto = countryList.get(0); + //对应国家的语言名称(对应国家标签里面) + String countryDepartmentName = countryDto.getDepartmentName(); + log.writeLog("---------------英语名称:" + countryDepartmentName); + + //只需要中文和英文 + retName = "~`~`7 " + deptName + "`~`8 " + countryDepartmentName + "`~`~"; + + log.writeLog("---------------多语言名称:" + retName); + } catch (Exception e) { + log.writeLog("---------------getDepartmentNameException:" + JavaUtil.getExceptionDetail(e)); + e.printStackTrace(); + } + return retName; + } + + + /** + * 获取海外部门国家数据 + * + * @param date 时间 + * @param point + * @return + */ + public JSONArray getOcDepartmentsGUOJIA(String date, String point, String guojia, String departmentCode) { + int current = 1, size = 5000, pages = 2; + String url = HttpClientToJT.baseUrl + "/dcopenedi/hrDept/pageNewHrDeptByUpdateTime"; + String token = HttpClientToJT.getToken(); + log.writeLog("-------token--------->" + token); + Map params = new HashMap<>(); + List list1 = new ArrayList(); + list1.add(guojia); + params.put("languageCds", list1); + params.put("updateTime", date); + params.put("point", point); + params.put("size", size); + params.put("deptCode", departmentCode); + log.writeLog("传入JSON--------------->" + JSON.toJSONString(params)); + String s = HttpClientToJT.sendPost(url, token, JSONObject.toJSONString(params)); + JSONObject jsonObject = JSONObject.parseObject(s); + JSONArray jsonArray = new JSONArray(); + + String code = Util.null2String(jsonObject.getString("code")); + log.writeLog("code------>" + code); + if ("1".equals(code)) { + JSONObject result = jsonObject.getJSONObject("data"); + JSONArray records = result.getJSONArray("records"); + // Object hasNextPage = result.get("hasNextPage"); + jsonArray.addAll(records); + } + + return jsonArray; + } + + + + public boolean isHasNextPage() { + return hasNextPage; + } + + public void setHasNextPage(boolean hasNextPage) { + this.hasNextPage = hasNextPage; + } + + public String getPoint() { + return point; + } + + public void setPoint(String point) { + this.point = point; + } + + public int getSize() { + return size; + } + + public void setSize(int size) { + this.size = size; + } + + public String getJkhzurl() { + return jkhzurl; + } + + public void setJkhzurl(String jkhzurl) { + this.jkhzurl = jkhzurl; + } +} diff --git a/src/main/youhong_ai_jitu_src/jntchina/schedule/hrm/SyncHrmjobtitlesToOA.java b/src/main/youhong_ai_jitu_src/jntchina/schedule/hrm/SyncHrmjobtitlesToOA.java new file mode 100644 index 0000000..f59acb9 --- /dev/null +++ b/src/main/youhong_ai_jitu_src/jntchina/schedule/hrm/SyncHrmjobtitlesToOA.java @@ -0,0 +1,531 @@ +package jntchina.schedule.hrm; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.JSONArray; +import com.alibaba.fastjson.JSONObject; +import com.alibaba.fastjson.serializer.SerializerFeature; +import jntchina.schedule.hrm.util.OrganizationUtil; +import jntchina.schedule.hrmNew.JobTitleMultilingualUtil; +import jntchina.util.HttpClientToJT; +import selfdev.util.base.TimeCommonUtil; +import selfdev.util.log.LogTool; +import weaver.conn.RecordSet; +import weaver.general.Util; +import weaver.hrm.job.JobTitlesComInfo; + +import java.io.BufferedWriter; +import java.io.FileWriter; +import java.io.IOException; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.stream.Collectors; + +/** + * 定时同步岗位到OA中 + * + * @author Cyq + * @date 2021年6月17日 02:01:51 + */ +@SuppressWarnings("all") +public class SyncHrmjobtitlesToOA { + + // 岗位编码和id map + // Map map_jobtitle_code_id = new HashMap(); + private LogTool log = new LogTool("/log/hrm/job/", false); + public int size;// 接口同步每页数量 + public boolean hasNextPage;// 是否有下一页 + public String point;// 页标 + public String jkhzurl;// 接口URL后缀 + private JSONArray allResult = new JSONArray(); + + public void execute(String today) { + /* ******************* 清除所有岗位信息,释放内存空间 start youhong.ai ******************* */ + allResult.clear(); + /* ******************* 清除所有岗位信息,释放内存空间 end youhong.ai ******************* */ + String now = TimeCommonUtil.obtainDate(0); + log.writeLog("--------------------同步岗位 start[" + now + "]----------------------"); + + // 为空时默认每页1000条数据 + if ("null".equals(String.valueOf(size)) || "0".equals(String.valueOf(size)) || size <= 0) { + setSize(1000); + } + // 设置同步HR数据时是否有下一页为是 + setHasNextPage(true); + setPoint("1"); + + SyncHrmdepartmentToOA hrmdepartment = new SyncHrmdepartmentToOA(); + Map map_dept_code_id = hrmdepartment.getDepartmentCodeIdMap(); + // 岗位自定义建模表中的ID和编码 map + // Map map_jobtitledefined_id_code = BaseUtil.getMapKeyValueInfoByParm("uf_jobtitledefined", "", "positionid", "positioncode"); + // map_jobtitle_code_id = getJobtitleCodeIdMap(); + + // 获取所有的岗位编码,同时将岗位编码存入List中 + List codeList = new ArrayList<>(); + // 当前库中已存在的记录集合 -- 系统岗位表 + Map sysExistMap = new HashMap<>(); + // 当前库中已存在的记录集合 -- 自定义岗位表 + Map definedExistMap = new HashMap<>(); + + + RecordSet rs = new RecordSet(); + log.writeLog("----------开始同步岗位-------"); + int count = 0; + int skipNum = 0, insertNum = 0, updateNum = 0; +// int page = getPages(date); + int page = 5000;// 默认为1万页 + log.writeLog("size---------------------->" + size); + // 查询条件 + Map map_parm = new HashMap(); + map_parm.put("beginTime", today);// 时间戳 + map_parm.put("size", size);// 每页数量 + /* ******************* 获取所有的岗位数据 start for youhong.ai ******************* */ + + JSONArray filterResultList = new JSONArray(); + for (int k = 1; k <= page; k++) { + map_parm.put("point", getPoint());// 起始位置,第一次 + JSONArray jobtitles = getJobsByPoint_New(map_parm); + filterResultList.addAll(jobtitles); + } + JobTitleMultilingualUtil jobTitleMultilingualUtil = new JobTitleMultilingualUtil(); + List splitArray = new ArrayList<>(); + + double size = 10_000; + int sizeInt = (int) size; + int totalResultSize = allResult.size(); + int batchNum = (int) Math.ceil(totalResultSize / size); + for (int i = 0; i < batchNum; i++) { + int start = i * sizeInt; + int endIndex = start + sizeInt; + List sub = JobTitleMultilingualUtil.sub(allResult, start, endIndex); + JSONArray objects = JSONArray.parseArray(JSON.toJSONString(sub)); + splitArray.add(objects); + } + /* ******************* 获取所有的杆位数据 end for youhong.ai ******************* */ + /* ******************* 注释原来循环获取接口数据 start for youhong.ai ******************* */ + /*for (int k = 1; k <= page; k++) { + if (!hasNextPage) { + log.writeLog("------------第【" + k + "】次循环获取数据不存在,跳出"); + break; + } + map_parm.put("point", getPoint());// 起始位置,第一次 + // JSONArray jobtitles = getJobsByPage(k,date); + // 调用接口获取数据 + JSONArray jobtitles = getJobsByPoint_New(map_parm);*/ + /* ******************* 注释原来循环获取接口数据 end for youhong.ai ******************* */ + /* ******************* 添加循环 start for youhong.ai ******************* */ + for (int k = 0; k < splitArray.size(); k++) { + + JSONArray jobtitles = splitArray.get(k); + + /* ******************* 添加循环 end for youhong.ai ******************* */ + // 未获取到数据,跳出循环 + if (jobtitles == null || jobtitles.isEmpty()) { + log.writeLog("------------第【" + k + "】调用接口未获取到数据,可能是语言languageCd!=ZHS,跳出本次循环,继续下次循环"); + continue; + } + + codeList.clear(); + sysExistMap.clear(); + definedExistMap.clear(); + for (int m = 0; m < jobtitles.size(); m++) { + JSONObject row = jobtitles.getJSONObject(m); + String positionCode = Util.null2String(row.getString("positionCode"));// 岗位编码 + if (!"".equals(positionCode)) { + codeList.add(positionCode); + } + } + + if (codeList.size() > 0) { + sysExistMap = OrganizationUtil.getExitsData(codeList, 0); + definedExistMap = OrganizationUtil.getExitsData(codeList, 1); + } + + + count = count + jobtitles.size(); + log.writeLog("----------同步岗位第" + k + "页,条数:" + jobtitles.size()); + for (int i = 0; i < jobtitles.size(); i++) { + JSONObject row = jobtitles.getJSONObject(i); + String positionCode = Util.null2String(row.getString("positionCode"));// 岗位编码 + /* ******************* 多语言岗位处理 start for youhong.ai ******************* */ + String positionName = jobTitleMultilingualUtil.getMultilingual(allResult, + row, + item -> aiyh.utils.Util.null2String(item.get("positionCode")), + item -> aiyh.utils.Util.null2String(item.get("positionName")), + item -> aiyh.utils.Util.null2String(item.get("languageCd"))); + if (JobTitleMultilingualUtil.isBlank(positionName)) { + positionName = Util.null2String(row.getString("positionName")); + } + /* ******************* 多语言岗位处理 end for youhong.ai ******************* */ + // String positionName = Util.null2String(row.getString("positionName"));// 岗位名称 + Integer canceled = "3".equals(Util.null2String(row.getString("status"))) ? 1 : null;// 1 新增 2 修改 3作废 + String deptCode = Util.null2String(row.getString("deptCode"));// 部门编码 + String jobdepartmentid = Util.null2String(map_dept_code_id.get(deptCode));// 所属部门ID + String jobtitleid = Util.null2String(sysExistMap.get(positionCode));// OA岗位ID +// String jobactivityid ="1545";//默认职务ID + String positionabbreviation = Util.null2String(row.getString("positionAbbreviation"));// 岗位简称 + String positiontype = Util.null2String(row.getString("positionType"));// 岗位类别 + String positiontypehighest = Util.null2String(row.getString("positionTypeHighest"));// 岗位类别最高 + String positiontypelowest = Util.null2String(row.getString("positionTypeLowest"));// 岗位类别最低 + String positionpropecode = Util.null2String(row.getString("positionPropeCode"));// 岗位属性编码 + String positionpropename = Util.null2String(row.getString("positionPropeName"));// 岗位属性名称 + String companycode = Util.null2String(row.getString("companyCode"));// 公司编码 + String companyname = Util.null2String(row.getString("companyName"));// 公司名称 + String deptname = Util.null2String(row.getString("deptName"));// 部门名称 + String locationcode = Util.null2String(row.getString("locationCode"));// 地点编码 + String locationname = Util.null2String(row.getString("locationName"));// 地点描述 + String stdpositioncode = Util.null2String(row.getString("stdPositionCode"));// 标准岗位编码 + String stdpositionname = Util.null2String(row.getString("stdPositionName"));// 标准岗位名称 + String postcode = Util.null2String(row.getString("postCode"));// 岗编码 + String postname = Util.null2String(row.getString("postName"));// 岗名称 + String sequencecode = Util.null2String(row.getString("sequenceCode"));// 序列编码 + String sequencename = Util.null2String(row.getString("sequenceName"));// 序列名称 + String positiongroupcode = Util.null2String(row.getString("positionGroupCode"));// 岗族编码 + String positiongroupname = Util.null2String(row.getString("positionGroupName"));// 岗族名称 + String ethnicgroupcode = Util.null2String(row.getString("ethnicGroupCode"));// 族群编码 + String ethnicgroupname = Util.null2String(row.getString("ethnicGroupName"));// 族群名称 + + String sql = ""; + // 判断HR岗位ID是否已经存在 + if ("".equals(jobdepartmentid)) { + skipNum++; + continue; + } + + if ("".equals(Util.null2String(jobtitleid))) {// 岗位不存在则插入生成新岗位 + // 新增数据,插入到hrmjobtitles表中 + sql = "insert into hrmjobtitles (jobtitlename,jobtitlemark,outkey,jobdepartmentid," + + "canceled,created,creater,modified,modifier) values(" + + "'" + positionName + "'," + + "'" + positionName + "'," + + "'" + positionCode + "'," + + "'" + jobdepartmentid + "'," + + "" + canceled + "," + + "to_date('" + now + "','yyyy-mm-dd hh24:mi:ss')," + + "'1'," + + "to_date('" + now + "','yyyy-mm-dd hh24:mi:ss')," + + "'1')"; + log.writeLog("插入岗位表生成新数据sql--------->" + sql); + rs.execute(sql); + insertNum++; + rs.execute("select max(id) from hrmjobtitles"); + int maxJobid = 0;// 新插入数据的岗位ID + if (rs.next()) { + maxJobid = rs.getInt(1); + // 将新增加的岗位加入至MAP中 + sysExistMap.put(positionCode, maxJobid + ""); + } + + // 新增数据,插入到hrmjobtitles表中 + sql = "insert into uf_jobtitledefined (formmodeid,modedatacreater,modedatacreatertype,modedatacreatedate,modedatacreatetime," + + "positionid,positioncode,positionname,positionabbreviation,positiontype,positiontypehighest,positiontypelowest," + + "positionpropecode,positionpropename,companycode,companyname,deptcode,deptname,locationcode,locationname,stdpositioncode," + + "stdpositionname,postcode,postname,sequencecode,sequencename,positiongroupcode,positiongroupname,ethnicgroupcode,ethnicgroupname) values" + + "(32501,1,0,to_char(sysdate, 'yyyy-MM-dd'),to_char(sysdate, 'HH24:mi:ss'),'" + maxJobid + "','" + positionCode + "','" + positionName + "'," + + "'" + positionabbreviation + "','" + positiontype + "','" + positiontypehighest + "','" + positiontypelowest + "','" + positionpropecode + "'," + + "'" + positionpropename + "','" + companycode + "','" + companyname + "','" + deptCode + "','" + deptname + "','" + locationcode + "'" + "," + + "'" + locationname + "','" + stdpositioncode + "','" + stdpositionname + "','" + postcode + "','" + postname + "','" + sequencecode + "','" + sequencename + "'," + + "'" + positiongroupcode + "','" + positiongroupname + "','" + ethnicgroupcode + "','" + ethnicgroupname + "')"; + log.writeLog("插入岗位建模自定义表生成新数据sql--------->" + sql); + rs.execute(sql); + // 将新增加的岗位加入至MAP中 + definedExistMap.put(maxJobid + "", positionCode); + + } else {// 岗位存在则更新 + sql = "update hrmjobtitles set " + + "jobtitlename = '" + positionName + "', " + + "jobtitlemark = '" + positionName + "', " + + "jobtitlecode = '" + positionCode + "', " + + "jobdepartmentid = '" + jobdepartmentid + "', " + + "modified = to_date('" + now + "','yyyy-mm-dd hh24:mi:ss')," + + "modifier = '1', " + + "canceled = " + canceled + " " + + "where id= '" + jobtitleid + "'"; + log.writeLog("更新岗位表中数据sql--------->" + sql); + rs.execute(sql); + updateNum++; + log.writeLog("更新岗位表---成功------>"); + + + if (definedExistMap.containsKey(jobtitleid)) {// 存在则更新岗位自定义表 + sql = "update uf_jobtitledefined set " + + "positionName = '" + positionName + "', " + + "positionabbreviation = '" + positionabbreviation + "', " + + "positiontype = '" + positiontype + "', " + + "positiontypehighest = '" + positiontypehighest + "', " + + "positiontypelowest = '" + positiontypelowest + "', " + + "positionpropecode = '" + positionpropecode + "', " + + "positionpropename = '" + positionpropename + "', " + + "companycode = '" + companycode + "', " + + "companyname = '" + companyname + "', " + + "deptCode = '" + deptCode + "', " + + "deptname = '" + deptname + "', " + + "locationcode = '" + locationcode + "', " + + "locationname = '" + locationname + "', " + + "stdpositioncode = '" + stdpositioncode + "', " + + "stdpositionname = '" + stdpositionname + "', " + + "postcode = '" + postcode + "', " + + "postname = '" + postname + "', " + + "sequencecode = '" + sequencecode + "', " + + "sequencename = '" + sequencename + "', " + + "positiongroupcode = '" + positiongroupcode + "', " + + "positiongroupname = '" + positiongroupname + "', " + + "ethnicgroupcode = '" + ethnicgroupcode + "', " + + "ethnicgroupname = '" + ethnicgroupname + "' " + + "where positionid= '" + jobtitleid + "'"; + log.writeLog("更新岗位建模自定义表中数据sql--------->" + sql); + rs.execute(sql); + + } else {// 不存在则插入岗位自定义表 + // 新增数据,插入到hrmjobtitles表中 + sql = "insert into uf_jobtitledefined (formmodeid,modedatacreater,modedatacreatertype,modedatacreatedate,modedatacreatetime," + + "positionid,positioncode,positionname,positionabbreviation,positiontype,positiontypehighest,positiontypelowest," + + "positionpropecode,positionpropename,companycode,companyname,deptcode,deptname,locationcode,locationname,stdpositioncode," + + "stdpositionname,postcode,postname,sequencecode,sequencename,positiongroupcode,positiongroupname,ethnicgroupcode,ethnicgroupname) values" + + "(32501,1,0,to_char(sysdate, 'yyyy-MM-dd'),to_char(sysdate, 'HH24:mi:ss'),'" + jobtitleid + "','" + positionCode + "','" + positionName + "'," + + "'" + positionabbreviation + "','" + positiontype + "','" + positiontypehighest + "','" + positiontypelowest + "','" + positionpropecode + "'," + + "'" + positionpropename + "','" + companycode + "','" + companyname + "','" + deptCode + "','" + deptname + "','" + locationcode + "'" + "," + + "'" + locationname + "','" + stdpositioncode + "','" + stdpositionname + "','" + postcode + "','" + postname + "','" + sequencecode + "','" + sequencename + "'," + + "'" + positiongroupcode + "','" + positiongroupname + "','" + ethnicgroupcode + "','" + ethnicgroupname + "')"; + log.writeLog("插入岗位建模自定义表生成新数据sql--------->" + sql); + rs.execute(sql); + // 将新增加的岗位加入至MAP中 + definedExistMap.put(jobtitleid + "", positionCode); + } + } + } + log.writeLog("----------同步结束岗位,第" + k + "页:" + count + + ",新增岗位数为:" + insertNum + " ,更新岗位数为:" + updateNum + ",跳出处理岗位数为:" + skipNum + "------------"); + skipNum = 0; + insertNum = 0; + updateNum = 0; + } + log.writeLog("----------同步结束岗位总数:" + count + "------------"); + // 更新岗位缓存 + JobTitlesComInfo jtci = new JobTitlesComInfo(); + jtci.removeJobTitlesCache(); + + // 释放map占用的内存 + // map_jobtitledefined_id_code.clear(); + // map_jobtitledefined_id_code=null; + map_dept_code_id.clear(); + map_dept_code_id = null; + // map_jobtitle_code_id.clear(); + // map_jobtitle_code_id=null; + + // 更新同步时间到中间表 + String sql1 = "update uf_HRRestDate set sctbsj ='" + now + "' where jkbs = 'post'"; + rs.execute(sql1); + /* ******************* 清除所有岗位信息,释放内存空间 start youhong.ai ******************* */ + allResult.clear(); + /* ******************* 清除所有岗位信息,释放内存空间 end youhong.ai ******************* */ + + } + + public Map getJobtitleCodeIdMap() { + RecordSet rs = new RecordSet(); + Map map = new HashMap<>(); + rs.executeQuery("select jobtitlecode,outkey,id from hrmjobtitles where outkey is not null and (CANCELED!=1 or CANCELED is null)"); + while (rs.next()) { + map.put(rs.getString("outkey"), rs.getString("id")); + } + return map; + } + + /** + * 获取岗位信息(新方法) + * + * @param map 查询条件 + * @return + */ + public JSONArray getJobsByPoint_New(Map map) { + // 新接口URL + String url = HttpClientToJT.baseUrl + getJkhzurl(); + log.writeLog("获取岗位数据url-------->" + url); + LogTool log2 = new LogTool("/log/hrm/job/detail", false); + // 获取token + String token = HttpClientToJT.getToken(); + // 将map转成字符串 + String param = JSONObject.toJSONString(map, SerializerFeature.DisableCircularReferenceDetect); + log.writeLog("获取岗位数据传入参数param------------>" + param); + log2.writeLog("获取岗位数据传入参数param------------>" + param); + String s = HttpClientToJT.sendPost(url, token, param); + log2.writeLog("岗位数据返回结果------------>" + s); + + JSONObject jsonObject = JSONObject.parseObject(s); + JSONArray jsonArray = new JSONArray(); + String code = Util.null2String(jsonObject.getString("code")); + if ("1".equals(code)) { + JSONObject result = jsonObject.getJSONObject("data"); + // 是否有下一页 + boolean sfyxyy = result.getBoolean("hasNextPage");// 是否有下一页 + String maxPoint = result.getString("maxPoint");// 下一页开始 + this.setHasNextPage(sfyxyy); + this.setPoint(maxPoint); + JSONArray records = result.getJSONArray("records"); + // 过滤未获取到数据 + if (records != null) { + /* ******************* 收集所有岗位信息 start for youhong.ai ******************* */ + allResult.addAll(records); + /* ******************* 收集所有岗位信息 end for youhong.ai ******************* */ + jsonArray.addAll(records); + Object directSales = jsonArray.stream().filter(item -> { + JSONObject itemJson = JSONObject.parseObject(JSON.toJSONString(item)); + return "ZHS".equals(itemJson.getString("languageCd")); + }).collect(Collectors.toList()); + jsonArray = JSONArray.parseArray(JSON.toJSONString(directSales)); + } + } else { + this.setHasNextPage(false); + } + + + return jsonArray; + } + + public int getPages(String date) { + int current = 1, pages = 1; + String url = HttpClientToJT.baseUrl + "/dcopenedi/hrPost/pageByUpdateTime"; + String token = HttpClientToJT.getToken(); + Map params = new HashMap<>(); +// LocalDateTime today_start = LocalDateTime.of(LocalDate.now(), LocalTime.MIN);//当天零点 +// String td_st_str = today_start.format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")); + params.put("updateTime", date); +// params.put("updateTime", "2018-03-21 00:00:00"); + params.put("current", current); + params.put("size", size); + String s = HttpClientToJT.sendGet(url, token, params); + JSONObject jsonObject = JSONObject.parseObject(s); + String code = Util.null2String(jsonObject.getString("code")); + log.writeLog("code------>" + code); + if ("1".equals(code)) { + JSONObject result = jsonObject.getJSONObject("data"); + pages = result.getInteger("pages"); + } else { + log.writeLog("获取页数返回结果------>" + s); + } + return pages; + } + + public JSONArray getJobsByPage(int pages, String date) { + String url = HttpClientToJT.baseUrl + "/dcopenedi/hrPost/pageByUpdateTime"; + String token = HttpClientToJT.getToken(); + Map params = new HashMap<>(); +// LocalDateTime today_start = LocalDateTime.of(LocalDate.now(), LocalTime.MIN);//当天零点 +// String td_st_str = today_start.format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")); + params.put("updateTime", date); +// params.put("updateTime", "2018-03-21 00:00:00"); + params.put("current", pages); + params.put("size", size); + String s = HttpClientToJT.sendGet(url, token, params); + JSONObject jsonObject = JSONObject.parseObject(s); + JSONArray jsonArray = new JSONArray(); + String code = Util.null2String(jsonObject.getString("code")); + if ("1".equals(code)) { + JSONObject result = jsonObject.getJSONObject("data"); + JSONArray records = result.getJSONArray("records"); + jsonArray.addAll(records); + } + Object directSales = jsonArray.stream().filter(item -> { + JSONObject itemJson = JSONObject.parseObject(JSON.toJSONString(item)); + return "ZHS".equals(itemJson.getString("languageCd")); + }).collect(Collectors.toList()); + jsonArray = JSONArray.parseArray(JSON.toJSONString(directSales)); + return jsonArray; + } + + public JSONArray getJobtitles() { + int current = 1, pages = 2; + String url = HttpClientToJT.baseUrl + "/dcopenedi/hrPost/pageByUpdateTime"; + String token = HttpClientToJT.getToken(); + Map params = new HashMap<>(); +// LocalDateTime today_start = LocalDateTime.of(LocalDate.now(), LocalTime.MIN);//当天零点 +// String td_st_str = today_start.format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")); +// params.put("updateTime",td_st_str); + params.put("updateTime", "2021-03-21 00:00:00"); + params.put("current", current); + params.put("size", size); + String s = HttpClientToJT.sendGet(url, token, params); + JSONObject jsonObject = JSONObject.parseObject(s); + JSONArray jsonArray = new JSONArray(); + String code = Util.null2String(jsonObject.getString("code")); + if ("1".equals(code)) { + JSONObject result = jsonObject.getJSONObject("data"); + pages = result.getInteger("pages"); + JSONArray records = result.getJSONArray("records"); + jsonArray.addAll(records); + for (int i = 2; i <= pages; i++) { + System.out.println(i); + params.put("current", i); + String str = HttpClientToJT.sendGet(url, token, params); + JSONObject jsonObject1 = JSONObject.parseObject(str); + JSONObject jsonResult = jsonObject1.getJSONObject("data"); + JSONArray records1 = jsonResult.getJSONArray("records"); + jsonArray.addAll(records1); + } + Object directSales = jsonArray.stream().filter(item -> { + JSONObject itemJson = JSONObject.parseObject(JSON.toJSONString(item)); + return "ZHS".equals(itemJson.getString("languageCd")); + }).collect(Collectors.toList()); + jsonArray = JSONArray.parseArray(JSON.toJSONString(directSales)); + } +// System.out.println(jsonArray.toJSONString()); +// System.out.println(s); + // 将写入转化为流的形式 + writeFile(jsonArray); + return jsonArray; + } + + private void writeFile(JSONArray jsonArray) { + BufferedWriter bw = null; + try { + bw = new BufferedWriter(new FileWriter("E:\\3.txt")); + // 一次写一行 + bw.write(jsonArray.toJSONString()); + bw.newLine(); // 换行用 + // 关闭流 + bw.close(); + } catch (IOException e) { + e.printStackTrace(); + } + System.out.println("写入成功"); + } + + public static void main(String[] args) { + SyncHrmjobtitlesToOA job = new SyncHrmjobtitlesToOA(); + job.getJobtitles(); + } + + public int getSize() { + return size; + } + + public void setSize(int size) { + this.size = size; + } + + public boolean isHasNextPage() { + return hasNextPage; + } + + public void setHasNextPage(boolean hasNextPage) { + this.hasNextPage = hasNextPage; + } + + public String getPoint() { + return point; + } + + public String getJkhzurl() { + return jkhzurl; + } + + public void setJkhzurl(String jkhzurl) { + this.jkhzurl = jkhzurl; + } + + public void setPoint(String point) { + this.point = point; + } +} diff --git a/src/main/youhong_ai_jitu_src/jntchina/schedule/hrm/SyncHrmjobtitlesToOAOc.java b/src/main/youhong_ai_jitu_src/jntchina/schedule/hrm/SyncHrmjobtitlesToOAOc.java new file mode 100644 index 0000000..f97354c --- /dev/null +++ b/src/main/youhong_ai_jitu_src/jntchina/schedule/hrm/SyncHrmjobtitlesToOAOc.java @@ -0,0 +1,442 @@ +package jntchina.schedule.hrm; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.JSONArray; +import com.alibaba.fastjson.JSONObject; +import jntchina.schedule.hrm.util.OrganizationUtil; +import jntchina.schedule.hrmNew.JobTitleMultilingualUtil; +import jntchina.util.HttpClientToJT; +import selfdev.util.base.TimeCommonUtil; +import selfdev.util.log.LogTool; +import weaver.conn.RecordSet; +import weaver.general.Util; +import weaver.hrm.job.JobTitlesComInfo; + +import java.io.BufferedWriter; +import java.io.FileWriter; +import java.io.IOException; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.stream.Collectors; + +/** + * @author Cyq + * @date 2021年6月17日 02:01:51 + */ +public class SyncHrmjobtitlesToOAOc { + + + // 分页接口参数 + static String maxPoint = "1"; + // 接口是否有下一页 默认为有 + static boolean ifPage = true; + + static int defaultPage = 0; + + // 岗位编码和id map + // Map map_jobtitle_code_id = new HashMap(); + + private final LogTool log = new LogTool("/log/hrm/jobOc/", false); + + // 岗位编码和id map + // Map map_jobtitle_code_id = new HashMap(); + private final JSONArray allResult = new JSONArray(); + + + protected void execute(String date) { + /* ******************* 清除所有岗位信息,释放内存空间 start youhong.ai ******************* */ + allResult.clear(); + /* ******************* 清除所有岗位信息,释放内存空间 end youhong.ai ******************* */ + String now = TimeCommonUtil.obtainDate(0); + SyncHrmdepartmentToOA hrmdepartment = new SyncHrmdepartmentToOA(); + Map map_dept_code_id = hrmdepartment.getDepartmentCodeIdMap(); + // 岗位自定义建模表中的ID和编码 map + // Map map_jobtitledefined_id_code = BaseUtil.getMapKeyValueInfoByParm("uf_jobtitledefined", "", "positionid", "positioncode"); + // map_jobtitle_code_id = getJobtitleCodeIdMap(); + RecordSet rs = new RecordSet(); + log.writeLog("----------开始同步岗位-------"); + int count = 0; + int skipNum = 0, insertNum = 0, updateNum = 0; + // int page = getPages(date); + + // 获取所有的岗位编码,同时将岗位编码存入List中 + List codeList = new ArrayList<>(); + // 当前库中已存在的记录集合 -- 系统岗位表 + Map sysExistMap = new HashMap<>(); + // 当前库中已存在的记录集合 -- 自定义岗位表 + Map definedExistMap = new HashMap<>(); + /* ******************* 获取所有的岗位数据 start for youhong.ai ******************* */ + + JSONArray filterResultList = new JSONArray(); + while (ifPage) { + defaultPage++; + JSONArray jobtitles = getJobsByPage(maxPoint, date); + filterResultList.addAll(jobtitles); + } + JobTitleMultilingualUtil jobTitleMultilingualUtil = new JobTitleMultilingualUtil(); + List splitArray = new ArrayList<>(); + double size = 10_000; + int sizeInt = (int) size; + int totalResultSize = allResult.size(); + int batchNum = (int) Math.ceil(totalResultSize / size); + for (int i = 0; i < batchNum; i++) { + int start = i * sizeInt; + int endIndex = start + sizeInt; + List sub = JobTitleMultilingualUtil.sub(allResult, start, endIndex); + JSONArray objects = JSONArray.parseArray(JSON.toJSONString(sub)); + splitArray.add(objects); + } + /* ******************* 获取所有的杆位数据 end for youhong.ai ******************* */ + + /* ******************* 注释原来循环获取接口数据 start for youhong.ai ******************* */ + /*while (ifPage) { + defaultPage++; + int k = defaultPage; + JSONArray jobtitles = getJobsByPage(maxPoint, date);*/ + /* ******************* 注释原来循环获取接口数据 end for youhong.ai ******************* */ + /* ******************* 添加循环 start for youhong.ai ******************* */ + for (int k = 0; k < splitArray.size(); k++) { + JSONArray jobtitles = splitArray.get(k); + /* ******************* 添加循环 end for youhong.ai ******************* */ + // 未获取到数据,跳出循环 + if (jobtitles == null || jobtitles.isEmpty()) { + log.writeLog("------------第【" + k + "】调用接口未获取到数据,可能是语言languageCd!=ZHS,跳出本次循环,继续下次循环"); + continue; + } + + codeList.clear(); + sysExistMap.clear(); + definedExistMap.clear(); + for (int m = 0; m < jobtitles.size(); m++) { + JSONObject row = jobtitles.getJSONObject(m); + String positionCode = Util.null2String(row.getString("positionCode"));// 岗位编码 + if (!"".equals(positionCode)) { + codeList.add(positionCode); + } + } + + if (codeList.size() > 0) { + sysExistMap = OrganizationUtil.getExitsData(codeList, 0); + definedExistMap = OrganizationUtil.getExitsData(codeList, 1); + } + + count = count + jobtitles.size(); + log.writeLog("----------同步岗位第" + k + "页,条数:" + jobtitles.size()); + for (int i = 0; i < jobtitles.size(); i++) { + JSONObject row = jobtitles.getJSONObject(i); + String positionCode = Util.null2String(row.getString("positionCode"));// 岗位编码 + /* ******************* 多语言岗位处理 start for youhong.ai ******************* */ + String positionName = jobTitleMultilingualUtil.getMultilingual(allResult, + row, + item -> aiyh.utils.Util.null2String(item.get("positionCode")), + item -> aiyh.utils.Util.null2String(item.get("positionName")), + item -> aiyh.utils.Util.null2String(item.get("languageCd"))); + if (JobTitleMultilingualUtil.isBlank(positionName)) { + positionName = Util.null2String(row.getString("positionName")); + } + /* ******************* 多语言岗位处理 end for youhong.ai ******************* */ + // String positionName = Util.null2String(row.getString("positionName"));// 岗位名称 + log.writeLog("------------岗位名称:" + positionName); + log.writeLog("------------岗位编码:" + positionCode); + Integer canceled = "3".equals(Util.null2String(row.getString("status"))) ? 1 : 0;// 1 新增 2 修改 3作废 + String deptCode = Util.null2String(row.getString("deptCode"));// 部门编码 + String jobdepartmentid = Util.null2String(map_dept_code_id.get(deptCode));// 所属部门ID + String jobtitleid = Util.null2String(sysExistMap.get(positionCode));// OA岗位ID +// String jobactivityid ="1545";//默认职务ID + String positionabbreviation = Util.null2String(row.getString("positionAbbreviation"));// 岗位简称 + String positiontype = Util.null2String(row.getString("positionType"));// 岗位类别 + String positiontypehighest = Util.null2String(row.getString("positionTypeHighest"));// 岗位类别最高 + String positiontypelowest = Util.null2String(row.getString("positionTypeLowest"));// 岗位类别最低 + String positionpropecode = Util.null2String(row.getString("positionPropeCode"));// 岗位属性编码 + String positionpropename = Util.null2String(row.getString("positionPropeName"));// 岗位属性名称 + String companycode = Util.null2String(row.getString("companyCode"));// 公司编码 + String companyname = Util.null2String(row.getString("companyName"));// 公司名称 + String deptname = Util.null2String(row.getString("deptName"));// 部门名称 + String locationcode = Util.null2String(row.getString("locationCode"));// 地点编码 + String locationname = Util.null2String(row.getString("locationName"));// 地点描述 + String stdpositioncode = Util.null2String(row.getString("stdPositionCode"));// 标准岗位编码 + String stdpositionname = Util.null2String(row.getString("stdPositionName"));// 标准岗位名称 + String postcode = Util.null2String(row.getString("postCode"));// 岗编码 + String postname = Util.null2String(row.getString("postName"));// 岗名称 + String sequencecode = Util.null2String(row.getString("sequenceCode"));// 序列编码 + String sequencename = Util.null2String(row.getString("sequenceName"));// 序列名称 + String positiongroupcode = Util.null2String(row.getString("positionGroupCode"));// 岗族编码 + String positiongroupname = Util.null2String(row.getString("positionGroupName"));// 岗族名称 + String ethnicgroupcode = Util.null2String(row.getString("ethnicGroupCode"));// 族群编码 + String ethnicgroupname = Util.null2String(row.getString("ethnicGroupName"));// 族群名称 + + String sql = ""; + // 判断HR岗位ID是否已经存在 +// if("".equals(jobdepartmentid)){ +// skipNum++; +// continue; +// } + +// if("".equals(canceled) || canceled == null){ +// canceled = 0; +// } + + if ("".equals(Util.null2String(jobtitleid))) {// 岗位不存在则插入生成新岗位 + // 新增数据,插入到hrmjobtitles表中 + sql = "insert into hrmjobtitles (jobtitlename,jobtitlemark,outkey,jobdepartmentid," + + "canceled,created,creater,modified,modifier) values(" + + "'" + positionName + "'," + + "'" + positionName + "'," + + "'" + positionCode + "'," + + "'" + jobdepartmentid + "'," + + "" + canceled + "," + + "to_date('" + now + "','yyyy-mm-dd hh24:mi:ss')," + + "'1'," + + "to_date('" + now + "','yyyy-mm-dd hh24:mi:ss')," + + "'1')"; + log.writeLog("插入岗位表生成新数据sql--------->" + sql); + boolean executeUpdate1 = rs.executeUpdate(sql); + log.writeLog("是否成功:" + executeUpdate1); + log.writeLog("原因:" + rs.getExceptionMsg()); + insertNum++; + rs.execute("select max(id) from hrmjobtitles"); + int maxJobid = 0;// 新插入数据的岗位ID + if (rs.next()) { + maxJobid = rs.getInt(1); + // 将新增加的岗位加入至MAP中 + sysExistMap.put(positionCode, maxJobid + ""); + } + + // 新增数据,插入到hrmjobtitles表中 + sql = "insert into uf_jobtitledefined (formmodeid,modedatacreater,modedatacreatertype,modedatacreatedate,modedatacreatetime," + + "positionid,positioncode,positionname,positionabbreviation,positiontype,positiontypehighest,positiontypelowest," + + "positionpropecode,positionpropename,companycode,companyname,deptcode,deptname,locationcode,locationname,stdpositioncode," + + "stdpositionname,postcode,postname,sequencecode,sequencename,positiongroupcode,positiongroupname,ethnicgroupcode,ethnicgroupname) values" + + "(32501,1,0,to_char(sysdate, 'yyyy-MM-dd'),to_char(sysdate, 'HH24:mi:ss'),'" + maxJobid + "','" + positionCode + "','" + positionName + "'," + + "'" + positionabbreviation + "','" + positiontype + "','" + positiontypehighest + "','" + positiontypelowest + "','" + positionpropecode + "'," + + "'" + positionpropename + "','" + companycode + "','" + companyname + "','" + deptCode + "','" + deptname + "','" + locationcode + "'" + "," + + "'" + locationname + "','" + stdpositioncode + "','" + stdpositionname + "','" + postcode + "','" + postname + "','" + sequencecode + "','" + sequencename + "'," + + "'" + positiongroupcode + "','" + positiongroupname + "','" + ethnicgroupcode + "','" + ethnicgroupname + "')"; + log.writeLog("插入岗位建模自定义表生成新数据sql--------->" + sql); + boolean executeUpdate = rs.executeUpdate(sql); + log.writeLog("是否成功:" + executeUpdate); + log.writeLog("原因:" + rs.getExceptionMsg()); + // 将新增加的岗位加入至MAP中 + definedExistMap.put(maxJobid + "", positionCode); + + } else {// 岗位存在则更新 + sql = "update hrmjobtitles set " + + "jobtitlename = '" + positionName + "', " + + "jobtitlemark = '" + positionName + "', " + + "jobtitlecode = '" + positionCode + "', " + + "jobdepartmentid = '" + jobdepartmentid + "', " + + "modified = to_date('" + now + "','yyyy-mm-dd hh24:mi:ss')," + + "modifier = '1', " + + "canceled = " + canceled + " " + + "where id= '" + jobtitleid + "'"; + log.writeLog("更新岗位表中数据sql--------->" + sql); + rs.executeUpdate(sql); + updateNum++; + log.writeLog("更新岗位表---成功------>"); + + + if (definedExistMap.containsKey(jobtitleid)) {// 存在则更新岗位自定义表 + sql = "update uf_jobtitledefined set " + + "positionName = '" + positionName + "', " + + "positionabbreviation = '" + positionabbreviation + "', " + + "positiontype = '" + positiontype + "', " + + "positiontypehighest = '" + positiontypehighest + "', " + + "positiontypelowest = '" + positiontypelowest + "', " + + "positionpropecode = '" + positionpropecode + "', " + + "positionpropename = '" + positionpropename + "', " + + "companycode = '" + companycode + "', " + + "companyname = '" + companyname + "', " + + "deptCode = '" + deptCode + "', " + + "deptname = '" + deptname + "', " + + "locationcode = '" + locationcode + "', " + + "locationname = '" + locationname + "', " + + "stdpositioncode = '" + stdpositioncode + "', " + + "stdpositionname = '" + stdpositionname + "', " + + "postcode = '" + postcode + "', " + + "postname = '" + postname + "', " + + "sequencecode = '" + sequencecode + "', " + + "sequencename = '" + sequencename + "', " + + "positiongroupcode = '" + positiongroupcode + "', " + + "positiongroupname = '" + positiongroupname + "', " + + "ethnicgroupcode = '" + ethnicgroupcode + "', " + + "ethnicgroupname = '" + ethnicgroupname + "' " + + "where positionid= '" + jobtitleid + "'"; + log.writeLog("更新岗位建模自定义表中数据sql--------->" + sql); + rs.executeUpdate(sql); + + } else {// 不存在则插入岗位自定义表 + // 新增数据,插入到hrmjobtitles表中 + sql = "insert into uf_jobtitledefined (formmodeid,modedatacreater,modedatacreatertype,modedatacreatedate,modedatacreatetime," + + "positionid,positioncode,positionname,positionabbreviation,positiontype,positiontypehighest,positiontypelowest," + + "positionpropecode,positionpropename,companycode,companyname,deptcode,deptname,locationcode,locationname,stdpositioncode," + + "stdpositionname,postcode,postname,sequencecode,sequencename,positiongroupcode,positiongroupname,ethnicgroupcode,ethnicgroupname) values" + + "(32501,1,0,to_char(sysdate, 'yyyy-MM-dd'),to_char(sysdate, 'HH24:mi:ss'),'" + jobtitleid + "','" + positionCode + "','" + positionName + "'," + + "'" + positionabbreviation + "','" + positiontype + "','" + positiontypehighest + "','" + positiontypelowest + "','" + positionpropecode + "'," + + "'" + positionpropename + "','" + companycode + "','" + companyname + "','" + deptCode + "','" + deptname + "','" + locationcode + "'" + "," + + "'" + locationname + "','" + stdpositioncode + "','" + stdpositionname + "','" + postcode + "','" + postname + "','" + sequencecode + "','" + sequencename + "'," + + "'" + positiongroupcode + "','" + positiongroupname + "','" + ethnicgroupcode + "','" + ethnicgroupname + "')"; + log.writeLog("插入岗位建模自定义表生成新数据sql--------->" + sql); + rs.executeUpdate(sql); + // 将新增加的岗位加入至MAP中 + definedExistMap.put(jobtitleid + "", positionCode); + } + } + } + log.writeLog("----------同步结束岗位,第" + k + "页:" + count + + ",新增岗位数为:" + insertNum + " ,更新岗位数为:" + updateNum + ",跳出处理岗位数为:" + skipNum + "------------"); + skipNum = 0; + insertNum = 0; + updateNum = 0; + } + log.writeLog("----------同步结束岗位总数:" + count + "------------"); + // 更新岗位缓存 + JobTitlesComInfo jtci = new JobTitlesComInfo(); + jtci.removeJobTitlesCache(); + + // 释放map占用的内存 + map_dept_code_id.clear(); + map_dept_code_id = null; + + // 更新同步时间到中间表 + String sql1 = "update uf_HRRestDate set sctbsj ='" + now + "' where jkm = '/dcopenedi/hrPost/pageByUpdateTime'"; + rs.executeUpdate(sql1); + /* ******************* 清除所有岗位信息,释放内存空间 start youhong.ai ******************* */ + allResult.clear(); + /* ******************* 清除所有岗位信息,释放内存空间 end youhong.ai ******************* */ + } + + + public Map getJobtitleCodeIdMap() { + RecordSet rs = new RecordSet(); + Map map = new HashMap<>(); + rs.executeQuery("select jobtitlecode,outkey,id from hrmjobtitles where outkey is not null and (CANCELED!=1 or CANCELED is null)"); + while (rs.next()) { + map.put(rs.getString("outkey"), rs.getString("id")); + } + return map; + } + + public int getPages(String date) { + int current = 1, size = 10000, pages = 1; + String url = HttpClientToJT.baseUrl + "/dcopenedi/hrPost/pageByUpdateTime"; + String token = HttpClientToJT.getToken(); + Map params = new HashMap<>(); +// LocalDateTime today_start = LocalDateTime.of(LocalDate.now(), LocalTime.MIN);//当天零点 +// String td_st_str = today_start.format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")); + params.put("updateTime", date); +// params.put("updateTime", "2018-03-21 00:00:00"); + params.put("current", current); + params.put("size", size); + String s = HttpClientToJT.sendGet(url, token, params); + JSONObject jsonObject = JSONObject.parseObject(s); + if (jsonObject.getInteger("code").equals(1)) { + JSONObject result = jsonObject.getJSONObject("data"); + pages = result.getInteger("pages"); + } + return pages; + } + + public JSONArray getJobsByPage(String pages, String date) { + int size = 5000; + String url = HttpClientToJT.baseUrl + "/dcopenedi/hrPost/pageByParam"; + String token = HttpClientToJT.getToken(); + Map params = new HashMap<>(); + + params.put("beginTime", date); + params.put("point", pages); + params.put("size", size); + + String s = HttpClientToJT.sendPost(url, token, JSONObject.toJSONString(params)); + JSONObject jsonObject = JSONObject.parseObject(s); + JSONArray jsonArray = new JSONArray(); + if (jsonObject.getInteger("code").equals(1)) { + JSONObject result = jsonObject.getJSONObject("data"); + JSONArray records = result.getJSONArray("records"); + + // 是否有下一页 + Object hasNextPage = result.get("hasNextPage"); + // 下次继续传 + maxPoint = result.get("maxPoint").toString(); + if ("false".equals(hasNextPage.toString())) { + ifPage = false; + } + /* ******************* 收集所有岗位信息 start for youhong.ai ******************* */ + allResult.addAll(records); + /* ******************* 收集所有岗位信息 end for youhong.ai ******************* */ + jsonArray.addAll(records); + } else { + ifPage = false; + } + Object directSales = jsonArray.stream().filter(item -> { + JSONObject itemJson = JSONObject.parseObject(JSON.toJSONString(item)); + return !"CHN".equals(itemJson.getString("countryCode")); + }).collect(Collectors.toList()); + jsonArray = JSONArray.parseArray(JSON.toJSONString(directSales)); + // log.writeLog("-------------------数据:"+jsonArray); + return jsonArray; + } + + public JSONArray getJobtitles() { + int current = 1, size = 10000, pages = 2; + String url = HttpClientToJT.baseUrl + "/dcopenedi/hrPost/pageByUpdateTime"; + // String url = "https://jtdcapi.jtexpress.com.cn/dcopenedi/hrPost/pageByUpdateTime"; + String token = HttpClientToJT.getToken(); + Map params = new HashMap<>(); +// LocalDateTime today_start = LocalDateTime.of(LocalDate.now(), LocalTime.MIN);//当天零点 +// String td_st_str = today_start.format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")); +// params.put("updateTime",td_st_str); + params.put("updateTime", "2021-03-21 00:00:00"); + params.put("current", current); + params.put("size", size); + String s = HttpClientToJT.sendGet(url, token, params); + JSONObject jsonObject = JSONObject.parseObject(s); + JSONArray jsonArray = new JSONArray(); + if (jsonObject.getInteger("code").equals(1)) { + JSONObject result = jsonObject.getJSONObject("data"); + pages = result.getInteger("pages"); + JSONArray records = result.getJSONArray("records"); + jsonArray.addAll(records); + for (int i = 2; i <= pages; i++) { + System.out.println(i); + params.put("current", i); + String str = HttpClientToJT.sendGet(url, token, params); + JSONObject jsonObject1 = JSONObject.parseObject(str); + JSONObject jsonResult = jsonObject1.getJSONObject("data"); + JSONArray records1 = jsonResult.getJSONArray("records"); + jsonArray.addAll(records1); + } + Object directSales = jsonArray.stream().filter(item -> { + JSONObject itemJson = JSONObject.parseObject(JSON.toJSONString(item)); + return !"ZHS".equals(itemJson.getString("languageCd")); + }).collect(Collectors.toList()); + jsonArray = JSONArray.parseArray(JSON.toJSONString(directSales)); + } +// System.out.println(jsonArray.toJSONString()); +// System.out.println(s); + // 将写入转化为流的形式 + writeFile(jsonArray); + return jsonArray; + } + + private void writeFile(JSONArray jsonArray) { + BufferedWriter bw = null; + try { + bw = new BufferedWriter(new FileWriter("E:\\3.txt")); + // 一次写一行 + bw.write(jsonArray.toJSONString()); + bw.newLine(); // 换行用 + // 关闭流 + bw.close(); + } catch (IOException e) { + e.printStackTrace(); + } + System.out.println("写入成功"); + } + + public static void main(String[] args) { + SyncHrmjobtitlesToOA job = new SyncHrmjobtitlesToOA(); + job.getJobtitles(); + } +} diff --git a/src/main/youhong_ai_jitu_src/jntchina/schedule/hrm/SyncHrmresourceToOA.java b/src/main/youhong_ai_jitu_src/jntchina/schedule/hrm/SyncHrmresourceToOA.java new file mode 100644 index 0000000..5d1006d --- /dev/null +++ b/src/main/youhong_ai_jitu_src/jntchina/schedule/hrm/SyncHrmresourceToOA.java @@ -0,0 +1,633 @@ +package jntchina.schedule.hrm; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.JSONArray; +import com.alibaba.fastjson.JSONObject; +import com.alibaba.fastjson.serializer.SerializerFeature; +import com.engine.common.service.impl.HrmCommonServiceImpl; +import jntchina.schedule.hrm.entity.HrmUserDto; +import jntchina.schedule.hrm.util.OrganizationUtil; +import jntchina.util.HttpClientToJT; +import selfdev.util.base.BaseUtil; +import selfdev.util.base.TimeCommonUtil; +import selfdev.util.log.LogTool; +import weaver.conn.RecordSet; +import weaver.general.Util; +import weaver.hrm.resource.ResourceComInfo; + +import java.time.LocalDate; +import java.time.LocalDateTime; +import java.time.LocalTime; +import java.time.format.DateTimeFormatter; +import java.util.*; +import java.util.stream.Collectors; + +/** + * 定时将HR系统中的员工同步至OA的人员表中 + * @author Cyq + * @date 2021年6月17日 02:01:51 + */ +public class SyncHrmresourceToOA { + + //人员编码和id map + Map map_user_code_id = new HashMap<>(); + private final LogTool log = new LogTool("/log/hrm/user/", false); + public int size;//接口同步每页数量 + public boolean hasNextPage;//是否有下一页 + public String point;//页标 + public String jkhzurl = "/dcopenedi/hrEmployee/pageByParam";//接口URL后缀 + + public void execute(String today) { + String now = TimeCommonUtil.obtainDate(0); + log.writeLog("--------------------同步人员 start["+now+"]----------------------"); + //为空时默认每页1000条数据 + if("null".equals(String.valueOf(size))||"0".equals(String.valueOf(size))||size<=0){ + setSize(1000); + } + //设置同步HR数据时是否有下一页为是 + setHasNextPage(true); + setPoint("1"); + + SyncHrmdepartmentToOA hrmdepartment = new SyncHrmdepartmentToOA(); + SyncHrmjobtitlesToOA hrmjobtitles = new SyncHrmjobtitlesToOA(); + + HrmCommonServiceImpl hrmCommonServiceImpl=new HrmCommonServiceImpl(); + + Map map_dept_code_id = hrmdepartment.getDepartmentCodeIdMap(); + Map map_jobtitle_code_id = hrmjobtitles.getJobtitleCodeIdMap(); + //未获取到的上级的集合 + Map noFindManagerMap = new HashMap<>(); + Map map_user_id_defined = getUserIdDefinedMap(); + map_user_code_id = getUserCodeIdMap(); + //获取部门ID-->分部ID的MAP + Map map_deptid_subcompanyid = BaseUtil.getMapKeyValueInfoByParm("hrmdepartment", " where subcompanyid1 is not null", "id", "subcompanyid1"); + //获取部门自定义字段信息map + Map> map_deptid_defined = getDeptDefinedMap(); + // 处理人员同步逻辑 + RecordSet rs = new RecordSet(); + RecordSet rs2 = new RecordSet(); + String sql; + + int totalCount = 0,insertCount=0,updateCount=0,skipCount=0; + int skipNum = 0,insertNum=0,updateNum = 0; + int page = 1000;//默认为1千页 + + log.writeLog("size---------------------->"+size); + //查询条件 + Map map_parm= new HashMap<>(); + map_parm.put("updateTime", today);//时间戳 + map_parm.put("size", size);//每页数量 + List languageCds_list= new ArrayList<>(); + languageCds_list.add("ZHS");//语言默认为中文 + map_parm.put("languageCds", languageCds_list);//支持多语言 + try { + //从建模表中读取默认密码(默认密码Jitu@2021) + String password = BaseUtil.getBaseInfoByParm("mrmm", "uf_tbygmrdllm", "1", "1", ""); + if("".equals(password)) { + password="Jitu@2021"; + } + log.writeLog("password----->"+password); + password=BaseUtil.MD5(password);//MD5加密后的密码 + log.writeLog("password_md5----->"+password); + //更新人员缓存 + ResourceComInfo rci = new ResourceComInfo(); + log.writeLog("----------hasNextPage------------>"+hasNextPage); + for (int k = 1; k <= page; k++) { + if(!hasNextPage){ + log.writeLog("------------第【"+k+"】次循环获取数据不存在,跳出"); + break; + } + map_parm.put("point", getPoint());//起始位置,第一次 + //获取结果 + JSONArray data = getUsersByPoint_New(map_parm); + //接口未获取到数据时,跳过当前循环,进入下一次 + if(data==null||data.isEmpty()){ + continue; + } + //将查询结果放到list对象中 + List users = JSONArray.parseArray(data.toJSONString(), HrmUserDto.class); + totalCount = totalCount+users.size(); + log.writeLog("----------同步人员第"+k+"页,条数:"+users.size()); + for (int i = 0; i < users.size(); i++) { + HrmUserDto row = users.get(i); + //昵称 + String field0 = Util.null2String(row.getEmployeeEnglishName());//员工code + + String employeeCode = Util.null2String(row.getEmployeeCode());//员工code + String employeeName = Util.null2String(row.getEmployeeName());//姓名 + String employeeSexCode = Util.null2String(row.getEmployeeSexCode());//性别 M男 F女 对应 OA 0男 1女 + int sex = "M".equals(employeeSexCode) ? 0 : 1; + String birthdate = Util.null2String(row.getEmployeeBirthdate());//出生年月 + String companyTel = Util.null2String(row.getCompanyTel());//办公电话 + String personalTel = Util.null2String(row.getPersonalTel());//手机号 + String email = Util.null2String(row.getCompanyEmail());//邮箱 + String idNumber = Util.null2String(row.getCertificateNum());//身份证号码 + String managerCode = Util.null2String(row.getSupervisorId());//上级次账号code + //获取人员姓名的拼音 + String name_pinyin = hrmCommonServiceImpl.generateQuickSearchStr(employeeName); + String EntryDate = Util.null2String(row.getEmplHireDate());//入职日期 无字段,暂用试用结束日期来替代 + String hrStatus = Util.null2String(row.getHrStatus());//状态A在职,I离职 对应OA的1正式 5离职 + int status = "A".equals(hrStatus) ? 1 : 5;//OA的在职状态 + String deptCode = Util.null2String(row.getDeptCode());//部门 + String positionCode = Util.null2String(row.getPositionCode());//岗位 + String bankBranchName = Util.null2String(row.getBankBranchName());//开户行 + String bankAccountId = Util.null2String(row.getBankAccountId());//银行卡号 + String bankName = Util.null2String(row.getBankName());//银行类型 + String action = Util.null2String(row.getAction());//操作编码 + String action_descr = Util.null2String(row.getActionDescr()).replace("'","''");//操作名称 + String departmentid,subcompanyid1; + //根据员工code获取员工id + String userId = Util.null2String(map_user_code_id.get(employeeCode));//员工ID + //员工离职 + if(status==5&&!"".equals(userId)){ + //清空账号信息 + sql = "update hrmresource set " + + "loginid = '', " + + "account='', "+ + "modified = to_date('" + now + "','yyyy-mm-dd hh24:mi:ss')," + + "modifier = '1', " + + "lastmoddate = '" + now.substring(0, 10) + "', " + + "lastmodid = '1', " + + "status = '5' " + + "where id ='" + userId +"' and workcode='"+employeeCode+"'"; + log.writeLog("更新员工状态为离职sql--------->"+sql); + rs.execute(sql); + continue; + } + + //处理岗位id + String jobtitleid = ""; + if (!"".equals(positionCode)) { + jobtitleid = Util.null2String(map_jobtitle_code_id.get(positionCode));//岗位ID + } + + //如果部门编码为空,跳过不同步 + if("".equals(deptCode)){ + skipNum++; + log.writeLog("员工编号【"+employeeCode+"】、员工姓名【"+employeeName+"】部门编码不存在,跳过同步"); + continue; + }else{ + //处理所属部门编码对应的OA部门、分部。在分部表,部门表匹配 + departmentid = Util.null2String(map_dept_code_id.get(deptCode));//部门ID + if("".equals(departmentid)){ + skipNum++; + log.writeLog("员工编号【"+employeeCode+"】、员工姓名【"+employeeName+"】、部门编码【"+deptCode+"】的部门编码对应部门ID在OA中未找到,跳过同步"); + continue; + }else{ + subcompanyid1 = Util.null2o(map_deptid_subcompanyid.get(departmentid));//分部ID + if("0".equals(subcompanyid1)){ + skipNum++; + log.writeLog("员工编号【"+employeeCode+"】、员工姓名【"+employeeName+"】、部门ID【"+departmentid+"】、部门编码【"+deptCode+"】的未找到对应的分部ID,跳过同步"); + continue; + } + } + } + String managerid = "";//部门负责人 + Map map_deptid_defined_detail=map_deptid_defined.get(departmentid); + if(!map_deptid_defined_detail.isEmpty()){ + //部门对应的国家 + String guojia_bm=Util.null2String(map_deptid_defined_detail.get("guojia")); + //部门负责人 + managerid=Util.null2String(map_deptid_defined_detail.get("bmfzr")); + //国家不为空,也不是中国CHN + if(!"".equals(guojia_bm)&&!"CHN".equals(guojia_bm)){ + skipNum++; + log.writeLog("员工编号【"+employeeCode+"】、员工姓名【"+employeeName+"】、部门ID【"+departmentid+"】、部门编码【"+deptCode+"】部门对应的国家是【"+guojia_bm+"】,跳过同步"); + continue; + } + } + + //若维护了上级次账号,则根据维护的数据找上级 + if (!"".equals(managerCode)) { + managerid = Util.null2String(map_user_code_id.get(managerCode));//直接上级 + } + //从HR获取有上级,但是在OA中未找到,则说明可能上级是新入职还未同步到OA中 + if("".equals(managerid)&&!"".equals(managerCode)){ + noFindManagerMap.put(employeeCode,managerCode); + } + log.writeLog("----人员code:"+employeeCode+",所属部门code:"+deptCode+",部门id:"+departmentid+",部门领导code:"+managerCode+",部门领导id:"+managerid+"--------->"); + + + String[] actionInfo = new String[] {action,action_descr}; + + //判断人员ID是否已经存在,不存在则插入生成新人员 + if (!map_user_code_id.containsKey(employeeCode)) { + log.writeLog("查询员工【"+employeeCode+"】在数据库中是否存在需要多久 start--------->" + TimeCommonUtil.obtainDate(0)); + String userid_2=""; + //为解决同时手工执行点击了2次同步时多线程产生的问题,故还需要再次查询一遍数据库中是否已存在 + rs2.execute("select id from hrmresource where workcode='"+employeeCode+"'"); + while(rs2.next()){ + userid_2=Util.null2String(rs2.getString("id")); + } + //若不存在则插入,若已存在则不做其他操作 + if(!"".equals(userid_2)){ + log.writeLog("员工ID【"+userid_2+"】、员工编号【"+employeeCode+"】在OA人员表中已存在,当前跳过,进入下一次循环"); + map_user_code_id.put(employeeCode,userid_2); + skipNum++; + continue; + } + log.writeLog("查询员工【"+employeeCode+"】在数据库中是否存在需要多久 end--------->" + TimeCommonUtil.obtainDate(0)); + //获取即将插入的人员ID + rs.executeProc("HrmResourceMaxId_Get", ""); + rs.next(); + String maxUserId = "" + rs.getInt(1); + log.writeLog("查在数据库中查询人员最大ID需要多久 --------->" + maxUserId); + //新增数据,插入到人员基本信息表HrmResource中 seclevel + sql = "insert into hrmresource(id,loginid,password,lastname,workcode,sex, " + + "mobile,email,departmentid,jobtitle,birthday,certificatenum," + + "seclevel,outkey,status,systemlanguage,createrid,createdate," + + "companystartdate,telephone,ecology_pinyin_search,pinyinlastname," + + "created,creater,modified,modifier,managerid,subcompanyid1) values( " + + "'" + maxUserId + "'," + + "'" + employeeCode + "'," + + "'" + password + "'," + + "?," + + "'" + employeeCode + "'," + + "'" + sex + "'," + + "'" + personalTel + "'," + + "'" + email + "'," + + "'" + departmentid + "'," + + "'" + jobtitleid + "'," + + "'" + birthdate + "'," + + "'" + idNumber + "'," + + "'" + 10 + "'," + + "'" + employeeCode + "'," + + "" + status + "," + + "'7'," + + "'1'," + + "'" + now.substring(0, 10) + "'," + + "'" + EntryDate + "'," + + "'" + companyTel + "'," + + "'" + name_pinyin + "'," + + "'" + name_pinyin + "'," + + "to_date('" + now + "','yyyy-mm-dd hh24:mi:ss')," + + "'1'," + + "to_date('" + now + "','yyyy-mm-dd hh24:mi:ss')," + + "'1'," + + "'" + managerid + "'," + + "'" + subcompanyid1 + "')"; + rs.executeUpdate(sql,employeeName); + log.writeLog("插入人员表中数据sql--------->" + sql); + + insertNum++; + //将新增加的人员加入至MAP中 + map_user_code_id.put(employeeCode,maxUserId); + //新增数据,插入到人员自定义表cus_fielddata中 + if(!map_user_id_defined.containsKey(maxUserId)){ + if("".equals(bankAccountId)){ + OrganizationUtil.insertEmployeeCustomizePersonal(maxUserId,null,actionInfo,row); + }else{ + String[] bankInfo = new String[] {bankBranchName,bankAccountId,bankName}; + OrganizationUtil.insertEmployeeCustomizePersonal(maxUserId,bankInfo,actionInfo,row); + } + log.writeLog("插入人员自定义表中数据sql--------->" + sql); + rs.execute(sql); + + //将新增加的人员自定义信息加入至MAP中 + map_user_id_defined.put(maxUserId,employeeCode); + } + + OrganizationUtil.dealEmployeeNickName(maxUserId,field0); + + //刷新人员缓存 + rci.addResourceInfoCache(maxUserId); + + } else {//存在则更新 + //根据工号获取人员ID + //userId = Util.null2String(map_user_code_id.get(employeeCode));//员工ID + String updateStr = ""; + updateStr += "departmentid = '" + departmentid + "', "; + updateStr += !"".equals(jobtitleid)?"jobtitle = '" + jobtitleid + "', ":""; + updateStr += !"".equals(subcompanyid1)?"subcompanyid1 = '" + subcompanyid1 + "', ":""; + updateStr += !"".equals(managerid)?"managerid = '" + managerid + "', ":""; + sql = "update hrmresource set " + + "workcode = '" + employeeCode + "', " + + "lastname = ?, " + + "sex = '" + sex + "', " + + "mobile = '" + personalTel + "', " + + "ecology_pinyin_search = '" + name_pinyin + "', " + + "pinyinlastname = '" + name_pinyin + "', " + + "email = '" + email + "', " + + "telephone = '" + companyTel + "', " + + "status = " + status + ", " + + "birthday = '" + birthdate + "', " + + "certificatenum = '" + idNumber + "', " + + "companystartdate = '" + EntryDate + "', " + + "modified = to_date('" + now + "','yyyy-mm-dd hh24:mi:ss')," + + "modifier = '1', " + + "lastmoddate = '" + now.substring(0, 10) + "', " + + updateStr + + "lastmodid = '1' " + + "where id ='" + userId + "'"; + log.writeLog("更新人员基本信息表中数据sql--------->" + sql); + rs.executeUpdate(sql,employeeName); + updateNum++; + + if(map_user_id_defined.containsKey(userId)){ + String[] bankInfo = new String[] {bankBranchName,bankAccountId,bankName}; + OrganizationUtil.updateEmployeeCustomizePersonal(userId,bankInfo,actionInfo,row); + } else { + //更新人员工作信息表数据 + if("".equals(bankAccountId)){ + OrganizationUtil.updateEmployeeCustomizePersonal(userId,null,actionInfo,row); + } else { + String[] bankInfo = new String[] {bankBranchName,bankAccountId,bankName}; + OrganizationUtil.updateEmployeeCustomizePersonal(userId,bankInfo,actionInfo,row); + } + } + log.writeLog("更新/插入人员自定义表中数据sql--------->" + sql); + rs.execute(sql); + + //基本信息处理 + OrganizationUtil.dealEmployeeNickName(userId,field0); + + //刷新人员缓存 + rci.addResourceInfoCache(userId); + + //将新增加的人员自定义信息加入至MAP中 + map_user_id_defined.put(userId, employeeCode); + } + } + insertCount += insertNum; + updateCount += updateNum; + skipCount += skipNum; + log.writeLog("----------同步结束人员,第" + k + "页:"+totalCount+ + ",新增人员数为:"+insertNum+" ,更新人员数为:"+updateNum+",跳过处理人员数为:"+skipNum+"------------"); + skipNum = 0;insertNum=0;updateNum = 0; + } + log.writeLog("---------开始处理未更新的直属领导信息-------"); + //donotfinduser(noFindManagerMap); + OrganizationUtil.dealNoFindMangerEmployeeData(noFindManagerMap); + log.writeLog("---------结束处理未更新的直属领导信息-------"); + log.writeLog("----------同步人员结束总人数:"+totalCount+",新增人数:"+insertCount+",更新人数:"+updateCount+",跳过人数:"+skipCount+"------------"); + + } catch (Exception e) { + e.printStackTrace(); + log.writeLog("员工同步异常,错误信息-------->"+e.toString()); + } + + //清空map缓存 + map_user_id_defined.clear(); + map_user_code_id.clear(); + map_user_code_id=null; + map_dept_code_id.clear(); + map_jobtitle_code_id.clear(); + noFindManagerMap.clear(); + map_deptid_subcompanyid.clear(); + map_deptid_defined.clear(); + + //更新同步时间到中间表 + String sql1 = "update uf_HRRestDate set sctbsj ='"+now+"' where jkbs = 'user'"; + rs.execute(sql1); + log.writeLog("--------------------同步人员 end["+TimeCommonUtil.obtainDate(0)+"]----------------------"); + } + + + /** + * 获取人员信息(新方法) + * @param map 查询条件 + * @return + */ + public JSONArray getUsersByPoint_New(Map map) { + //新接口URL + String url = HttpClientToJT.baseUrl + getJkhzurl(); + log.writeLog("获取员工数据url-------->"+url); + LogTool log2 = new LogTool("/log/hrm/user/detail", false); + //获取token + String token = HttpClientToJT.getToken(); + //将map转成字符串 + String param=JSONObject.toJSONString(map, SerializerFeature.DisableCircularReferenceDetect); + log.writeLog("获取员工数据传入参数param------------>"+param); + log2.writeLog("获取员工数据传入参数param------------>"+param); + String s = HttpClientToJT.sendPost(url, token, param); + log2.writeLog("员工数据返回结果------------>"+s); + + JSONObject jsonObject = JSONObject.parseObject(s); + JSONArray jsonArray = new JSONArray(); + String code=Util.null2String(jsonObject.getString("code")); + if ("1".equals(code)) { + JSONObject result = jsonObject.getJSONObject("data"); + //是否有下一页 + boolean sfyxyy=result.getBoolean("hasNextPage");//是否有下一页 + String maxPoint=Util.null2String(result.getString("maxPoint"));//下一页开始 + this.setHasNextPage(sfyxyy); + this.setPoint(maxPoint); + JSONArray records = result.getJSONArray("records"); + //过滤未获取到数据 + if(records!=null){ + jsonArray.addAll(records); + Object directSales = jsonArray.stream().filter(item -> { + JSONObject itemJson = JSONObject.parseObject(JSON.toJSONString(item)); + return "CHN".equals(itemJson.getString("deptCountryCode"))&&"ZHS".equals(itemJson.getString("languageCd")); + }).collect(Collectors.toList()); + jsonArray = JSONArray.parseArray(JSON.toJSONString(directSales)); + } + }else{ + this.setHasNextPage(false); + } + + return jsonArray; + } + + /** + * 获取人员信息(旧方法,弃用) + * @param pages 第几页 + * @param today 时间戳 + * @return + */ + public JSONArray getUsersByPage(int pages, String today) { + String url = HttpClientToJT.baseUrl + "/dcopenedi/hrEmployee/pageByUpdateTime"; + String token = HttpClientToJT.getToken(); + Map params = new HashMap<>(); + params.put("updateTime", today); +// params.put("updateTime", "2018-03-21 00:00:00"); + params.put("current", pages); + params.put("size", size); + String s = HttpClientToJT.sendGet(url, token, params); + JSONObject jsonObject = JSONObject.parseObject(s); + JSONArray jsonArray = new JSONArray(); + String code=Util.null2String(jsonObject.getString("code")); + if ("1".equals(code)) { + JSONObject result = jsonObject.getJSONObject("data"); + JSONArray records = result.getJSONArray("records"); + jsonArray.addAll(records); + } + //-------modifier by KangMD 取消国家,全部同步 start-------// + Object directSales = jsonArray.stream().filter(item -> { + JSONObject itemJson = JSONObject.parseObject(JSON.toJSONString(item)); + return "CHN".equals(itemJson.getString("countryCode"))&&"ZHS".equals(itemJson.getString("languageCd")); + //return "ZHS".equals(itemJson.getString("languageCd")); + }).collect(Collectors.toList()); + jsonArray = JSONArray.parseArray(JSON.toJSONString(directSales)); + //-------modifier by KangMD 取消国家,全部同步 end-------// + return jsonArray; + } + + /** + * 获取页数(旧方法,弃用) + * @param today 时间戳 + * @return + */ + public int getPage(String today){ + int current = 1, pages = 1; + String url = HttpClientToJT.baseUrl + "/dcopenedi/hrEmployee/pageByUpdateTime"; + String token = HttpClientToJT.getToken(); + Map params = new HashMap<>(); + params.put("updateTime", today); + params.put("current", current); + params.put("size", size); + log.writeLog("获取页数传入JSON--->"+JSON.toJSONString(params)); + String s = HttpClientToJT.sendGet(url, token, params); + JSONObject jsonObject = JSONObject.parseObject(s); + String code=Util.null2String(jsonObject.getString("code")); + log.writeLog("code------>"+code); + if ("1".equals(code)) { + JSONObject result = jsonObject.getJSONObject("data"); + pages = result.getInteger("pages"); + }else{ + log.writeLog("获取页数返回结果------>"+s); + } + return pages; + } + + /** + * 根据部门编号获取所属分部 + * @return + */ + public String getSubcomBydept(String deptId){ + String subComid = ""; + RecordSet rs = new RecordSet(); + rs.executeQuery("select supdepid,subcompanyid1,outkey from HrmDepartment where id ='"+deptId+"'"); + if(rs.next()) { + subComid = Util.null2String(rs.getString("subcompanyid1")); + String supdepid = Util.null2String(rs.getString("supdepid")); + //判断是一级部门或者无上级部门返回 + if("0".equals(supdepid)||"".equals(supdepid)){ + return subComid; + } else{ + return getSubcomBydept(supdepid); + } + } + return subComid; + } + + public JSONArray getUsers() { + int current = 1, pages = 2; + String url = HttpClientToJT.baseUrl + "/dcopenedi/hrEmployee/pageByUpdateTime"; + String token = HttpClientToJT.getToken(); + Map params = new HashMap<>(); + LocalDateTime today_start = LocalDateTime.of(LocalDate.now(), LocalTime.MIN);//当天零点 + String td_st_str = today_start.format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")); +// params.put("updateTime", td_st_str); + params.put("updateTime", "2021-07-09 00:00:00"); + params.put("current", current); + params.put("size", size); + String s = HttpClientToJT.sendGet(url, token, params); + JSONObject jsonObject = JSONObject.parseObject(s); + JSONArray jsonArray = new JSONArray(); + if (jsonObject.getInteger("code").equals(1)) { + JSONObject result = jsonObject.getJSONObject("data"); + pages = result.getInteger("pages"); + JSONArray records = result.getJSONArray("records"); + jsonArray.addAll(records); + for (int i = 1; i <= pages; i++) { + params.put("current", i); + String str = HttpClientToJT.sendGet(url, token, params); + JSONObject jsonObject1 = JSONObject.parseObject(str); + JSONObject jsonResult = jsonObject1.getJSONObject("data"); + JSONArray records1 = jsonResult.getJSONArray("records"); + Optional first = records1.stream().filter(item -> { + JSONObject itemJson = JSONObject.parseObject(JSON.toJSONString(item)); + return "00367587".equals(itemJson.getString("employeeCode")); + }).findFirst(); + if(first.isPresent()){ + System.out.println(JSON.toJSONString(first.get())); + return null; + } + } + } +// jsonArray = JSONArray.parseArray(JSON.toJSONString(directSales)); +// System.out.println(jsonArray.toJSONString()); +// System.out.println(s); +// //将写入转化为流的形式 +// writeFile(jsonArray); + return jsonArray; + } + + /** + * 获取人员自定义字段map id-->id + * + * @return + */ + public Map getUserIdDefinedMap() { + + RecordSet rs = new RecordSet(); + Map map = new HashMap<>(); + rs.executeQuery("select id,field15 from cus_fielddata where scopeid='1' and scope='HrmCustomFieldByInfoType'"); + while (rs.next()) { + map.put(rs.getString("id"), rs.getString("field15")); + } + return map; + + } + + /** + * 获取部门自定义信息 + * @return + */ + public Map> getDeptDefinedMap() { + RecordSet rs = new RecordSet(); + Map> map = new HashMap<>(); + rs.execute("select * from hrmdepartmentdefined"); + while (rs.next()) { + Map map_d=new HashMap<>(); + map_d.put("guojia", Util.null2String(rs.getString("guojia")));//国家 + map_d.put("bmfzr", Util.null2String(rs.getString("bmfzr")));//部门负责人 + map.put(Util.null2String(rs.getString("deptid")), map_d); + } + return map; + + } + + public Map getUserCodeIdMap() { + RecordSet rs = new RecordSet(); + Map map = new HashMap<>(); + rs.executeQuery("select workcode,outkey,id from hrmresource where outkey is not null "); + while (rs.next()) { + map.put(rs.getString("outkey"), rs.getString("id")); + } + return map; + } + + public int getSize() { + return size; + } + + public void setSize(int size) { + this.size = size; + } + + public boolean isHasNextPage() { + return hasNextPage; + } + + public void setHasNextPage(boolean hasNextPage) { + this.hasNextPage = hasNextPage; + } + + public String getPoint() { + return point; + } + + public void setPoint(String point) { + this.point = point; + } + + public String getJkhzurl() { + return jkhzurl; + } + + public void setJkhzurl(String jkhzurl) { + this.jkhzurl = jkhzurl; + } +} diff --git a/src/main/youhong_ai_jitu_src/jntchina/schedule/hrm/SyncHrmresourceToOAOc.java b/src/main/youhong_ai_jitu_src/jntchina/schedule/hrm/SyncHrmresourceToOAOc.java new file mode 100644 index 0000000..3cd09ad --- /dev/null +++ b/src/main/youhong_ai_jitu_src/jntchina/schedule/hrm/SyncHrmresourceToOAOc.java @@ -0,0 +1,438 @@ +package jntchina.schedule.hrm; + +import com.alibaba.fastjson.JSONArray; +import com.alibaba.fastjson.JSONObject; +import com.api.integration.util.JavaUtil; +import com.engine.common.service.impl.HrmCommonServiceImpl; +import com.engine.common.service.impl.ThemeServiceImpl; +import jntchina.schedule.hrm.entity.HrmUserDto; +import jntchina.schedule.hrm.util.OrganizationUtil; +import selfdev.util.base.TimeCommonUtil; +import selfdev.util.log.LogTool; +import weaver.conn.RecordSet; +import weaver.general.Util; +import weaver.hrm.resource.ResourceComInfo; + +import java.util.*; + +/** + * @author Cyq + * @date 2021年6月17日 02:01:51 + */ +public class SyncHrmresourceToOAOc { + + //是否有下一页 + boolean isNext = true; + + //国际编码集合 + private final List deptCountryCodesList = Arrays.asList("EGY","BRA","MEX","SAU","VNM","THA","MYS","SGP","KHM","PHL"); + + //页码 + String current = "1"; + + private final LogTool log = new LogTool("/log/hrm/userOC/", false); + + /** + * 执行同步操作 + * @param today 当前日期 + */ + @SuppressWarnings("unchecked") + public void execute(String today) { + log.writeLog("---------进入海外人员同步------------"); + try { + + HrmCommonServiceImpl hrmCommonServiceImpl = new HrmCommonServiceImpl(); + + String now = TimeCommonUtil.obtainDate(0); + ThemeServiceImpl themeService = new ThemeServiceImpl(); + //获取当前系统中未封存的分部信息 <外部主键,OA主键> + //Map oaSubCompanyMap = OrganizationUtil.getEffectiveSubCompanyCodeIdMap(); + //获取当前系统中未封存的部门信息 <外部主键,OA主键> + //Map map_dept_code_id = OrganizationUtil.getEffectiveDepartmentCodeIdMap(); + //获取当前OA系统中 未封存的部门和分部信息集合 + Map oaDeptAndComMap = OrganizationUtil.getEffectiveDeptAndCompany(); + + //用于存储 直接上级不存在的员工信息 <员工编码,直接上级编码> + Map noFindManagerMap = new HashMap<>(); + + // 处理人员同步逻辑 + RecordSet rs = new RecordSet(); + String sql; + log.writeLog("----------海外 开始同步人员------------"); + int totalCount = 0, insertCount = 0, updateCount = 0, skipCount = 0; + int skipNum = 0, insertNum = 0, updateNum = 0; + + //更新人员缓存 + ResourceComInfo rci = new ResourceComInfo(); + //如果有下一页就会循环 + int count = 0; + + //部门与国家对应关系集合 + Map deptCountryMap = OrganizationUtil.getDeptCountryMap(); + + String password = "9F51B4682F92AB843B401218BF27C301";//默认密码Jitu@2021 + + while (isNext) { + count ++; + JSONArray data = getUsersByPage(current, today); + List users = JSONArray.parseArray(data.toJSONString(), HrmUserDto.class); + totalCount = totalCount + users.size(); + log.writeLog("----------同步人员第" + count + "页,条数:" + users.size()); + for (HrmUserDto row : users) { + try { + String field0 = ""; + String employeeCode = Util.null2String(row.getEmployeeCode());//员工code + String employeeName = Util.null2String(row.getEmployeeName());//姓名 + String employeeSexCode = Util.null2String(row.getEmployeeSexCode());//性别 M男 F女 对应 OA 0男 1女 + int sex = "M".equals(employeeSexCode) ? 0 : 1; + String birthdate = Util.null2String(row.getEmployeeBirthdate());//出生年月 + String companyTel = Util.null2String(row.getCompanyTel());//办公电话 + String personalTel = Util.null2String(row.getPersonalTel());//手机号 + String email = Util.null2String(row.getCompanyEmail());//邮箱 + String idNumber = Util.null2String(row.getCertificateNum());//身份证号码 + String managerCode = Util.null2String(row.getSupervisorId());//上级次账号code + //获取人员姓名的拼音 + String name_pinyin = hrmCommonServiceImpl.generateQuickSearchStr(employeeName); + String EntryDate = Util.null2String(row.getEmplHireDate());//入职日期 无字段,暂用试用结束日期来替代 + String hrStatus = Util.null2String(row.getHrStatus());//状态A在职,I离职 对应OA的1正式 5离职 + int status = "A".equals(hrStatus) ? 1 : 5;//OA的在职状态 + String countryCode = Util.null2String(row.getCountryCode());//所属国家 + String deptCode = Util.null2String(row.getDeptCode());//部门 + String positionCode = Util.null2String(row.getPositionCode());//岗位 + log.writeLog("工号:[" + employeeCode + "],姓名:[" + employeeName + "],部门:[" + deptCode + "],领导:[" + managerCode + "],岗位:[" + positionCode + "],国家:[" + countryCode + "]"); + + String bankBranchName = Util.null2String(row.getBankBranchName());//开户行 + String bankAccountId = Util.null2String(row.getBankAccountId());//银行卡号 + String bankName = Util.null2String(row.getBankName());//银行类型 + String managerId,departmentid, subcompanyid1; + + //处理岗位id + String jobtitleId = OrganizationUtil.getJobtitleIdByOutKey(positionCode); + + //如果部门编码为空,跳过不同步 + if ("".equals(deptCode)) { + skipNum++; + log.writeLog("cylnb is dept null1:" + deptCode + "; userCode" + employeeCode); + continue; + } else { + if(oaDeptAndComMap.containsKey(deptCode)){ + String mapValue = oaDeptAndComMap.get(deptCode); + + departmentid = Util.TokenizerString2(mapValue,"^_^")[0]; + subcompanyid1 = Util.TokenizerString2(mapValue,"^_^")[1]; + } else { + log.writeLog("cylnb is dept and sub null Code:" + deptCode + "; userCode" + employeeCode); + skipNum++; + continue; + } + + managerId = OrganizationUtil.getEmployeeManagerId(managerCode,departmentid); + + //从HR获取有上级,但是在OA中未找到,则说明可能上级是新入职还未同步到OA中 + if ("".equals(managerId) && !"".equals(managerCode)) { + noFindManagerMap.put(employeeCode, managerCode); + } + } + + //是否排除昵称同步(人员所在部门为泰国时,排除昵称同步) + boolean exSynNickName = true; + if (deptCountryMap.containsKey(departmentid)) { + String tempCountryCode = deptCountryMap.get(departmentid); + + if ("THA".equals(tempCountryCode)) { + exSynNickName = false; + } + + //当国家编码为 中国、印尼或是为空时 直接跳过 + if ("CHN".equals(tempCountryCode) || "IDN".equals(tempCountryCode) || "".equals(tempCountryCode)) { + log.writeLog("cylnb continue user 部门是中国或没有国家字段:" + employeeCode + " 部门:" + deptCode); + skipNum++; + continue; + } + } else { + log.writeLog("cylnb continue 找不到部门:" + employeeCode + " 部门:" + deptCode); + skipNum++; + continue; + } + + //自定义表的昵称 + if ("CHN".equals(countryCode)) { + field0 = row.getEmployeeEnglishName(); + } else { + //海外 + String language = ""; + if ("BRA".equals(countryCode)) { + language = "POR"; + } + if ("SAU".equals(countryCode) || "ARE".equals(countryCode) + || "EGY".equals(countryCode) + || "MEX".equals(countryCode) + || "SGP".equals(countryCode) + || "PHL".equals(countryCode) + || "MYS".equals(countryCode) + || "KHM".equals(countryCode) + ) { + language = "ENG"; + } + // 、 • 7中°~^8英文、心‘9繁体、• ~‘14 越南°~17泰国°~‘21 葡萄牙‘~‘22 印尼 + if ("IDN".equals(countryCode)) { + language = "IDN"; + } + if ("THA".equals(countryCode)) { + language = "THA"; + } + if ("VNM".equals(countryCode)) { + language = "VIE"; + } + try { + JSONArray userGUOJIA = getUserGUOJIA("5000", today, language, employeeCode); + List country = JSONArray.parseArray(userGUOJIA.toJSONString(), HrmUserDto.class); + HrmUserDto hrmUserDto = country.get(0); + employeeName = hrmUserDto.getEmployeeName(); + field0 = hrmUserDto.getEmployeeEnglishName(); + } catch (Exception e) { + log.writeLog("-------------获取多语言报错:" + employeeCode); + } + } + log.writeLog("-----------------countryCode:" + countryCode); + log.writeLog("-----------------field0:" + field0); + log.writeLog("-----------------employeeName:" + employeeName); + + //判断人员ID是否已经存在,不存在则插入生成新人员 + rs.executeQuery("select id,lastname from hrmResource where workCode = ?", employeeCode); + if (!rs.next()) { + //获取即将插入的人员ID + rs.executeProc("HrmResourceMaxId_Get", ""); + rs.next(); + String maxUserId = "" + rs.getInt(1); + //新增数据,插入到人员基本信息表HrmResource中 seclevel + sql = "insert into hrmResource(id,loginid,password,lastname,workcode,sex, " + + "mobile,email,departmentid,jobtitle,birthday,certificatenum," + + "seclevel,outkey,status,systemlanguage,createrid,createdate," + + "companystartdate,telephone,ecology_pinyin_search,pinyinlastname," + + "created,creater,modified,modifier,managerid,subcompanyid1) values( " + + "'" + maxUserId + "'," + + "'" + employeeCode + "'," + + "'" + password + "'," + + "?," + + "'" + employeeCode + "'," + + "'" + sex + "'," + + "'" + personalTel + "'," + + "'" + email + "'," + + "'" + departmentid + "'," + + "'" + jobtitleId + "'," + + "'" + birthdate + "'," + + "'" + idNumber + "'," + + "'" + 10 + "'," + + "'" + employeeCode + "'," + + "" + status + "," + + "'7'," + + "'1'," + + "'" + now.substring(0, 10) + "'," + + "'" + EntryDate + "'," + + "'" + companyTel + "'," + + "?," + + "?," + + "to_date('" + now + "','yyyy-mm-dd hh24:mi:ss')," + + "'1'," + + "to_date('" + now + "','yyyy-mm-dd hh24:mi:ss')," + + "'1'," + + "'" + managerId + "'," + + "'" + subcompanyid1 + "')"; + boolean executeUpdate = rs.executeUpdate(sql, employeeName, name_pinyin, name_pinyin); + log.writeLog("新增人员是否正确" + executeUpdate); + log.writeLog("插入人员表中数据sql--------->" + sql); + log.writeLog("msg:" + rs.getExceptionMsg()); + insertNum++; + //新增数据,插入到人员自定义表cus_fielddata中 + rs.executeQuery("select id,field15 from cus_fielddata where scopeid='1' and scope='HrmCustomFieldByInfoType' and field15='" + employeeCode + "'"); + if (!rs.next()) { + boolean b; + if ("".equals(bankAccountId)) { + b = OrganizationUtil.insertEmployeeCustomizePersonal(maxUserId,null,null,row); + } else { + String[] bankInfo = new String[] {bankBranchName,bankAccountId,bankName}; + b = OrganizationUtil.insertEmployeeCustomizePersonal(maxUserId,bankInfo,null,row); + } + log.writeLog("-------------新增自定义信息个人信息是否成功:" + b); + } else { + //如果已经存在就修改 + log.writeLog("---------------已经存在但是信息不是自己"); + } + + if (exSynNickName) {//是否有昵称 + OrganizationUtil.dealEmployeeNickName(maxUserId,field0); + } + + // log.writeLog("插入人员自定义表中数据sql--------->" + sql); + themeService.createSubCompanyMenu(Integer.parseInt(maxUserId), Integer.parseInt(subcompanyid1)); + //刷新人员缓存 + rci.addResourceInfoCache(maxUserId); + } else {//存在则更新 + String id = rs.getString("id"); + //系统中已存在的姓名 + String oldLastName = Util.null2String(rs.getString("lastname")); + + // String newEmployeeName = OrganizationUtil.dealEmployeeName(oldLastName, employeeName); + String newEmployeeName = employeeName; + + //更新人员基本信息表数据 + String updateStr = ""; + updateStr += !"".equals(departmentid) ? "departmentid = '" + departmentid + "', " : ""; + updateStr += !"".equals(jobtitleId) ? "jobtitle = '" + jobtitleId + "', " : ""; + updateStr += !"".equals(subcompanyid1) ? "subcompanyid1 = '" + subcompanyid1 + "', " : ""; + updateStr += !"".equals(managerId) ? "managerid = '" + managerId + "', " : ""; + sql = "update hrmresource set " + + "workcode = '" + employeeCode + "', " + + "lastname = ?, " + + "sex = '" + sex + "', " + + "mobile = '" + personalTel + "', " + + "ecology_pinyin_search = ?, " + + "pinyinlastname = ?, " + + "email = '" + email + "', " + + "telephone = '" + companyTel + "', " + + "status = " + status + ", " + + "birthday = '" + birthdate + "', " + + "certificatenum = '" + idNumber + "', " + + "companystartdate = '" + EntryDate + "', " + + "modified = to_date('" + now + "','yyyy-mm-dd hh24:mi:ss')," + + "modifier = '1', " + + "lastmoddate = '" + now.substring(0, 10) + "', " + + updateStr + + "lastmodid = '1' " + + "where id ='" + id + "'"; + boolean executeUpdate = rs.executeUpdate(sql, newEmployeeName, name_pinyin, name_pinyin); + log.writeLog("更新人员基本信息表中数据sql--------->" + sql); + log.writeLog("更新人员是否正确:" + executeUpdate); + log.writeLog("msg:" + rs.getExceptionMsg()); + updateNum++; + + + boolean executeUpdate1; + String[] bankInfo = new String[] {bankBranchName,bankAccountId,bankName}; + + rs.executeQuery("select id,field15 from cus_fielddata where scopeid='1' and scope='HrmCustomFieldByInfoType' and id='" + id + "'"); + if (!rs.next()) { + executeUpdate1 = OrganizationUtil.insertEmployeeCustomizePersonal(id,bankInfo,null,row); + } else { + //更新人员工作信息表数据 + if ("".equals(bankAccountId)) { + executeUpdate1 = OrganizationUtil.updateEmployeeCustomizePersonal(id,null,null,row); + } else { + executeUpdate1 = OrganizationUtil.updateEmployeeCustomizePersonal(id,bankInfo,null,row); + } + } + log.writeLog("是否正确--------->" + executeUpdate1); + + if (exSynNickName) {//是否有昵称 + OrganizationUtil.dealEmployeeNickName(id,field0); + } + + //刷新人员缓存 + rci.addResourceInfoCache(id); + } + } catch (Exception e) { + log.writeLog("--------------报错了:" + JavaUtil.getExceptionDetail(e)); + } + } + insertCount += insertNum; + updateCount += updateNum; + skipCount += skipNum; + log.writeLog("----------同步结束人员,第" + count + "页:" + totalCount + + ",新增人员数为:" + insertNum + " ,更新人员数为:" + updateNum + ",跳过处理人员数为:" + skipNum + "------------"); + skipNum = 0; + insertNum = 0; + updateNum = 0; + } + log.writeLog("---------开始处理未更新的直属领导信息-------"); + OrganizationUtil.dealNoFindMangerEmployeeData(noFindManagerMap); + log.writeLog("---------结束处理未更新的直属领导信息-------"); + log.writeLog("----------海外 同步人员结束总人数:" + totalCount + ",新增人数:" + insertCount + ",更新人数:" + updateCount + ",跳过人数:" + skipCount + "------------"); + + //更新同步时间到中间表 + String sql1 = "update uf_HRRestDate set sctbsj ='" + now + "' where jkm = '/dcopenedi/hrEmployee/pageByUpdateTime'"; + rs.executeUpdate(sql1); + + } catch (Exception e) { + log.writeLog("---------Exception------------:" + JavaUtil.getExceptionDetail(e)); + e.printStackTrace(); + } + + } + + /** + * 分页获取人员信息 + * @param pages 页码 + * @param today 日期 + * @return 返回人员信息JSONArray数组 + */ + private JSONArray getUsersByPage(String pages, String today) { + return callInterface(pages,today,"ENG","",true); + } + + + /** + * 根据固定人员对应国家编码的信息 + * @param pages 页码 + * @param today 日期 + * @param countryCode 国家编码 + * @param code 编码 + * @return 国家信息数组 + */ + private JSONArray getUserGUOJIA(String pages, String today, String countryCode, String code) { + return callInterface(pages,today,countryCode,code,false); + } + + /** + * 调用人员信息接口 + * @param pages 对应的页码 + * @param today 数据日期 + * @param countryCode 国家编码 + * @param code 人员编码 + * @param needUpdate 是否需要更新全局变量 + * @return 人员信息JSONArray数组 + */ + private JSONArray callInterface(String pages, String today, String countryCode, String code,boolean needUpdate) { + int size = 5000; + + JSONArray jsonArray = new JSONArray(); + + List languageCds = new ArrayList<>(); + languageCds.add(countryCode); + + String s = OrganizationUtil.callEmployeeInterface(size,pages,today,languageCds,deptCountryCodesList,code); + + if (!"".equals(s) && null != s) { + log.writeLog("---------------接口返回空成功"); + } else { + log.writeLog("---------------接口返回空"); + + return jsonArray; + } + + JSONObject jsonObject = JSONObject.parseObject(s); + + if(needUpdate){ + if (jsonObject.getInteger("code").equals(1)) { + JSONObject result = jsonObject.getJSONObject("data"); + if (result.get("hasNextPage").toString().equals("true")) { + current = result.get("maxPoint").toString(); + } else { + isNext = false; + } + } else { + isNext = false; + } + } + + if (jsonObject.getInteger("code").equals(1)) { + JSONObject result = jsonObject.getJSONObject("data"); + JSONArray records = result.getJSONArray("records"); + jsonArray.addAll(records); + } + + return jsonArray; + } + + +} diff --git a/src/main/youhong_ai_jitu_src/jntchina/schedule/hrm/SyncHrmsubcompanyToOA.java b/src/main/youhong_ai_jitu_src/jntchina/schedule/hrm/SyncHrmsubcompanyToOA.java new file mode 100644 index 0000000..a36d9fe --- /dev/null +++ b/src/main/youhong_ai_jitu_src/jntchina/schedule/hrm/SyncHrmsubcompanyToOA.java @@ -0,0 +1,319 @@ +package jntchina.schedule.hrm; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.JSONArray; +import com.alibaba.fastjson.JSONObject; +import com.engine.common.service.impl.ThemeServiceImpl; + +import jntchina.schedule.hrm.entity.DepartmentDto; +import jntchina.util.HttpClientToJT; +import selfdev.util.base.TimeCommonUtil; +import selfdev.util.log.LogTool; +import weaver.conn.RecordSet; +import weaver.general.Util; +import weaver.hrm.company.SubCompanyComInfo; + +import java.io.BufferedWriter; +import java.io.FileWriter; +import java.io.IOException; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.stream.Collectors; + +/** + * 定时将HR系统中的组织同步至OA的分部中 + * @author Cyq + * @date 2021年6月17日 02:01:51 + */ +public class SyncHrmsubcompanyToOA { + + //分部编码和id map + Map map_subcompany_code_id = new HashMap(); + private LogTool log = new LogTool("/log/hrm/subcompany/", false); + + /** + * 同步分部信息 + */ + public void execute(List subcompanys ) { + map_subcompany_code_id = getSubCodeIdMap(); + RecordSet rs = new RecordSet(); + RecordSet rs2 = new RecordSet(); + log.writeLog("----------开始同步分部,条数:" + subcompanys.size()); + ThemeServiceImpl themeService = new ThemeServiceImpl(); + // 处理公司同步逻辑 + for (int i = 0; i < subcompanys.size(); i++) { + DepartmentDto row = subcompanys.get(i); + String countryCode = Util.null2String(row.getCountryCode());//国家编码 + String departmentCode = Util.null2String(row.getDepartmentCode());//分部编码 + String departmentName = Util.null2String(row.getDepartmentName());//分部全称 +// String ShortName = Util.null2String(row.getDepartmentAbbreviation());//部门简称 + String superiorDepartment = Util.null2String(row.getSuperiorDepartment());//上级分部编码 +// String departmentOrder = Util.null2String(row.getDepartmentOrder());//排序 + Integer canceled = Util.null2String(row.getStatus()).equals("3") ? 1 : null;//1 新增 2 修改 3作废 + String sql = ""; + //判断HR分部ID是否已经存在 + String now = TimeCommonUtil.obtainDate(0); + String supsubcomid = "0"; + if(map_subcompany_code_id.containsKey(superiorDepartment)){ + supsubcomid = map_subcompany_code_id.get(superiorDepartment); + } + +// //多语言 +// departmentName = getDepartmentName("2018-04-23 00:00:00",departmentCode,departmentName); +// if("".equals(departmentName)){ +// log.writeLog("--------------多语言为空code:"+departmentCode); +// departmentName = row.getDepartmentName(); +// } + + //只需要中文和英文 + departmentName = "~`~`7 " + departmentName + "`~`8 `~`~"; + log.writeLog("-------------英语刷为空:"+departmentName); + + //分部不存在则插入生成新分部 + if (!map_subcompany_code_id.containsKey(departmentCode)) { + String subconpanyid_2=""; + //为解决同时手工执行点击了2次同步时多线程产生的问题,故还需要再次查询一遍数据库中是否已存在 + rs2.execute("select * from hrmsubcompany where outkey='"+departmentCode+"'"); + while(rs2.next()){ + subconpanyid_2=Util.null2String(rs2.getString("id")); + } + //若已存在则不做其他操作,跳过 + if(!"".equals(subconpanyid_2)){ + log.writeLog("分部ID【"+subconpanyid_2+"】、分部编码【"+departmentCode+"】、分部outkey【"+departmentCode+"】、已存在,当前跳过,进入下一次循环"); + map_subcompany_code_id.put(departmentCode, subconpanyid_2); + continue; + } + + //新增数据,插入到hrmsubcompany表中 + sql = "insert into hrmsubcompany (companyid,supsubcomid,subcompanyname,subcompanydesc,outkey,subcompanycode," + + "canceled,created,creater,modified,modifier) values(" + + "'1'," + + "'" + supsubcomid + "'," + + "'" + departmentName + "'," + + "'" + departmentName + "'," + + "'" + departmentCode + "'," + + "'" + departmentCode + "'," + + canceled + "," + + "to_date('" + now + "','yyyy-mm-dd hh24:mi:ss')," + + "'1'," + + "to_date('" + now + "','yyyy-mm-dd hh24:mi:ss')," + + "'1')"; + log.writeLog("插入分部表生成新数据sql--------->" + sql); + rs.execute(sql); + + rs.execute("select max(id) from hrmsubcompany"); + int maxSubcompanyid = 0;//新插入数据的分部ID + if (rs.next()) { + maxSubcompanyid = rs.getInt(1); + } + //将新增加的分部加入至MAP中 + map_subcompany_code_id.put(departmentCode, maxSubcompanyid + ""); +// rs.execute("select max(id) from hrmsubcompany"); +// //新增数据,插入到部门自定义表HrmDepartmentDefined中 +// int maxSubID = 0;//新插入数据的部门ID +// if (rs.next()) { +// maxSubID = rs.getInt(1); +// } + sql = "insert into hrmsubcompanyDefined(SUBCOMID,guojia,sfzy) " + + "values('" + maxSubcompanyid + "','" + countryCode + "'," + + "'" + row.getIsDirectSales()+ "')"; + rs.execute(sql); + log.writeLog("插入分部自定义表中数据sql--------->" + sql); + + log.writeLog("初始化分部菜单需要多久 start--------->" + TimeCommonUtil.obtainDate(0)); + //初始化人员分部菜单 + themeService.createSubCompanyMenu(Integer.valueOf(maxSubcompanyid),Integer.valueOf(supsubcomid)); + log.writeLog("初始化分部菜单需要多久 end--------->" + TimeCommonUtil.obtainDate(0)); + + } else {//分部存在则更新 + String updateStr = ""; + updateStr += !"0".equals(supsubcomid)?"supsubcomid= '"+ supsubcomid + "', ":"" ; + sql = "update hrmsubcompany set " + + updateStr + + "subcompanyname = '" + departmentName + "', " + + "subcompanydesc = '" + departmentName + "', " + + "subcompanycode = '" + departmentCode + "', " + + "modified = to_date('" + now + "','yyyy-mm-dd hh24:mi:ss')," + + "modifier = '1', " + + "canceled = " + canceled + " " + + "where outkey= '" + departmentCode + "'"; + log.writeLog("更新分部表中数据sql--------->" + sql); + rs.execute(sql); + + //处理分部自定义表 + String subcomid = map_subcompany_code_id.get(departmentCode); + rs.execute("select SUBCOMID from hrmsubcompanyDefined where SUBCOMID='"+subcomid+"'"); + if(rs.next()){ + sql = "update hrmsubcompanyDefined set "+ + "sfzy = '"+row.getIsDirectSales()+"', "+ + "guojia = '"+countryCode+"' "+ + "where SUBCOMID = '"+subcomid+"'"; + rs.execute(sql); + log.writeLog("更新分部自定义表中数据sql--------->" + sql); + + }else{ + sql = "insert into hrmsubcompanyDefined(SUBCOMID,guojia,sfzy) " + + "values('" + subcomid + "','" + countryCode + "','" + row.getIsDirectSales()+ "')"; + rs.execute(sql); + log.writeLog("插入分部自定义表中数据sql--------->" + sql); + } + } + } + SubCompanyComInfo sccif = new SubCompanyComInfo(); + sccif.removeCompanyCache(); + + map_subcompany_code_id.clear(); + map_subcompany_code_id=null; + + } + + public Map getSubCodeIdMap() { + RecordSet rs = new RecordSet(); + Map map = new HashMap<>(); + //rs.executeQuery("select subcompanycode,outkey,id from HrmSubCompany where outkey is not null and (CANCELED!=1 or CANCELED is null)"); + rs.executeQuery("select subcompanycode,outkey,id from HrmSubCompany where outkey is not null"); + while (rs.next()) { + map.put(rs.getString("outkey"), rs.getString("id")); + } + return map; + } + + + public JSONArray getSubcompanys() { + int current = 1, size = 10000, pages = 2; + String url = HttpClientToJT.baseUrl + "/dcopenedi/hrCompany/pageByUpdateTime"; + String token = HttpClientToJT.getToken(); + Map params = new HashMap<>(); +// LocalDateTime today_start = LocalDateTime.of(LocalDate.now(), LocalTime.MIN);//当天零点 +// String td_st_str = today_start.format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")); +// params.put("updateTime", td_st_str); + params.put("updateTime", "2018-03-21 00:00:00"); + params.put("current", current); + params.put("size", size); + String s = HttpClientToJT.sendGet(url, token, params); + JSONObject jsonObject = JSONObject.parseObject(s); + JSONArray jsonArray = new JSONArray(); + if (jsonObject.getInteger("code").equals(1)) { + JSONObject result = jsonObject.getJSONObject("data"); + pages = result.getInteger("pages"); + JSONArray records = result.getJSONArray("records"); + jsonArray.addAll(records); + for (int i = 2; i <= pages; i++) { + params.put("current", i); + String str = HttpClientToJT.sendGet(url, token, params); + JSONObject jsonObject1 = JSONObject.parseObject(str); + JSONObject jsonResult = jsonObject1.getJSONObject("data"); + JSONArray records1 = jsonResult.getJSONArray("records"); + jsonArray.addAll(records1); + } + Object directSales = jsonArray.stream().filter(item -> { + JSONObject itemJson = JSONObject.parseObject(JSON.toJSONString(item)); + return "Y".equals(itemJson.getString("isDirectSales")); + }).collect(Collectors.toList()); + jsonArray = JSONArray.parseArray(JSON.toJSONString(directSales)); + } + System.out.println(jsonArray.toJSONString()); + //将写入转化为流的形式 +// writeFile(jsonArray); + return jsonArray; + } + + private void writeFile(JSONArray jsonArray) { + BufferedWriter bw = null; + try { + bw = new BufferedWriter(new FileWriter("D:\\1.txt")); + //一次写一行 + bw.write(jsonArray.toJSONString()); + bw.newLine(); //换行用 + //关闭流 + bw.close(); + } catch (IOException e) { + e.printStackTrace(); + } + System.out.println("写入成功"); + } + + public static void main(String[] args) { + SyncHrmsubcompanyToOA ss= new SyncHrmsubcompanyToOA(); + ss.getSubcompanys(); + } + + + /** + * 获取多语言 + * + * @param date 时间 + * @param departmentCode 部门code + * @param deptName 部门中文名称 + * @return 多语言名称 + */ + public String getDepartmentName(String date, String departmentCode, String deptName) { + String retName = ""; + boolean existence = true; + String language = "ENG"; + String cdIndex = ""; + try { + String country = ""; + // 日期 位置 国家 部门code + JSONArray ocDepartmentsGUOJIA = getOcDepartmentsGUOJIA(date, "1", language, departmentCode); + log.writeLog("--------------多语言是否拿到数据:"+ocDepartmentsGUOJIA.size()); + List countryList = JSONArray.parseArray(ocDepartmentsGUOJIA.toJSONString(), DepartmentDto.class); + DepartmentDto countryDto = countryList.get(0); + //对应国家的语言名称(对应国家标签里面) + String countryDepartmentName = countryDto.getDepartmentName(); + log.writeLog("---------------英语名称:" + countryDepartmentName); + + //只需要中文和英文 + retName = "~`~`7 " + deptName + "`~`8 " + countryDepartmentName + "`~`~"; + + log.writeLog("---------------多语言名称:" + retName); + } catch (Exception e) { + log.writeLog("--------------拿多语言报错了"); + return deptName; + } + return retName; + } + + + /** + * 获取海外部门国家数据 + * + * @param date 时间 + * @param point + * @return + */ + public JSONArray getOcDepartmentsGUOJIA(String date, String point, String guojia, String departmentCode) { + int current = 1, size = 5000, pages = 2; + String url = HttpClientToJT.baseUrl + "/dcopenedi/hrDept/pageNewHrDeptByUpdateTime"; + String token = HttpClientToJT.getToken(); + log.writeLog("-------token--------->" + token); + Map params = new HashMap<>(); + List list1 = new ArrayList(); + list1.add(guojia); + params.put("languageCds", list1); + params.put("updateTime", date); + params.put("point", point); + params.put("size", size); + params.put("deptCode", departmentCode); + log.writeLog("传入JSON--------------->" + JSON.toJSONString(params)); + String s = HttpClientToJT.sendPost(url, token, JSONObject.toJSONString(params)); + JSONObject jsonObject = JSONObject.parseObject(s); + JSONArray jsonArray = new JSONArray(); + + String code = Util.null2String(jsonObject.getString("code")); + log.writeLog("code------>" + code); + if ("1".equals(code)) { + JSONObject result = jsonObject.getJSONObject("data"); + JSONArray records = result.getJSONArray("records"); + // Object hasNextPage = result.get("hasNextPage"); + jsonArray.addAll(records); + } + + return jsonArray; + } + + + +} diff --git a/src/main/youhong_ai_jitu_src/jntchina/schedule/hrm/SyncHrmsubcompanyToOAOC.java b/src/main/youhong_ai_jitu_src/jntchina/schedule/hrm/SyncHrmsubcompanyToOAOC.java new file mode 100644 index 0000000..8bcb4c1 --- /dev/null +++ b/src/main/youhong_ai_jitu_src/jntchina/schedule/hrm/SyncHrmsubcompanyToOAOC.java @@ -0,0 +1,409 @@ +package jntchina.schedule.hrm; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.JSONArray; +import com.alibaba.fastjson.JSONObject; +import com.api.integration.util.JavaUtil; +import jntchina.schedule.hrm.entity.DepartmentDto; +import jntchina.util.HttpClientToJT; +import selfdev.util.base.TimeCommonUtil; +import selfdev.util.log.LogTool; +import weaver.conn.RecordSet; +import weaver.general.Util; +import weaver.hrm.company.SubCompanyComInfo; + +import java.io.BufferedWriter; +import java.io.FileWriter; +import java.io.IOException; +import java.time.LocalDate; +import java.time.LocalDateTime; +import java.time.LocalTime; +import java.time.format.DateTimeFormatter; +import java.util.*; +import java.util.stream.Collectors; + +/** + * @author Cyq + * @date 2021年6月17日 02:01:51 + */ +public class SyncHrmsubcompanyToOAOC { + + + Map subMap = new HashMap<>(); + + //分部编码和id map + Map map_subcompany_code_id = new HashMap(); + private LogTool log = new LogTool("/log/hrm/subcompanyOc/", false); + + /** + * 同步分部信息 + */ + public List execute(List subcompanys, List departments) { + log.writeLog("----------开始同步分部,条数:" + subcompanys.size()); + try { + RecordSet rss = new RecordSet(); +// for (int i = 0; i < departments.size(); i++) { +// DepartmentDto row = departments.get(i); +// String departmentCode = Util.null2String(row.getDepartmentCode());//部门编码 +// String departmentName = Util.null2String(row.getDepartmentName());//部门全称 +// String ShortName = Util.null2String(row.getDepartmentAbbreviation());//部门简称 +// String superiorDepartment = Util.null2String(row.getSuperiorDepartment());//上级部门编码 +// log.writeLog("----------部门编码:" + departmentCode); +// +// rss.executeQuery("select * from HrmDepartment where outkey = ? ",departmentCode); +// if(!rss.next()){ +// boolean executeUpdate = rss.executeUpdate("insert into HrmDepartment(Departmentname,outkey,uuid) values(?,?,?) ", departmentName, departmentCode, superiorDepartment); +// log.writeLog("----------先把部门同步进去:" + executeUpdate); +// log.writeLog("----------msg:" + rss.getExceptionMsg()); +// }else{ +// log.writeLog("----------这个部门已经放进去了不用新增:" + departmentName); +// } +// } + + map_subcompany_code_id = getSubCodeIdMap(); + RecordSet rs = new RecordSet(); +// log.writeLog("----------同步分部源数据:" + JSON.toJSONString(subcompanys)); + // 处理公司同步逻辑 + for (int i = 0; i < subcompanys.size(); i++) { + DepartmentDto row = subcompanys.get(i); + String countryCode = Util.null2String(row.getCountryCode());//国家编码 + String departmentCode = Util.null2String(row.getDepartmentCode());//部门编码 + String departmentName = Util.null2String(row.getDepartmentName());//部门全称 + String ShortName = Util.null2String(row.getDepartmentAbbreviation());//部门简称 + String superiorDepartment = Util.null2String(row.getSuperiorDepartment());//上级部门编码 + String departmentOrder = Util.null2String(row.getDepartmentOrder());//排序 + Integer canceled = Util.null2String(row.getStatus()).equals("3") ? 1 : null;//1 新增 2 修改 3作废 + String sql = ""; + //判断HR分部ID是否已经存在 + log.writeLog("----------------分部编码:" + departmentCode); + log.writeLog("----------------国家:" + countryCode); + log.writeLog("----------------分部名称:" + departmentName); + log.writeLog("----------------上级分部编码:" + superiorDepartment); + log.writeLog("----------------canceled:" + canceled); + String now = TimeCommonUtil.obtainDate(0); + String supsubcomid = "0"; + if (map_subcompany_code_id.containsKey(superiorDepartment)) { + supsubcomid = map_subcompany_code_id.get(superiorDepartment); + } + if("0".equals(supsubcomid) && !"".equals(superiorDepartment)){ + subMap.put(departmentCode,superiorDepartment); + } + + //分部不存在则插入生成新分部 + if (!map_subcompany_code_id.containsKey(departmentCode)) { + //新增数据,插入到hrmsubcompany表中 + sql = "insert into hrmsubcompany (companyid,supsubcomid,subcompanyname,subcompanydesc,outkey," + + "canceled,created,creater,modified,modifier) values(" + + "'1'," + + "'" + supsubcomid + "'," + + "'" + departmentName + "'," + + "'" + departmentName + "'," + + "'" + departmentCode + "'," + + canceled + "," + + "to_date('" + now + "','yyyy-mm-dd hh24:mi:ss')," + + "'1'," + + "to_date('" + now + "','yyyy-mm-dd hh24:mi:ss')," + + "'1')"; + log.writeLog("插入分部表生成新数据sql--------->" + sql); + rs.executeUpdate(sql); + + rs.executeQuery("select id from hrmsubcompany outkey = ?",departmentCode); + int maxSubcompanyid = 0;//新插入数据的分部ID + if (rs.next()) { + maxSubcompanyid = rs.getInt("id"); + } + //将新增加的分部加入至MAP中 + map_subcompany_code_id.put(departmentCode, maxSubcompanyid + ""); + rs.executeQuery("select id from hrmsubcompany outkey = ?",departmentCode); + //新增数据,插入到部门自定义表HrmDepartmentDefined中 + int maxSubID = 0;//新插入数据的部门ID + if (rs.next()) { + maxSubID = rs.getInt("id"); + } + sql = "insert into hrmsubcompanyDefined(SUBCOMID,guojia,sfzy) " + + "values('" + maxSubID + "','" + countryCode + "','" + row.getIsDirectSales() + "')"; + rs.executeUpdate(sql); + log.writeLog("插入分部自定义表中数据sql--------->" + sql); + + } else {//分部存在则更新 + String updateStr = ""; + updateStr += !"0".equals(supsubcomid) ? "supsubcomid= '" + supsubcomid + "', " : ""; + sql = "update hrmsubcompany set " + + updateStr + + "subcompanyname = '" + departmentName + "', " + + "subcompanydesc = '" + departmentName + "', " + + "outkey = '" + departmentCode + "', " + + "modified = to_date('" + now + "','yyyy-mm-dd hh24:mi:ss')," + + "modifier = '1', " + + "canceled = " + canceled + " " + + "where outkey= '" + departmentCode + "'"; + log.writeLog("更新分部表中数据sql--------->" + sql ); + rs.executeUpdate(sql); + + //处理分部自定义表 + String subcomid = map_subcompany_code_id.get(departmentCode); + rs.execute("select SUBCOMID from hrmsubcompanyDefined where SUBCOMID='" + subcomid + "'"); + if (rs.next()) { + sql = "update hrmsubcompanyDefined set " + + " sfzy = '" + row.getIsDirectSales() + "' ," + + " guojia = '" + countryCode + "' " + + " where SUBCOMID = '" + subcomid + "'"; + boolean b = rs.executeUpdate(sql); + log.writeLog("更新部门自定义表中数据sql--------->" + sql+" ;结果"+b); + + } else { + sql = "insert into hrmsubcompanyDefined(SUBCOMID,guojia,sfzy) " + + "values('" + subcomid + "','" + countryCode + "','" + row.getIsDirectSales() + "')"; + boolean b = rs.executeUpdate(sql); + log.writeLog("插入分部自定义表中数据sql--------->" + sql+" ;结果"+b); + } + } + } + + for (int i = 0; i < subcompanys.size(); i++) { + log.writeLog("---------分部上级查询--------->"); + DepartmentDto row = subcompanys.get(i); + String departmentCode = Util.null2String(row.getDepartmentCode());//部门编码 + String superiorDepartment = Util.null2String(row.getSuperiorDepartment());//上级部门编码 + String parId = ""; + log.writeLog("---------分部编码:" + departmentCode); + log.writeLog("---------上级分部编码:" + superiorDepartment); + rs.executeQuery("select * from HRMSUBCOMPANY where outkey = ?", superiorDepartment); + if (rs.next()) { + log.writeLog("---------在HRMSUBCOMPANY表查到了上级"); + parId = rs.getString("id"); + } +// else{ +// String now = TimeCommonUtil.obtainDate(0); +// rs.executeQuery("select * from HrmDepartment where outkey = ? ",superiorDepartment); +// if(rs.next()){ +// log.writeLog("---------在HrmDepartment表查到了上级"); +// String departmentname = rs.getString("Departmentname"); +// String parCode = rs.getString("uuid"); +// String outkey = rs.getString("outkey"); +// String supid = "0"; +// rs.executeQuery("select * from HRMSUBCOMPANY where outkey = ?",parCode); +// if(rs.next()) { +// supid = rs.getString("id"); +// } +// String sql = "insert into hrmsubcompany (companyid,supsubcomid,subcompanyname,subcompanydesc,outkey," + +// "created,creater,modified,modifier) values(" +// + "'1'," +// + "'" + supid + "'," +// + "'" + departmentname + "'," +// + "'" + departmentname + "'," +// + "'" + outkey + "'," +// + "to_date('" + now + "','yyyy-mm-dd hh24:mi:ss')," +// + "'1'," +// + "to_date('" + now + "','yyyy-mm-dd hh24:mi:ss')," +// + "'1')"; +// boolean executeUpdate = rs.executeUpdate(sql); +// log.writeLog("部门插入分部表生成新数据sql--------->" + sql); +// log.writeLog("sql:" + executeUpdate); +// log.writeLog("msg:" + rs.getExceptionMsg()); +// //删除部门 +// rs.executeUpdate("delete from HrmDepartment where outkey = ? ",outkey); +// //数据里面清理 +// for (int j = 0; j < departments.size(); j++) { +// DepartmentDto deptRow = departments.get(j); +// String deptCode = Util.null2String(deptRow.getDepartmentCode());//部门编码 +// String deptName = Util.null2String(deptRow.getDepartmentName());//部门编码 +// //如果部门的编码等于分部的上级就把数据库这个部门删掉 新增到分部 +// if(deptCode.equals(superiorDepartment)) { +// departments.remove(j); +// log.writeLog("去除部门的第"+j+"条数据名称:"+deptName); +// } +// } +// rs.executeQuery("select * from HRMSUBCOMPANY where outkey = ?",superiorDepartment); +// if(rs.next()){ +// parId = rs.getString("id"); +// } +// } +// } + log.writeLog("---------拿到上级id:" + parId); + if (!"".equals(parId)) { + boolean executeUpdate = rs.executeUpdate("update HRMSUBCOMPANY set supsubcomid = ? where outkey = ? ", parId, departmentCode); + log.writeLog("---------sql:" + executeUpdate); + log.writeLog("---------msg:" + rs.getExceptionMsg()); + } else { + boolean executeUpdate = rs.executeUpdate("delete from HRMSUBCOMPANY where outkey = ? ", departmentCode); + log.writeLog("---------找不到上级就删除:" + executeUpdate); + log.writeLog("---------msg:" + rs.getExceptionMsg()); + } + } + + log.writeLog("----sta:"+subMap.size()); + setSup(); + log.writeLog("----end"); + + + SubCompanyComInfo sccif = new SubCompanyComInfo(); + sccif.removeCompanyCache(); + + map_subcompany_code_id.clear(); + map_subcompany_code_id = null; + + } catch (Exception e) { + log.writeLog("----------Exception:" + JavaUtil.getExceptionDetail(e)); + e.printStackTrace(); + } + + return departments; + } + + public Map getSubCodeIdMap() { + RecordSet rs = new RecordSet(); + Map map = new HashMap<>(); + rs.executeQuery("select subcompanycode,outkey,id from HrmSubCompany where outkey is not null and (CANCELED!=1 or CANCELED is null)"); + while (rs.next()) { + map.put(rs.getString("outkey"), rs.getString("id")); + } + return map; + } + + + public void setSup() { + RecordSet rss = new RecordSet(); + Set keySet = subMap.keySet(); + Iterator it = keySet.iterator(); + while (it.hasNext()) { + try { + String subCode = (String) it.next(); + String supCode = String.valueOf(subMap.get(subCode)); + String SUPSubID = ""; + rss.executeQuery("select * from hrmsubcompany where SUBCOMPANYCODE = ?", supCode); + if (rss.next()) { + SUPSubID = rss.getString("id"); + rss.executeUpdate("update hrmsubcompany set SUPSUBCOMID = ? where SUBCOMPANYCODE = ? ", SUPSubID, subCode); + it.remove(); + } + } catch (Exception e) { + log.writeLog("--------------------Exception:" + JavaUtil.getExceptionDetail(e)); + } + } + + } + + + public JSONArray getSubcompanys() { + int current = 1, size = 10000, pages = 2; + String url = HttpClientToJT.baseUrl + "/dcopenedi/hrCompany/pageByUpdateTime"; + String token = HttpClientToJT.getToken(); + Map params = new HashMap<>(); + LocalDateTime today_start = LocalDateTime.of(LocalDate.now(), LocalTime.MIN);//当天零点 + String td_st_str = today_start.format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")); +// params.put("updateTime", td_st_str); + params.put("updateTime", "2018-03-21 00:00:00"); + params.put("current", current); + params.put("size", size); + String s = HttpClientToJT.sendGet(url, token, params); + JSONObject jsonObject = JSONObject.parseObject(s); + JSONArray jsonArray = new JSONArray(); + if (jsonObject.getInteger("code").equals(1)) { + JSONObject result = jsonObject.getJSONObject("data"); + pages = result.getInteger("pages"); + JSONArray records = result.getJSONArray("records"); + jsonArray.addAll(records); + for (int i = 2; i <= pages; i++) { + params.put("current", i); + String str = HttpClientToJT.sendGet(url, token, params); + JSONObject jsonObject1 = JSONObject.parseObject(str); + JSONObject jsonResult = jsonObject1.getJSONObject("data"); + JSONArray records1 = jsonResult.getJSONArray("records"); + jsonArray.addAll(records1); + } + Object directSales = jsonArray.stream().filter(item -> { + JSONObject itemJson = JSONObject.parseObject(JSON.toJSONString(item)); + return "Y".equals(itemJson.getString("isDirectSales")); + }).collect(Collectors.toList()); + jsonArray = JSONArray.parseArray(JSON.toJSONString(directSales)); + } + System.out.println(jsonArray.toJSONString()); + //将写入转化为流的形式 +// writeFile(jsonArray); + return jsonArray; + } + + private void writeFile(JSONArray jsonArray) { + BufferedWriter bw = null; + try { + bw = new BufferedWriter(new FileWriter("D:\\1.txt")); + //一次写一行 + bw.write(jsonArray.toJSONString()); + bw.newLine(); //换行用 + //关闭流 + bw.close(); + } catch (IOException e) { + e.printStackTrace(); + } + System.out.println("写入成功"); + } + + public static void main(String[] args) { + SyncHrmsubcompanyToOA ss = new SyncHrmsubcompanyToOA(); + ss.getSubcompanys(); + } + +// /** +// * 此方法废弃 +// */ +// public void executeInvail() { +// JSONArray subcompanys = getSubcompanys(); +// map_subcompany_code_id = getSubCodeIdMap(); +// RecordSet rs = new RecordSet(); +// log.writeLog("----------开始同步分部,条数:"+subcompanys.size()); +// log.writeLog("----------同步分部源数据:"+subcompanys.toJSONString()); +// // 处理公司同步逻辑 +// for (int i = 0; i < subcompanys.size(); i++) { +// JSONObject sub = subcompanys.getJSONObject(i); +// String Code = Util.null2String(sub.getString("companyCode"));//分部编码 +// String Name = Util.null2String(sub.getString("companyName"));//分部全称 +// String ShortName = Util.null2String(sub.getString("companyAbbreviation"));//分部简称 +// String companyLevelCode = Util.null2String(sub.getString("companyLevelCode"));//公司级别编码 +// String companyLevelName = Util.null2String(sub.getString("companyLevelName"));//公司级别描述 +// String countryCode = Util.null2String(sub.getString("countryCode"));//国家代码 +// String countryName = Util.null2String(sub.getString("countryName"));//国家名称 +// Integer canceled = Util.null2String(sub.getString("status"))== "3"?1:null;//1 新增 2 修改 3作废 +// String sql = ""; +// //判断HR分部ID是否已经存在 +// String now = TimeCommonUtil.obtainDate(0); +// if (!map_subcompany_code_id.containsKey(Code)) {//分部不存在则插入生成新分部 +// //新增数据,插入到hrmsubcompany表中 +// sql = "insert into hrmsubcompany (subcompanyname,subcompanydesc,outkey," + +// "tlevel,canceled,created,creater,modified,modifier,companyid) values(" +// + "'" + ShortName + "'," +// + "'" + Name + "'," +// + "'" + Code + "'," +// + "'" + companyLevelCode + "'," +// + canceled + "," +// + "to_date('" + now + "','yyyy-mm-dd hh24:mi:ss')," +// + "'1'," +// + "to_date('" + now + "','yyyy-mm-dd hh24:mi:ss')," +// + "'1'," +// + "'1')"; +// log.writeLog("插入分部表生成新数据sql--------->" + sql); +// rs.execute(sql); +// +// rs.execute("select max(id) from hrmsubcompany"); +// int maxSubcompanyid = 0;//新插入数据的分部ID +// if (rs.next()) { +// maxSubcompanyid = rs.getInt(1); +// } +// //将新增加的分部加入至MAP中 +// map_subcompany_code_id.put(Code, maxSubcompanyid + ""); +// +// } else {//分部存在则更新 +// sql = "update hrmsubcompany set " + +// "subcompanyname = '" + ShortName + "', " + +// "subcompanydesc = '" + Name + "', " + +// "outkey = '" + Code + "', " + +// "modified = to_date('" + now + "','yyyy-mm-dd hh24:mi:ss')," + +// "modifier = '1', "+ +// "canceled = " + canceled + " "+ +// "where outkey= '" + Code + "'"; +// log.writeLog("更新分部表中数据sql--------->" + sql); +// rs.execute(sql); +// } +// } +// } +} diff --git a/src/main/youhong_ai_jitu_src/jntchina/schedule/hrm/SyncJTBaseData.java b/src/main/youhong_ai_jitu_src/jntchina/schedule/hrm/SyncJTBaseData.java new file mode 100644 index 0000000..39d1242 --- /dev/null +++ b/src/main/youhong_ai_jitu_src/jntchina/schedule/hrm/SyncJTBaseData.java @@ -0,0 +1,165 @@ +package jntchina.schedule.hrm; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.JSONArray; +import com.alibaba.fastjson.JSONObject; +import com.weaver.formmodel.util.DateHelper; +import com.weaver.general.Util; + +import jntchina.util.HttpClientToJT; +import jntchina.util.JTHrmApiUtil; +import selfdev.util.base.BaseUtil; +import selfdev.util.log.LogTool; +import weaver.conn.RecordSet; +import weaver.formmode.data.ModeDataIdUpdate; +import weaver.formmode.setup.ModeRightInfo; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +/** + * 同步基础数据到建模表里 + */ +public class SyncJTBaseData { + + private LogTool log = new LogTool("/log/hrm/baseData/", false); + + public String syncBaseData(){ + RecordSet rs1 = new RecordSet(); + RecordSet rs = new RecordSet(); + Map> baseDataMap =getBaseDataMap(); + //log.writeLog("---已有字典:"+JSON.toJSONString(baseDataMap)); + //查询建模表维护了需要同步哪些基础数据 + String sql = "select FIELDNAME,zdms from uf_fieldname"; + rs.executeQuery(sql); + String token = HttpClientToJT.getToken(); + //根据表面查询modeid + int modelId = Integer.parseInt(Util.null2o(BaseUtil.getBaseInfoByParm("id", "modeinfo", "1", "1", + " and formid in (select id from workflow_bill where tablename='uf_fieldvalue')"))); + while (rs.next()){ + //基础数据唯一标识字段名 + String fieldname_s=rs.getString("FIELDNAME"); + //Map> baseDataMap = BaseUtil.getMapKeyValueInfoByParm("uf_fieldvalue","","FIELDVALUE","XLADLONGNAME"); + Map paramMap = new HashMap<>(); + paramMap.put("LANGUAGE_CD", "ZHS"); + paramMap.put("FIELDNAME", fieldname_s); + log.writeLog("获取【"+fieldname_s+"】基础数据传入参数paramMap------->"+JSON.toJSONString(paramMap)); + //调用接口获取数据 + JSONArray jsonArray = JTHrmApiUtil.translateValue(token, JSON.toJSONString(paramMap)); + log.writeLog("获取【"+fieldname_s+"】基础数据返回结果--->"+JSON.toJSONString(jsonArray)); + for (int i = 0; i < jsonArray.size(); i++) { + JSONObject jsonObject = jsonArray.getJSONObject(i); + String fieldvalue = jsonObject.getString("FIELDVALUE");//字段值 + String fieldname = jsonObject.getString("FIELDNAME");//基础数据唯一标识字段名 + String xlADLONGNAME = jsonObject.getString("XlADLONGNAME");//字段值 + String xladshortname = jsonObject.getString("XLADSHORTNAME");//字段值 + String descr1 = jsonObject.getString("DESCR1"); + String descr2 = jsonObject.getString("DESCR2"); + String descr3 = jsonObject.getString("DESCR3"); + String descr4 = jsonObject.getString("DESCR4"); + String descr5 = jsonObject.getString("DESCR5"); + String descr6 = jsonObject.getString("DESCR6"); + + + if(baseDataMap.containsKey(fieldname)){ + //不存在 + if(!baseDataMap.get(fieldname).contains(fieldvalue)){ + int id = ModeDataIdUpdate.getInstance().getModeDataNewIdByUUID("uf_fieldvalue", modelId, 1, 1, DateHelper.getCurrentDate(), DateHelper.getCurrentTime()); + ModeRightInfo ModeRightInfo = new ModeRightInfo(); + ModeRightInfo.setNewRight(true); + // 新建的时候添加共享 + ModeRightInfo.editModeDataShare(1, modelId, id); + // 新建的时候添加文档共享 + ModeRightInfo.addDocShare(1, modelId, id); + sql = "update uf_fieldvalue set " + + "FIELDVALUE = '" + fieldvalue + "', " + + "XlADLONGNAME = '" + xlADLONGNAME + "', " + + "FIELDNAME = '" + fieldname + "', " + + "XLADSHORTNAME = '" + xladshortname + "', " + + "DESCR1 = '" + descr1 + "', " + + "DESCR2 = '" + descr2 + "', " + + "DESCR3 = '" + descr3 + "', " + + "DESCR4 = '" + descr4 + "', " + + "DESCR5 = '" + descr5 + "', " + + "DESCR6 = '" + descr6 + "' "+ + "where id = " +id ; + log.writeLog("-----------基础数据新增sql:"+sql); + rs1.executeUpdate(sql); + //加入字典 + List datas = baseDataMap.get(fieldname); + datas.add(fieldvalue); + baseDataMap.put(fieldname,datas); + }else{ + //已存在,则更新 + sql = "update uf_fieldvalue set " + + "XlADLONGNAME = '" + xlADLONGNAME + "', " + + "XLADSHORTNAME = '" + xladshortname + "', " + + "DESCR1 = '" + descr1 + "', " + + "DESCR2 = '" + descr2 + "', " + + "DESCR3 = '" + descr3 + "', " + + "DESCR4 = '" + descr4 + "', " + + "DESCR5 = '" + descr5 + "', " + + "DESCR6 = '" + descr6 + "' "+ + "where FIELDVALUE = '" + fieldvalue + "' and FIELDNAME = '" + fieldname + "'"; + log.writeLog("-----------基础数据更新sql:"+sql); + rs1.executeUpdate(sql); + } + }else{ + // 建模插入数据 + int id = ModeDataIdUpdate.getInstance().getModeDataNewIdByUUID("uf_fieldvalue", modelId, 1, 1, DateHelper.getCurrentDate(), DateHelper.getCurrentTime()); + ModeRightInfo ModeRightInfo = new ModeRightInfo(); + ModeRightInfo.setNewRight(true); + // 新建的时候添加共享 + ModeRightInfo.editModeDataShare(1, modelId, id); + // 新建的时候添加文档共享 + ModeRightInfo.addDocShare(1, modelId, id); + sql = "update uf_fieldvalue set " + + "FIELDVALUE = '" + fieldvalue + "', " + + "XlADLONGNAME = '" + xlADLONGNAME + "', " + + "FIELDNAME = '" + fieldname + "', " + + "XLADSHORTNAME = '" + xladshortname + "', " + + "DESCR1 = '" + descr1 + "', " + + "DESCR2 = '" + descr2 + "', " + + "DESCR3 = '" + descr3 + "', " + + "DESCR4 = '" + descr4 + "', " + + "DESCR5 = '" + descr5 + "', " + + "DESCR6 = '" + descr6 + "' "+ + "where id = " +id ; + log.writeLog("-----------基础数据新增sql:"+sql); + rs1.executeUpdate(sql); + //加入字典 + List datas = new ArrayList<>(); + datas.add(fieldvalue); + baseDataMap.put(fieldname,datas); + } + } + } + + return "success"; + } + + + + public Map> getBaseDataMap(){ + RecordSet rs = new RecordSet(); + Map> map = new HashMap<>(); + String sql = "select FIELDVALUE,FIELDNAME from uf_fieldvalue"; + rs.executeQuery(sql); + while (rs.next()){ + if(map.containsKey(rs.getString("FIELDNAME"))){ + List list = map.get(rs.getString("FIELDNAME")); + list.add(rs.getString("FIELDVALUE")); + map.put(rs.getString("FIELDNAME"),list); + }else{ + List datas = new ArrayList<>(); + datas.add(rs.getString("FIELDVALUE")); + map.put(rs.getString("FIELDNAME"),datas ); + } + + } + return map; + } + +} diff --git a/src/main/youhong_ai_jitu_src/jntchina/schedule/hrm/aiyh_synccompany/SyncOtherHrmCompanyMapper.java b/src/main/youhong_ai_jitu_src/jntchina/schedule/hrm/aiyh_synccompany/SyncOtherHrmCompanyMapper.java new file mode 100644 index 0000000..9c77635 --- /dev/null +++ b/src/main/youhong_ai_jitu_src/jntchina/schedule/hrm/aiyh_synccompany/SyncOtherHrmCompanyMapper.java @@ -0,0 +1,34 @@ +package jntchina.schedule.hrm.aiyh_synccompany; + +import aiyh.utils.annotation.recordset.Delete; +import aiyh.utils.annotation.recordset.ParamMapper; +import aiyh.utils.annotation.recordset.Select; +import aiyh.utils.annotation.recordset.SqlMapper; + +import java.util.List; +import java.util.Map; + +/** + *

同步公司信息查询数据库文件

+ *

create 2022/7/7 16:19

+ * + * @author ayh + */ + +@SqlMapper +public interface SyncOtherHrmCompanyMapper { + /** + *

查询已经存在的公司信息数据

+ * @param tableName 查询的建模表 + * @return 已存在的公司 id -> value , code -> code + */ + @Select("select company_code,id from $t{table}") + List> selectExitsCompanyCodeList(@ParamMapper("table") String tableName); + + /** + *

删除由于批量更新或批量插入时,只生成ID未能正确插入的数据的记录,避免造成过多的冗余数据

+ * @param tableName 表名 + */ + @Delete("delete from $t{table} where company_code is null or company_code = ''") + void deleteRedundancyData(@ParamMapper("table") String tableName); +} diff --git a/src/main/youhong_ai_jitu_src/jntchina/schedule/hrm/aiyh_synccompany/SyncOtherHrmcompanyToOA.java b/src/main/youhong_ai_jitu_src/jntchina/schedule/hrm/aiyh_synccompany/SyncOtherHrmcompanyToOA.java new file mode 100644 index 0000000..901dfb0 --- /dev/null +++ b/src/main/youhong_ai_jitu_src/jntchina/schedule/hrm/aiyh_synccompany/SyncOtherHrmcompanyToOA.java @@ -0,0 +1,536 @@ +package jntchina.schedule.hrm.aiyh_synccompany; + +import aiyh.utils.Util; +import aiyh.utils.annotation.ActionDesc; +import aiyh.utils.annotation.PrintParamMark; +import aiyh.utils.annotation.RequiredMark; +import aiyh.utils.excention.CustomerException; +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.JSONArray; +import com.alibaba.fastjson.JSONObject; +import com.google.common.base.Strings; +import jntchina.schedule.hrm.entity.CompanyOtherDto; +import jntchina.util.HttpClientToJT; +import lombok.AccessLevel; +import lombok.Data; +import lombok.Getter; +import lombok.Setter; +import org.apache.log4j.Logger; +import weaver.conn.RecordSet; +import weaver.file.Prop; +import weaver.interfaces.schedule.BaseCronJob; + +import java.util.*; +import java.util.concurrent.ConcurrentHashMap; +import java.util.concurrent.ExecutionException; +import java.util.concurrent.Future; +import java.util.stream.Collectors; +import java.util.stream.Stream; + +/** + *

同步除Cyq过滤添加到uf_hrmcompany建模外的其他数据到其他建模

+ *

create 2022/7/7 15:11

+ * + * @author ayh + */ + +@Data +@ActionDesc(value = "同步海外公司数据定时任务", author = "aiyh") +public class SyncOtherHrmcompanyToOA extends BaseCronJob { + + @RequiredMark("modeId 参数必填,请检查必填配置是否配置正确。") + @PrintParamMark + private String modeId; + + @RequiredMark("tableName 参数必填,请检查必填配置是否配置正确。") + @PrintParamMark + private String tableName; + + private String pageSize; + + private static String ENG = "ENG"; + + private static String ZHS = "ZHS"; + + private String mode = "pro"; + + private final SyncOtherHrmCompanyMapper mapper = Util.getMapper(SyncOtherHrmCompanyMapper.class); + + @Getter(AccessLevel.NONE) + @Setter(AccessLevel.NONE) + private Map exitsCompanyCode; + + @Getter(AccessLevel.NONE) + @Setter(AccessLevel.NONE) + private static final ThreadLocal TASK_ID_MAP = new ThreadLocal<>(); + + @Getter(AccessLevel.NONE) + @Setter(AccessLevel.NONE) + private final Logger log = Util.getLogger(); + + @Override + public void execute() { + log.info(Util.logStr("start sync companies data!")); + long startTime = System.currentTimeMillis(); + try { + Util.verifyRequiredField(this); + } catch (Exception e) { + throw new CustomerException("参数验证未通过!" + e.getMessage()); + } + try { + JSONArray companies = this.getCompanies(); + List companyDtoList = JSONArray.parseArray(companies.toJSONString(), CompanyOtherDto.class); + exitsCompanyCode = this.getExitsCompanyCode(); + List upateList = new ArrayList<>(); + List insertList = new ArrayList<>(); + for (CompanyOtherDto companyDto : companyDtoList) { + if (exitsCompanyCode.containsKey(companyDto.getCompanyCode())) { +// 存在数据,需要更新数据到建模表 + companyDto.setId(String.valueOf(exitsCompanyCode.get(companyDto.getCompanyCode()))); + upateList.add(companyDto); + } else { + insertList.add(companyDto); + } + } + this.updateDateToModeTableAll(upateList); + this.insertDateToModeTableByAll(insertList); + log.info(Util.logStr("sync companies data finish! update data [{}], insert data [{}], all data [{}], use time [{}]ms", + upateList.size(), insertList.size(), companyDtoList.size(), System.currentTimeMillis() - startTime)); + } catch (Exception e) { + log.error("sync companies data error, error message is :" + Util.getErrString(e)); + throw e; + } + } + + + /** + * 将建模表中没有的数据全部插入到建模表中 + * + * @param listData 带插入数据 + */ + private void insertDateToModeTableByAll(List listData) { + if (listData.size() > 0) { + long startTime = System.currentTimeMillis(); + List> futureList = new ArrayList<>(); + Set repetitionCheckSet = new HashSet<>(listData.size()); + List repetitionCompanies = new ArrayList<>(listData.size()); + Map> groupCompaniesMap = listData.stream() + .peek(item -> { + if (Strings.isNullOrEmpty(item.getLanguageCd())) { + item.setLanguageCd(SyncOtherHrmcompanyToOA.ENG); + } + }) + .collect(Collectors.groupingBy(CompanyOtherDto::getLanguageCd)); + List companyDtoZhsList = groupCompaniesMap.get(SyncOtherHrmcompanyToOA.ZHS); + List companyDtoEngList = groupCompaniesMap.get(SyncOtherHrmcompanyToOA.ENG); + // 一次1000条 + int batchSize = 3_000; +// 计算需要进行几次拆分,最低拆分一次 + int limit = (listData.size() + batchSize - 1) / batchSize; +// 每次加1,共执行limit次,即从 0 -> limit ,并将得到的数据遍历 +// type 0 表示英文,其他表示中文 + executeInsert(futureList, repetitionCheckSet, repetitionCompanies, companyDtoZhsList, batchSize, limit, 1); + futureList.clear(); + executeInsert(futureList, repetitionCheckSet, repetitionCompanies, companyDtoEngList, batchSize, limit, 0); + if (!repetitionCompanies.isEmpty()) { +// 等待其他子线程执行完,将重复数据重新添加 +// 将数据id放入到公司对象中,并更具中英文分组 + SyncOtherHrmcompanyToOA.TASK_ID_MAP.set(UUID.randomUUID().toString()); + Map> groupByLanguage = repetitionCompanies.stream(). + peek(item -> item.setId(this.exitsCompanyCode.get(item.getCompanyCode()))) + .collect(Collectors.groupingBy(CompanyOtherDto::getLanguageCd)); + this.updateDateToModeTableByGroup(groupByLanguage); + } + log.info(Util.logStr("insert companies data finish ! insert [{}] data, use time [{}]ms", + listData.size() - repetitionCompanies.size(), System.currentTimeMillis() - startTime)); + } + } + + /** + *

将数据分批次使用多线程插入到建模表中

+ * + * @param futureList 任务返回对象列表 + * @param repetitionCheckSet 重复检验set + * @param repetitionCompanies 重复数据公司 + * @param companyDtoList 分组待插入公司 + * @param batchSize 分批次大小 + * @param limit 分批次次数 + */ + private void executeInsert(List> futureList, Set repetitionCheckSet, List repetitionCompanies, + List companyDtoList, int batchSize, int limit, + int type) { + if (null != companyDtoList && !companyDtoList.isEmpty()) { + Stream.iterate(0, n -> n + 1).limit(limit).forEach(a -> { + List batchEngList = companyDtoList.stream().peek(item -> { + if (Strings.isNullOrEmpty(item.getLanguageCd())) { + item.setLanguageCd(SyncOtherHrmcompanyToOA.ENG); + } + }).skip((long) a * batchSize) + .limit(batchSize) + .filter(item -> { +// 判断当前集合中是否与之前的数据重复 + boolean contains = repetitionCheckSet.contains(item.getCompanyCode()); + if (contains) { +// 如果重复,添加到重复集合中,等最后在处理 + repetitionCompanies.add(item); + } else { +// 不重复,将数据添加到重复检查集合中 + repetitionCheckSet.add(item.getCompanyCode()); + } + return !contains; + }) + .collect(Collectors.toList()); + Future submit = Util.threadPool.submit(() -> insertDateToModeTableByBatch(batchEngList, type)); + futureList.add(submit); + }); + for (Future future : futureList) { + try { + future.get(); + } catch (InterruptedException | ExecutionException e) { + log.error(Util.logStr("main thread wait other insert thread error!")); + } + } + + } + } + + + /** + * 插入同步的公司信息数据,通过异步线程插入,提高插入效率。 + * + * @param batchList 批量插入数据参数 + */ + private void insertDateToModeTableByBatch(List batchList, int type) { + String taskId = UUID.randomUUID().toString(); + log.info(Util.logStr("insert task start run, the taskId is [{}]", taskId)); + SyncOtherHrmcompanyToOA.TASK_ID_MAP.set(taskId); +// 将新增数据添加到缓存中 + for (CompanyOtherDto companyOtherDto : batchList) { + companyOtherDto.setId(String.valueOf(Util.getModeDataId(this.tableName, Integer.parseInt(modeId), 1))); + exitsCompanyCode.put(companyOtherDto.getCompanyCode(), companyOtherDto.getId()); + } + insertDateToModeTableByGroup(batchList, type); + } + + + private void insertDateToModeTableByGroup(List companyDtoEngList, int type) { + long startTime = System.currentTimeMillis(); + String taskId = SyncOtherHrmcompanyToOA.TASK_ID_MAP.get(); + SyncOtherHrmcompanyToOA.TASK_ID_MAP.remove(); + log.info(Util.logStr("taskId [{}] is running!", taskId)); + RecordSet recordSet = new RecordSet(); + // List companyDtoZhsList = insertOrUpdateZhsCompanies(groupByLanguage, recordSet); +// 获取英文分组 +// List companyDtoEngList = groupByLanguage.get(SyncOtherHrmcompanyToOA.ENG); + if (null != companyDtoEngList && !companyDtoEngList.isEmpty()) { +// 获取英文分组中的建模id + List companiesEngIdList = companyDtoEngList.stream().map(CompanyOtherDto::getId).map(Integer::parseInt).collect(Collectors.toList()); +// 将英文分组转为list,组装sql参数 + List companyDtoEngSqlArgs = companyDtoEngList.stream().map(this::companyDtoToList).collect(Collectors.toList()); + String engSql = getInsertSql(type); + boolean b = recordSet.executeBatchSql(engSql, companyDtoEngSqlArgs); + if (!b) { + mapper.deleteRedundancyData(tableName); + } + Util.rebuildModeDataShareByAsyncList(1, Integer.parseInt((modeId)), companiesEngIdList); + } + + log.info(Util.logStr("taskId [{}] execute finish! sync company datas [{}], use time [{}]", + taskId, (companyDtoEngList == null ? 0 : companyDtoEngList.size()), + System.currentTimeMillis() - startTime)); + } + + private String getInsertSql(int type) { + if (type == 0) { + // 英文 + return "update " + tableName + " set " + + "language_cd = ?, " + + "company_code = ?, " + + "company_english_name = ?, " + + "company_abbreviation = ?, " + + "country_code = ?, " + + "country_name = ?, " + + "company_level_code = ?, " + + "company_level_name = ?, " + + "is_direct_sales = ?, " + + "unify_social_credit_code = ?, " + + "status = ?, " + + "modedatamodifier = ?," + + "modedatamodifydatetime = ? " + + "where id = ?"; + } else { + return "update " + tableName + " set " + + "language_cd = ?, " + + "company_code = ?, " + + "company_name = ?, " + + "company_abbreviation = ?, " + + "country_code = ?, " + + "country_name = ?, " + + "company_level_code = ?, " + + "company_level_name = ?, " + + "is_direct_sales = ?, " + + "unify_social_credit_code = ?, " + + "status = ?, " + + "modedatamodifier = ?," + + "modedatamodifydatetime = ? " + + "where id = ?"; + } + } + + /** + *

更新建模表中的数据

+ * + * @param listData 待更新的数据 + */ + private void updateDateToModeTableAll(List listData) { + if (listData.size() > 0) { + long startTime = System.currentTimeMillis(); + List> futureList = new ArrayList<>(); + // 一次500条 + int batchSize = 500; +// 计算需要进行几次拆分,最低拆分一次 + int limit = (listData.size() + batchSize - 1) / batchSize; + Stream.iterate(0, n -> n + 1).limit(limit).forEach(a -> { + Map> groupByLanguage = listData.stream().skip(a * batchSize) + .limit(batchSize) + .peek(item -> { + if (Strings.isNullOrEmpty(item.getLanguageCd())) { + item.setLanguageCd(SyncOtherHrmcompanyToOA.ENG); + } + }) + .collect(Collectors.groupingBy(CompanyOtherDto::getLanguageCd)); + Future submit = Util.threadPool.submit(() -> { + String taskId = UUID.randomUUID().toString(); + SyncOtherHrmcompanyToOA.TASK_ID_MAP.set(taskId); + log.info(Util.logStr("update task start run, the taskId id [{}]", taskId)); + updateDateToModeTableByGroup(groupByLanguage); + }); + futureList.add(submit); + }); + for (Future future : futureList) { + try { + future.get(); + } catch (InterruptedException | ExecutionException e) { + log.error(Util.logStr("main thread wait other insert thread error!")); + } + } + log.info(Util.logStr("update companies data finish ! update [{}] data, use time [{}]ms", + listData.size(), System.currentTimeMillis() - startTime)); + } + } + + /** + *

根据中英文分组更新建模数据

+ * + * @param groupByLanguage 中英文分组数据 + */ + private void updateDateToModeTableByGroup(Map> groupByLanguage) { + long startTime = System.currentTimeMillis(); + String taskId = SyncOtherHrmcompanyToOA.TASK_ID_MAP.get(); + SyncOtherHrmcompanyToOA.TASK_ID_MAP.remove(); + log.info(Util.logStr("taskId [{}] is running!", taskId)); + RecordSet recordSet = new RecordSet(); +// 中文分组 + List companyDtoZhsList = groupByLanguage.get(SyncOtherHrmcompanyToOA.ZHS); +// 获取英文分组 + List companyDtoEngList = groupByLanguage.get(SyncOtherHrmcompanyToOA.ENG); + if (null != companyDtoEngList && !companyDtoEngList.isEmpty()) { +// 获取英文分组中的建模id + List companiesEngIdList = companyDtoEngList.stream().map(CompanyOtherDto::getId).map(Integer::parseInt).collect(Collectors.toList()); +// 将英文分组转为list,组装sql参数 + List companyDtoEngSqlArgs = companyDtoEngList.stream().map(this::companyDtoToListByEn).collect(Collectors.toList()); + String engSql = "update " + tableName + " set " + + "company_english_name = ?, " + + "modedatamodifier = ?," + + "modedatamodifydatetime = ? " + + "where id = ?"; + boolean b = recordSet.executeBatchSql(engSql, companyDtoEngSqlArgs); + if (!b) { + mapper.deleteRedundancyData(tableName); + } + Util.rebuildModeDataShareByAsyncList(1, Integer.parseInt((modeId)), companiesEngIdList); + } + if (null != companyDtoZhsList && !companyDtoZhsList.isEmpty()) { + // insertOrUpdateZhsCompanies(groupByLanguage, recordSet); +// 获取中文分组数据建模id + List companiesZshIdList = companyDtoZhsList.stream().map(CompanyOtherDto::getId).map(Integer::parseInt).collect(Collectors.toList()); +// 将中文分组数据转换为list,用于批量修改数据的sql参数 + List companyDtoZhsSqlArgs = companyDtoZhsList.stream().map(this::companyDtoToList).collect(Collectors.toList()); + String zshSql = "update " + tableName + " set " + + "language_cd = ?, " + + "company_code = ?, " + + "company_name = ?, " + + "company_abbreviation = ?, " + + "country_code = ?, " + + "country_name = ?, " + + "company_level_code = ?, " + + "company_level_name = ?, " + + "is_direct_sales = ?, " + + "unify_social_credit_code = ?, " + + "status = ?, " + + "modedatamodifier = ?," + + "modedatamodifydatetime = ? " + + "where id = ?"; + + boolean b = recordSet.executeBatchSql(zshSql, companyDtoZhsSqlArgs); + if (!b) { + mapper.deleteRedundancyData(tableName); + } + Util.rebuildModeDataShareByAsyncList(1, Integer.parseInt((modeId)), companiesZshIdList); + } + log.info(Util.logStr("taskId [{}] execute finish! sync company datas [{}], use time [{}]", + taskId, (companyDtoZhsList == null ? 0 : companyDtoZhsList.size()) + (companyDtoEngList == null ? 0 : companyDtoEngList.size()), + System.currentTimeMillis() - startTime)); + } + + /** + *

将实体类转换为list 用于批量插入的参数,切记字段顺序不可乱,否则字段无法一一对应

+ * + * @param companyDto 公司信息实体 + * @return list + */ + private List companyDtoToList(CompanyOtherDto companyDto) { + List list = new ArrayList<>(16); +// 语言字段 + list.add(companyDto.getLanguageCd()); + list.add(companyDto.getCompanyCode()); + list.add(companyDto.getCompanyName()); + list.add(companyDto.getCompanyAbbreviation()); + list.add(companyDto.getCountryCode()); + list.add(companyDto.getCountryName()); + list.add(companyDto.getCompanyLevelCode()); + list.add(companyDto.getCompanyLevelName()); + list.add(companyDto.getIsDirectSales()); + list.add(companyDto.getUnifySocialCreditCode()); + list.add(companyDto.getStatus()); + list.add(1); + list.add(Util.getTime("yyyy-MM-dd HH:mm:ss")); + list.add(companyDto.getId()); + return list; + } + + /** + *

将实体类转化为list,用于批量更新英文的公司名称

+ * + * @param companyDto 待转换的公司实体 + * @return 转换后的集合 + */ + private List companyDtoToListByEn(CompanyOtherDto companyDto) { + List list = new ArrayList<>(); + list.add(companyDto.getCompanyName()); + list.add(1); + list.add(Util.getTime("yyyy-MM-dd HH:mm:ss")); + list.add(companyDto.getId()); + return list; + } + + + /** + *

查询一存在的公司信息数据

+ * + * @return 查询一存在的公司信息数据 + */ + private Map getExitsCompanyCode() { + List> codeList = mapper.selectExitsCompanyCodeList(tableName); + Map codeMap = new ConcurrentHashMap<>(codeList.size()); + codeList.forEach(item -> codeMap.put(item.get("companyCode"), String.valueOf(item.get("id")))); + return codeMap; + } + + + /** + *

获取需要同步的公司信息数据

+ * + * @return 需要同步额公司数据 + */ + @SuppressWarnings("all") + private JSONArray getCompanies() { + int current = 1, size = Util.getIntValue(pageSize, 2000), pages; + String url = getBaseUrl() + "/dcopenedi/hrCompany/pageByUpdateTime"; + String token = HttpClientToJT.getToken(); + JSONArray jsonArray = new JSONArray(); + do { + Map params = new HashMap<>(); + params.put("updateTime", "2018-03-21 00:00:00"); + params.put("current", current++); + params.put("size", size); + String s = HttpClientToJT.sendGet(url, token, params); + JSONObject jsonObject; +// 如果不能解析jsonObject即表示请求未能正确到达目标服务器或参数、身份校验未通过等报错信息 + try { + jsonObject = JSONObject.parseObject(s); + } catch (Exception e) { + throw new CustomerException("parse response string error, can't parse response to JsonObject, check you request params and network link status!" + + " response str is : [" + s + "] ; this request params is : [" + JSON.toJSONString(params) + "],this request token is : " + token + ", request url is :" + url); + } + boolean code = jsonObject.getInteger("code").equals(1); + if (!code) { + throw new CustomerException("get hrmcompany data error, the request's param is :[" + JSON.toJSONString(params) + "], this response is :" + s + ",this request token is : " + token + ", request url is :" + url); + } + JSONObject result = jsonObject.getJSONObject("data"); + pages = result.getInteger("pages"); + JSONArray records = result.getJSONArray("records"); + jsonArray.addAll(records); + } while (current <= pages); +// 过滤掉之前逻辑中已经添加到建模表中的数据,将其他的数据返回后填写到其他建模表中 + Object collect = jsonArray.stream().filter(item -> { + JSONObject itemJson = JSONObject.parseObject(JSON.toJSONString(item)); + return !("CHN".equals(itemJson.getString("countryCode")) && "ZHS".equals(itemJson.getString("languageCd"))) && !Strings.isNullOrEmpty(itemJson.getString("companyCode")); + }).collect(Collectors.toList()); + jsonArray = JSON.parseArray(JSON.toJSONString(collect)); + Object companyCodeList = jsonArray.stream().filter(item -> { + JSONObject itemJson = JSONObject.parseObject(JSON.toJSONString(item)); + boolean b = !("CHN".equals(itemJson.getString("countryCode")) && "ZHS".equals(itemJson.getString("languageCd"))); + boolean isNull = Strings.isNullOrEmpty(itemJson.getString("companyCode")); + return b && isNull; + }).collect(Collectors.toList()); + if (null != companyCodeList) { + JSONArray companyCodeJsonList = JSON.parseArray(JSON.toJSONString(companyCodeList)); + log.warn(Util.logStr("get companies success, but hava [{}] companies is have't company_code, all data is [ {} ]", + companyCodeJsonList.toJSONString())); + } + return jsonArray; + } + + + /** + *

复制他们的代码,不推荐使用,有很多隐藏的bug

+ * + * @return 不推荐使用 + */ + @Deprecated + public JSONArray getCompanys() { + int current = 1, size = 10000, pages = 2; + String url = getBaseUrl() + "/dcopenedi/hrCompany/pageByUpdateTime"; + System.out.println(url); + String token = HttpClientToJT.getToken(); + Map params = new HashMap<>(); + params.put("updateTime", "2018-03-21 00:00:00"); + params.put("current", current); + params.put("size", size); + String s = HttpClientToJT.sendGet(url, token, params); + JSONObject jsonObject = JSONObject.parseObject(s); + JSONArray jsonArray = new JSONArray(); + if (jsonObject.getInteger("code").equals(1)) { + JSONObject result = jsonObject.getJSONObject("data"); + pages = result.getInteger("pages"); + JSONArray records = result.getJSONArray("records"); + jsonArray.addAll(records); + for (int i = 2; i <= pages; i++) { + params.put("current", i); + String str = HttpClientToJT.sendGet(url, token, params); + JSONObject jsonObject1 = JSONObject.parseObject(str); + JSONObject jsonResult = jsonObject1.getJSONObject("data"); + JSONArray records1 = jsonResult.getJSONArray("records"); + jsonArray.addAll(records1); + } + } + // 将写入转化为流的形式 +// writeFile(jsonArray); + return jsonArray; + } + + public String getBaseUrl() { + return Prop.getPropValue("DevToDC_jntchina", mode + "_baseUrl"); + } +} diff --git a/src/main/youhong_ai_jitu_src/jntchina/schedule/hrm/entity/AssetGroup.java b/src/main/youhong_ai_jitu_src/jntchina/schedule/hrm/entity/AssetGroup.java new file mode 100644 index 0000000..5db01cc --- /dev/null +++ b/src/main/youhong_ai_jitu_src/jntchina/schedule/hrm/entity/AssetGroup.java @@ -0,0 +1,39 @@ +package jntchina.schedule.hrm.entity; + +import java.io.Serializable; + +/** + * @title: assetGroup + * @Author ycf + * @Date: 2021/9/28 10:35 + * @Version 1.0 + */ +public class AssetGroup implements Serializable { + + private String company_name; + private String company_code; + + public AssetGroup() { + } + + public AssetGroup(String company_name, String company_code) { + this.company_name = company_name; + this.company_code = company_code; + } + + public String getCompany_name() { + return company_name; + } + + public void setCompany_name(String company_name) { + this.company_name = company_name; + } + + public String getCompany_code() { + return company_code; + } + + public void setCompany_code(String company_code) { + this.company_code = company_code; + } +} diff --git a/src/main/youhong_ai_jitu_src/jntchina/schedule/hrm/entity/CompanyDto.java b/src/main/youhong_ai_jitu_src/jntchina/schedule/hrm/entity/CompanyDto.java new file mode 100644 index 0000000..8f8f293 --- /dev/null +++ b/src/main/youhong_ai_jitu_src/jntchina/schedule/hrm/entity/CompanyDto.java @@ -0,0 +1,103 @@ +package jntchina.schedule.hrm.entity; + +public class CompanyDto{ + private String isDirectSales; + private String languageCd; + private String countryCode; + private String companyLevelName; + private String companyName; + private String companyAbbreviation; + private String countryName; + private String companyCode; + private String companyLevelCode; + private String unifySocialCreditCode; + private String status; + + public void setIsDirectSales(String isDirectSales){ + this.isDirectSales = isDirectSales; + } + + public String getIsDirectSales(){ + return isDirectSales; + } + + public void setLanguageCd(String languageCd){ + this.languageCd = languageCd; + } + + public String getLanguageCd(){ + return languageCd; + } + + public void setCountryCode(String countryCode){ + this.countryCode = countryCode; + } + + public String getCountryCode(){ + return countryCode; + } + + public void setCompanyLevelName(String companyLevelName){ + this.companyLevelName = companyLevelName; + } + + public String getCompanyLevelName(){ + return companyLevelName; + } + + public void setCompanyName(String companyName){ + this.companyName = companyName; + } + + public String getCompanyName(){ + return companyName; + } + + public void setCompanyAbbreviation(String companyAbbreviation){ + this.companyAbbreviation = companyAbbreviation; + } + + public String getCompanyAbbreviation(){ + return companyAbbreviation; + } + + public void setCountryName(String countryName){ + this.countryName = countryName; + } + + public String getCountryName(){ + return countryName; + } + + public void setCompanyCode(String companyCode){ + this.companyCode = companyCode; + } + + public String getCompanyCode(){ + return companyCode; + } + + public void setCompanyLevelCode(String companyLevelCode){ + this.companyLevelCode = companyLevelCode; + } + + public String getCompanyLevelCode(){ + return companyLevelCode; + } + + public void setUnifySocialCreditCode(String unifySocialCreditCode){ + this.unifySocialCreditCode = unifySocialCreditCode; + } + + public String getUnifySocialCreditCode(){ + return unifySocialCreditCode; + } + + public void setStatus(String status){ + this.status = status; + } + + public String getStatus(){ + return status; + } +} diff --git a/src/main/youhong_ai_jitu_src/jntchina/schedule/hrm/entity/CompanyOtherDto.java b/src/main/youhong_ai_jitu_src/jntchina/schedule/hrm/entity/CompanyOtherDto.java new file mode 100644 index 0000000..652e67a --- /dev/null +++ b/src/main/youhong_ai_jitu_src/jntchina/schedule/hrm/entity/CompanyOtherDto.java @@ -0,0 +1,112 @@ +package jntchina.schedule.hrm.entity; + +public class CompanyOtherDto { + private String id; + private String isDirectSales; + private String languageCd; + private String countryCode; + private String companyLevelName; + private String companyName; + private String companyAbbreviation; + private String countryName; + private String companyCode; + private String companyLevelCode; + private String unifySocialCreditCode; + private String status; + + public String getId(){ + return this.id; + } + + public void setId(String id){ + this.id = id; + } + + public void setIsDirectSales(String isDirectSales){ + this.isDirectSales = isDirectSales; + } + + public String getIsDirectSales(){ + return isDirectSales; + } + + public void setLanguageCd(String languageCd){ + this.languageCd = languageCd; + } + + public String getLanguageCd(){ + return languageCd; + } + + public void setCountryCode(String countryCode){ + this.countryCode = countryCode; + } + + public String getCountryCode(){ + return countryCode; + } + + public void setCompanyLevelName(String companyLevelName){ + this.companyLevelName = companyLevelName; + } + + public String getCompanyLevelName(){ + return companyLevelName; + } + + public void setCompanyName(String companyName){ + this.companyName = companyName; + } + + public String getCompanyName(){ + return companyName; + } + + public void setCompanyAbbreviation(String companyAbbreviation){ + this.companyAbbreviation = companyAbbreviation; + } + + public String getCompanyAbbreviation(){ + return companyAbbreviation; + } + + public void setCountryName(String countryName){ + this.countryName = countryName; + } + + public String getCountryName(){ + return countryName; + } + + public void setCompanyCode(String companyCode){ + this.companyCode = companyCode; + } + + public String getCompanyCode(){ + return companyCode; + } + + public void setCompanyLevelCode(String companyLevelCode){ + this.companyLevelCode = companyLevelCode; + } + + public String getCompanyLevelCode(){ + return companyLevelCode; + } + + public void setUnifySocialCreditCode(String unifySocialCreditCode){ + this.unifySocialCreditCode = unifySocialCreditCode; + } + + public String getUnifySocialCreditCode(){ + return unifySocialCreditCode; + } + + public void setStatus(String status){ + this.status = status; + } + + public String getStatus(){ + return status; + } +} diff --git a/src/main/youhong_ai_jitu_src/jntchina/schedule/hrm/entity/DepartmentDto.java b/src/main/youhong_ai_jitu_src/jntchina/schedule/hrm/entity/DepartmentDto.java new file mode 100644 index 0000000..ea9bfd4 --- /dev/null +++ b/src/main/youhong_ai_jitu_src/jntchina/schedule/hrm/entity/DepartmentDto.java @@ -0,0 +1,233 @@ +package jntchina.schedule.hrm.entity; + +import java.io.Serializable; + +public class DepartmentDto implements Serializable { + + private String companyCode; + private String departmentName; + private String businessUnitName; + private String deptManager; + private String languageCd; + private String departmentOrder; + private String brchLeaderName; + private String companyName; + private String departmentCode; + private String departmentAbbreviation; + private String updateTime; + private String isDirectSales; + private String superiorDepartment; + private String organizationCode; + private String organizationType; + private String organizationTypeDescr; + private String organizationClass; + private String organizationClassDescr; + private String createTime; + private String countryCode; + private String deptManagerName; + private String businessUnitCode; +// private List rank; + private String countryName; + private String brchLeader; + private String status; + + public void setCompanyCode(String companyCode){ + this.companyCode = companyCode; + } + + public String getCompanyCode(){ + return companyCode; + } + + public void setDepartmentName(String departmentName){ + this.departmentName = departmentName; + } + + public String getDepartmentName(){ + return departmentName; + } + + public void setBusinessUnitName(String businessUnitName){ + this.businessUnitName = businessUnitName; + } + + public String getBusinessUnitName(){ + return businessUnitName; + } + + public void setDeptManager(String deptManager){ + this.deptManager = deptManager; + } + + public String getDeptManager(){ + return deptManager; + } + + public void setLanguageCd(String languageCd){ + this.languageCd = languageCd; + } + + public String getLanguageCd(){ + return languageCd; + } + + public void setDepartmentOrder(String departmentOrder){ + this.departmentOrder = departmentOrder; + } + + public String getDepartmentOrder(){ + return departmentOrder; + } + + public void setBrchLeaderName(String brchLeaderName){ + this.brchLeaderName = brchLeaderName; + } + + public String getBrchLeaderName(){ + return brchLeaderName; + } + + public void setCompanyName(String companyName){ + this.companyName = companyName; + } + + public String getCompanyName(){ + return companyName; + } + + public void setDepartmentCode(String departmentCode){ + this.departmentCode = departmentCode; + } + + public String getDepartmentCode(){ + return departmentCode; + } + + public void setDepartmentAbbreviation(String departmentAbbreviation){ + this.departmentAbbreviation = departmentAbbreviation; + } + + public String getDepartmentAbbreviation(){ + return departmentAbbreviation; + } + + public void setUpdateTime(String updateTime){ + this.updateTime = updateTime; + } + + public String getUpdateTime(){ + return updateTime; + } + + public void setIsDirectSales(String isDirectSales){ + this.isDirectSales = isDirectSales; + } + + public String getIsDirectSales(){ + return isDirectSales; + } + + public void setOrganizationTypeDescr(String organizationTypeDescr){ + this.organizationTypeDescr = organizationTypeDescr; + } + + public String getOrganizationTypeDescr(){ + return organizationTypeDescr; + } + + public void setSuperiorDepartment(String superiorDepartment){ + this.superiorDepartment = superiorDepartment; + } + + public String getSuperiorDepartment(){ + return superiorDepartment; + } + + public void setOrganizationType(String organizationType){ + this.organizationType = organizationType; + } + + public String getOrganizationType(){ + return organizationType; + } + + public void setCreateTime(String createTime){ + this.createTime = createTime; + } + + public String getCreateTime(){ + return createTime; + } + + public void setOrganizationCode(String organizationCode){ + this.organizationCode = organizationCode; + } + + public String getOrganizationCode(){ + return organizationCode; + } + + public void setCountryCode(String countryCode){ + this.countryCode = countryCode; + } + + public String getCountryCode(){ + return countryCode; + } + + public void setDeptManagerName(String deptManagerName){ + this.deptManagerName = deptManagerName; + } + + public String getDeptManagerName(){ + return deptManagerName; + } + + public void setBusinessUnitCode(String businessUnitCode){ + this.businessUnitCode = businessUnitCode; + } + + public String getBusinessUnitCode(){ + return businessUnitCode; + } + + public void setCountryName(String countryName){ + this.countryName = countryName; + } + + public String getCountryName(){ + return countryName; + } + + public void setBrchLeader(String brchLeader){ + this.brchLeader = brchLeader; + } + + public String getBrchLeader(){ + return brchLeader; + } + + public void setStatus(String status){ + this.status = status; + } + + public String getStatus(){ + return status; + } + + public String getOrganizationClass() { + return organizationClass; + } + + public void setOrganizationClass(String organizationClass) { + this.organizationClass = organizationClass; + } + + public String getOrganizationClassDescr() { + return organizationClassDescr; + } + + public void setOrganizationClassDescr(String organizationClassDescr) { + this.organizationClassDescr = organizationClassDescr; + } +} \ No newline at end of file diff --git a/src/main/youhong_ai_jitu_src/jntchina/schedule/hrm/entity/HrmUserDto.java b/src/main/youhong_ai_jitu_src/jntchina/schedule/hrm/entity/HrmUserDto.java new file mode 100644 index 0000000..cceb370 --- /dev/null +++ b/src/main/youhong_ai_jitu_src/jntchina/schedule/hrm/entity/HrmUserDto.java @@ -0,0 +1,794 @@ +package jntchina.schedule.hrm.entity; + +public class HrmUserDto{ + private String deptName; + private String personalTel; + private String positionType; + private String actionSubReasonDescr; + private String companyName; + private String inspectEndDate; + private String actionDescr; + private String highestEducation; + private String emplTerminationDate; + private String isStay; + private String positonRankDescr; + private String bankCountry; + private String personalEmail; + private String positionPropeCode; + private String actionReasonDescr; + private String positionGroupName; + private String action; + private String stdPositionName; + private String bankCountryName; + private String bankAccountOpenDt; + private String companyCode; + private String oldEmployeeCode; + private String employeeName; + private String languageCd; + private String ethnicGroupCode; + private String bankCurrencyName; + private String companyTel; + private String bankAccountAc; + private String supervisorId; + private String hrStatus; + private String positonRankCode; + private String workLocationCode; + private String bankCurrencyId; + private String bankId; + private String bankAccountId; + private String employeeEnglishName; + private String postCode; + private String countryName; + private String deptCode; + private String certificateType; + private String positionPropeName; + private String status; + private String supervisorName; + private String emergeContactName; + private String religiousFaithDescr; + private String ethnicGroupName; + private String bankBranchName; + private String actionReason; + private String positionCode; + private String bankName; + private String actionSubReason; + private String sequenceName; + private String positionTypeDescr; + private String employeeCode; + private String positionName; + private String employeeSexCode; + private String politicalStatusDescr; + private String sequenceCode; + private String companyEmail; + private String employeeBirthdate; + private String countryCode; + private String postName; + private String employeeTypeName; + private String workLocaltionName; + private String employeeSexDescr; + private String politicalStatus; + private String updateTime; + private String emergeContactPhone; + private String certificateTypeName; + private String currentAddress; + private String highestEducationDescr; + private String stdPositionCode; + private String positionGroupCode; + private String religiousFaith; + private String trialEndDate; + private String createTime; + private String employeeTypeCode; + private String emplHireDate; + private String certificateNum; + + + // 字段说明 + // language_cd 语言编码 CHN + // employee_code 员工ID 10000002 + // employee_name 姓名 李四 + // employee_english_name 英文名 Four Li + // employee_birthdate 出生日期 34255 + // personal_tel 移动电话 15719312349 + // company_tel 公司电话 3030127 + // country_code 国家/地区编码 CHN + // country_name 国家/地区 中国 + // employee_sex_code 性别,转换值 M/F + // employee_sex_descr 性别 男 /女 + // personal_email 个人邮箱 1387597880@qq.com + // company_email 公司邮箱 13213@123.com + // current_address 现居住地址 黑龙江双鸭山市 + // certificate_type 证件类型,NID\PASP\PASS\TCS NID + // certificate_type_name 证件描述:身份证号、护照、港澳通行证、台胞证 身份证号 + // certificate_num 证件号码 1309031993025310000 + // highest_education 最高学历,转换值 50 + // highest_education_descr 最高学历 50-博士研究生 + // political_status 政治面貌,转换值 10 + // political_status_descr 政治面貌 10-群众 + // religious_faith 宗教信仰,转换值 60 + // religious_faith_descr 宗教信仰 60-无神论者 + // action 操作,转换值 PRD + // action_descr 操作 转正 + // action_reason 操作原因,转换值 P01 + // action_reason_descr 操作原因 试用期转正 + // action_sub_reason 操作原因子项,转换值 10 + // action_sub_reason_descr 操作原因子项 按期转正 + // hr_status A在职,I离职 A + // position_code 岗位编码 00000012 + // position_name 岗位名称 安全监察专员 + // company_code 公司编码 100 + // company_name 公司名称 上海极兔极致供应链管理有限公司 + // dept_code 部门编码 10000011 + // dept_name 部门名称 安全监察部 + // std_position_code 标准岗位编码 1000001 + // std_position_name 标准岗位名称 转运中心主管 + // ethnic_group_code 族群编码 40002 + // ethnic_group_name 族群名称 运作 + // position_group_code 岗族编码 30002 + // position_group_name 岗族名称 转运 + // position_prope_code 岗位属性编码 10 + // position_prope_name 岗位属性名称 一线 + // sequence_code 序列编码 20002 + // sequence_name 序列名称 仓储与分拣 + // post_code 岗编码 10005 + // post_name 岗名称 配送与分拣 + // employee_type_code 员工类型编码 10 + // employee_type_name 员工类型名称 10-全日制 + // position_type 岗位类别 10 + // position_type_descr 岗位类别名称 M + // positon_rank_code 职级编码 20 + // positon_rank_descr 职级编码名称 M02 + // is_stay 是否住宿 Y-是 N-否 + // trial_end_date 试用期结束日期 2021-04-20 + // inspect_end_date 考察期结束日期 2021-04-20 + // work_location_code 工作地点编码 10000 + // work_localtion_name 工作地点描述 上海 + // supervisor_id 直属领导编码 0000010000 + // supervisor_name 直属领导姓名 张三 + // emerge_contact_name 紧急联系人姓名 张五 + // emerge_contact_phone 紧急联系人电话 13393344566 + // old_employee_code 老工号 1232142324 + // bank_country 银行所属国家地区编码 CHN + // bank_country_name 银行所属国家地区描述 中国 + // bank_id 银行编码 CIB + // bank_name 银行名称 兴业银行 + // bank_account_id 银行账号 12349999 + // bank_branch_name 开户行支行 开户行支行 + // bank_currency_id 币种编码 CNY + // bank_currency_name 币种名称 人民币 + // bank_account_ac 银行联码 9999999999 + // bank_account_open_dt 开户日期 2021-04-01 + // status 状态码 1 新增 2 修改 3作废 + + + public void setDeptName(String deptName){ + this.deptName = deptName; + } + + public String getDeptName(){ + return deptName; + } + + public void setPersonalTel(String personalTel){ + this.personalTel = personalTel; + } + + public String getPersonalTel(){ + return personalTel; + } + + public void setPositionType(String positionType){ + this.positionType = positionType; + } + + public String getPositionType(){ + return positionType; + } + + public void setActionSubReasonDescr(String actionSubReasonDescr){ + this.actionSubReasonDescr = actionSubReasonDescr; + } + + public String getActionSubReasonDescr(){ + return actionSubReasonDescr; + } + + public void setCompanyName(String companyName){ + this.companyName = companyName; + } + + public String getCompanyName(){ + return companyName; + } + + public void setInspectEndDate(String inspectEndDate){ + this.inspectEndDate = inspectEndDate; + } + + public String getInspectEndDate(){ + return inspectEndDate; + } + + public void setActionDescr(String actionDescr){ + this.actionDescr = actionDescr; + } + + public String getActionDescr(){ + return actionDescr; + } + + public void setHighestEducation(String highestEducation){ + this.highestEducation = highestEducation; + } + + public String getHighestEducation(){ + return highestEducation; + } + + public void setEmplTerminationDate(String emplTerminationDate){ + this.emplTerminationDate = emplTerminationDate; + } + + public String getEmplTerminationDate(){ + return emplTerminationDate; + } + + public void setIsStay(String isStay){ + this.isStay = isStay; + } + + public String getIsStay(){ + return isStay; + } + + public void setPositonRankDescr(String positonRankDescr){ + this.positonRankDescr = positonRankDescr; + } + + public String getPositonRankDescr(){ + return positonRankDescr; + } + + public void setBankCountry(String bankCountry){ + this.bankCountry = bankCountry; + } + + public String getBankCountry(){ + return bankCountry; + } + + public void setPersonalEmail(String personalEmail){ + this.personalEmail = personalEmail; + } + + public String getPersonalEmail(){ + return personalEmail; + } + + public void setPositionPropeCode(String positionPropeCode){ + this.positionPropeCode = positionPropeCode; + } + + public String getPositionPropeCode(){ + return positionPropeCode; + } + + public void setActionReasonDescr(String actionReasonDescr){ + this.actionReasonDescr = actionReasonDescr; + } + + public String getActionReasonDescr(){ + return actionReasonDescr; + } + + public void setPositionGroupName(String positionGroupName){ + this.positionGroupName = positionGroupName; + } + + public String getPositionGroupName(){ + return positionGroupName; + } + + public void setAction(String action){ + this.action = action; + } + + public String getAction(){ + return action; + } + + public void setStdPositionName(String stdPositionName){ + this.stdPositionName = stdPositionName; + } + + public String getStdPositionName(){ + return stdPositionName; + } + + public void setBankCountryName(String bankCountryName){ + this.bankCountryName = bankCountryName; + } + + public String getBankCountryName(){ + return bankCountryName; + } + + public void setBankAccountOpenDt(String bankAccountOpenDt){ + this.bankAccountOpenDt = bankAccountOpenDt; + } + + public String getBankAccountOpenDt(){ + return bankAccountOpenDt; + } + + public void setCompanyCode(String companyCode){ + this.companyCode = companyCode; + } + + public String getCompanyCode(){ + return companyCode; + } + + public void setOldEmployeeCode(String oldEmployeeCode){ + this.oldEmployeeCode = oldEmployeeCode; + } + + public String getOldEmployeeCode(){ + return oldEmployeeCode; + } + + public void setEmployeeName(String employeeName){ + this.employeeName = employeeName; + } + + public String getEmployeeName(){ + return employeeName; + } + + public void setLanguageCd(String languageCd){ + this.languageCd = languageCd; + } + + public String getLanguageCd(){ + return languageCd; + } + + public void setEthnicGroupCode(String ethnicGroupCode){ + this.ethnicGroupCode = ethnicGroupCode; + } + + public String getEthnicGroupCode(){ + return ethnicGroupCode; + } + + public void setBankCurrencyName(String bankCurrencyName){ + this.bankCurrencyName = bankCurrencyName; + } + + public String getBankCurrencyName(){ + return bankCurrencyName; + } + + public void setCompanyTel(String companyTel){ + this.companyTel = companyTel; + } + + public String getCompanyTel(){ + return companyTel; + } + + public void setBankAccountAc(String bankAccountAc){ + this.bankAccountAc = bankAccountAc; + } + + public String getBankAccountAc(){ + return bankAccountAc; + } + + public void setSupervisorId(String supervisorId){ + this.supervisorId = supervisorId; + } + + public String getSupervisorId(){ + return supervisorId; + } + + public void setHrStatus(String hrStatus){ + this.hrStatus = hrStatus; + } + + public String getHrStatus(){ + return hrStatus; + } + + public void setPositonRankCode(String positonRankCode){ + this.positonRankCode = positonRankCode; + } + + public String getPositonRankCode(){ + return positonRankCode; + } + + public void setWorkLocationCode(String workLocationCode){ + this.workLocationCode = workLocationCode; + } + + public String getWorkLocationCode(){ + return workLocationCode; + } + + public void setBankCurrencyId(String bankCurrencyId){ + this.bankCurrencyId = bankCurrencyId; + } + + public String getBankCurrencyId(){ + return bankCurrencyId; + } + + public void setBankId(String bankId){ + this.bankId = bankId; + } + + public String getBankId(){ + return bankId; + } + + public void setBankAccountId(String bankAccountId){ + this.bankAccountId = bankAccountId; + } + + public String getBankAccountId(){ + return bankAccountId; + } + + public void setEmployeeEnglishName(String employeeEnglishName){ + this.employeeEnglishName = employeeEnglishName; + } + + public String getEmployeeEnglishName(){ + return employeeEnglishName; + } + + public void setPostCode(String postCode){ + this.postCode = postCode; + } + + public String getPostCode(){ + return postCode; + } + + public void setCountryName(String countryName){ + this.countryName = countryName; + } + + public String getCountryName(){ + return countryName; + } + + public void setDeptCode(String deptCode){ + this.deptCode = deptCode; + } + + public String getDeptCode(){ + return deptCode; + } + + public void setCertificateType(String certificateType){ + this.certificateType = certificateType; + } + + public String getCertificateType(){ + return certificateType; + } + + public void setPositionPropeName(String positionPropeName){ + this.positionPropeName = positionPropeName; + } + + public String getPositionPropeName(){ + return positionPropeName; + } + + public void setStatus(String status){ + this.status = status; + } + + public String getStatus(){ + return status; + } + + public void setSupervisorName(String supervisorName){ + this.supervisorName = supervisorName; + } + + public String getSupervisorName(){ + return supervisorName; + } + + public void setEmergeContactName(String emergeContactName){ + this.emergeContactName = emergeContactName; + } + + public String getEmergeContactName(){ + return emergeContactName; + } + + public void setReligiousFaithDescr(String religiousFaithDescr){ + this.religiousFaithDescr = religiousFaithDescr; + } + + public String getReligiousFaithDescr(){ + return religiousFaithDescr; + } + + public void setEthnicGroupName(String ethnicGroupName){ + this.ethnicGroupName = ethnicGroupName; + } + + public String getEthnicGroupName(){ + return ethnicGroupName; + } + + public void setBankBranchName(String bankBranchName){ + this.bankBranchName = bankBranchName; + } + + public String getBankBranchName(){ + return bankBranchName; + } + + public void setActionReason(String actionReason){ + this.actionReason = actionReason; + } + + public String getActionReason(){ + return actionReason; + } + + public void setPositionCode(String positionCode){ + this.positionCode = positionCode; + } + + public String getPositionCode(){ + return positionCode; + } + + public void setBankName(String bankName){ + this.bankName = bankName; + } + + public String getBankName(){ + return bankName; + } + + public void setActionSubReason(String actionSubReason){ + this.actionSubReason = actionSubReason; + } + + public String getActionSubReason(){ + return actionSubReason; + } + + public void setSequenceName(String sequenceName){ + this.sequenceName = sequenceName; + } + + public String getSequenceName(){ + return sequenceName; + } + + public void setPositionTypeDescr(String positionTypeDescr){ + this.positionTypeDescr = positionTypeDescr; + } + + public String getPositionTypeDescr(){ + return positionTypeDescr; + } + + public void setEmployeeCode(String employeeCode){ + this.employeeCode = employeeCode; + } + + public String getEmployeeCode(){ + return employeeCode; + } + + public void setPositionName(String positionName){ + this.positionName = positionName; + } + + public String getPositionName(){ + return positionName; + } + + public void setEmployeeSexCode(String employeeSexCode){ + this.employeeSexCode = employeeSexCode; + } + + public String getEmployeeSexCode(){ + return employeeSexCode; + } + + public void setPoliticalStatusDescr(String politicalStatusDescr){ + this.politicalStatusDescr = politicalStatusDescr; + } + + public String getPoliticalStatusDescr(){ + return politicalStatusDescr; + } + + public void setSequenceCode(String sequenceCode){ + this.sequenceCode = sequenceCode; + } + + public String getSequenceCode(){ + return sequenceCode; + } + + public void setCompanyEmail(String companyEmail){ + this.companyEmail = companyEmail; + } + + public String getCompanyEmail(){ + return companyEmail; + } + + public void setEmployeeBirthdate(String employeeBirthdate){ + this.employeeBirthdate = employeeBirthdate; + } + + public String getEmployeeBirthdate(){ + return employeeBirthdate; + } + + public void setCountryCode(String countryCode){ + this.countryCode = countryCode; + } + + public String getCountryCode(){ + return countryCode; + } + + public void setPostName(String postName){ + this.postName = postName; + } + + public String getPostName(){ + return postName; + } + + public void setEmployeeTypeName(String employeeTypeName){ + this.employeeTypeName = employeeTypeName; + } + + public String getEmployeeTypeName(){ + return employeeTypeName; + } + + public void setWorkLocaltionName(String workLocaltionName){ + this.workLocaltionName = workLocaltionName; + } + + public String getWorkLocaltionName(){ + return workLocaltionName; + } + + public void setEmployeeSexDescr(String employeeSexDescr){ + this.employeeSexDescr = employeeSexDescr; + } + + public String getEmployeeSexDescr(){ + return employeeSexDescr; + } + + public void setPoliticalStatus(String politicalStatus){ + this.politicalStatus = politicalStatus; + } + + public String getPoliticalStatus(){ + return politicalStatus; + } + + public void setUpdateTime(String updateTime){ + this.updateTime = updateTime; + } + + public String getUpdateTime(){ + return updateTime; + } + + public void setEmergeContactPhone(String emergeContactPhone){ + this.emergeContactPhone = emergeContactPhone; + } + + public String getEmergeContactPhone(){ + return emergeContactPhone; + } + + public void setCertificateTypeName(String certificateTypeName){ + this.certificateTypeName = certificateTypeName; + } + + public String getCertificateTypeName(){ + return certificateTypeName; + } + + public void setCurrentAddress(String currentAddress){ + this.currentAddress = currentAddress; + } + + public String getCurrentAddress(){ + return currentAddress; + } + + public void setHighestEducationDescr(String highestEducationDescr){ + this.highestEducationDescr = highestEducationDescr; + } + + public String getHighestEducationDescr(){ + return highestEducationDescr; + } + + public void setStdPositionCode(String stdPositionCode){ + this.stdPositionCode = stdPositionCode; + } + + public String getStdPositionCode(){ + return stdPositionCode; + } + + public void setPositionGroupCode(String positionGroupCode){ + this.positionGroupCode = positionGroupCode; + } + + public String getPositionGroupCode(){ + return positionGroupCode; + } + + public void setReligiousFaith(String religiousFaith){ + this.religiousFaith = religiousFaith; + } + + public String getReligiousFaith(){ + return religiousFaith; + } + + public void setTrialEndDate(String trialEndDate){ + this.trialEndDate = trialEndDate; + } + + public String getTrialEndDate(){ + return trialEndDate; + } + + public void setCreateTime(String createTime){ + this.createTime = createTime; + } + + public String getCreateTime(){ + return createTime; + } + + public void setEmployeeTypeCode(String employeeTypeCode){ + this.employeeTypeCode = employeeTypeCode; + } + + public String getEmployeeTypeCode(){ + return employeeTypeCode; + } + + public void setEmplHireDate(String emplHireDate){ + this.emplHireDate = emplHireDate; + } + + public String getEmplHireDate(){ + return emplHireDate; + } + + public void setCertificateNum(String certificateNum){ + this.certificateNum = certificateNum; + } + + public String getCertificateNum(){ + return certificateNum; + } +} diff --git a/src/main/youhong_ai_jitu_src/jntchina/schedule/hrm/entity/ResoutDate.java b/src/main/youhong_ai_jitu_src/jntchina/schedule/hrm/entity/ResoutDate.java new file mode 100644 index 0000000..58fd9dc --- /dev/null +++ b/src/main/youhong_ai_jitu_src/jntchina/schedule/hrm/entity/ResoutDate.java @@ -0,0 +1,70 @@ +package jntchina.schedule.hrm.entity; + +import java.io.Serializable; + +/** + * @title: ResoutDate + * @Author ycf + * @Date: 2021/9/28 14:07 + * @Version 1.0 + */ +public class ResoutDate implements Serializable { + private String FIELDVALUE; + private String XlADLONGNAME; + private String FIELDNAME; + private String XLADSHORTNAME; + private String gs; + + @Override + public String toString() { + return "ResoutDate{" + + "FIELDVALUE='" + FIELDVALUE + '\'' + + ", XlADLONGNAME='" + XlADLONGNAME + '\'' + + ", FIELDNAME='" + FIELDNAME + '\'' + + ", XLADSHORTNAME='" + XLADSHORTNAME + '\'' + + ", gs='" + gs + '\'' + + '}'; + } + + public String getGs() { + return gs; + } + + public void setGs(String gs) { + this.gs = gs; + } + + public String getFIELDVALUE() { + return FIELDVALUE; + } + + public void setFIELDVALUE(String FIELDVALUE) { + this.FIELDVALUE = FIELDVALUE; + } + + public String getXlADLONGNAME() { + return XlADLONGNAME; + } + + public void setXlADLONGNAME(String xlADLONGNAME) { + XlADLONGNAME = xlADLONGNAME; + } + + public String getFIELDNAME() { + return FIELDNAME; + } + + public void setFIELDNAME(String FIELDNAME) { + this.FIELDNAME = FIELDNAME; + } + + public String getXLADSHORTNAME() { + return XLADSHORTNAME; + } + + public void setXLADSHORTNAME(String XLADSHORTNAME) { + this.XLADSHORTNAME = XLADSHORTNAME; + } + + +} diff --git a/src/main/youhong_ai_jitu_src/jntchina/schedule/hrm/idn/HRSynIDN.java b/src/main/youhong_ai_jitu_src/jntchina/schedule/hrm/idn/HRSynIDN.java new file mode 100644 index 0000000..7e9fdb0 --- /dev/null +++ b/src/main/youhong_ai_jitu_src/jntchina/schedule/hrm/idn/HRSynIDN.java @@ -0,0 +1,41 @@ +package jntchina.schedule.hrm.idn; + +import weaver.conn.RecordSet; +import weaver.interfaces.schedule.BaseCronJob; + +import java.time.LocalDate; +import java.time.LocalDateTime; +import java.time.LocalTime; +import java.time.format.DateTimeFormatter; + +public class HRSynIDN extends BaseCronJob { + + + @Override + public void execute() { + LocalDateTime today_start = LocalDateTime.of(LocalDate.now(), LocalTime.MIN);//当天零点 + String today = today_start.format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")); + String allDay = "2018-03-21 00:00:00"; + SynHrmdepartmentToOAIDN dept = new SynHrmdepartmentToOAIDN(); + SyncHrmjobtitlesToOAIDN job = new SyncHrmjobtitlesToOAIDN(); + SyncHrmresourceToOAIDN user = new SyncHrmresourceToOAIDN(); + RecordSet rs = new RecordSet(); + rs.executeQuery("select * from controltaskidn"); + if (!rs.next()) { + rs.executeUpdate("insert into controltaskidn(task) values(?)", 0); + } + rs.executeQuery("select * from controltaskidn where task = ?", 0); + if (rs.next()) { + rs.executeUpdate("update controltaskidn set task = ?", 1); + dept.execute(today); + job.execute(today); + user.execute(today); + rs.executeUpdate("update controltaskidn set task = ?", 0); + } + + } +} + + + + diff --git a/src/main/youhong_ai_jitu_src/jntchina/schedule/hrm/idn/SynHrmdepartmentToOAIDN.java b/src/main/youhong_ai_jitu_src/jntchina/schedule/hrm/idn/SynHrmdepartmentToOAIDN.java new file mode 100644 index 0000000..6321a86 --- /dev/null +++ b/src/main/youhong_ai_jitu_src/jntchina/schedule/hrm/idn/SynHrmdepartmentToOAIDN.java @@ -0,0 +1,781 @@ +package jntchina.schedule.hrm.idn; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.JSONArray; +import com.alibaba.fastjson.JSONObject; +import com.api.integration.util.JavaUtil; +import jntchina.schedule.hrm.SyncHrmdepartmentToOA; +import jntchina.schedule.hrm.SyncHrmresourceToOA; +import jntchina.schedule.hrm.entity.DepartmentDto; +import jntchina.util.HttpClientToJT; +import selfdev.util.base.TimeCommonUtil; +import selfdev.util.log.LogTool; +import weaver.conn.RecordSet; +import weaver.general.Util; +import weaver.hrm.company.DepartmentComInfo; +import weaver.matrix.MatrixUtil; + +import java.io.BufferedWriter; +import java.io.FileWriter; +import java.io.IOException; +import java.util.*; +import java.util.stream.Collectors; + +public class SynHrmdepartmentToOAIDN { + + Map deptMap = new HashMap<>(); + + + //分页接口参数 + String maxPoint = "1"; + //接口是否有下一页 默认为有 + boolean ifPage = true; + + + //部门编码和id map + Map map_dept_code_id = new HashMap(); + private LogTool log = new LogTool("/log/hrm/IDN/dept/", false); + + //60里面是否还有分部 + boolean ifExistenceSub = true; + + //所有10分部的上级 + List subList = new ArrayList(); + + + //存放60分部 + List list60 = new ArrayList(); + + + public void ScreenSub(Map supSubMap) { + try { + boolean ifSub = false; + Set keySet = supSubMap.keySet(); + Iterator it = keySet.iterator(); + while (it.hasNext()) { + //60的key + String deptCode = (String) it.next(); + if (subList.contains(deptCode)) { + ifSub = true; + String supDeptCode = String.valueOf(supSubMap.get(deptCode)); + //60的value + list60.add(deptCode); + subList.add(supDeptCode); + supSubMap.remove(deptCode); + } + } + ifExistenceSub = ifSub; + } catch (Exception e) { + e.printStackTrace(); + } + } + + + /** + * 同步分部、部门数据 + * 注:对方整个组织数不区分部门和分部,全部用部门接口数据,用类型区分 + */ + public Map> execute(String date) { + Map> rtMap = new HashMap<>(); + try { + String now = TimeCommonUtil.obtainDate(0); + //匹配部门id,关联的上级部门,所属分部 map + Map> map_dept_id_data = new HashMap<>(); + map_dept_id_data = getDeptDataMap(); +// log.writeLog("字典:"+JSON.toJSONString(map_dept_id_data)); + map_dept_code_id = getAllDepartmentCodeIdMap(); + SyncHrmsubcompanyToOAIDN hrmsubcompany = new SyncHrmsubcompanyToOAIDN(); + SyncHrmresourceToOA hrmresource = new SyncHrmresourceToOA(); + //人员map,用于匹配上级领导 + Map map_user_code_id = hrmresource.getUserCodeIdMap(); + //拆分数据、organizationClass 10类型是组织,其他类型当部门,【代理区】在对方那是虚拟部门,特殊处理划分为OA 分部 + //JSONArray data = getDepartments(date); + //JSONArray ocData = getOcDepartments(date); + + JSONArray ocData = new JSONArray(); + while (ifPage) { + ocData.addAll(getOcDepartments(date, maxPoint)); + } + + //key为60自己,value为上级 + Map supSubMap = new HashMap<>(); + + Object directSales = ocData.stream().filter(item -> { + JSONObject itemJson = JSONObject.parseObject(JSON.toJSONString(item)); + if ("10".equals(itemJson.getString("organizationClass"))) { + subList.add(itemJson.getString("superiorDepartment")); + } + if ("60".equals(itemJson.getString("organizationClass"))) { + //key为60自己,value为上级 + supSubMap.put(itemJson.getString("departmentCode"), itemJson.getString("superiorDepartment")); + } + return !"10".equals(itemJson.getString("organizationClass")); + }).collect(Collectors.toList()); + /* + while (ifExistenceSub) { + ScreenSub(supSubMap); + }*/ + + List dataList = JSONArray.parseArray(ocData.toJSONString(), DepartmentDto.class); + log.writeLog("-----------------全部长度:" + dataList.size()); + + //分部数据 + List subcompanys = dataList.stream().filter(item -> { + return "10".equals(item.getOrganizationClass()) || "60".equals(item.getOrganizationClass()); + //return "10".equals(item.getOrganizationClass()) || ("60".equals(item.getOrganizationClass()) && list60.contains(item.getDepartmentCode())); + }).collect(Collectors.toList()); + //部门数据 注意:10000300代理区编码 + List departments = dataList.stream().filter(item -> { + return "20".equals(item.getOrganizationClass()) + || "30".equals(item.getOrganizationClass()) + || "40".equals(item.getOrganizationClass()) + || "50".equals(item.getOrganizationClass()) ; + //|| ("60".equals(item.getOrganizationClass()) && !list60.contains(item.getDepartmentCode())); + }).collect(Collectors.toList()); + log.writeLog("-----------------分部长度:" + subcompanys.size()); + log.writeLog("-----------------部门长度:" + departments.size()); + + rtMap.put("department", departments); + //处理分部同步逻辑 + List execute = hrmsubcompany.execute(subcompanys, departments); + //departments = execute; + Map map_subcompany_code_id = hrmsubcompany.getSubCodeIdMap(); + //处理部门同步逻辑 + RecordSet rs = new RecordSet(); + int skipNum = 0, insertNum = 0, updateNum = 0; + List skipList = new ArrayList<>(); + log.writeLog("----------开始同步部门,条数:" + departments.size()); + //log.writeLog("----------同步部门源数据:" + JSON.toJSONString(departments)); + // 处理部门同步逻辑 1.未匹配到分部,不新增, + for (int i = 0; i < departments.size(); i++) { + DepartmentDto row = departments.get(i); + String countryCode = Util.null2String(row.getCountryCode());//国家 + String departmentCode = Util.null2String(row.getDepartmentCode());//部门编码 + String departmentName = Util.null2String(row.getDepartmentName());//部门全称 + String shortName = Util.null2String(row.getDepartmentAbbreviation());//部门简称 + String superiorDepartment = Util.null2String(row.getSuperiorDepartment());//上级部门编码 + String departmentOrder = Util.null2String(row.getDepartmentOrder());//排序 + String deptManager = Util.null2String(row.getDeptManager());//部门负责人code + String brchLeader = Util.null2String(row.getBrchLeader());//分管领导code + Integer canceled = Util.null2String(row.getStatus()).equals("3") ? 1 : null;//1 新增 2 修改 3作废 + String companyCode = Util.null2String(row.getCompanyCode());// 公司 +// String companyName = Util.null2String(row.getCompanyName());//公司名称 + if ("".equals(superiorDepartment)) { + skipList.add(row); + log.writeLog("cylnb superiorDepartment is null:" + superiorDepartment); + skipNum++; + deptMap.put(departmentCode, superiorDepartment); + // continue; + } + //各种code转id + String bmfzr = Util.null2String(map_user_code_id.get(deptManager));//部门负责人 + String bmfgld = Util.null2String(map_user_code_id.get(brchLeader));//分管领导 + String subcompanyid1 = Util.null2String(map_subcompany_code_id.get(superiorDepartment));//分部ID + String supdepid = Util.null2String(map_dept_code_id.get(superiorDepartment));//获取上级ID + log.writeLog("------------subcompanyid1:" + subcompanyid1 + "-----deptCode:" + departmentCode + ",status:" + row.getStatus() + ",canceled:" + canceled + "-------"); + log.writeLog("------------supdepid:" + supdepid + "----deptCode:" + departmentCode + ",status:" + row.getStatus() + ",canceled:" + canceled + "--------"); + //如果上级编码为空、所属分部,上级部门都找不到,不作处理 + if ("".equals(superiorDepartment) || ("".equals(subcompanyid1) && "".equals(supdepid))) { + skipList.add(row); + skipNum++; + log.writeLog("cylnb 上级编码为空、所属分部,上级部门都找不到,不作处理deptcode:" + departmentCode + ";supcode:" + superiorDepartment); + deptMap.put(departmentCode, superiorDepartment); + //continue; + } + String sql = ""; + //判断HR部门ID是否已经存在 + + String status = row.getStatus(); + if (!"3".equals(status)) { + log.writeLog("---------------国家:" + countryCode); + departmentName = getDepartmentName(date, countryCode, departmentCode, departmentName); + } else { + log.writeLog("----------------状态为3"); + } + + if ("".equals(departmentName)) { + log.writeLog("----------------多语言为空"); + departmentName = row.getDepartmentName(); + } + + log.writeLog("-----------------countryCode:" + countryCode); + log.writeLog("-----------------departmentName:" + departmentName); + log.writeLog("第" + (i + 1) + "条,取数据完成!"); + if (!map_dept_code_id.containsKey(departmentCode)) {//部门不存在则插入生成新部门 + rs.executeQuery("select id from hrmdepartment where outkey = ?", departmentCode); + if (rs.next()) { + String id = rs.getString("id"); + //如果找到subcompanyid1不为空,说明是顶级部门, + //String deptid = Util.null2String(map_dept_code_id.get(departmentCode));//OA部门ID + String deptid = id;//OA部门ID + if ("".equals(deptid)) { + skipNum++; + log.writeLog("cylnb deptid is null"); + deptMap.put(departmentCode, superiorDepartment); + //continue; + } + if (!"".equals(subcompanyid1)) { + supdepid = "0"; + } + if (!"".equals(supdepid) && "".equals(subcompanyid1)) { + log.writeLog("开始取部门" + departmentCode + "上级分部id:" + supdepid + "。"); + subcompanyid1 = getSubId(map_dept_id_data, supdepid); + log.writeLog("结束取部门" + departmentCode + "上级分部id:" + supdepid + "。取到的分部id:" + subcompanyid1); + if ("".equals(subcompanyid1)) { + log.writeLog("----------------分部id找不到"); + deptMap.put(departmentCode, superiorDepartment); + } + } + String updateStr = ""; + //只有有值才覆盖 + updateStr += !"".equals(subcompanyid1) ? "subcompanyid1 = '" + subcompanyid1 + "', " : ""; + updateStr += !"".equals(supdepid) ? "supdepid = '" + supdepid + "', " : ""; + updateStr += !"".equals(bmfzr) ? "bmfzr = '" + bmfzr + "', " : ""; + updateStr += !"".equals(bmfgld) ? "bmfgld = '" + bmfgld + "', " : ""; + sql = "update HrmDepartment set " + + "departmentname = '" + departmentName + "', " + + "departmentmark = '" + departmentName + "', " + + updateStr + + "canceled = " + canceled + ", " + + "modified = to_date('" + now + "','yyyy-mm-dd hh24:mi:ss'), " + + "modifier = '1', " + + "showorder = '" + departmentOrder + "' " + + "where id= '" + deptid + "'"; + log.writeLog("更新部门表中数据sql--------->" + sql); + boolean b1 = rs.executeUpdate(sql); + log.writeLog("deptid " + deptid + " ---------是否成功:" + b1); + updateNum++; + //处理部门矩阵 + sql = "select deptid,bmfzr,bmfgld,sfzy from HrmDepartmentDefined where deptid ='" + deptid + "'"; + rs.executeQuery(sql); + if (rs.next()) { + bmfzr = !"".equals(bmfzr) ? bmfzr : Util.null2String(rs.getString("bmfzr")); + bmfgld = !"".equals(bmfgld) ? bmfgld : Util.null2String(rs.getString("bmfgld")); + sql = "update HrmDepartmentDefined set " + + "bmfzr = '" + bmfzr + "' " + + ",sfzy = '" + row.getIsDirectSales() + "' " + + ",frgs= '" + companyCode + "'" + + ",bmfgld= '" + bmfgld + "'" + + ",guojia = '" + countryCode + "' " + + " where deptid = '" + deptid + "'"; + boolean b = rs.executeUpdate(sql); + log.writeLog("更新部门自定义表中数据sql--------->" + sql); + log.writeLog("deptid " + deptid + " ---------是否成功:" + b); + } else { + sql = "insert into HrmDepartmentDefined(deptid,sfzy,frgs,bmfzr,bmfgld,guojia) " + + "values('" + deptid + "'," + + "'" + row.getIsDirectSales() + "'," + + "'" + companyCode + "'," + + "'" + bmfzr + "'," + + "'" + bmfgld + ",'" + + "'" + countryCode + "')"; + boolean b = rs.executeUpdate(sql); + log.writeLog("插入部门自定义表中数据sql--------->" + sql); + log.writeLog("deptid " + deptid + " ---------是否成功:" + b); + } + //同步部门矩阵信息 + MatrixUtil.updateDepartmentData(deptid); + continue; + } + //如果找到subcompanyid1不为空,说明是顶级部门, + if (!"".equals(subcompanyid1)) { + supdepid = "0"; + } + if (!"".equals(supdepid) && "".equals(subcompanyid1)) { + log.writeLog("开始取部门:" + departmentCode + ",上级分部id:" + supdepid + "。"); + subcompanyid1 = getSubId(map_dept_id_data, supdepid); + log.writeLog("结束取部门:" + departmentCode + ",上级分部id:" + supdepid + ",取到的分部id:" + subcompanyid1); + if ("".equals(subcompanyid1)) { + log.writeLog("---------------分部id找不到:"); + deptMap.put(departmentCode, superiorDepartment); + } + } + sql = "insert into HrmDepartment (departmentname,departmentcode,departmentmark,outkey," + + "supdepid,canceled,created,creater,modified,modifier," + + "showorder,subcompanyid1,bmfzr,bmfgld) values(" + + "'" + departmentName + "'," + + "'" + departmentCode + "'," + + "'" + departmentName + "'," + + "'" + departmentCode + "'," + + "'" + supdepid + "'," + + "" + canceled + "," + + "to_date('" + now + "','yyyy-mm-dd hh24:mi:ss')," + + "'1'," + + "to_date('" + now + "','yyyy-mm-dd hh24:mi:ss')," + + "'1'," + + "'" + departmentOrder + "'," + + "'" + subcompanyid1 + "', " + + "'" + bmfzr + "', " + + "'" + bmfgld + "')"; + log.writeLog("插入部门表生成新数据sql--------->" + sql); + rs.executeUpdate(sql); + insertNum++; + rs.executeQuery("select id from HrmDepartment where departmentcode = ?", departmentCode); + int maxDeptID = 0;//新插入数据的部门ID + if (rs.next()) { + maxDeptID = rs.getInt("id"); + //将新增加的部门加入至MAP中 + map_dept_code_id.put(departmentCode, maxDeptID + ""); + Map map1 = new HashMap<>(); + map1.put("outkey", departmentCode); + map1.put("supdepid", supdepid); + map1.put("subcompanyid1", subcompanyid1); + log.writeLog("maxDeptID--------->" + maxDeptID + ",size:" + map_dept_id_data.size()); + map_dept_id_data.put(maxDeptID + "", map1); + } + //新增数据,插入到部门自定义表HrmDepartmentDefined中 + sql = "insert into HrmDepartmentDefined(deptid,sfzy,frgs,bmfzr,bmfgld,guojia) " + + "values('" + maxDeptID + "'," + + "'" + row.getIsDirectSales() + "'," + + "'" + companyCode + "'," + + "'" + bmfzr + "'," + + "'" + bmfgld + "'," + + "'" + countryCode + "')"; + boolean b = rs.executeUpdate(sql); + log.writeLog("插入部门自定义表中数据sql--------->" + sql); + log.writeLog("deptid " + maxDeptID + " ---------是否成功:" + b); + //同步部门矩阵信息 + MatrixUtil.updateDepartmentData(maxDeptID + ""); +// //将新增加的人员自定义信息加入至MAP中 +// map_dept_id_defined.put(maxDeptID + "", maxDeptID + ""); +// //将部门与所属分部对应关系放到map中 +// map_deptid_subcompanyid.put(maxDeptID + "", subcompanyid1); + } else {//部门存在则更新 + //如果找到subcompanyid1不为空,说明是顶级部门, + String deptid = Util.null2String(map_dept_code_id.get(departmentCode));//OA部门ID + if ("".equals(deptid)) { + skipNum++; + log.writeLog("cylnb deptid is null"); + deptMap.put(departmentCode, superiorDepartment); + //continue; + } + if (!"".equals(subcompanyid1)) { + supdepid = "0"; + } + if (!"".equals(supdepid) && "".equals(subcompanyid1)) { + log.writeLog("开始取部门" + departmentCode + "上级分部id:" + supdepid + "。"); + subcompanyid1 = getSubId(map_dept_id_data, supdepid); + log.writeLog("结束取部门" + departmentCode + "上级分部id:" + supdepid + "。取到的分部id:" + subcompanyid1); + if ("".equals(subcompanyid1)) { + log.writeLog("----------------分部id找不到"); + deptMap.put(departmentCode, superiorDepartment); + } + } + String updateStr = ""; + //只有有值才覆盖 + updateStr += !"".equals(subcompanyid1) ? "subcompanyid1 = '" + subcompanyid1 + "', " : ""; + updateStr += !"".equals(supdepid) ? "supdepid = '" + supdepid + "', " : ""; + updateStr += !"".equals(bmfzr) ? "bmfzr = '" + bmfzr + "', " : ""; + updateStr += !"".equals(bmfgld) ? "bmfgld = '" + bmfgld + "', " : ""; + sql = "update HrmDepartment set " + + "departmentname = '" + departmentName + "', " + + "departmentmark = '" + departmentName + "', " + + updateStr + + "canceled = " + canceled + ", " + + "modified = to_date('" + now + "','yyyy-mm-dd hh24:mi:ss'), " + + "modifier = '1', " + + "showorder = '" + departmentOrder + "' " + + "where id= '" + deptid + "'"; + log.writeLog("更新部门表中数据sql--------->" + sql); + boolean b1 = rs.executeUpdate(sql); + log.writeLog("deptid " + deptid + " ---------是否成功:" + b1); + // map_dept_code_id.put(departmentCode, deptid + ""); + Map map1 = new HashMap<>(); + map1.put("outkey", departmentCode); + map1.put("supdepid", supdepid); + map1.put("subcompanyid1", subcompanyid1); + log.writeLog("update-maxDeptID--------->" + deptid + ",size:" + map_dept_id_data.size()); + map_dept_id_data.put(deptid + "", map1); + updateNum++; + //处理部门矩阵 + sql = "select deptid,bmfzr,bmfgld,sfzy from HrmDepartmentDefined where deptid ='" + deptid + "'"; + rs.executeQuery(sql); + if (rs.next()) { + bmfzr = !"".equals(bmfzr) ? bmfzr : Util.null2String(rs.getString("bmfzr")); + bmfgld = !"".equals(bmfgld) ? bmfgld : Util.null2String(rs.getString("bmfgld")); + sql = "update HrmDepartmentDefined set " + + "bmfzr = '" + bmfzr + "' " + + ",sfzy = '" + row.getIsDirectSales() + "' " + + ",frgs= '" + companyCode + "'" + + ",bmfgld= '" + bmfgld + "'" + + ",guojia = '" + countryCode + "' " + + " where deptid = '" + deptid + "'"; + boolean b = rs.executeUpdate(sql); + log.writeLog("更新部门自定义表中数据sql--------->" + sql); + log.writeLog("deptid " + deptid + " ---------是否成功:" + b); + } else { + sql = "insert into HrmDepartmentDefined(deptid,sfzy,frgs,bmfzr,bmfgld,guojia) " + + "values('" + deptid + "'," + + "'" + row.getIsDirectSales() + "'," + + "'" + companyCode + "'," + + "'" + bmfzr + "'," + + "'" + bmfgld + ",'" + + "'" + countryCode + "')"; + boolean b = rs.executeUpdate(sql); + log.writeLog("插入部门自定义表中数据sql--------->" + sql); + log.writeLog("deptid " + deptid + " ---------是否成功:" + b); + } + //人员信息伴随部门信息变化 + if (!"".equals(subcompanyid1) && !"".equals(deptid)) { + sql = "update hrmResource set subCompanyId1='" + subcompanyid1 + "' where departmentId = '" + deptid + "' "; + rs.executeUpdate(sql); + + //更新该部门的所有下级部门的所属分部 + sql = "update hrmdepartment set subCompanyId1 = '" + subcompanyid1 + "' where exists ( \n" + + " select 1 from (" + + " select id from hrmdepartment start with id = " + deptid + " connect by supdepid = prior id \n" + + " ) s where s.id = hrmdepartment.id \n" + + ")"; + + rs.executeUpdate(sql); + } + //同步部门矩阵信息 + MatrixUtil.updateDepartmentData(deptid); + } + } + + +// for (int i = 0; i < departments.size(); i++) { +// DepartmentDto row = departments.get(i); +// String departmentCode = Util.null2String(row.getDepartmentCode());//部门编码 +// String superiorDepartment = Util.null2String(row.getSuperiorDepartment());//上级部门编码 +// String parId = ""; +// rs.executeQuery("select * from HRMDEPARTMENT where outkey = ?",superiorDepartment); +// if(rs.next()){ +// parId = rs.getString("id"); +// } +// rs.executeUpdate("update HRMDEPARTMENT set supdepid = ? where outkey = ?",parId,departmentCode); +// } + + log.writeLog("此次同步部门总数为:" + departments.size() + ",新增部门数为:" + insertNum + + ",更新部门数为:" + updateNum + ",跳出处理部门数为:" + skipNum); + log.writeLog("此次同步部门跳过是数据为:" + JSON.toJSONString(skipList)); + + + log.writeLog("----sta:" + deptMap.size()); + int size = deptMap.size(); + int lastCount = deptMap.size(); + for (int i = 0; i < size; i++) { + if (deptMap.size() == 0) { + break; + } + log.writeLog("---------------当前正在执行第" + i + "次,本次剩余" + deptMap.size() + "条部门待处理"); + setSup(); + if (lastCount <= deptMap.size()) { + log.writeLog("---------------异常,有" + deptMap.size() + "条部门无分部的数据异常"); + break; + } else { + lastCount = deptMap.size(); + } + } + log.writeLog("----end"); + + + //更新部门缓存 + DepartmentComInfo dci = new DepartmentComInfo(); + dci.removeCompanyCache(); + + //释放map内存 + map_dept_id_data.clear(); + map_dept_id_data = null; + map_dept_code_id.clear(); + map_dept_code_id = null; + map_user_code_id.clear(); + map_user_code_id = null; + + //更新同步时间到中间表 + String sql1 = "update uf_HRRestDate set sctbsj ='" + now + "' where jkm = '/dcopenedi/hrDept/pageByUpdateTime'"; + rs.executeUpdate(sql1); + + } catch (Exception e) { + log.writeLog("--------------------Exception:" + JavaUtil.getExceptionDetail(e)); + e.printStackTrace(); + } + return rtMap; + } + + + public void setSup() { + RecordSet rss = new RecordSet(); + Set keySet = deptMap.keySet(); + Iterator it = keySet.iterator(); + while (it.hasNext()) { + try { + String deptCode = (String) it.next(); + String supCode = String.valueOf(deptMap.get(deptCode)); + String SUPDEPID = ""; + String SUBCOMPANYID1 = ""; + rss.executeQuery("select * from hrmdepartment where departmentcode = ?", supCode); + if (rss.next()) { + SUPDEPID = rss.getString("id"); + SUBCOMPANYID1 = rss.getString("SUBCOMPANYID1"); + if (SUBCOMPANYID1 != null && !"".equals(SUBCOMPANYID1)) { + rss.executeUpdate("update hrmdepartment set SUPDEPID = ? ,SUBCOMPANYID1 = ? where departmentcode = ? ", SUPDEPID, SUBCOMPANYID1, deptCode); + it.remove(); + } + log.writeLog("-----------------已补处理部门code:" + deptCode + ",分部id:" + SUBCOMPANYID1); + } + } catch (Exception e) { + log.writeLog("--------------------Exception:" + JavaUtil.getExceptionDetail(e)); + } + } + + } + + + /** + * 匹配部门id,关联的上级部门,所属分部 map + * + * @return + */ + private Map> getDeptDataMap() { + RecordSet rs = new RecordSet(); + Map> map = new HashMap<>(); + rs.executeQuery("select id, outkey,supdepid,subcompanyid1 from HrmDepartment where (CANCELED!=1 or CANCELED is null)"); + while (rs.next()) { + Map map1 = new HashMap<>(); + map1.put("outkey", rs.getString("outkey")); + map1.put("supdepid", rs.getString("supdepid")); + map1.put("subcompanyid1", rs.getString("subcompanyid1")); + map.put(rs.getString("id"), map1); + } + return map; + } + + /** + * 根据部门id匹配所属分部 + * + * @return + */ + public String getSubId(Map> map_dept_id_data, String deptId) { + String subcompanyid = ""; + if (!map_dept_id_data.containsKey(deptId)) { + return ""; + } + Map map = map_dept_id_data.get(deptId); + subcompanyid = map.get("subcompanyid1"); + return subcompanyid; + } +// /** +// * 获取部门编码和上级分部的集合 +// * +// * @return +// */ +// public Map getDeptComMap() { +// RecordSet rs = new RecordSet(); +// Map map = new HashMap<>(); +// rs.executeQuery("select outkey,supdepid from HrmDepartment where outkey is not null and (CANCELED!=1 or CANCELED is null)"); +// while (rs.next()) { +// map.put(rs.getString("outkey"), rs.getString("supdepid")); +// } +// return map; +// } + + private Map getAllDepartmentCodeIdMap() { + RecordSet rs = new RecordSet(); + Map map = new HashMap<>(); + rs.executeQuery("select departmentcode,outkey,id from HrmDepartment where outkey is not null"); + while (rs.next()) { + map.put(rs.getString("outkey"), rs.getString("id")); + } + return map; + } + + public Map getDepartmentCodeIdMap() { + RecordSet rs = new RecordSet(); + Map map = new HashMap<>(); + rs.executeQuery("select departmentcode,outkey,id from HrmDepartment where outkey is not null and (CANCELED!=1 or CANCELED is null)"); + while (rs.next()) { + map.put(rs.getString("outkey"), rs.getString("id")); + } + return map; + } + + + /** + * 获取印尼部门数据 + * + * @param date 时间 + * @param point + * @return + */ + public JSONArray getOcDepartments(String date, String point) { + int current = 1, size = 5000, pages = 2; + String url = HttpClientToJT.baseUrl + "/dcopenedi/hrDept/pageNewHrDeptByUpdateTime"; + String token = HttpClientToJT.getToken(); + log.writeLog("-------token--------->" + token); + Map params = new HashMap<>(); + List list1 = new ArrayList(); + list1.add("ZHS"); + params.put("languageCds", list1); + params.put("countryCode", "IDN"); + params.put("updateTime", date); + params.put("point", point); + params.put("size", size); + log.writeLog("传入JSON--------------->" + JSON.toJSONString(params)); + String s = HttpClientToJT.sendPost(url, token, JSONObject.toJSONString(params)); + JSONObject jsonObject = JSONObject.parseObject(s); + JSONArray jsonArray = new JSONArray(); + + String code = Util.null2String(jsonObject.getString("code")); + log.writeLog("code------>" + code); + if ("1".equals(code)) { + JSONObject result = jsonObject.getJSONObject("data"); + JSONArray records = result.getJSONArray("records"); + Object hasNextPage = result.get("hasNextPage"); + jsonArray.addAll(records); + //下次继续传 + maxPoint = result.get("maxPoint").toString(); + if ("false".equals(hasNextPage.toString())) { + ifPage = false; + } + + Object directSales = jsonArray.stream().filter(item -> { + JSONObject itemJson = JSONObject.parseObject(JSON.toJSONString(item)); + return "IDN".equals(itemJson.getString("countryCode")); + }).collect(Collectors.toList()); + jsonArray = JSONArray.parseArray(JSON.toJSONString(directSales)); + } + + return jsonArray; + } + + /** + * 获取海外部门国家数据 + * + * @param date 时间 + * @param point + * @return + */ + public JSONArray getOcDepartmentsGUOJIA(String date, String point, String guojia, String departmentCode) { + int current = 1, size = 5000, pages = 2; + String url = HttpClientToJT.baseUrl + "/dcopenedi/hrDept/pageNewHrDeptByUpdateTime"; + String token = HttpClientToJT.getToken(); + log.writeLog("-------token--------->" + token); + Map params = new HashMap<>(); + List list1 = new ArrayList(); + list1.add(guojia); + params.put("languageCds", list1); + params.put("updateTime", date); + params.put("point", point); + params.put("size", size); + params.put("deptCode", departmentCode); + log.writeLog("传入JSON--------------->" + JSON.toJSONString(params)); + String s = HttpClientToJT.sendPost(url, token, JSONObject.toJSONString(params)); + JSONObject jsonObject = JSONObject.parseObject(s); + JSONArray jsonArray = new JSONArray(); + + String code = Util.null2String(jsonObject.getString("code")); + log.writeLog("code------>" + code); + if ("1".equals(code)) { + JSONObject result = jsonObject.getJSONObject("data"); + JSONArray records = result.getJSONArray("records"); + Object hasNextPage = result.get("hasNextPage"); + jsonArray.addAll(records); +// //下次继续传 +// maxPoint = result.get("maxPoint").toString(); +// if ("false".equals(hasNextPage.toString())) { +// ifPage = false; +// } + + Object directSales = jsonArray.stream().filter(item -> { + JSONObject itemJson = JSONObject.parseObject(JSON.toJSONString(item)); + return !"CHN".equals(itemJson.getString("countryCode")); + }).collect(Collectors.toList()); + jsonArray = JSONArray.parseArray(JSON.toJSONString(directSales)); + } + + return jsonArray; + } + + + /** + * 获取多语言 + * + * @param date 时间 + * @param countryCode 国家code + * @param departmentCode 部门code + * @param deptName 部门中文名称 + * @return 多语言名称 + */ + public String getDepartmentName(String date, String countryCode, String departmentCode, String deptName) { + String retName = ""; + boolean existence = true; + String language = ""; + String cdIndex = ""; + try { + if ("CHN".equals(countryCode)) { + language = "ZHS"; + } + if ("BRA".equals(countryCode)) { + language = "POR"; + cdIndex = "21"; + } + + if ("SAU".equals(countryCode) || "ARE".equals(countryCode) + || "EGY".equals(countryCode) + || "MEX".equals(countryCode) + || "SGP".equals(countryCode) + || "PHL".equals(countryCode) + || "MYS".equals(countryCode) + || "KHM".equals(countryCode) + ) { + existence = false; + language = "ENG"; + } + // 、 • 7中°~^8英文、心‘9繁体、• ~‘14 越南°~17泰国°~‘21 葡萄牙‘~‘22 印尼 + if ("IDN".equals(countryCode)) { + language = "IDN"; + cdIndex = "22"; + } + if ("THA".equals(countryCode)) { + language = "THA"; + cdIndex = "17"; + } + if ("VNM".equals(countryCode)) { + language = "VIE"; + cdIndex = "14"; + } + + String country = ""; + // 日期 位置 国家 部门code + JSONArray ocDepartmentsGUOJIA = getOcDepartmentsGUOJIA(date, "1", language, departmentCode); + List countryList = JSONArray.parseArray(ocDepartmentsGUOJIA.toJSONString(), DepartmentDto.class); + DepartmentDto countryDto = countryList.get(0); + //对应国家的语言名称(对应国家标签里面) + String countryDepartmentName = countryDto.getDepartmentName(); + log.writeLog("---------------对应国家语言名称:" + countryDepartmentName); + + //departmentName = + if (existence) { + //需要3个标签 + retName = "~`~`7 " + deptName + "`~`8 " + countryDepartmentName + "`~`" + cdIndex + " " + countryDepartmentName + "`~`~"; + } else { + //只需要中文和英文 + retName = "~`~`7 " + deptName + "`~`8 " + countryDepartmentName + "`~`~"; + } + + log.writeLog("---------------多语言名称:" + retName); + } catch (Exception e) { + e.printStackTrace(); + } + return retName; + } + + + private void writeFile(JSONArray jsonArray) { + BufferedWriter bw = null; + try { + bw = new BufferedWriter(new FileWriter("D:\\2.txt")); + //一次写一行 + bw.write(jsonArray.toJSONString()); + bw.newLine(); //换行用 + //关闭流 + bw.close(); + } catch (IOException e) { + e.printStackTrace(); + } + System.out.println("写入成功"); + } + +} diff --git a/src/main/youhong_ai_jitu_src/jntchina/schedule/hrm/idn/SynHrmdepartmentToOAIDNOld.java b/src/main/youhong_ai_jitu_src/jntchina/schedule/hrm/idn/SynHrmdepartmentToOAIDNOld.java new file mode 100644 index 0000000..6580085 --- /dev/null +++ b/src/main/youhong_ai_jitu_src/jntchina/schedule/hrm/idn/SynHrmdepartmentToOAIDNOld.java @@ -0,0 +1,807 @@ +package jntchina.schedule.hrm.idn; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.JSONArray; +import com.alibaba.fastjson.JSONObject; +import com.api.integration.util.JavaUtil; +import jntchina.schedule.hrm.SyncHrmdepartmentToOA; +import jntchina.schedule.hrm.SyncHrmresourceToOA; +import jntchina.schedule.hrm.entity.DepartmentDto; +import jntchina.util.HttpClientToJT; +import selfdev.util.base.TimeCommonUtil; +import selfdev.util.log.LogTool; +import weaver.conn.RecordSet; +import weaver.general.Util; +import weaver.hrm.company.DepartmentComInfo; +import weaver.matrix.MatrixUtil; + +import java.io.BufferedWriter; +import java.io.FileWriter; +import java.io.IOException; +import java.util.*; +import java.util.stream.Collectors; + +public class SynHrmdepartmentToOAIDNOld { + + Map deptMap = new HashMap<>(); + + + //分页接口参数 + String maxPoint = "1"; + //接口是否有下一页 默认为有 + boolean ifPage = true; + + + //部门编码和id map + Map map_dept_code_id = new HashMap(); + private LogTool log = new LogTool("/log/hrm/IDN/dept/", false); + + //60里面是否还有分部 + boolean ifExistenceSub = true; + + //所有10分部的上级 + List subList = new ArrayList(); + + + //存放60分部 + List list60 = new ArrayList(); + + + public void ScreenSub(Map supSubMap) { + try { + boolean ifSub = false; + Set keySet = supSubMap.keySet(); + Iterator it = keySet.iterator(); + while (it.hasNext()) { + //60的key + String deptCode = (String) it.next(); + if (subList.contains(deptCode)) { + ifSub = true; + String supDeptCode = String.valueOf(supSubMap.get(deptCode)); + //60的value + list60.add(deptCode); + subList.add(supDeptCode); + supSubMap.remove(deptCode); + } + } + ifExistenceSub = ifSub; + } catch (Exception e) { + e.printStackTrace(); + } + } + + + /** + * 同步分部、部门数据 + * 注:对方整个组织数不区分部门和分部,全部用部门接口数据,用类型区分 + */ + public Map> execute(String date) { + Map> rtMap = new HashMap<>(); + try { + String now = TimeCommonUtil.obtainDate(0); + //匹配部门id,关联的上级部门,所属分部 map + Map> map_dept_id_data = new HashMap<>(); + map_dept_id_data = getDeptDataMap(); +// log.writeLog("字典:"+JSON.toJSONString(map_dept_id_data)); + map_dept_code_id = getAllDepartmentCodeIdMap(); + SyncHrmsubcompanyToOAIDN hrmsubcompany = new SyncHrmsubcompanyToOAIDN(); + SyncHrmresourceToOA hrmresource = new SyncHrmresourceToOA(); + //人员map,用于匹配上级领导 + Map map_user_code_id = hrmresource.getUserCodeIdMap(); + //拆分数据、organizationClass 10类型是组织,其他类型当部门,【代理区】在对方那是虚拟部门,特殊处理划分为OA 分部 + //JSONArray data = getDepartments(date); + //JSONArray ocData = getOcDepartments(date); + + JSONArray ocData = new JSONArray(); + while (ifPage) { + ocData.addAll(getOcDepartments(date, maxPoint)); + } + + //key为60自己,value为上级 + Map supSubMap = new HashMap<>(); + + Object directSales = ocData.stream().filter(item -> { + JSONObject itemJson = JSONObject.parseObject(JSON.toJSONString(item)); + if ("10".equals(itemJson.getString("organizationClass"))) { + subList.add(itemJson.getString("superiorDepartment")); + } + if ("60".equals(itemJson.getString("organizationClass"))) { + //key为60自己,value为上级 + supSubMap.put(itemJson.getString("departmentCode"), itemJson.getString("superiorDepartment")); + } + return !"10".equals(itemJson.getString("organizationClass")); + }).collect(Collectors.toList()); + + while (ifExistenceSub) { + ScreenSub(supSubMap); + } + + List dataList = JSONArray.parseArray(ocData.toJSONString(), DepartmentDto.class); + log.writeLog("-----------------全部长度:" + dataList.size()); + + //分部数据 + List subcompanys = dataList.stream().filter(item -> { + //return "10".equals(item.getOrganizationClass()) || "60".equals(item.getOrganizationClass()); + return "10".equals(item.getOrganizationClass()) || ("60".equals(item.getOrganizationClass()) && list60.contains(item.getDepartmentCode())); + }).collect(Collectors.toList()); + //部门数据 注意:10000300代理区编码 + List departments = dataList.stream().filter(item -> { + return "20".equals(item.getOrganizationClass()) + || "30".equals(item.getOrganizationClass()) + || "40".equals(item.getOrganizationClass()) + || "50".equals(item.getOrganizationClass()) + || ("60".equals(item.getOrganizationClass()) && !list60.contains(item.getDepartmentCode())); + }).collect(Collectors.toList()); + log.writeLog("-----------------分部长度:" + subcompanys.size()); + log.writeLog("-----------------部门长度:" + departments.size()); + + rtMap.put("department", departments); + //处理分部同步逻辑 + List execute = hrmsubcompany.execute(subcompanys, departments); + //departments = execute; + Map map_subcompany_code_id = hrmsubcompany.getSubCodeIdMap(); + //处理部门同步逻辑 + RecordSet rs = new RecordSet(); + int skipNum = 0, insertNum = 0, updateNum = 0; + List skipList = new ArrayList<>(); + log.writeLog("----------开始同步部门,条数:" + departments.size()); + //log.writeLog("----------同步部门源数据:" + JSON.toJSONString(departments)); + // 处理部门同步逻辑 1.未匹配到分部,不新增, + for (int i = 0; i < departments.size(); i++) { + DepartmentDto row = departments.get(i); + String countryCode = Util.null2String(row.getCountryCode());//国家 + String departmentCode = Util.null2String(row.getDepartmentCode());//部门编码 + String departmentName = Util.null2String(row.getDepartmentName());//部门全称 + String shortName = Util.null2String(row.getDepartmentAbbreviation());//部门简称 + String superiorDepartment = Util.null2String(row.getSuperiorDepartment());//上级部门编码 + String departmentOrder = Util.null2String(row.getDepartmentOrder());//排序 + String deptManager = Util.null2String(row.getDeptManager());//部门负责人code + String brchLeader = Util.null2String(row.getBrchLeader());//分管领导code + Integer canceled = Util.null2String(row.getStatus()).equals("3") ? 1 : null;//1 新增 2 修改 3作废 + String companyCode = Util.null2String(row.getCompanyCode());// 公司 +// String companyName = Util.null2String(row.getCompanyName());//公司名称 + if ("".equals(superiorDepartment)) { + skipList.add(row); + log.writeLog("cylnb superiorDepartment is null:" + superiorDepartment); + skipNum++; + deptMap.put(departmentCode, superiorDepartment); + // continue; + } + //各种code转id + String bmfzr = Util.null2String(map_user_code_id.get(deptManager));//部门负责人 + String bmfgld = Util.null2String(map_user_code_id.get(brchLeader));//分管领导 + String subcompanyid1 = Util.null2String(map_subcompany_code_id.get(superiorDepartment));//分部ID + String supdepid = Util.null2String(map_dept_code_id.get(superiorDepartment));//获取上级ID + log.writeLog("------------subcompanyid1:" + subcompanyid1 + "-----deptCode:" + departmentCode + ",status:" + row.getStatus() + ",canceled:" + canceled + "-------"); + log.writeLog("------------supdepid:" + supdepid + "----deptCode:" + departmentCode + ",status:" + row.getStatus() + ",canceled:" + canceled + "--------"); + //如果上级编码为空、所属分部,上级部门都找不到,不作处理 + if ("".equals(superiorDepartment) || ("".equals(subcompanyid1) && "".equals(supdepid))) { + skipList.add(row); + skipNum++; + log.writeLog("cylnb 上级编码为空、所属分部,上级部门都找不到,不作处理deptcode:" + departmentCode + ";supcode:" + superiorDepartment); + deptMap.put(departmentCode, superiorDepartment); + //continue; + } + String sql = ""; + //判断HR部门ID是否已经存在 + + String status = row.getStatus(); + if (!"3".equals(status)) { + log.writeLog("---------------国家:" + countryCode); + departmentName = getDepartmentName(date, countryCode, departmentCode, departmentName); + } else { + log.writeLog("----------------状态为3"); + } + + if ("".equals(departmentName)) { + log.writeLog("----------------多语言为空"); + departmentName = row.getDepartmentName(); + } + + log.writeLog("-----------------countryCode:" + countryCode); + log.writeLog("-----------------departmentName:" + departmentName); + log.writeLog("第" + (i + 1) + "条,取数据完成!"); + if (!map_dept_code_id.containsKey(departmentCode)) {//部门不存在则插入生成新部门 + rs.executeQuery("select id from hrmdepartment where outkey = ?", departmentCode); + if (rs.next()) { + String id = rs.getString("id"); + //如果找到subcompanyid1不为空,说明是顶级部门, + //String deptid = Util.null2String(map_dept_code_id.get(departmentCode));//OA部门ID + String deptid = id;//OA部门ID + if ("".equals(deptid)) { + skipNum++; + log.writeLog("cylnb deptid is null"); + deptMap.put(departmentCode, superiorDepartment); + //continue; + } + if (!"".equals(subcompanyid1)) { + supdepid = "0"; + } + if (!"".equals(supdepid) && "".equals(subcompanyid1)) { + log.writeLog("开始取部门" + departmentCode + "上级分部id:" + supdepid + "。"); + subcompanyid1 = getSubId(map_dept_id_data, supdepid); + log.writeLog("结束取部门" + departmentCode + "上级分部id:" + supdepid + "。取到的分部id:" + subcompanyid1); + if ("".equals(subcompanyid1)) { + log.writeLog("----------------分部id找不到"); + deptMap.put(departmentCode, superiorDepartment); + } + } + String updateStr = ""; + //只有有值才覆盖 + updateStr += !"".equals(subcompanyid1) ? "subcompanyid1 = '" + subcompanyid1 + "', " : ""; + updateStr += !"".equals(supdepid) ? "supdepid = '" + supdepid + "', " : ""; + updateStr += !"".equals(bmfzr) ? "bmfzr = '" + bmfzr + "', " : ""; + updateStr += !"".equals(bmfgld) ? "bmfgld = '" + bmfgld + "', " : ""; + sql = "update HrmDepartment set " + + "departmentname = '" + departmentName + "', " + + "departmentmark = '" + departmentName + "', " + + updateStr + + "canceled = " + canceled + ", " + + "modified = to_date('" + now + "','yyyy-mm-dd hh24:mi:ss'), " + + "modifier = '1', " + + "showorder = '" + departmentOrder + "' " + + "where id= '" + deptid + "'"; + log.writeLog("更新部门表中数据sql--------->" + sql); + boolean b1 = rs.executeUpdate(sql); + log.writeLog("deptid " + deptid + " ---------是否成功:" + b1); + updateNum++; + //处理部门矩阵 + sql = "select deptid,bmfzr,bmfgld,sfzy from HrmDepartmentDefined where deptid ='" + deptid + "'"; + rs.executeQuery(sql); + if (rs.next()) { + bmfzr = !"".equals(bmfzr) ? bmfzr : Util.null2String(rs.getString("bmfzr")); + bmfgld = !"".equals(bmfgld) ? bmfgld : Util.null2String(rs.getString("bmfgld")); + sql = "update HrmDepartmentDefined set " + + "bmfzr = '" + bmfzr + "' " + + ",sfzy = '" + row.getIsDirectSales() + "' " + + ",frgs= '" + companyCode + "'" + + ",bmfgld= '" + bmfgld + "'" + + ",guojia = '" + countryCode + "' " + + " where deptid = '" + deptid + "'"; + boolean b = rs.executeUpdate(sql); + log.writeLog("更新部门自定义表中数据sql--------->" + sql); + log.writeLog("deptid " + deptid + " ---------是否成功:" + b); + } else { + sql = "insert into HrmDepartmentDefined(deptid,sfzy,frgs,bmfzr,bmfgld,guojia) " + + "values('" + deptid + "'," + + "'" + row.getIsDirectSales() + "'," + + "'" + companyCode + "'," + + "'" + bmfzr + "'," + + "'" + bmfgld + ",'" + + "'" + countryCode + "')"; + boolean b = rs.executeUpdate(sql); + log.writeLog("插入部门自定义表中数据sql--------->" + sql); + log.writeLog("deptid " + deptid + " ---------是否成功:" + b); + } + //同步部门矩阵信息 + MatrixUtil.updateDepartmentData(deptid); + continue; + } + //如果找到subcompanyid1不为空,说明是顶级部门, + if (!"".equals(subcompanyid1)) { + supdepid = "0"; + } + if (!"".equals(supdepid) && "".equals(subcompanyid1)) { + log.writeLog("开始取部门:" + departmentCode + ",上级分部id:" + supdepid + "。"); + subcompanyid1 = getSubId(map_dept_id_data, supdepid); + log.writeLog("结束取部门:" + departmentCode + ",上级分部id:" + supdepid + ",取到的分部id:" + subcompanyid1); + if ("".equals(subcompanyid1)) { + log.writeLog("---------------分部id找不到:"); + deptMap.put(departmentCode, superiorDepartment); + } + } + sql = "insert into HrmDepartment (departmentname,departmentcode,departmentmark,outkey," + + "supdepid,canceled,created,creater,modified,modifier," + + "showorder,subcompanyid1,bmfzr,bmfgld) values(" + + "'" + departmentName + "'," + + "'" + departmentCode + "'," + + "'" + departmentName + "'," + + "'" + departmentCode + "'," + + "'" + supdepid + "'," + + "" + canceled + "," + + "to_date('" + now + "','yyyy-mm-dd hh24:mi:ss')," + + "'1'," + + "to_date('" + now + "','yyyy-mm-dd hh24:mi:ss')," + + "'1'," + + "'" + departmentOrder + "'," + + "'" + subcompanyid1 + "', " + + "'" + bmfzr + "', " + + "'" + bmfgld + "')"; + log.writeLog("插入部门表生成新数据sql--------->" + sql); + rs.executeUpdate(sql); + insertNum++; + rs.executeQuery("select id from HrmDepartment where departmentcode = ?", departmentCode); + int maxDeptID = 0;//新插入数据的部门ID + if (rs.next()) { + maxDeptID = rs.getInt("id"); + //将新增加的部门加入至MAP中 + map_dept_code_id.put(departmentCode, maxDeptID + ""); + Map map1 = new HashMap<>(); + map1.put("outkey", departmentCode); + map1.put("supdepid", supdepid); + map1.put("subcompanyid1", subcompanyid1); + log.writeLog("maxDeptID--------->" + maxDeptID + ",size:" + map_dept_id_data.size()); + map_dept_id_data.put(maxDeptID + "", map1); + } + //新增数据,插入到部门自定义表HrmDepartmentDefined中 + sql = "insert into HrmDepartmentDefined(deptid,sfzy,frgs,bmfzr,bmfgld,guojia) " + + "values('" + maxDeptID + "'," + + "'" + row.getIsDirectSales() + "'," + + "'" + companyCode + "'," + + "'" + bmfzr + "'," + + "'" + bmfgld + "'," + + "'" + countryCode + "')"; + boolean b = rs.executeUpdate(sql); + log.writeLog("插入部门自定义表中数据sql--------->" + sql); + log.writeLog("deptid " + maxDeptID + " ---------是否成功:" + b); + //同步部门矩阵信息 + MatrixUtil.updateDepartmentData(maxDeptID + ""); +// //将新增加的人员自定义信息加入至MAP中 +// map_dept_id_defined.put(maxDeptID + "", maxDeptID + ""); +// //将部门与所属分部对应关系放到map中 +// map_deptid_subcompanyid.put(maxDeptID + "", subcompanyid1); + } else {//部门存在则更新 + //如果找到subcompanyid1不为空,说明是顶级部门, + String deptid = Util.null2String(map_dept_code_id.get(departmentCode));//OA部门ID + if ("".equals(deptid)) { + skipNum++; + log.writeLog("cylnb deptid is null"); + deptMap.put(departmentCode, superiorDepartment); + //continue; + } + if (!"".equals(subcompanyid1)) { + supdepid = "0"; + } + if (!"".equals(supdepid) && "".equals(subcompanyid1)) { + log.writeLog("开始取部门" + departmentCode + "上级分部id:" + supdepid + "。"); + subcompanyid1 = getSubId(map_dept_id_data, supdepid); + log.writeLog("结束取部门" + departmentCode + "上级分部id:" + supdepid + "。取到的分部id:" + subcompanyid1); + if ("".equals(subcompanyid1)) { + log.writeLog("----------------分部id找不到"); + deptMap.put(departmentCode, superiorDepartment); + } + } + String updateStr = ""; + //只有有值才覆盖 + updateStr += !"".equals(subcompanyid1) ? "subcompanyid1 = '" + subcompanyid1 + "', " : ""; + updateStr += !"".equals(supdepid) ? "supdepid = '" + supdepid + "', " : ""; + updateStr += !"".equals(bmfzr) ? "bmfzr = '" + bmfzr + "', " : ""; + updateStr += !"".equals(bmfgld) ? "bmfgld = '" + bmfgld + "', " : ""; + sql = "update HrmDepartment set " + + "departmentname = '" + departmentName + "', " + + "departmentmark = '" + departmentName + "', " + + updateStr + + "canceled = " + canceled + ", " + + "modified = to_date('" + now + "','yyyy-mm-dd hh24:mi:ss'), " + + "modifier = '1', " + + "showorder = '" + departmentOrder + "' " + + "where id= '" + deptid + "'"; + log.writeLog("更新部门表中数据sql--------->" + sql); + boolean b1 = rs.executeUpdate(sql); + log.writeLog("deptid " + deptid + " ---------是否成功:" + b1); + // map_dept_code_id.put(departmentCode, deptid + ""); + Map map1 = new HashMap<>(); + map1.put("outkey", departmentCode); + map1.put("supdepid", supdepid); + map1.put("subcompanyid1", subcompanyid1); + log.writeLog("update-maxDeptID--------->" + deptid + ",size:" + map_dept_id_data.size()); + map_dept_id_data.put(deptid + "", map1); + updateNum++; + //处理部门矩阵 + sql = "select deptid,bmfzr,bmfgld,sfzy from HrmDepartmentDefined where deptid ='" + deptid + "'"; + rs.executeQuery(sql); + if (rs.next()) { + bmfzr = !"".equals(bmfzr) ? bmfzr : Util.null2String(rs.getString("bmfzr")); + bmfgld = !"".equals(bmfgld) ? bmfgld : Util.null2String(rs.getString("bmfgld")); + sql = "update HrmDepartmentDefined set " + + "bmfzr = '" + bmfzr + "' " + + ",sfzy = '" + row.getIsDirectSales() + "' " + + ",frgs= '" + companyCode + "'" + + ",bmfgld= '" + bmfgld + "'" + + ",guojia = '" + countryCode + "' " + + " where deptid = '" + deptid + "'"; + boolean b = rs.executeUpdate(sql); + log.writeLog("更新部门自定义表中数据sql--------->" + sql); + log.writeLog("deptid " + deptid + " ---------是否成功:" + b); + } else { + sql = "insert into HrmDepartmentDefined(deptid,sfzy,frgs,bmfzr,bmfgld,guojia) " + + "values('" + deptid + "'," + + "'" + row.getIsDirectSales() + "'," + + "'" + companyCode + "'," + + "'" + bmfzr + "'," + + "'" + bmfgld + ",'" + + "'" + countryCode + "')"; + boolean b = rs.executeUpdate(sql); + log.writeLog("插入部门自定义表中数据sql--------->" + sql); + log.writeLog("deptid " + deptid + " ---------是否成功:" + b); + } + //人员信息伴随部门信息变化 + if (!"".equals(subcompanyid1) && !"".equals(deptid)) { + sql = "update hrmResource set subCompanyId1='" + subcompanyid1 + "' where departmentId = '" + deptid + "' "; + rs.executeUpdate(sql); + + //更新该部门的所有下级部门的所属分部 + sql = "update hrmdepartment set subCompanyId1 = '" + subcompanyid1 + "' where exists ( \n" + + " select 1 from (" + + " select id from hrmdepartment start with id = " + deptid + " connect by supdepid = prior id \n" + + " ) s where s.id = hrmdepartment.id \n" + + ")"; + + rs.executeUpdate(sql); + } + //同步部门矩阵信息 + MatrixUtil.updateDepartmentData(deptid); + } + } + + +// for (int i = 0; i < departments.size(); i++) { +// DepartmentDto row = departments.get(i); +// String departmentCode = Util.null2String(row.getDepartmentCode());//部门编码 +// String superiorDepartment = Util.null2String(row.getSuperiorDepartment());//上级部门编码 +// String parId = ""; +// rs.executeQuery("select * from HRMDEPARTMENT where outkey = ?",superiorDepartment); +// if(rs.next()){ +// parId = rs.getString("id"); +// } +// rs.executeUpdate("update HRMDEPARTMENT set supdepid = ? where outkey = ?",parId,departmentCode); +// } + + log.writeLog("此次同步部门总数为:" + departments.size() + ",新增部门数为:" + insertNum + + ",更新部门数为:" + updateNum + ",跳出处理部门数为:" + skipNum); + log.writeLog("此次同步部门跳过是数据为:" + JSON.toJSONString(skipList)); + + + log.writeLog("----sta:" + deptMap.size()); + int size = deptMap.size(); + int lastCount = deptMap.size(); + for (int i = 0; i < size; i++) { + if (deptMap.size() == 0) { + break; + } + log.writeLog("---------------当前正在执行第" + i + "次,本次剩余" + deptMap.size() + "条部门待处理"); + setSup(); + if (lastCount <= deptMap.size()) { + log.writeLog("---------------异常,有" + deptMap.size() + "条部门无分部的数据异常"); + break; + } else { + lastCount = deptMap.size(); + } + } + log.writeLog("----end"); + + + //更新部门缓存 + DepartmentComInfo dci = new DepartmentComInfo(); + dci.removeCompanyCache(); + + //释放map内存 + map_dept_id_data.clear(); + map_dept_id_data = null; + map_dept_code_id.clear(); + map_dept_code_id = null; + map_user_code_id.clear(); + map_user_code_id = null; + + //更新同步时间到中间表 + String sql1 = "update uf_HRRestDate set sctbsj ='" + now + "' where jkm = '/dcopenedi/hrDept/pageByUpdateTime'"; + rs.executeUpdate(sql1); + + } catch (Exception e) { + log.writeLog("--------------------Exception:" + JavaUtil.getExceptionDetail(e)); + e.printStackTrace(); + } + return rtMap; + } + + + public void setSup() { + RecordSet rss = new RecordSet(); + Set keySet = deptMap.keySet(); + Iterator it = keySet.iterator(); + while (it.hasNext()) { + try { + String deptCode = (String) it.next(); + String supCode = String.valueOf(deptMap.get(deptCode)); + String SUPDEPID = ""; + String SUBCOMPANYID1 = ""; + rss.executeQuery("select * from hrmdepartment where departmentcode = ?", supCode); + if (rss.next()) { + SUPDEPID = rss.getString("id"); + SUBCOMPANYID1 = rss.getString("SUBCOMPANYID1"); + if (SUBCOMPANYID1 != null && !"".equals(SUBCOMPANYID1)) { + rss.executeUpdate("update hrmdepartment set SUPDEPID = ? ,SUBCOMPANYID1 = ? where departmentcode = ? ", SUPDEPID, SUBCOMPANYID1, deptCode); + it.remove(); + } + log.writeLog("-----------------已补处理部门code:" + deptCode + ",分部id:" + SUBCOMPANYID1); + } + } catch (Exception e) { + log.writeLog("--------------------Exception:" + JavaUtil.getExceptionDetail(e)); + } + } + + } + + + /** + * 匹配部门id,关联的上级部门,所属分部 map + * + * @return + */ + private Map> getDeptDataMap() { + RecordSet rs = new RecordSet(); + Map> map = new HashMap<>(); + rs.executeQuery("select id, outkey,supdepid,subcompanyid1 from HrmDepartment where (CANCELED!=1 or CANCELED is null)"); + while (rs.next()) { + Map map1 = new HashMap<>(); + map1.put("outkey", rs.getString("outkey")); + map1.put("supdepid", rs.getString("supdepid")); + map1.put("subcompanyid1", rs.getString("subcompanyid1")); + map.put(rs.getString("id"), map1); + } + return map; + } + + /** + * 根据部门id匹配所属分部 + * + * @return + */ + public String getSubId(Map> map_dept_id_data, String deptId) { + String subcompanyid = ""; + if (!map_dept_id_data.containsKey(deptId)) { + return ""; + } + Map map = map_dept_id_data.get(deptId); + subcompanyid = map.get("subcompanyid1"); + return subcompanyid; + } +// /** +// * 获取部门编码和上级分部的集合 +// * +// * @return +// */ +// public Map getDeptComMap() { +// RecordSet rs = new RecordSet(); +// Map map = new HashMap<>(); +// rs.executeQuery("select outkey,supdepid from HrmDepartment where outkey is not null and (CANCELED!=1 or CANCELED is null)"); +// while (rs.next()) { +// map.put(rs.getString("outkey"), rs.getString("supdepid")); +// } +// return map; +// } + + /** + * 获取当前OA系统中的所有部门信息(存在外键) + * @return 部门信息集合 + */ + private Map getAllDepartmentCodeIdMap() { + RecordSet rs = new RecordSet(); + Map map = new HashMap<>(); + rs.executeQuery("select departmentcode,outkey,id from HrmDepartment where outkey is not null"); + while (rs.next()) { + map.put(rs.getString("outkey"), rs.getString("id")); + } + return map; + } + + public Map getDepartmentCodeIdMap() { + RecordSet rs = new RecordSet(); + Map map = new HashMap<>(); + rs.executeQuery("select departmentcode,outkey,id from HrmDepartment where outkey is not null and (CANCELED!=1 or CANCELED is null)"); + while (rs.next()) { + map.put(rs.getString("outkey"), rs.getString("id")); + } + return map; + } + + + /** + * 获取印尼部门数据 + * + * @param date 时间 + * @param point + * @return + */ + public JSONArray getOcDepartments(String date, String point) { + int current = 1, size = 5000, pages = 2; + String url = HttpClientToJT.baseUrl + "/dcopenedi/hrDept/pageNewHrDeptByUpdateTime"; + String token = HttpClientToJT.getToken(); + log.writeLog("-------token--------->" + token); + Map params = new HashMap<>(); + List list1 = new ArrayList(); + list1.add("ZHS"); + params.put("languageCds", list1); + params.put("countryCode", "IDN"); + params.put("updateTime", date); + params.put("point", point); + params.put("size", size); + log.writeLog("传入JSON--------------->" + JSON.toJSONString(params)); + String s = HttpClientToJT.sendPost(url, token, JSONObject.toJSONString(params)); + JSONObject jsonObject = JSONObject.parseObject(s); + JSONArray jsonArray = new JSONArray(); + + String code = Util.null2String(jsonObject.getString("code")); + log.writeLog("code------>" + code); + if ("1".equals(code)) { + JSONObject result = jsonObject.getJSONObject("data"); + JSONArray records = result.getJSONArray("records"); + Object hasNextPage = result.get("hasNextPage"); + jsonArray.addAll(records); + //下次继续传 + maxPoint = result.get("maxPoint").toString(); + if ("false".equals(hasNextPage.toString())) { + ifPage = false; + } + + Object directSales = jsonArray.stream().filter(item -> { + JSONObject itemJson = JSONObject.parseObject(JSON.toJSONString(item)); + return "IDN".equals(itemJson.getString("countryCode")); + }).collect(Collectors.toList()); + jsonArray = JSONArray.parseArray(JSON.toJSONString(directSales)); + } + + return jsonArray; + } + + /** + * 获取海外部门国家数据 + * + * @param date 时间 + * @param point + * @return + */ + public JSONArray getOcDepartmentsGUOJIA(String date, String point, String guojia, String departmentCode) { + int current = 1, size = 5000, pages = 2; + String url = HttpClientToJT.baseUrl + "/dcopenedi/hrDept/pageNewHrDeptByUpdateTime"; + String token = HttpClientToJT.getToken(); + log.writeLog("-------token--------->" + token); + Map params = new HashMap<>(); + List list1 = new ArrayList(); + list1.add(guojia); + params.put("languageCds", list1); + params.put("updateTime", date); + params.put("point", point); + params.put("size", size); + params.put("deptCode", departmentCode); + log.writeLog("传入JSON--------------->" + JSON.toJSONString(params)); + String s = HttpClientToJT.sendPost(url, token, JSONObject.toJSONString(params)); + JSONObject jsonObject = JSONObject.parseObject(s); + JSONArray jsonArray = new JSONArray(); + + String code = Util.null2String(jsonObject.getString("code")); + log.writeLog("code------>" + code); + if ("1".equals(code)) { + JSONObject result = jsonObject.getJSONObject("data"); + JSONArray records = result.getJSONArray("records"); + Object hasNextPage = result.get("hasNextPage"); + jsonArray.addAll(records); +// //下次继续传 +// maxPoint = result.get("maxPoint").toString(); +// if ("false".equals(hasNextPage.toString())) { +// ifPage = false; +// } + + Object directSales = jsonArray.stream().filter(item -> { + JSONObject itemJson = JSONObject.parseObject(JSON.toJSONString(item)); + return !"CHN".equals(itemJson.getString("countryCode")); + }).collect(Collectors.toList()); + jsonArray = JSONArray.parseArray(JSON.toJSONString(directSales)); + } + + return jsonArray; + } + + + /** + * 获取多语言 + * + * @param date 时间 + * @param countryCode 国家code + * @param departmentCode 部门code + * @param deptName 部门中文名称 + * @return 多语言名称 + */ + public String getDepartmentName(String date, String countryCode, String departmentCode, String deptName) { + String retName = ""; + boolean existence = true; + String language = ""; + String cdIndex = ""; + try { + if ("CHN".equals(countryCode)) { + language = "ZHS"; + } + if ("BRA".equals(countryCode)) { + language = "POR"; + cdIndex = "21"; + } + + if ("SAU".equals(countryCode) || "ARE".equals(countryCode) + || "EGY".equals(countryCode) + || "MEX".equals(countryCode) + || "SGP".equals(countryCode) + || "PHL".equals(countryCode) + || "MYS".equals(countryCode) + || "KHM".equals(countryCode) + ) { + existence = false; + language = "ENG"; + } + // 、 • 7中°~^8英文、心‘9繁体、• ~‘14 越南°~17泰国°~‘21 葡萄牙‘~‘22 印尼 + if ("IDN".equals(countryCode)) { + language = "IDN"; + cdIndex = "22"; + } + if ("THA".equals(countryCode)) { + language = "THA"; + cdIndex = "17"; + } + if ("VNM".equals(countryCode)) { + language = "VIE"; + cdIndex = "14"; + } + + String country = ""; + // 日期 位置 国家 部门code + JSONArray ocDepartmentsGUOJIA = getOcDepartmentsGUOJIA(date, "1", language, departmentCode); + List countryList = JSONArray.parseArray(ocDepartmentsGUOJIA.toJSONString(), DepartmentDto.class); + DepartmentDto countryDto = countryList.get(0); + //对应国家的语言名称(对应国家标签里面) + String countryDepartmentName = countryDto.getDepartmentName(); + log.writeLog("---------------对应国家语言名称:" + countryDepartmentName); + + //departmentName = + if (existence) { + //需要3个标签 + retName = "~`~`7 " + deptName + "`~`8 " + countryDepartmentName + "`~`" + cdIndex + " " + countryDepartmentName + "`~`~"; + } else { + //只需要中文和英文 + retName = "~`~`7 " + deptName + "`~`8 " + countryDepartmentName + "`~`~"; + } + + log.writeLog("---------------多语言名称:" + retName); + } catch (Exception e) { + e.printStackTrace(); + } + return retName; + } + + + private void writeFile(JSONArray jsonArray) { + BufferedWriter bw = null; + try { + bw = new BufferedWriter(new FileWriter("D:\\2.txt")); + //一次写一行 + bw.write(jsonArray.toJSONString()); + bw.newLine(); //换行用 + //关闭流 + bw.close(); + } catch (IOException e) { + e.printStackTrace(); + } + System.out.println("写入成功"); + } + + + public static void main(String[] args) { +// String token = HttpClientToJT.getToken(); +// SyncHrmsubcompanyToOA hrmsubcompany = new SyncHrmsubcompanyToOA(); +// hrmsubcompany.getSubcompanys(); + SyncHrmdepartmentToOA hrmdepartment = new SyncHrmdepartmentToOA(); + JSONArray data = hrmdepartment.getDepartments("2018-08-01 00:00:00"); + // hrmdepartment.writeFile(data); +// List dataList = JSONArray.parseArray(data.toJSONString(), DepartmentDto.class); +// System.out.println(JSON.toJSONString(dataList)); +// SyncHrmjobtitlesToOA hrmjobtitles = new SyncHrmjobtitlesToOA(); +// hrmjobtitles.getJobtitles(); +// SyncHrmresourceToOA hrmresource = new SyncHrmresourceToOA(); +// JSONArray users = hrmresource.getUsers(); +// System.out.println(users); +// System.out.println(JSON.toJSONString(users)); +// JSONObject row =new JSONObject(); +// Integer status = Util.null2String(row.getInteger("status"))== "3" ? 1 : null; +// System.out.println(status); + } + + +} diff --git a/src/main/youhong_ai_jitu_src/jntchina/schedule/hrm/idn/SyncHrmjobtitlesToOAIDN.java b/src/main/youhong_ai_jitu_src/jntchina/schedule/hrm/idn/SyncHrmjobtitlesToOAIDN.java new file mode 100644 index 0000000..e09558a --- /dev/null +++ b/src/main/youhong_ai_jitu_src/jntchina/schedule/hrm/idn/SyncHrmjobtitlesToOAIDN.java @@ -0,0 +1,450 @@ +package jntchina.schedule.hrm.idn; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.JSONArray; +import com.alibaba.fastjson.JSONObject; +import jntchina.schedule.hrm.SyncHrmdepartmentToOA; +import jntchina.schedule.hrm.SyncHrmjobtitlesToOA; +import jntchina.schedule.hrm.util.OrganizationUtil; +import jntchina.schedule.hrmNew.JobTitleMultilingualUtil; +import jntchina.util.HttpClientToJT; +import selfdev.util.base.TimeCommonUtil; +import selfdev.util.log.LogTool; +import weaver.conn.RecordSet; +import weaver.general.Util; +import weaver.hrm.job.JobTitlesComInfo; + +import java.io.BufferedWriter; +import java.io.FileWriter; +import java.io.IOException; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.stream.Collectors; + +/** + * @author Cyq + * @date 2021年6月17日 02:01:51 + */ +public class SyncHrmjobtitlesToOAIDN { + + + // 分页接口参数 + static String maxPoint = "1"; + // 接口是否有下一页 默认为有 + static boolean ifPage = true; + + static int defaultPage = 0; + + // 岗位编码和id map + // Map map_jobtitle_code_id = new HashMap(); + + private final LogTool log = new LogTool("/log/hrm/IDN/job/", false); + + // 岗位编码和id map + // Map map_jobtitle_code_id = new HashMap(); + + private final JSONArray allResult = new JSONArray(); + + protected void execute(String date) { + /* ******************* 清除所有岗位信息,释放内存空间 start youhong.ai ******************* */ + allResult.clear(); + /* ******************* 清除所有岗位信息,释放内存空间 end youhong.ai ******************* */ + String now = TimeCommonUtil.obtainDate(0); + SyncHrmdepartmentToOA hrmdepartment = new SyncHrmdepartmentToOA(); + Map map_dept_code_id = hrmdepartment.getDepartmentCodeIdMap(); + // 岗位自定义建模表中的ID和编码 map + // Map map_jobtitledefined_id_code = BaseUtil.getMapKeyValueInfoByParm("uf_jobtitledefined", "", "positionid", "positioncode"); + // map_jobtitle_code_id = getJobtitleCodeIdMap(); + RecordSet rs = new RecordSet(); + log.writeLog("----------开始同步岗位-------"); + int count = 0; + int skipNum = 0, insertNum = 0, updateNum = 0; + // int page = getPages(date); + // 获取所有的岗位编码,同时将岗位编码存入List中 + List codeList = new ArrayList<>(); + // 当前库中已存在的记录集合 -- 系统岗位表 + Map sysExistMap = new HashMap<>(); + // 当前库中已存在的记录集合 -- 自定义岗位表 + Map definedExistMap = new HashMap<>(); + /* ******************* 获取所有的岗位数据 start for youhong.ai ******************* */ + + JSONArray filterResultList = new JSONArray(); + while (ifPage) { + defaultPage++; + JSONArray jobtitles = getJobsByPage(maxPoint, date); + filterResultList.addAll(jobtitles); + } + JobTitleMultilingualUtil jobTitleMultilingualUtil = new JobTitleMultilingualUtil(); + List splitArray = new ArrayList<>(); + double size = 10_000; + int sizeInt = (int) size; + int totalResultSize = allResult.size(); + int batchNum = (int) Math.ceil(totalResultSize / size); + for (int i = 0; i < batchNum; i++) { + int start = i * sizeInt; + int endIndex = start + sizeInt; + List sub = JobTitleMultilingualUtil.sub(allResult, start, endIndex); + JSONArray objects = JSONArray.parseArray(JSON.toJSONString(sub)); + splitArray.add(objects); + } + /* ******************* 获取所有的杆位数据 end for youhong.ai ******************* */ + + /* ******************* 注释原来循环获取接口数据 start for youhong.ai ******************* */ + /* while(ifPage){ + defaultPage++; + int k = defaultPage; + + JSONArray jobtitles = getJobsByPage(maxPoint,date); +*/ + /* ******************* 注释原来循环获取接口数据 end for youhong.ai ******************* */ + /* ******************* 添加循环 start for youhong.ai ******************* */ + for (int k = 0; k < splitArray.size(); k++) { + JSONArray jobtitles = splitArray.get(k); + /* ******************* 添加循环 end for youhong.ai ******************* */ + // 未获取到数据,跳出循环 + if (jobtitles == null || jobtitles.isEmpty()) { + log.writeLog("------------第【" + k + "】调用接口未获取到数据,可能是语言languageCd!=ZHS,跳出本次循环,继续下次循环"); + continue; + } + + codeList.clear(); + sysExistMap.clear(); + definedExistMap.clear(); + for (int m = 0; m < jobtitles.size(); m++) { + JSONObject row = jobtitles.getJSONObject(m); + String positionCode = Util.null2String(row.getString("positionCode"));// 岗位编码 + if (!"".equals(positionCode)) { + codeList.add(positionCode); + } + } + + if (codeList.size() > 0) { + sysExistMap = OrganizationUtil.getExitsData(codeList, 0); + definedExistMap = OrganizationUtil.getExitsData(codeList, 1); + } + + + count = count + jobtitles.size(); + log.writeLog("----------同步岗位第" + k + "页,条数:" + jobtitles.size()); + for (int i = 0; i < jobtitles.size(); i++) { + JSONObject row = jobtitles.getJSONObject(i); + String positionCode = Util.null2String(row.getString("positionCode"));// 岗位编码 + /* ******************* 多语言岗位处理 start for youhong.ai ******************* */ + String positionName = jobTitleMultilingualUtil.getMultilingual(allResult, + row, + item -> aiyh.utils.Util.null2String(item.get("positionCode")), + item -> aiyh.utils.Util.null2String(item.get("positionName")), + item -> aiyh.utils.Util.null2String(item.get("languageCd"))); + if (JobTitleMultilingualUtil.isBlank(positionName)) { + positionName = Util.null2String(row.getString("positionName")); + } + /* ******************* 多语言岗位处理 end for youhong.ai ******************* */ + // String positionName = Util.null2String(row.getString("positionName"));// 岗位名称 + log.writeLog("------------岗位名称:" + positionName); + log.writeLog("------------岗位编码:" + positionCode); + Integer canceled = "3".equals(Util.null2String(row.getString("status"))) ? 1 : 0;// 1 新增 2 修改 3作废 + String deptCode = Util.null2String(row.getString("deptCode"));// 部门编码 + String jobdepartmentid = Util.null2String(map_dept_code_id.get(deptCode));// 所属部门ID + String jobtitleid = Util.null2String(sysExistMap.get(positionCode));// OA岗位ID +// String jobactivityid ="1545";//默认职务ID + String positionabbreviation = Util.null2String(row.getString("positionAbbreviation"));// 岗位简称 + String positiontype = Util.null2String(row.getString("positionType"));// 岗位类别 + String positiontypehighest = Util.null2String(row.getString("positionTypeHighest"));// 岗位类别最高 + String positiontypelowest = Util.null2String(row.getString("positionTypeLowest"));// 岗位类别最低 + String positionpropecode = Util.null2String(row.getString("positionPropeCode"));// 岗位属性编码 + String positionpropename = Util.null2String(row.getString("positionPropeName"));// 岗位属性名称 + String companycode = Util.null2String(row.getString("companyCode"));// 公司编码 + String companyname = Util.null2String(row.getString("companyName"));// 公司名称 + String deptname = Util.null2String(row.getString("deptName"));// 部门名称 + String locationcode = Util.null2String(row.getString("locationCode"));// 地点编码 + String locationname = Util.null2String(row.getString("locationName"));// 地点描述 + String stdpositioncode = Util.null2String(row.getString("stdPositionCode"));// 标准岗位编码 + String stdpositionname = Util.null2String(row.getString("stdPositionName"));// 标准岗位名称 + String postcode = Util.null2String(row.getString("postCode"));// 岗编码 + String postname = Util.null2String(row.getString("postName"));// 岗名称 + String sequencecode = Util.null2String(row.getString("sequenceCode"));// 序列编码 + String sequencename = Util.null2String(row.getString("sequenceName"));// 序列名称 + String positiongroupcode = Util.null2String(row.getString("positionGroupCode"));// 岗族编码 + String positiongroupname = Util.null2String(row.getString("positionGroupName"));// 岗族名称 + String ethnicgroupcode = Util.null2String(row.getString("ethnicGroupCode"));// 族群编码 + String ethnicgroupname = Util.null2String(row.getString("ethnicGroupName"));// 族群名称 + + String sql = ""; + // 判断HR岗位ID是否已经存在 +// if("".equals(jobdepartmentid)){ +// skipNum++; +// continue; +// } + +// if("".equals(canceled) || canceled == null){ +// canceled = 0; +// } + + if ("".equals(Util.null2String(jobtitleid))) {// 岗位不存在则插入生成新岗位 + // 新增数据,插入到hrmjobtitles表中 + sql = "insert into hrmjobtitles (jobtitlename,jobtitlemark,outkey,jobdepartmentid," + + "canceled,created,creater,modified,modifier) values(" + + "'" + positionName + "'," + + "'" + positionName + "'," + + "'" + positionCode + "'," + + "'" + jobdepartmentid + "'," + + "" + canceled + "," + + "to_date('" + now + "','yyyy-mm-dd hh24:mi:ss')," + + "'1'," + + "to_date('" + now + "','yyyy-mm-dd hh24:mi:ss')," + + "'1')"; + log.writeLog("插入岗位表生成新数据sql--------->" + sql); + boolean executeUpdate1 = rs.executeUpdate(sql); + log.writeLog("是否成功:" + executeUpdate1); + log.writeLog("原因:" + rs.getExceptionMsg()); + insertNum++; + rs.execute("select max(id) from hrmjobtitles"); + int maxJobid = 0;// 新插入数据的岗位ID + if (rs.next()) { + maxJobid = rs.getInt(1); + // 将新增加的岗位加入至MAP中 + sysExistMap.put(positionCode, maxJobid + ""); + } + + // 新增数据,插入到hrmjobtitles表中 + sql = "insert into uf_jobtitledefined (formmodeid,modedatacreater,modedatacreatertype,modedatacreatedate,modedatacreatetime," + + "positionid,positioncode,positionname,positionabbreviation,positiontype,positiontypehighest,positiontypelowest," + + "positionpropecode,positionpropename,companycode,companyname,deptcode,deptname,locationcode,locationname,stdpositioncode," + + "stdpositionname,postcode,postname,sequencecode,sequencename,positiongroupcode,positiongroupname,ethnicgroupcode,ethnicgroupname) values" + + "(32501,1,0,to_char(sysdate, 'yyyy-MM-dd'),to_char(sysdate, 'HH24:mi:ss'),'" + maxJobid + "','" + positionCode + "','" + positionName + "'," + + "'" + positionabbreviation + "','" + positiontype + "','" + positiontypehighest + "','" + positiontypelowest + "','" + positionpropecode + "'," + + "'" + positionpropename + "','" + companycode + "','" + companyname + "','" + deptCode + "','" + deptname + "','" + locationcode + "'" + "," + + "'" + locationname + "','" + stdpositioncode + "','" + stdpositionname + "','" + postcode + "','" + postname + "','" + sequencecode + "','" + sequencename + "'," + + "'" + positiongroupcode + "','" + positiongroupname + "','" + ethnicgroupcode + "','" + ethnicgroupname + "')"; + log.writeLog("插入岗位建模自定义表生成新数据sql--------->" + sql); + boolean executeUpdate = rs.executeUpdate(sql); + log.writeLog("是否成功:" + executeUpdate); + log.writeLog("原因:" + rs.getExceptionMsg()); + // 将新增加的岗位加入至MAP中 + definedExistMap.put(maxJobid + "", positionCode); + + } else {// 岗位存在则更新 + sql = "update hrmjobtitles set " + + "jobtitlename = '" + positionName + "', " + + "jobtitlemark = '" + positionName + "', " + + "jobtitlecode = '" + positionCode + "', " + + "jobdepartmentid = '" + jobdepartmentid + "', " + + "modified = to_date('" + now + "','yyyy-mm-dd hh24:mi:ss')," + + "modifier = '1', " + + "canceled = " + canceled + " " + + "where id= '" + jobtitleid + "'"; + log.writeLog("更新岗位表中数据sql--------->" + sql); + rs.executeUpdate(sql); + updateNum++; + log.writeLog("更新岗位表---成功------>"); + + + if (definedExistMap.containsKey(jobtitleid)) {// 存在则更新岗位自定义表 + sql = "update uf_jobtitledefined set " + + "positionName = '" + positionName + "', " + + "positionabbreviation = '" + positionabbreviation + "', " + + "positiontype = '" + positiontype + "', " + + "positiontypehighest = '" + positiontypehighest + "', " + + "positiontypelowest = '" + positiontypelowest + "', " + + "positionpropecode = '" + positionpropecode + "', " + + "positionpropename = '" + positionpropename + "', " + + "companycode = '" + companycode + "', " + + "companyname = '" + companyname + "', " + + "deptCode = '" + deptCode + "', " + + "deptname = '" + deptname + "', " + + "locationcode = '" + locationcode + "', " + + "locationname = '" + locationname + "', " + + "stdpositioncode = '" + stdpositioncode + "', " + + "stdpositionname = '" + stdpositionname + "', " + + "postcode = '" + postcode + "', " + + "postname = '" + postname + "', " + + "sequencecode = '" + sequencecode + "', " + + "sequencename = '" + sequencename + "', " + + "positiongroupcode = '" + positiongroupcode + "', " + + "positiongroupname = '" + positiongroupname + "', " + + "ethnicgroupcode = '" + ethnicgroupcode + "', " + + "ethnicgroupname = '" + ethnicgroupname + "' " + + "where positionid= '" + jobtitleid + "'"; + log.writeLog("更新岗位建模自定义表中数据sql--------->" + sql); + rs.executeUpdate(sql); + + } else {// 不存在则插入岗位自定义表 + // 新增数据,插入到hrmjobtitles表中 + sql = "insert into uf_jobtitledefined (formmodeid,modedatacreater,modedatacreatertype,modedatacreatedate,modedatacreatetime," + + "positionid,positioncode,positionname,positionabbreviation,positiontype,positiontypehighest,positiontypelowest," + + "positionpropecode,positionpropename,companycode,companyname,deptcode,deptname,locationcode,locationname,stdpositioncode," + + "stdpositionname,postcode,postname,sequencecode,sequencename,positiongroupcode,positiongroupname,ethnicgroupcode,ethnicgroupname) values" + + "(32501,1,0,to_char(sysdate, 'yyyy-MM-dd'),to_char(sysdate, 'HH24:mi:ss'),'" + jobtitleid + "','" + positionCode + "','" + positionName + "'," + + "'" + positionabbreviation + "','" + positiontype + "','" + positiontypehighest + "','" + positiontypelowest + "','" + positionpropecode + "'," + + "'" + positionpropename + "','" + companycode + "','" + companyname + "','" + deptCode + "','" + deptname + "','" + locationcode + "'" + "," + + "'" + locationname + "','" + stdpositioncode + "','" + stdpositionname + "','" + postcode + "','" + postname + "','" + sequencecode + "','" + sequencename + "'," + + "'" + positiongroupcode + "','" + positiongroupname + "','" + ethnicgroupcode + "','" + ethnicgroupname + "')"; + log.writeLog("插入岗位建模自定义表生成新数据sql--------->" + sql); + rs.executeUpdate(sql); + // 将新增加的岗位加入至MAP中 + definedExistMap.put(jobtitleid + "", positionCode); + } + } + } + log.writeLog("----------同步结束岗位,第" + k + "页:" + count + + ",新增岗位数为:" + insertNum + " ,更新岗位数为:" + updateNum + ",跳出处理岗位数为:" + skipNum + "------------"); + skipNum = 0; + insertNum = 0; + updateNum = 0; + } + log.writeLog("----------同步结束岗位总数:" + count + "------------"); + // 更新岗位缓存 + JobTitlesComInfo jtci = new JobTitlesComInfo(); + jtci.removeJobTitlesCache(); + + // 释放map占用的内存 + // map_jobtitledefined_id_code.clear(); + // map_jobtitledefined_id_code=null; + map_dept_code_id.clear(); + map_dept_code_id = null; + // map_jobtitle_code_id.clear(); + // map_jobtitle_code_id=null; + + // 更新同步时间到中间表 + String sql1 = "update uf_HRRestDate set sctbsj ='" + now + "' where jkm = '/dcopenedi/hrPost/pageByUpdateTime'"; + rs.executeUpdate(sql1); + /* ******************* 清除所有岗位信息,释放内存空间 start youhong.ai ******************* */ + allResult.clear(); + /* ******************* 清除所有岗位信息,释放内存空间 end youhong.ai ******************* */ + } + + + public Map getJobtitleCodeIdMap() { + RecordSet rs = new RecordSet(); + Map map = new HashMap<>(); + rs.executeQuery("select jobtitlecode,outkey,id from hrmjobtitles where outkey is not null and (CANCELED!=1 or CANCELED is null)"); + while (rs.next()) { + map.put(rs.getString("outkey"), rs.getString("id")); + } + return map; + } + + public int getPages(String date) { + int current = 1, size = 10000, pages = 1; + String url = HttpClientToJT.baseUrl + "/dcopenedi/hrPost/pageByUpdateTime"; + String token = HttpClientToJT.getToken(); + Map params = new HashMap<>(); +// LocalDateTime today_start = LocalDateTime.of(LocalDate.now(), LocalTime.MIN);//当天零点 +// String td_st_str = today_start.format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")); + params.put("updateTime", date); +// params.put("updateTime", "2018-03-21 00:00:00"); + params.put("current", current); + params.put("size", size); + String s = HttpClientToJT.sendGet(url, token, params); + JSONObject jsonObject = JSONObject.parseObject(s); + if (jsonObject.getInteger("code").equals(1)) { + JSONObject result = jsonObject.getJSONObject("data"); + pages = result.getInteger("pages"); + } + return pages; + } + + public JSONArray getJobsByPage(String pages, String date) { + int size = 5000; + String url = HttpClientToJT.baseUrl + "/dcopenedi/hrPost/pageByParam"; + String token = HttpClientToJT.getToken(); + Map params = new HashMap<>(); + + params.put("beginTime", date); + params.put("point", pages); + params.put("size", size); + + String s = HttpClientToJT.sendPost(url, token, JSONObject.toJSONString(params)); + JSONObject jsonObject = JSONObject.parseObject(s); + JSONArray jsonArray = new JSONArray(); + if (jsonObject.getInteger("code").equals(1)) { + JSONObject result = jsonObject.getJSONObject("data"); + JSONArray records = result.getJSONArray("records"); + + // 是否有下一页 + Object hasNextPage = result.get("hasNextPage"); + // 下次继续传 + maxPoint = result.get("maxPoint").toString(); + if ("false".equals(hasNextPage.toString())) { + ifPage = false; + } + /* ******************* 收集所有岗位信息 start for youhong.ai ******************* */ + allResult.addAll(records); + /* ******************* 收集所有岗位信息 end for youhong.ai ******************* */ + jsonArray.addAll(records); + } else { + ifPage = false; + } + Object directSales = jsonArray.stream().filter(item -> { + JSONObject itemJson = JSONObject.parseObject(JSON.toJSONString(item)); + return "IDN".equals(itemJson.getString("countryCode")); + }).collect(Collectors.toList()); + jsonArray = JSONArray.parseArray(JSON.toJSONString(directSales)); + // log.writeLog("-------------------数据:"+jsonArray); + return jsonArray; + } + + public JSONArray getJobtitles() { + int current = 1, size = 10000, pages = 2; + String url = HttpClientToJT.baseUrl + "/dcopenedi/hrPost/pageByUpdateTime"; + // String url = "https://jtdcapi.jtexpress.com.cn/dcopenedi/hrPost/pageByUpdateTime"; + String token = HttpClientToJT.getToken(); + Map params = new HashMap<>(); +// LocalDateTime today_start = LocalDateTime.of(LocalDate.now(), LocalTime.MIN);//当天零点 +// String td_st_str = today_start.format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")); +// params.put("updateTime",td_st_str); + params.put("updateTime", "2021-03-21 00:00:00"); + params.put("current", current); + params.put("size", size); + String s = HttpClientToJT.sendGet(url, token, params); + JSONObject jsonObject = JSONObject.parseObject(s); + JSONArray jsonArray = new JSONArray(); + if (jsonObject.getInteger("code").equals(1)) { + JSONObject result = jsonObject.getJSONObject("data"); + pages = result.getInteger("pages"); + JSONArray records = result.getJSONArray("records"); + jsonArray.addAll(records); + for (int i = 2; i <= pages; i++) { + System.out.println(i); + params.put("current", i); + String str = HttpClientToJT.sendGet(url, token, params); + JSONObject jsonObject1 = JSONObject.parseObject(str); + JSONObject jsonResult = jsonObject1.getJSONObject("data"); + JSONArray records1 = jsonResult.getJSONArray("records"); + jsonArray.addAll(records1); + } + Object directSales = jsonArray.stream().filter(item -> { + JSONObject itemJson = JSONObject.parseObject(JSON.toJSONString(item)); + return !"ZHS".equals(itemJson.getString("languageCd")); + }).collect(Collectors.toList()); + jsonArray = JSONArray.parseArray(JSON.toJSONString(directSales)); + } +// System.out.println(jsonArray.toJSONString()); +// System.out.println(s); + // 将写入转化为流的形式 + writeFile(jsonArray); + return jsonArray; + } + + private void writeFile(JSONArray jsonArray) { + BufferedWriter bw = null; + try { + bw = new BufferedWriter(new FileWriter("E:\\3.txt")); + // 一次写一行 + bw.write(jsonArray.toJSONString()); + bw.newLine(); // 换行用 + // 关闭流 + bw.close(); + } catch (IOException e) { + e.printStackTrace(); + } + System.out.println("写入成功"); + } + + public static void main(String[] args) { + SyncHrmjobtitlesToOA job = new SyncHrmjobtitlesToOA(); + job.getJobtitles(); + } +} diff --git a/src/main/youhong_ai_jitu_src/jntchina/schedule/hrm/idn/SyncHrmresourceToOAIDN.java b/src/main/youhong_ai_jitu_src/jntchina/schedule/hrm/idn/SyncHrmresourceToOAIDN.java new file mode 100644 index 0000000..3ee8b74 --- /dev/null +++ b/src/main/youhong_ai_jitu_src/jntchina/schedule/hrm/idn/SyncHrmresourceToOAIDN.java @@ -0,0 +1,344 @@ +package jntchina.schedule.hrm.idn; + +import com.alibaba.fastjson.JSONArray; +import com.alibaba.fastjson.JSONObject; +import com.api.integration.util.JavaUtil; +import com.engine.common.service.impl.HrmCommonServiceImpl; +import com.engine.common.service.impl.ThemeServiceImpl; +import jntchina.schedule.hrm.entity.HrmUserDto; +import jntchina.schedule.hrm.util.OrganizationUtil; +import selfdev.util.base.TimeCommonUtil; +import selfdev.util.log.LogTool; +import weaver.conn.RecordSet; +import weaver.general.Util; +import weaver.hrm.resource.ResourceComInfo; + +import java.util.*; + +/** + * @author Cyq + * @date 2021年6月17日 02:01:51 + */ +public class SyncHrmresourceToOAIDN { + + //是否有下一页 + boolean isNext = true; + + //页码 + String current = "1"; + private final LogTool log = new LogTool("/log/hrm/IDN/user/", false); + + /** + * 人员同步操作 + * @param today 当前日期 + */ + @SuppressWarnings("unchecked") + public void execute(String today) { + log.writeLog("---------进入印尼人员同步------------"); + try { + HrmCommonServiceImpl hrmCommonServiceImpl = new HrmCommonServiceImpl(); + String now = TimeCommonUtil.obtainDate(0); + ThemeServiceImpl themeService = new ThemeServiceImpl(); + + //当前系统中 部门、分部信息 + Map oaDeptAndComMap = OrganizationUtil.getEffectiveDeptAndCompany(); + + + //部门与国家对应关系集合 + Map deptCountryMap = OrganizationUtil.getDeptCountryMap(); + + + //未获取到的上级的集合 + Map noFindManagerMap = new HashMap<>(); + + // 处理人员同步逻辑 + RecordSet rs = new RecordSet(); + String sql; + log.writeLog("----------印尼 开始同步人员------------"); + int totalCount = 0, insertCount = 0, updateCount = 0, skipCount = 0; + int skipNum = 0, insertNum = 0, updateNum = 0; + + //更新人员缓存 + ResourceComInfo rci = new ResourceComInfo(); + //如果有下一页就会循环 + int count = 0; + while (isNext) { + count++; + JSONArray data = getUsersByPage(current, today); + List users = JSONArray.parseArray(data.toJSONString(), HrmUserDto.class); + totalCount = totalCount + users.size(); + log.writeLog("----------同步人员第" + count + "页,条数:" + users.size()); + String password = "9F51B4682F92AB843B401218BF27C301";//默认密码Jitu@2021 + for (HrmUserDto row : users) { + String field0; + String employeeCode = Util.null2String(row.getEmployeeCode());//员工code + String employeeName = Util.null2String(row.getEmployeeName());//姓名 + String employeeSexCode = Util.null2String(row.getEmployeeSexCode());//性别 M男 F女 对应 OA 0男 1女 + int sex = "M".equals(employeeSexCode) ? 0 : 1; + String birthdate = Util.null2String(row.getEmployeeBirthdate());//出生年月 + String companyTel = Util.null2String(row.getCompanyTel());//办公电话 + String personalTel = Util.null2String(row.getPersonalTel());//手机号 + String email = Util.null2String(row.getCompanyEmail());//邮箱 + String idNumber = Util.null2String(row.getCertificateNum());//身份证号码 + String managerCode = Util.null2String(row.getSupervisorId());//上级次账号code + //获取人员姓名的拼音 + String name_pinyin = hrmCommonServiceImpl.generateQuickSearchStr(employeeName); + String EntryDate = Util.null2String(row.getEmplHireDate());//入职日期 无字段,暂用试用结束日期来替代 + String hrStatus = Util.null2String(row.getHrStatus());//状态A在职,I离职 对应OA的1正式 5离职 + int status = "A".equals(hrStatus) ? 1 : 5;//OA的在职状态 + String deptCode = Util.null2String(row.getDeptCode());//部门 + String positionCode = Util.null2String(row.getPositionCode());//岗位 + String bankBranchName = Util.null2String(row.getBankBranchName());//开户行 + String bankAccountId = Util.null2String(row.getBankAccountId());//银行卡号 + String bankName = Util.null2String(row.getBankName());//银行类型 + String departmentid, subcompanyid1; + + log.writeLog("工号:[" + employeeCode + "],姓名:[" + employeeName + "],部门:[" + deptCode + "],领导:[" + managerCode + "],岗位:[" + positionCode + "]"); + + String managerid; + + //处理岗位id + String jobtitleId = OrganizationUtil.getJobtitleIdByOutKey(positionCode); + + //如果部门编码为空,跳过不同步 + if ("".equals(deptCode)) { + skipNum++; + log.writeLog("cylnb is dept null1:" + deptCode + "; userCode" + employeeCode); + continue; + } else { + if(oaDeptAndComMap.containsKey(deptCode)){ + String mapValue = oaDeptAndComMap.get(deptCode); + + departmentid = Util.TokenizerString2(mapValue,"^_^")[0]; + subcompanyid1 = Util.TokenizerString2(mapValue,"^_^")[1]; + } else { + log.writeLog("cylnb is dept and sub null Code:" + deptCode + "; userCode" + employeeCode); + skipNum++; + continue; + } + + managerid = OrganizationUtil.getEmployeeManagerId(managerCode,departmentid); + + //从HR获取有上级,但是在OA中未找到,则说明可能上级是新入职还未同步到OA中 + if ("".equals(managerid) && !"".equals(managerCode)) { + noFindManagerMap.put(employeeCode, managerCode); + } + } + + //去除国家 + if(deptCountryMap.containsKey(departmentid)){ + String tmpCountryCode = deptCountryMap.get(departmentid); + + if (!"IDN".equals(tmpCountryCode)) { + log.writeLog("cylnb continue user 部门不是印尼或没有国家字段:" + employeeCode + " 部门:" + deptCode); + skipNum++; + continue; + } + } else { + log.writeLog("cylnb continue 找不到部门所属国家自定义信息:" + employeeCode + " 部门:" + deptCode); + skipNum++; + continue; + } + + field0 = Util.null2String(row.getEmployeeEnglishName()); + + String[] bankInfo = new String[] {bankBranchName,bankAccountId,bankName}; + + //判断人员ID是否已经存在,不存在则插入生成新人员 + rs.executeQuery("select id,lastname from hrmresource where workcode = ?", employeeCode); + if (!rs.next()) { + // if (!map_user_code_id.containsKey(employeeCode)) { + //获取即将插入的人员ID + rs.executeProc("HrmResourceMaxId_Get", ""); + rs.next(); + String maxUserId = "" + rs.getInt(1); + //新增数据,插入到人员基本信息表HrmResource中 seclevel + sql = "insert into hrmresource(id,loginid,password,lastname,workcode,sex, " + + "mobile,email,departmentid,jobtitle,birthday,certificatenum," + + "seclevel,outkey,status,systemlanguage,createrid,createdate," + + "companystartdate,telephone,ecology_pinyin_search,pinyinlastname," + + "created,creater,modified,modifier,managerid,subcompanyid1) values( " + + "'" + maxUserId + "'," + + "'" + employeeCode + "'," + + "'" + password + "'," + + "?," + + "'" + employeeCode + "'," + + "'" + sex + "'," + + "'" + personalTel + "'," + + "'" + email + "'," + + "'" + departmentid + "'," + + "'" + jobtitleId + "'," + + "'" + birthdate + "'," + + "'" + idNumber + "'," + + "'" + 10 + "'," + + "'" + employeeCode + "'," + + "" + status + "," + + "'7'," + + "'1'," + + "'" + now.substring(0, 10) + "'," + + "'" + EntryDate + "'," + + "'" + companyTel + "'," + + "?," + + "?," + + "to_date('" + now + "','yyyy-mm-dd hh24:mi:ss')," + + "'1'," + + "to_date('" + now + "','yyyy-mm-dd hh24:mi:ss')," + + "'1'," + + "'" + managerid + "'," + + "'" + subcompanyid1 + "')"; + + boolean executeUpdate = rs.executeUpdate(sql, employeeName, name_pinyin, name_pinyin); + log.writeLog("新增人员是否正确" + executeUpdate); + log.writeLog("插入人员表中数据sql--------->" + sql); + //将新增加的人员加入至MAP中 + insertNum++; + // map_user_code_id.put(employeeCode,maxUserId); + //新增数据,插入到人员自定义表cus_fielddata中 + + rs.executeQuery("select id,field15 from cus_fielddata where scopeid='1' and scope='HrmCustomFieldByInfoType' and id='" + maxUserId + "'"); + if (!rs.next()) { + if ("".equals(bankAccountId)) { + OrganizationUtil.insertEmployeeCustomizePersonal(maxUserId,null,null,row); + } else { + OrganizationUtil.insertEmployeeCustomizePersonal(maxUserId,bankInfo,null,row); + } + } else { + //如果已经存在就修改 + log.writeLog("---------------已经存在但是信息不是自己"); + } + + OrganizationUtil.dealEmployeeNickName(maxUserId,field0); + + themeService.createSubCompanyMenu(Integer.parseInt(maxUserId), Integer.parseInt(subcompanyid1)); + //刷新人员缓存 + rci.addResourceInfoCache(maxUserId); + } else {//存在则更新 + + String id = rs.getString("id"); + //OA库中人员姓名 + String oaLastName = Util.null2String(rs.getString("lastname")); + + // String newEmployeeName = OrganizationUtil.dealEmployeeName(oaLastName,employeeName); + String newEmployeeName = employeeName; + + //更新人员基本信息表数据 + String updateStr = ""; + updateStr += !"".equals(departmentid) ? "departmentid = '" + departmentid + "', " : ""; + updateStr += !"".equals(jobtitleId) ? "jobtitle = '" + jobtitleId + "', " : ""; + updateStr += !"".equals(subcompanyid1) ? "subcompanyid1 = '" + subcompanyid1 + "', " : ""; + updateStr += !"".equals(managerid) ? "managerid = '" + managerid + "', " : ""; + sql = "update hrmresource set " + + "workcode = '" + employeeCode + "', " + + "lastname = ?, " + + "sex = '" + sex + "', " + + "mobile = '" + personalTel + "', " + + "ecology_pinyin_search = ?, " + + "pinyinlastname = ?, " + + "email = '" + email + "', " + + "telephone = '" + companyTel + "', " + + "status = " + status + ", " + + "birthday = '" + birthdate + "', " + + "certificatenum = '" + idNumber + "', " + + "companystartdate = '" + EntryDate + "', " + + "modified = to_date('" + now + "','yyyy-mm-dd hh24:mi:ss')," + + "modifier = '1', " + + "lastmoddate = '" + now.substring(0, 10) + "', " + + updateStr + + "lastmodid = '1' " + + "where id ='" + id + "'"; + boolean executeUpdate = rs.executeUpdate(sql, newEmployeeName, name_pinyin, name_pinyin); + log.writeLog("更新人员是否正确:" + executeUpdate); + updateNum++; + + log.writeLog("更新人员基本信息表中数据sql--------->" + sql); + rs.executeQuery("select id,field15 from cus_fielddata where scopeid='1' and scope='HrmCustomFieldByInfoType' and id='" + id + "'"); + if (!rs.next()) { + OrganizationUtil.insertEmployeeCustomizePersonal(id,bankInfo,null,row); + } else { + //更新人员工作信息表数据 + if ("".equals(bankAccountId)) { + OrganizationUtil.updateEmployeeCustomizePersonal(id,null,null,row); + } else { + OrganizationUtil.updateEmployeeCustomizePersonal(id,bankInfo,null,row); + } + } + + OrganizationUtil.dealEmployeeNickName(id,field0); + //刷新人员缓存 + rci.updateResourceInfoCache(id); + } + } + insertCount += insertNum; + updateCount += updateNum; + skipCount += skipNum; + log.writeLog("----------同步结束人员,第" + count + "页:" + totalCount + + ",新增人员数为:" + insertNum + " ,更新人员数为:" + updateNum + ",跳过处理人员数为:" + skipNum + "------------"); + skipNum = 0; + insertNum = 0; + updateNum = 0; + } + log.writeLog("---------开始处理未更新的直属领导信息-------"); + OrganizationUtil.dealNoFindMangerEmployeeData(noFindManagerMap); + log.writeLog("---------结束处理未更新的直属领导信息-------"); + log.writeLog("----------印尼 同步人员结束总人数:" + totalCount + ",新增人数:" + insertCount + ",更新人数:" + updateCount + ",跳过人数:" + skipCount + "------------"); + + //更新同步时间到中间表 + String sql1 = "update uf_HRRestDate set sctbsj ='" + now + "' where jkm = '/dcopenedi/hrEmployee/pageByUpdateTime'"; + rs.executeUpdate(sql1); + + } catch (Exception e) { + log.writeLog("---------Exception------------:" + JavaUtil.getExceptionDetail(e)); + e.printStackTrace(); + } + + } + + /** + * 获取员工信息 + * @param pages 页码 + * @param today 日期 + * @return 返回员工信息 + */ + public JSONArray getUsersByPage(String pages, String today) { + int size = 5000; + List list = new ArrayList<>(); + list.add("IDN"); + + String s = OrganizationUtil.callEmployeeInterface(size,pages,today,list,list,""); + if (!"".equals(s) && null != s) { + log.writeLog("---------------接口返回空成功:" + s.substring(0, 1000)); + } else { + log.writeLog("---------------接口返回空"); + } + + JSONObject jsonObject = JSONObject.parseObject(s); + + //人员数据集合 + JSONArray jsonArray = new JSONArray(); + + if(jsonObject.containsKey("code")){ + int code = jsonObject.getInteger("code"); + + if(code == 1){ + JSONObject result = jsonObject.getJSONObject("data"); + + JSONArray records = result.getJSONArray("records"); + jsonArray.addAll(records); + + //是否存在下一页 + if (result.get("hasNextPage").toString().equals("true")) { + current = result.get("maxPoint").toString(); + } else { + isNext = false; + } + } + }else{ + isNext = false; + } + + log.writeLog("没筛选之前条数:" + jsonArray.size()); + + return jsonArray; + } + +} diff --git a/src/main/youhong_ai_jitu_src/jntchina/schedule/hrm/idn/SyncHrmresourceToOAIDNOld.java b/src/main/youhong_ai_jitu_src/jntchina/schedule/hrm/idn/SyncHrmresourceToOAIDNOld.java new file mode 100644 index 0000000..8c8a330 --- /dev/null +++ b/src/main/youhong_ai_jitu_src/jntchina/schedule/hrm/idn/SyncHrmresourceToOAIDNOld.java @@ -0,0 +1,856 @@ +package jntchina.schedule.hrm.idn; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.JSONArray; +import com.alibaba.fastjson.JSONObject; +import com.api.integration.util.JavaUtil; +import com.engine.common.service.impl.HrmCommonServiceImpl; +import com.engine.common.service.impl.ThemeServiceImpl; +import jntchina.schedule.hrm.SyncHrmdepartmentToOA; +import jntchina.schedule.hrm.SyncHrmjobtitlesToOA; +import jntchina.schedule.hrm.SyncHrmresourceToOA; +import jntchina.schedule.hrm.SyncHrmsubcompanyToOA; +import jntchina.schedule.hrm.entity.HrmUserDto; +import jntchina.util.HttpClientToJT; +import selfdev.util.base.TimeCommonUtil; +import selfdev.util.log.LogTool; +import weaver.conn.RecordSet; +import weaver.file.Prop; +import weaver.general.Util; +import weaver.hrm.resource.ResourceComInfo; + +import java.io.BufferedWriter; +import java.io.FileWriter; +import java.io.IOException; +import java.time.LocalDate; +import java.time.LocalDateTime; +import java.time.LocalTime; +import java.time.format.DateTimeFormatter; +import java.util.*; +import java.util.stream.Collectors; + +/** + * @author Cyq + * @date 2021年6月17日 02:01:51 + */ +public class SyncHrmresourceToOAIDNOld { + + //是否有下一页 + boolean isNext = true; + + //页码 + String current = "1"; + //人员编码和id map + Map map_user_code_id = new HashMap(); + private LogTool log = new LogTool("/log/hrm/IDN/user/", false); + + public void execute(String today) { + log.writeLog("---------进入印尼人员同步------------"); + try { + + HrmCommonServiceImpl hrmCommonServiceImpl = new HrmCommonServiceImpl(); + String now = TimeCommonUtil.obtainDate(0); + SyncHrmsubcompanyToOA hrmsubcompany = new SyncHrmsubcompanyToOA(); + SyncHrmdepartmentToOA hrmdepartment = new SyncHrmdepartmentToOA(); + SyncHrmjobtitlesToOA hrmjobtitles = new SyncHrmjobtitlesToOA(); + ThemeServiceImpl themeService = new ThemeServiceImpl(); + Map map_subcompany_code_id = hrmsubcompany.getSubCodeIdMap(); + Map map_dept_code_id = hrmdepartment.getDepartmentCodeIdMap(); +// Map map_zybm = getZyBmMap();//直营部门 +// Map map_zyfb = getZyFbMap();//直营分部 +// log.writeLog("----------直营部门MAP:"+JSON.toJSONString(map_zybm)+"------------"); +// log.writeLog("----------map_dept_code_id:"+JSON.toJSONString(map_dept_code_id)+"------------"); +// Map map_dept_com= hrmdepartment.getDeptComMap(); + //Map map_jobtitle_code_id = hrmjobtitles.getJobtitleCodeIdMap(); +// Map map_gzdd_OA = getGzddOAMap(); + //未获取到的上级的集合 + Map map_usernofindsuper = new HashMap<>(); + Map map_user_id_defined = getUserIdDefinedMap(); + map_user_code_id = getUserCodeIdMap(); +// log.writeLog("----------UserCodeIdmap:"+JSON.toJSONString(map_user_code_id)+"------------"); + // 处理人员同步逻辑 + RecordSet rs = new RecordSet(); + String sql = ""; + log.writeLog("----------开始同步人员------------"); + int totalCount = 0, insertCount = 0, updateCount = 0, skipCount = 0; + int skipNum = 0, insertNum = 0, updateNum = 0; + //int page = getPage(today); + //log.writeLog("page------------>" + page); + + //更新人员缓存 + ResourceComInfo rci = new ResourceComInfo(); + // for (int k = 1; k <= page; k++) { + //如果有下一页就会循环 + int count = 0; + while (isNext) { + count++; + JSONArray data = getUsersByPage(current, today); + List users = JSONArray.parseArray(data.toJSONString(), HrmUserDto.class); + totalCount = totalCount + users.size(); + // log.writeLog("----------同步人员第" + current + "页,条数:" + users.size()); + log.writeLog("----------同步人员第" + count + "页,条数:" + users.size()); +// log.writeLog("----------同步人员源数据:"+users.toJSONString()); +// String password = "96E79218965EB72C92A549DD5A330112";//默认密码111111 + String password = "9F51B4682F92AB843B401218BF27C301";//默认密码Jitu@2021 + for (int i = 0; i < users.size(); i++) { + try { + String field0 = ""; + HrmUserDto row = users.get(i); + String employeeCode = Util.null2String(row.getEmployeeCode());//员工code + log.writeLog("----------------工号:" + employeeCode); + String employeeName = Util.null2String(row.getEmployeeName());//姓名 + log.writeLog("----------------姓名:" + employeeName); + String employeeSexCode = Util.null2String(row.getEmployeeSexCode());//性别 M男 F女 对应 OA 0男 1女 + Integer sex = "M".equals(employeeSexCode) ? 0 : 1; + String birthdate = Util.null2String(row.getEmployeeBirthdate());//出生年月 + String companyTel = Util.null2String(row.getCompanyTel());//办公电话 + String personalTel = Util.null2String(row.getPersonalTel());//手机号 + String email = Util.null2String(row.getCompanyEmail());//邮箱 + String idNumber = Util.null2String(row.getCertificateNum());//身份证号码 +// String seclevel = "0"; + String managerCode = Util.null2String(row.getSupervisorId());//上级次账号code + //获取人员姓名的拼音 + String name_pinyin = hrmCommonServiceImpl.generateQuickSearchStr(employeeName); + String EntryDate = Util.null2String(row.getEmplHireDate());//入职日期 无字段,暂用试用结束日期来替代 + String hrStatus = Util.null2String(row.getHrStatus());//状态A在职,I离职 对应OA的1正式 5离职 + Integer status = "A".equals(hrStatus) ? 1 : 5;//OA的在职状态 + String companyCode = Util.null2String(row.getCompanyCode());//所属组织 + String deptCode = Util.null2String(row.getDeptCode());//部门 + String positionCode = Util.null2String(row.getPositionCode());//岗位 + log.writeLog("----------------岗位:" + positionCode); + log.writeLog("----------------部门:" + deptCode); + + String workLocationCode = Util.null2String(row.getWorkLocationCode());//工作地点code + String workLocaltionName = Util.null2String(row.getWorkLocaltionName());//工作地点 +// String OIdJobSequence = Util.null2String(map_zwxl_HR.get(row.getString("positonRankCode")));//职务序列 + String jobLevel = Util.null2String(row.getPositonRankCode());//职级 + String bankBranchName = Util.null2String(row.getBankBranchName());//开户行 + String bankAccountId = Util.null2String(row.getBankAccountId());//银行卡号 + String bankName = Util.null2String(row.getBankName());//银行类型 +// String locationid = "521"; //默认上海 + String departmentid = "", subcompanyid1 = ""; + //各种code换id + // String userId = Util.null2String(map_user_code_id.get(employeeCode));//员工ID + String managerid = ""; + //若维护了上级次账号,则根据维护的数据找上级 + if (!"".equals(managerCode)) { + rs.executeQuery("select id from hrmresource where workcode = ?", managerCode); + if (rs.next()) { + managerid = rs.getString("id"); + } + //managerid = Util.null2String(map_user_code_id.get(managerCode));//直接上级 + } else { + String depid = Util.null2String(map_dept_code_id.get(deptCode));//部门ID +// rs.executeQuery("select id from hrmdepartment where code = ?",deptCode); +// rs.next(); +// String depid = rs.getString("id"); + if (!"".equals(depid)) { + rs.executeQuery("select bmfzr from HRMDEPARTMENTDEFINED where DEPTID = " + depid); + if (rs.next()) { + managerid = Util.null2String(rs.getString("bmfzr")); + } + } + } + //从HR获取有上级,但是在OA中未找到,则说明可能上级是新入职还未同步到OA中 + if ("".equals(managerid) && !"".equals(managerCode)) { + map_usernofindsuper.put(employeeCode, managerCode); + } + //处理岗位id + String jobtitleid = ""; + if (!"".equals(positionCode)) { + // jobtitleid = Util.null2String(map_jobtitle_code_id.get(positionCode));//岗位ID + rs.executeQuery("select id from hrmjobtitles where outkey = ?", positionCode); + if (rs.next()) { + jobtitleid = rs.getString("id"); + } else { + log.writeLog("cylnb 这个人的岗位不存在:" + employeeName); + log.writeLog("cylnb 岗位编码:" + positionCode); + } + } + + + //如果部门编码为空,跳过不同步 + if ("".equals(deptCode)) { + skipNum++; + log.writeLog("cylnb is dept null1:" + deptCode + "; userCode" + employeeCode); + continue; + } else { + //处理所属部门编码对应的OA部门、分部。在分部表,部门表匹配 + departmentid = Util.null2String(map_dept_code_id.get(deptCode));//部门ID + subcompanyid1 = Util.null2String(map_subcompany_code_id.get(deptCode));//分部ID + log.writeLog("----人员code:" + employeeCode + ",所属部门code:" + deptCode + ",部门id:" + departmentid + ",部门领导code:" + managerCode + ",部门领导id:" + managerid + "--------->"); + if ("".equals(departmentid) && "".equals(subcompanyid1)) { + log.writeLog("cylnb is dept and sub null Code:" + deptCode + "; userCode" + employeeCode); + skipNum++; + continue; + } else if (!"".equals(departmentid)) { + subcompanyid1 = getSubcomBydept(departmentid); + log.writeLog("----人员code:" + employeeCode + ",所属部门code:" + deptCode + ",所属部门id:" + departmentid + ",对应的分部id:" + subcompanyid1 + "--------->"); + } else if (!"".equals(subcompanyid1)) { + log.writeLog("cylnb is dept null Code:" + deptCode + "; userCode" + employeeCode); + + //String deptId = Prop.getPropValue("", guojia); +// String deptId = "800117"; +// departmentid = deptId; +// rs.executeQuery("select from hrmdepartment where id = ?", deptId); +// if (rs.next()) { +// subcompanyid1 = rs.getString("subcompanyid1"); +// } + skipNum++; + continue; + //departmentid = ""; + } + + } + + //去除国家 + rs.executeQuery("select * from hrmdepartmentdefined where deptid = ?", departmentid); + if (rs.next()) { + String guojia = rs.getString("guojia"); + if (!"IDN".equals(guojia) || "".equals(guojia)) { + log.writeLog("cylnb continue user 部门不是印尼或没有国家字段:" + employeeCode + " 部门:" + deptCode); + skipNum++; + continue; + } + } else { + log.writeLog("cylnb continue 找不到部门:" + employeeCode + " 部门:" + deptCode); + skipNum++; + continue; + } + //是否直营判断 +// if(departmentid!=null){ +// status = map_zybm.containsKey(departmentid)?7:status; +// } +// if(subcompanyid1!=null){ +// status = map_zyfb.containsKey(subcompanyid1)?7:status; +// } + + + //判断人员ID是否已经存在,不存在则插入生成新人员 +// employeeName = row.getEmployeeEnglishName(); +// bankBranchName = row.getEmployeeName(); + +// employeeName = row.getEmployeeEnglishName(); +// field0 = row.getEmployeeName(); + field0 = row.getEmployeeEnglishName(); + employeeName = row.getEmployeeName(); + + + log.writeLog("-----------------field0:" + field0); + log.writeLog("-----------------employeeName:" + employeeName); + + rs.executeQuery("select id from hrmresource where workcode = ?", employeeCode); + if (!rs.next()) { + // if (!map_user_code_id.containsKey(employeeCode)) { + //获取即将插入的人员ID + rs.executeProc("HrmResourceMaxId_Get", ""); + rs.next(); + String maxUserId = "" + rs.getInt(1); + //新增数据,插入到人员基本信息表HrmResource中 seclevel + sql = "insert into hrmresource(id,loginid,password,lastname,workcode,sex, " + + "mobile,email,departmentid,jobtitle,birthday,certificatenum," + + "seclevel,outkey,status,systemlanguage,createrid,createdate," + + "companystartdate,telephone,ecology_pinyin_search,pinyinlastname," + + "created,creater,modified,modifier,managerid,subcompanyid1) values( " + + "'" + maxUserId + "'," + + "'" + employeeCode + "'," + + "'" + password + "'," + + "'" + employeeName + "'," + + "'" + employeeCode + "'," + + "'" + sex + "'," + + "'" + personalTel + "'," + + "'" + email + "'," + + "'" + departmentid + "'," + + "'" + jobtitleid + "'," + + "'" + birthdate + "'," + + "'" + idNumber + "'," + + "'" + 10 + "'," + + "'" + employeeCode + "'," + + "" + status + "," + + "'7'," + + "'1'," + + "'" + now.substring(0, 10) + "'," + + "'" + EntryDate + "'," + + "'" + companyTel + "'," + + "'" + name_pinyin + "'," + + "'" + name_pinyin + "'," + + "to_date('" + now + "','yyyy-mm-dd hh24:mi:ss')," + + "'1'," + + "to_date('" + now + "','yyyy-mm-dd hh24:mi:ss')," + + "'1'," + + "'" + managerid + "'," + + "'" + subcompanyid1 + "')"; + boolean executeUpdate = rs.executeUpdate(sql); + log.writeLog("新增人员是否正确" + executeUpdate); + log.writeLog("插入人员表中数据sql--------->" + sql); + //将新增加的人员加入至MAP中 + insertNum++; + // map_user_code_id.put(employeeCode,maxUserId); + //新增数据,插入到人员自定义表cus_fielddata中 + + String uid = maxUserId; +// rs.executeQuery("select id from hrmresource where workcode = ?", employeeCode); +// if (rs.next()) { +// uid = rs.getString("id"); +// } + + rs.executeQuery("select id,field15 from cus_fielddata where scopeid='1' and scope='HrmCustomFieldByInfoType' and field15='" + employeeCode + "'"); + //rs.executeQuery("select id,field15 from cus_fielddata where scope='HrmCustomFieldByInfoType' and id='" + uid + "'"); + if (!rs.next()) { + if ("".equals(bankAccountId)) { + sql = "insert into cus_fielddata(scope,scopeid,id,field0,field15,field16,field17,field18,field19,field20,field21,field14,field22,field23,field24) values(" + + "'HrmCustomFieldByInfoType'," + + "'1'," + + "'" + uid + "'," + + "'" + bankAccountId + "'," //多语言 昵称 + + "'" + employeeCode + "'," + + "'" + Util.null2String(row.getCompanyCode()) + "'," + + "'" + Util.null2String(row.getCompanyName()) + "'," + + "'" + Util.null2String(row.getDeptCode()) + "'," + + "'" + Util.null2String(row.getDeptName()) + "'," + + "'" + Util.null2String(row.getPositionCode()) + "'," + + "'" + Util.null2String(row.getPositionName()) + "'," + + "'" + Util.null2String(row.getPositionType()) + "'," + + "'" + Util.null2String(row.getPositionTypeDescr()) + "'," + + "'" + Util.null2String(row.getPositonRankCode()) + "'," + + "'" + Util.null2String(row.getPositonRankDescr()) + "')"; + } else { + sql = "insert into cus_fielddata(scope,scopeid,id,field0,field1,field5,field7,field15,field16,field17,field18,field19,field20,field21,field14,field22,field23,field24) values(" + + "'HrmCustomFieldByInfoType'," + + "'1'," + + "'" + uid + "'," + + "'" + bankBranchName + "'," + + "'" + bankAccountId + "'," //多语言 昵称 + + "'" + employeeName + "'," + + "'" + bankName + "'," + + "'" + employeeCode + "'," + + "'" + Util.null2String(row.getCompanyCode()) + "'," + + "'" + Util.null2String(row.getCompanyName()) + "'," + + "'" + Util.null2String(row.getDeptCode()) + "'," + + "'" + Util.null2String(row.getDeptName()) + "'," + + "'" + Util.null2String(row.getPositionCode()) + "'," + + "'" + Util.null2String(row.getPositionName()) + "'," + + "'" + Util.null2String(row.getPositionType()) + "'," + + "'" + Util.null2String(row.getPositionTypeDescr()) + "'," + + "'" + Util.null2String(row.getPositonRankCode()) + "'," + + "'" + Util.null2String(row.getPositonRankDescr()) + "')"; + + } + boolean b = rs.executeUpdate(sql); + log.writeLog("-------------新增自定义信息:" + sql); + log.writeLog("-------------新增自定义信息是否成功:" + b); + //将新增加的人员自定义信息加入至MAP中 + //map_user_id_defined.put(maxUserId,employeeCode); + } else { + //如果已经存在就修改 + log.writeLog("---------------已经存在但是信息不是自己"); + } + //log.writeLog("插入人员自定义表中数据sql--------->" + sql); + //基本信息 + rs.executeQuery("select id from cus_fielddata where scopeid='-1' and scope='HrmCustomFieldByInfoType' "); + if (!rs.next()) { + String cusSql = "insert into cus_fielddata(scope,scopeid,id,field0) values(" + + "'HrmCustomFieldByInfoType'," + + "'-1'," + + "'" + uid + "'," + + "'" + field0 + "')"; + boolean b = rs.executeUpdate(cusSql); + log.writeLog("-------------新增自定义基本信息:" + cusSql); + log.writeLog("-------------新增自定义基本是否成功:" + b); + } else { + String cusSql = "update cus_fielddata set " + + "scopeid = '-1', " + + "field0 = '" + field0 + "' " + + "where id ='" + uid + "' and scopeid='-1' and scope = 'HrmCustomFieldByInfoType'"; + + boolean b = rs.executeUpdate(cusSql); + log.writeLog("-------------修改自定义基本信息:" + cusSql); + log.writeLog("-------------修改自定义基本是否成功:" + b); + } + themeService.createSubCompanyMenu(Integer.valueOf(maxUserId), Integer.valueOf(subcompanyid1)); + //刷新人员缓存 + rci.addResourceInfoCache(maxUserId); + } else {//存在则更新 + + String id = rs.getString("id"); + //更新人员基本信息表数据 + //userId = Util.null2String(map_user_code_id.get(employeeCode));//员工ID + String updateStr = ""; + updateStr += !"".equals(departmentid) ? "departmentid = '" + departmentid + "', " : ""; + updateStr += !"".equals(jobtitleid) ? "jobtitle = '" + jobtitleid + "', " : ""; + updateStr += !"".equals(subcompanyid1) ? "subcompanyid1 = '" + subcompanyid1 + "', " : ""; + updateStr += !"".equals(managerid) ? "managerid = '" + managerid + "', " : ""; + sql = "update hrmresource set " + + "workcode = '" + employeeCode + "', " + + "lastname = '" + employeeName + "', " + + "sex = '" + sex + "', " + + "mobile = '" + personalTel + "', " + + "ecology_pinyin_search = '" + name_pinyin + "', " + + "pinyinlastname = '" + name_pinyin + "', " + + "email = '" + email + "', " + + "telephone = '" + companyTel + "', " + + "status = " + status + ", " + + "birthday = '" + birthdate + "', " + + "certificatenum = '" + idNumber + "', " + + "companystartdate = '" + EntryDate + "', " + + "modified = to_date('" + now + "','yyyy-mm-dd hh24:mi:ss')," + + "modifier = '1', " + + "lastmoddate = '" + now.substring(0, 10) + "', " + + updateStr + + "lastmodid = '1' " + +// "loginid = '"+employeeCode+"' , "+ +// "password = '"+password+"' "+ + "where id ='" + id + "'"; + boolean executeUpdate = rs.executeUpdate(sql); + log.writeLog("更新人员是否正确:" + executeUpdate); + updateNum++; + +// themeService.createSubCompanyMenu(Integer.valueOf(userId),Integer.valueOf(subcompanyid1)); + log.writeLog("更新人员基本信息表中数据sql--------->" + sql); + rs.executeQuery("select id,field15 from cus_fielddata where scopeid='1' and scope='HrmCustomFieldByInfoType' and id='" + id + "'"); + //rs.executeQuery("select id,field15 from cus_fielddata where scope='HrmCustomFieldByInfoType' and id='" + id + "'"); + if (!rs.next()) { + //if ("".equals(Util.null2String(map_user_id_defined.get(userId)))) { + + //新增数据,插入到人员自定义表cus_fielddata中 + sql = "insert into cus_fielddata(scope,scopeid,id,field0,field1,field5,field7,field15,field16,field17,field18,field19,field20,field21,field14,field22,field23,field24) values(" + + "'HrmCustomFieldByInfoType'," + + "'1'," + + "'" + id + "'," + + "'" + bankBranchName + "'," + + "'" + bankAccountId + "'," + + "'" + employeeName + "'," + + "'" + bankName + "'," + + "'" + employeeCode + "'," + + "'" + Util.null2String(row.getCompanyCode()) + "'," + + "'" + Util.null2String(row.getCompanyName()) + "'," + + "'" + Util.null2String(row.getDeptCode()) + "'," + + "'" + Util.null2String(row.getDeptName()) + "'," + + "'" + Util.null2String(row.getPositionCode()) + "'," + + "'" + Util.null2String(row.getPositionName()) + "'," + + "'" + Util.null2String(row.getPositionType()) + "'," + + "'" + Util.null2String(row.getPositionTypeDescr()) + "'," + + "'" + Util.null2String(row.getPositonRankCode()) + "'," + + "'" + Util.null2String(row.getPositonRankDescr()) + "')"; + + } else { + //更新人员工作信息表数据 + if ("".equals(bankAccountId)) { + sql = "update cus_fielddata set " + + //"scopeid = '-1', " + + "field0 = '" + bankBranchName + "', " + + "field15 = '" + employeeCode + "', " + + "field16 = '" + Util.null2String(row.getCompanyCode()) + "', " + + "field17 = '" + Util.null2String(row.getCompanyName()) + "', " + + "field18 = '" + Util.null2String(row.getDeptCode()) + "', " + + "field19 = '" + Util.null2String(row.getDeptName()) + "', " + + "field20 = '" + Util.null2String(row.getPositionCode()) + "', " + + "field21 = '" + Util.null2String(row.getPositionName()) + "', " + + "field14 = '" + Util.null2String(row.getPositionType()) + "', " + + "field22 = '" + Util.null2String(row.getPositionTypeDescr()) + "', " + + "field23 = '" + Util.null2String(row.getPositonRankCode()) + "', " + + "field24 = '" + Util.null2String(row.getPositonRankDescr()) + "' " + + "where id ='" + id + "' and scopeid='1' and scope = 'HrmCustomFieldByInfoType'"; + //"where id ='" + id + "' and scope = 'HrmCustomFieldByInfoType'"; + } else { + sql = "update cus_fielddata set " + + //"scopeid = '-1', " + + "field0 = '" + bankBranchName + "', " + + "field1 = '" + bankAccountId + "', " + + "field5 = '" + employeeName + "', " + + "field7 = '" + bankName + "', " + + "field15 = '" + employeeCode + "', " + + "field16 = '" + Util.null2String(row.getCompanyCode()) + "', " + + "field17 = '" + Util.null2String(row.getCompanyName()) + "', " + + "field18 = '" + Util.null2String(row.getDeptCode()) + "', " + + "field19 = '" + Util.null2String(row.getDeptName()) + "', " + + "field20 = '" + Util.null2String(row.getPositionCode()) + "', " + + "field21 = '" + Util.null2String(row.getPositionName()) + "', " + + "field14 = '" + Util.null2String(row.getPositionType()) + "', " + + "field22 = '" + Util.null2String(row.getPositionTypeDescr()) + "', " + + "field23 = '" + Util.null2String(row.getPositonRankCode()) + "', " + + "field24 = '" + Util.null2String(row.getPositonRankDescr()) + "' " + + "where id ='" + id + "' and scopeid='1' and scope = 'HrmCustomFieldByInfoType'"; + // "where id ='" + id + "' and scope = 'HrmCustomFieldByInfoType'"; + } + } + boolean executeUpdate1 = rs.executeUpdate(sql); + log.writeLog("更新人员自定义表中数据sql--------->" + sql); + log.writeLog("是否正确--------->" + executeUpdate1); + //将新增加的人员自定义信息加入至MAP中 + // map_user_id_defined.put(userId, employeeCode); + + + //基本信息 + rs.executeQuery("select id from cus_fielddata where scopeid='-1' and scope='HrmCustomFieldByInfoType' and id='" + id + "'"); + if (!rs.next()) { + String cusSql = "insert into cus_fielddata(scope,scopeid,id,field0) values(" + + "'HrmCustomFieldByInfoType'," + + "'-1'," + + "'" + id + "'," + + "'" + field0 + "')"; + boolean b = rs.executeUpdate(cusSql); + log.writeLog("-------------新增自定义基本信息:" + cusSql); + log.writeLog("-------------新增自定义基本是否成功:" + b); + } else { + String cusSql = "update cus_fielddata set " + + "scopeid = '-1', " + + "field0 = '" + field0 + "' " + + "where id ='" + id + "' and scopeid='-1' and scope = 'HrmCustomFieldByInfoType'"; + + boolean b = rs.executeUpdate(cusSql); + log.writeLog("-------------修改自定义基本信息:" + cusSql); + log.writeLog("-------------修改自定义基本是否成功:" + b); + } + + //刷新人员缓存 + rci.addResourceInfoCache(id); + } + } catch (Exception e) { + log.writeLog("--------------报错了:" + JavaUtil.getExceptionDetail(e)); + continue; + } + } + insertCount += insertNum; + updateCount += updateNum; + skipCount += skipNum; + log.writeLog("----------同步结束人员,第" + count + "页:" + totalCount + + ",新增人员数为:" + insertNum + " ,更新人员数为:" + updateNum + ",跳过处理人员数为:" + skipNum + "------------"); + skipNum = 0; + insertNum = 0; + updateNum = 0; + } + log.writeLog("---------开始处理未更新的直属领导信息-------"); + donotfinduser(map_usernofindsuper); + log.writeLog("---------结束处理未更新的直属领导信息-------"); + log.writeLog("----------同步人员结束总人数:" + totalCount + ",新增人数:" + insertCount + ",更新人数:" + updateCount + ",跳过人数:" + skipCount + "------------"); + try { + //更新人员缓存 + // ResourceComInfo rci = new ResourceComInfo(); + // rci.removeResourceCache(); + } catch (Exception e) { + e.printStackTrace(); + } + + //更新同步时间到中间表 + String sql1 = "update uf_HRRestDate set sctbsj ='" + now + "' where jkm = '/dcopenedi/hrEmployee/pageByUpdateTime'"; + rs.executeUpdate(sql1); + + } catch (Exception e) { + log.writeLog("---------Exception------------:" + JavaUtil.getExceptionDetail(e)); + e.printStackTrace(); + } + + } + + /** + * 更新上级领导(原先还未同步的上级领导) + * + * @param map_usernofindsuper + */ + private void donotfinduser(Map map_usernofindsuper) { + map_usernofindsuper.keySet(); + Iterator entries = map_usernofindsuper.entrySet().iterator(); + String sql = "", updateSql = ""; + RecordSet rs = new RecordSet(); + while (entries.hasNext()) { + Map.Entry entry = (Map.Entry) entries.next(); + String userId = entry.getKey(); + String managerCode = entry.getValue(); + sql = "select id,outkey from hrmresource where outkey='" + managerCode + "'"; + rs.executeQuery(sql); + if (rs.next()) { + String id = Util.null2String(rs.getString("id")); + if (!"".equals(id)) { + updateSql = "update hrmresource set managerid = '" + rs.getString("id") + "' where workcode ='" + userId + "'"; + rs.execute(updateSql); + } + } + } + + } + + + public JSONArray getUsersByPage(String pages, String today) { + int size = 5000; + List list = new ArrayList(); +// list.add("EGY"); +// list.add("BRA"); +// list.add("MEX"); +// list.add("SAU"); +// list.add("VNM"); +// list.add("THA"); +// list.add("MYS"); +// list.add("SGP"); +// list.add("KHM"); +// list.add("PHL"); + list.add("IDN"); + List list1 = new ArrayList(); + list1.add("IDN"); + + + // String[] deptCountryCodes = new String[]{"EGY","BRA","MEX","SAU","VNM","THA","MYS","SGP","KHM","PHL"}; + //String url = HttpClientToJT.baseUrl + "/dcopenedi/hrEmployee/pageByUpdateTime"; + String url = HttpClientToJT.baseUrl + "/dcopenedi/hrEmployee/pageByParam"; + String token = HttpClientToJT.getToken(); + Map params = new HashMap<>(); + params.put("updateTime", today); + params.put("point", pages); + params.put("languageCds", list1); +// params.put("updateTime", "2018-03-21 00:00:00"); +// params.put("current", pages); + params.put("size", size); + params.put("deptCountryCodes", list); + // params.put("deptCountryCodes", "CHN"); + log.writeLog("-----------------user请求地址:" + url); + log.writeLog("-----------------userToken:" + token); + log.writeLog("-----------------userParams:" + params); + String s = HttpClientToJT.sendPost(url, token, JSONObject.toJSONString(params)); + if (!"".equals(s) && null != s) { + log.writeLog("---------------接口返回空成功:" + s.substring(0, 1000)); + } else { + log.writeLog("---------------接口返回空"); + } + + JSONObject jsonObject = JSONObject.parseObject(s); + + if (jsonObject.getInteger("code").equals(1)) { + JSONObject result = jsonObject.getJSONObject("data"); + if (result.get("hasNextPage").toString().equals("true")) { + // if (result.getJSONArray("records").size() > 0) { + //pages = result.getInteger("pages"); + // pages++; + current = result.get("maxPoint").toString(); + // current++; + } else { + isNext = false; + } + } else { + isNext = false; + } + JSONArray jsonArray = new JSONArray(); + if (jsonObject.getInteger("code").equals(1)) { + JSONObject result = jsonObject.getJSONObject("data"); + JSONArray records = result.getJSONArray("records"); + jsonArray.addAll(records); + } + log.writeLog("没塞选之前条数:" + jsonArray.size()); + //-------modifier by KangMD 取消国家,全部同步 start-------// +// Object directSales = jsonArray.stream().filter(item -> { +// JSONObject itemJson = JSONObject.parseObject(JSON.toJSONString(item)); +// //return !"CHN".equals(itemJson.getString("countryCode"))&&!"IDN".equals(itemJson.getString("countryCode")); +// return !"CHN".equals(itemJson.getString("deptCountryCode")) && !"IDN".equals(itemJson.getString("deptCountryCode")); +// //return "ZHS".equals(itemJson.getString("languageCd")); +// }).collect(Collectors.toList()); +// jsonArray = JSONArray.parseArray(JSON.toJSONString(directSales)); + //-------modifier by KangMD 取消国家,全部同步 end-------// + // log.writeLog("塞选之后条数:"+jsonArray.size()); + +// System.out.println(jsonArray.toJSONString()); +// System.out.println(s); + //将写入转化为流的形式 +// writeFile(jsonArray); + return jsonArray; + } + + public int getPage(String today) { + int current = 1, size = 5000, pages = 1; + String url = HttpClientToJT.baseUrl + "/dcopenedi/hrEmployee/pageByUpdateTime"; + String token = HttpClientToJT.getToken(); + boolean is = true; + while (is) { + Map params = new HashMap<>(); + params.put("updateTime", today); +// params.put("updateTime", "2018-03-21 00:00:00"); + params.put("current", current); + params.put("size", size); + // params.put("deptCountryCodes", "EGY,BRA,MEX,SAU,VNM,THA,MYS,SGP,KHM,PHL"); + params.put("deptCountryCodes", "CHN"); + log.writeLog("-----------------page请求地址:" + url); + log.writeLog("-----------------pagetoken:" + token); + log.writeLog("-----------------pageparams:" + params); + String s = HttpClientToJT.sendGet(url, token, params); + JSONObject jsonObject = JSONObject.parseObject(s); + if (jsonObject.getInteger("code").equals(1)) { + JSONObject result = jsonObject.getJSONObject("data"); + if (result.getJSONArray("records").size() > 0) { + //pages = result.getInteger("pages"); + pages++; + current++; + } else { + is = false; + } + } else { + is = false; + } + try { + Thread.sleep(900); + } catch (InterruptedException e) { + + } + } + return pages; + } + + /** + * 根据部门编号获取所属分部 + * + * @return + */ + public String getSubcomBydept(String deptId) { + String subComid = ""; + RecordSet rs = new RecordSet(); + rs.executeQuery("select supdepid,subcompanyid1,outkey from HrmDepartment where id ='" + deptId + "'"); + if (rs.next()) { + subComid = Util.null2String(rs.getString("subcompanyid1")); + String supdepid = Util.null2String(rs.getString("supdepid")); + //判断是一级部门或者无上级部门返回 + if ("0".equals(supdepid) || "".equals(supdepid)) { + return subComid; + } else { + return getSubcomBydept(supdepid); + } + } + return subComid; + } + + public JSONArray getUsers() { + int current = 1, size = 10000, pages = 2; + String url = HttpClientToJT.baseUrl + "/dcopenedi/hrEmployee/pageByUpdateTime"; + String token = HttpClientToJT.getToken(); + Map params = new HashMap<>(); + LocalDateTime today_start = LocalDateTime.of(LocalDate.now(), LocalTime.MIN);//当天零点 + String td_st_str = today_start.format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")); +// params.put("updateTime", td_st_str); + params.put("updateTime", "2021-07-09 00:00:00"); + params.put("current", current); + params.put("size", size); + log.writeLog("-----------------请求地址:" + url); + log.writeLog("-----------------token:" + token); + log.writeLog("-----------------params:" + params); + String s = HttpClientToJT.sendGet(url, token, params); + JSONObject jsonObject = JSONObject.parseObject(s); + JSONArray jsonArray = new JSONArray(); + if (jsonObject.getInteger("code").equals(1)) { + JSONObject result = jsonObject.getJSONObject("data"); + pages = result.getInteger("pages"); + JSONArray records = result.getJSONArray("records"); + jsonArray.addAll(records); + for (int i = 1; i <= pages; i++) { + params.put("current", i); + String str = HttpClientToJT.sendGet(url, token, params); + JSONObject jsonObject1 = JSONObject.parseObject(str); + JSONObject jsonResult = jsonObject1.getJSONObject("data"); + JSONArray records1 = jsonResult.getJSONArray("records"); + Optional first = records1.stream().filter(item -> { + JSONObject itemJson = JSONObject.parseObject(JSON.toJSONString(item)); + return "00367587".equals(itemJson.getString("employeeCode")); + }).findFirst(); + if (first.isPresent()) { + System.out.println(JSON.toJSONString(first.get())); + return null; + } + } + } +// jsonArray = JSONArray.parseArray(JSON.toJSONString(directSales)); +// System.out.println(jsonArray.toJSONString()); +// System.out.println(s); +// //将写入转化为流的形式 +// writeFile(jsonArray); + return jsonArray; + } + + /** + * 获取人员自定义字段map id-->id + * + * @return + */ + public Map getUserIdDefinedMap() { + + RecordSet rs = new RecordSet(); + Map map = new HashMap<>(); + rs.executeQuery("select id,field15 from cus_fielddata where scopeid='1' and scope='HrmCustomFieldByInfoType'"); + while (rs.next()) { + map.put(rs.getString("id"), rs.getString("field15")); + } + return map; + + } + + /** + * 获取工作地点map code-->id + * + * @return + */ + public Map getGzddOAMap() { + RecordSet rs = new RecordSet(); + Map map = new HashMap<>(); + rs.executeQuery("select locationname,id from HrmLocations where locationname is not null"); + while (rs.next()) { + map.put(rs.getString("locationname"), rs.getString("id")); + } + return map; + } + + /** + * 获取获取直营部门 + * + * @return + */ + public Map getZyBmMap() { + RecordSet rs = new RecordSet(); + Map map = new HashMap<>(); + rs.executeQuery("select a.id,a.created from HrmDepartment a left join HrmDepartmentDefined b on a.id=b.deptid where b.sfzy = 'N' " + + "and a.created > to_date('2021-07-27 00:00:00','yyyy-mm-dd hh24:mi:ss')"); + while (rs.next()) { + map.put(rs.getString("id"), rs.getString("created")); + } + return map; + } + + /** + * 获取获取直营分部 + * + * @return + */ + public Map getZyFbMap() { + RecordSet rs = new RecordSet(); + Map map = new HashMap<>(); + rs.executeQuery("select a.id,a.created from hrmsubcompany a left join hrmsubcompanyDefined b on a.id=b.SUBCOMID where b.sfzy = 'N' " + + "and a.created > to_date('2021-07-27 00:00:00','yyyy-mm-dd hh24:mi:ss')"); + while (rs.next()) { + map.put(rs.getString("id"), rs.getString("created")); + } + return map; + } + + public Map getUserCodeIdMap() { + RecordSet rs = new RecordSet(); + Map map = new HashMap<>(); + rs.executeQuery("select workcode,outkey,id from hrmresource where outkey is not null "); + while (rs.next()) { + map.put(rs.getString("outkey"), rs.getString("id")); + } + return map; + } + + private void writeFile(JSONArray jsonArray) { + BufferedWriter bw = null; + try { + bw = new BufferedWriter(new FileWriter("D:\\4.txt")); + //一次写一行 + bw.write(jsonArray.toJSONString()); + bw.newLine(); //换行用 + //关闭流 + bw.close(); + } catch (IOException e) { + e.printStackTrace(); + } + System.out.println("写入成功"); + } + + public static void main(String[] args) { + SyncHrmresourceToOA xx = new SyncHrmresourceToOA(); + xx.getUsersByPage(1, "2021-08-29 10:00:00"); + } +} diff --git a/src/main/youhong_ai_jitu_src/jntchina/schedule/hrm/idn/SyncHrmsubcompanyToOAIDN.java b/src/main/youhong_ai_jitu_src/jntchina/schedule/hrm/idn/SyncHrmsubcompanyToOAIDN.java new file mode 100644 index 0000000..7260028 --- /dev/null +++ b/src/main/youhong_ai_jitu_src/jntchina/schedule/hrm/idn/SyncHrmsubcompanyToOAIDN.java @@ -0,0 +1,576 @@ +package jntchina.schedule.hrm.idn; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.JSONArray; +import com.alibaba.fastjson.JSONObject; +import com.api.integration.util.JavaUtil; +import jntchina.schedule.hrm.SyncHrmsubcompanyToOA; +import jntchina.schedule.hrm.entity.DepartmentDto; +import jntchina.util.HttpClientToJT; +import selfdev.util.base.TimeCommonUtil; +import selfdev.util.log.LogTool; +import weaver.conn.RecordSet; +import weaver.general.Util; +import weaver.hrm.company.SubCompanyComInfo; + +import java.io.BufferedWriter; +import java.io.FileWriter; +import java.io.IOException; +import java.time.LocalDate; +import java.time.LocalDateTime; +import java.time.LocalTime; +import java.time.format.DateTimeFormatter; +import java.util.*; +import java.util.stream.Collectors; + +/** + * @author Cyq + * @date 2021年6月17日 02:01:51 + */ +public class SyncHrmsubcompanyToOAIDN { + + //分页接口参数 + String maxPoint = "1"; + //接口是否有下一页 默认为有 + boolean ifPage = true; + + Map subMap = new HashMap<>(); + + //分部编码和id map + Map map_subcompany_code_id = new HashMap(); + private LogTool log = new LogTool("/log/hrm/IDN/subcompany/", false); + + /** + * 同步分部信息 + */ + public List execute(List subcompanys, List departments) { + log.writeLog("----------开始同步分部,条数:" + subcompanys.size()); + try { + RecordSet rss = new RecordSet(); +// for (int i = 0; i < departments.size(); i++) { +// DepartmentDto row = departments.get(i); +// String departmentCode = Util.null2String(row.getDepartmentCode());//部门编码 +// String departmentName = Util.null2String(row.getDepartmentName());//部门全称 +// String ShortName = Util.null2String(row.getDepartmentAbbreviation());//部门简称 +// String superiorDepartment = Util.null2String(row.getSuperiorDepartment());//上级部门编码 +// log.writeLog("----------部门编码:" + departmentCode); +// +// rss.executeQuery("select * from HrmDepartment where outkey = ? ",departmentCode); +// if(!rss.next()){ +// boolean executeUpdate = rss.executeUpdate("insert into HrmDepartment(Departmentname,outkey,uuid) values(?,?,?) ", departmentName, departmentCode, superiorDepartment); +// log.writeLog("----------先把部门同步进去:" + executeUpdate); +// log.writeLog("----------msg:" + rss.getExceptionMsg()); +// }else{ +// log.writeLog("----------这个部门已经放进去了不用新增:" + departmentName); +// } +// } + + map_subcompany_code_id = getAllSubCodeIdMap(); + RecordSet rs = new RecordSet(); +// log.writeLog("----------同步分部源数据:" + JSON.toJSONString(subcompanys)); + // 处理公司同步逻辑 + for (int i = 0; i < subcompanys.size(); i++) { + DepartmentDto row = subcompanys.get(i); + String countryCode = Util.null2String(row.getCountryCode());//国家编码 + String departmentCode = Util.null2String(row.getDepartmentCode());//部门编码 + String departmentName = Util.null2String(row.getDepartmentName());//部门全称 + String ShortName = Util.null2String(row.getDepartmentAbbreviation());//部门简称 + String superiorDepartment = Util.null2String(row.getSuperiorDepartment());//上级部门编码 + String departmentOrder = Util.null2String(row.getDepartmentOrder());//排序 + Integer canceled = Util.null2String(row.getStatus()).equals("3") ? 1 : null;//1 新增 2 修改 3作废 + String sql = ""; + //判断HR分部ID是否已经存在 + log.writeLog("----------------分部编码:" + departmentCode); + log.writeLog("----------------国家:" + countryCode); + log.writeLog("----------------分部名称:" + departmentName); + log.writeLog("----------------上级分部编码:" + superiorDepartment); + log.writeLog("----------------canceled:" + canceled); + String now = TimeCommonUtil.obtainDate(0); + String supsubcomid = "0"; + if (map_subcompany_code_id.containsKey(superiorDepartment)) { + supsubcomid = map_subcompany_code_id.get(superiorDepartment); + } + if("0".equals(supsubcomid) && !"".equals(superiorDepartment)){ + subMap.put(departmentCode,superiorDepartment); + } + + String status = row.getStatus(); + if (!"3".equals(status)) { + log.writeLog("---------------国家:"+countryCode); + departmentName = getDepartmentName("2018-04-23 00:00:00",countryCode,departmentCode,departmentName); + }else{ + log.writeLog("----------------状态为3"); + } + + if("".equals(departmentName)) { + log.writeLog("----------------多语言为空"); + departmentName = row.getDepartmentName(); + } + + + log.writeLog("-----------------countryCode:"+countryCode); + log.writeLog("-----------------departmentName:"+departmentName); + //分部不存在则插入生成新分部 + if (!map_subcompany_code_id.containsKey(departmentCode)) { + //新增数据,插入到hrmsubcompany表中 + sql = "insert into hrmsubcompany (companyid,supsubcomid,subcompanyname,subcompanydesc,outkey," + + "canceled,created,creater,modified,modifier) values(" + + "'1'," + + "'" + supsubcomid + "'," + + "'" + departmentName + "'," + + "'" + departmentName + "'," + + "'" + departmentCode + "'," + + canceled + "," + + "to_date('" + now + "','yyyy-mm-dd hh24:mi:ss')," + + "'1'," + + "to_date('" + now + "','yyyy-mm-dd hh24:mi:ss')," + + "'1')"; + log.writeLog("插入分部表生成新数据sql--------->" + sql); + rs.executeUpdate(sql); + + rs.executeQuery("select id from hrmsubcompany where outkey = ?",departmentCode); + int maxSubcompanyid = 0;//新插入数据的分部ID + if (rs.next()) { + maxSubcompanyid = rs.getInt("id"); + } + //将新增加的分部加入至MAP中 + map_subcompany_code_id.put(departmentCode, maxSubcompanyid + ""); + rs.executeQuery("select id from hrmsubcompany where outkey = ?",departmentCode); + //新增数据,插入到部门自定义表HrmDepartmentDefined中 + int maxSubID = 0;//新插入数据的部门ID + if (rs.next()) { + maxSubID = rs.getInt("id"); + } + sql = "insert into hrmsubcompanyDefined(SUBCOMID,guojia,sfzy) " + + "values('" + maxSubID + "','" + countryCode + "','" + row.getIsDirectSales() + "')"; + rs.executeUpdate(sql); + log.writeLog("插入分部自定义表中数据sql--------->" + sql); + + } else {//分部存在则更新 + String updateStr = ""; + updateStr += !"0".equals(supsubcomid) ? "supsubcomid= '" + supsubcomid + "', " : ""; + sql = "update hrmsubcompany set " + + updateStr + + "subcompanyname = '" + departmentName + "', " + + "subcompanydesc = '" + departmentName + "', " + + "outkey = '" + departmentCode + "', " + + "modified = to_date('" + now + "','yyyy-mm-dd hh24:mi:ss')," + + "modifier = '1', " + + "canceled = " + canceled + " " + + "where outkey= '" + departmentCode + "'"; + log.writeLog("更新分部表中数据sql--------->" + sql ); + rs.executeUpdate(sql); + + //处理分部自定义表 + String subcomid = map_subcompany_code_id.get(departmentCode); + rs.execute("select SUBCOMID from hrmsubcompanyDefined where SUBCOMID='" + subcomid + "'"); + if (rs.next()) { + sql = "update hrmsubcompanyDefined set " + + " sfzy = '" + row.getIsDirectSales() + "' ," + + " guojia = '" + countryCode + "' " + + " where SUBCOMID = '" + subcomid + "'"; + boolean b = rs.executeUpdate(sql); + log.writeLog("更新部门自定义表中数据sql--------->" + sql+" ;结果"+b); + + } else { + sql = "insert into hrmsubcompanyDefined(SUBCOMID,guojia,sfzy) " + + "values('" + subcomid + "','" + countryCode + "','" + row.getIsDirectSales() + "')"; + boolean b = rs.executeUpdate(sql); + log.writeLog("插入分部自定义表中数据sql--------->" + sql+" ;结果"+b); + } + } + } + + for (int i = 0; i < subcompanys.size(); i++) { + log.writeLog("---------分部上级查询--------->"); + DepartmentDto row = subcompanys.get(i); + String departmentCode = Util.null2String(row.getDepartmentCode());//部门编码 + String superiorDepartment = Util.null2String(row.getSuperiorDepartment());//上级部门编码 + String parId = ""; + log.writeLog("---------分部编码:" + departmentCode); + log.writeLog("---------上级分部编码:" + superiorDepartment); + rs.executeQuery("select * from HRMSUBCOMPANY where outkey = ?", superiorDepartment); + if (rs.next()) { + log.writeLog("---------在HRMSUBCOMPANY表查到了上级"); + parId = rs.getString("id"); + } +// else{ +// String now = TimeCommonUtil.obtainDate(0); +// rs.executeQuery("select * from HrmDepartment where outkey = ? ",superiorDepartment); +// if(rs.next()){ +// log.writeLog("---------在HrmDepartment表查到了上级"); +// String departmentname = rs.getString("Departmentname"); +// String parCode = rs.getString("uuid"); +// String outkey = rs.getString("outkey"); +// String supid = "0"; +// rs.executeQuery("select * from HRMSUBCOMPANY where outkey = ?",parCode); +// if(rs.next()) { +// supid = rs.getString("id"); +// } +// String sql = "insert into hrmsubcompany (companyid,supsubcomid,subcompanyname,subcompanydesc,outkey," + +// "created,creater,modified,modifier) values(" +// + "'1'," +// + "'" + supid + "'," +// + "'" + departmentname + "'," +// + "'" + departmentname + "'," +// + "'" + outkey + "'," +// + "to_date('" + now + "','yyyy-mm-dd hh24:mi:ss')," +// + "'1'," +// + "to_date('" + now + "','yyyy-mm-dd hh24:mi:ss')," +// + "'1')"; +// boolean executeUpdate = rs.executeUpdate(sql); +// log.writeLog("部门插入分部表生成新数据sql--------->" + sql); +// log.writeLog("sql:" + executeUpdate); +// log.writeLog("msg:" + rs.getExceptionMsg()); +// //删除部门 +// rs.executeUpdate("delete from HrmDepartment where outkey = ? ",outkey); +// //数据里面清理 +// for (int j = 0; j < departments.size(); j++) { +// DepartmentDto deptRow = departments.get(j); +// String deptCode = Util.null2String(deptRow.getDepartmentCode());//部门编码 +// String deptName = Util.null2String(deptRow.getDepartmentName());//部门编码 +// //如果部门的编码等于分部的上级就把数据库这个部门删掉 新增到分部 +// if(deptCode.equals(superiorDepartment)) { +// departments.remove(j); +// log.writeLog("去除部门的第"+j+"条数据名称:"+deptName); +// } +// } +// rs.executeQuery("select * from HRMSUBCOMPANY where outkey = ?",superiorDepartment); +// if(rs.next()){ +// parId = rs.getString("id"); +// } +// } +// } + log.writeLog("---------拿到上级id:" + parId); + if (!"".equals(parId)) { + boolean executeUpdate = rs.executeUpdate("update HRMSUBCOMPANY set supsubcomid = ? where outkey = ? ", parId, departmentCode); + log.writeLog("---------sql:" + executeUpdate); + log.writeLog("---------msg:" + rs.getExceptionMsg()); + } else { + boolean executeUpdate = rs.executeUpdate("delete from HRMSUBCOMPANY where outkey = ? ", departmentCode); + log.writeLog("---------找不到上级就删除:" + executeUpdate); + log.writeLog("---------msg:" + rs.getExceptionMsg()); + } + } + + log.writeLog("----sta:"+subMap.size()); + setSup(); + log.writeLog("----end"); + + + SubCompanyComInfo sccif = new SubCompanyComInfo(); + sccif.removeCompanyCache(); + + map_subcompany_code_id.clear(); + map_subcompany_code_id = null; + + } catch (Exception e) { + log.writeLog("----------Exception:" + JavaUtil.getExceptionDetail(e)); + e.printStackTrace(); + } + + return departments; + } + + /** + * 获取当前OA系统中所有的分部信息 + * @return 分部信息集合 + */ + private Map getAllSubCodeIdMap() { + RecordSet rs = new RecordSet(); + Map map = new HashMap<>(); + //rs.executeQuery("select subcompanycode,outkey,id from HrmSubCompany where outkey is not null and (CANCELED!=1 or CANCELED is null)"); + rs.executeQuery("select subcompanycode,outkey,id from HrmSubCompany where outkey is not null"); + while (rs.next()) { + map.put(rs.getString("outkey"), rs.getString("id")); + } + return map; + } + + /** + * 获取当前OA系统中状态未封存的分部信息 + * @return 分部信息集合 + */ + public Map getSubCodeIdMap() { + RecordSet rs = new RecordSet(); + Map map = new HashMap<>(); + //rs.executeQuery("select subcompanycode,outkey,id from HrmSubCompany where outkey is not null and (CANCELED!=1 or CANCELED is null)"); + rs.executeQuery("select subcompanycode,outkey,id from HrmSubCompany where outkey is not null and (CANCELED!=1 or CANCELED is null)"); + while (rs.next()) { + map.put(rs.getString("outkey"), rs.getString("id")); + } + return map; + } + + + public void setSup() { + RecordSet rss = new RecordSet(); + Set keySet = subMap.keySet(); + Iterator it = keySet.iterator(); + while (it.hasNext()) { + try { + String subCode = (String) it.next(); + String supCode = String.valueOf(subMap.get(subCode)); + String SUPSubID = ""; + rss.executeQuery("select * from hrmsubcompany where SUBCOMPANYCODE = ?", supCode); + if (rss.next()) { + SUPSubID = rss.getString("id"); + rss.executeUpdate("update hrmsubcompany set SUPSUBCOMID = ? where SUBCOMPANYCODE = ? ", SUPSubID, subCode); + it.remove(); + log.writeLog("-----------------已补处理分部code:"+subCode+",上级分部code:"+supCode); + } + } catch (Exception e) { + log.writeLog("--------------------Exception:" + JavaUtil.getExceptionDetail(e)); + } + } + + } + + + public JSONArray getSubcompanys() { + int current = 1, size = 10000, pages = 2; + String url = HttpClientToJT.baseUrl + "/dcopenedi/hrCompany/pageByUpdateTime"; + String token = HttpClientToJT.getToken(); + Map params = new HashMap<>(); + LocalDateTime today_start = LocalDateTime.of(LocalDate.now(), LocalTime.MIN);//当天零点 + String td_st_str = today_start.format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")); +// params.put("updateTime", td_st_str); + params.put("updateTime", "2018-03-21 00:00:00"); + params.put("current", current); + params.put("size", size); + String s = HttpClientToJT.sendGet(url, token, params); + JSONObject jsonObject = JSONObject.parseObject(s); + JSONArray jsonArray = new JSONArray(); + if (jsonObject.getInteger("code").equals(1)) { + JSONObject result = jsonObject.getJSONObject("data"); + pages = result.getInteger("pages"); + JSONArray records = result.getJSONArray("records"); + jsonArray.addAll(records); + for (int i = 2; i <= pages; i++) { + params.put("current", i); + String str = HttpClientToJT.sendGet(url, token, params); + JSONObject jsonObject1 = JSONObject.parseObject(str); + JSONObject jsonResult = jsonObject1.getJSONObject("data"); + JSONArray records1 = jsonResult.getJSONArray("records"); + jsonArray.addAll(records1); + } + Object directSales = jsonArray.stream().filter(item -> { + JSONObject itemJson = JSONObject.parseObject(JSON.toJSONString(item)); + return "Y".equals(itemJson.getString("isDirectSales")); + }).collect(Collectors.toList()); + jsonArray = JSONArray.parseArray(JSON.toJSONString(directSales)); + } + System.out.println(jsonArray.toJSONString()); + //将写入转化为流的形式 +// writeFile(jsonArray); + return jsonArray; + } + + + /** + * 获取海外部门国家数据 + * + * @param date 时间 + * @param point + * @return + */ + public JSONArray getOcDepartmentsGUOJIA(String date, String point, String guojia, String departmentCode) { + int current = 1, size = 5000, pages = 2; + String url = HttpClientToJT.baseUrl + "/dcopenedi/hrDept/pageNewHrDeptByUpdateTime"; + String token = HttpClientToJT.getToken(); + log.writeLog("-------token--------->" + token); + Map params = new HashMap<>(); + List list1 = new ArrayList(); + list1.add(guojia); + params.put("languageCds", list1); + params.put("updateTime", date); + params.put("point", point); + params.put("size", size); + params.put("deptCode", departmentCode); + log.writeLog("传入JSON--------------->" + JSON.toJSONString(params)); + String s = HttpClientToJT.sendPost(url, token, JSONObject.toJSONString(params)); + JSONObject jsonObject = JSONObject.parseObject(s); + JSONArray jsonArray = new JSONArray(); + + String code = Util.null2String(jsonObject.getString("code")); + log.writeLog("code------>" + code); + if ("1".equals(code)) { + JSONObject result = jsonObject.getJSONObject("data"); + JSONArray records = result.getJSONArray("records"); + Object hasNextPage = result.get("hasNextPage"); + jsonArray.addAll(records); +// //下次继续传 +// maxPoint = result.get("maxPoint").toString(); +// if ("false".equals(hasNextPage.toString())) { +// ifPage = false; +// } + +// Object directSales = jsonArray.stream().filter(item -> { +// JSONObject itemJson = JSONObject.parseObject(JSON.toJSONString(item)); +// return !"CHN".equals(itemJson.getString("countryCode")); +// }).collect(Collectors.toList()); +// jsonArray = JSONArray.parseArray(JSON.toJSONString(directSales)); + } + + return jsonArray; + } + + + + /** + * 获取多语言 + * + * @param date 时间 + * @param countryCode 国家code + * @param departmentCode 部门code + * @param deptName 部门中文名称 + * @return 多语言名称 + */ + public String getDepartmentName(String date, String countryCode, String departmentCode, String deptName) { + String retName = ""; + boolean existence = true; + String language = ""; + String cdIndex = ""; + try { + if ("CHN".equals(countryCode)) { + language = "ZHS"; + } + if ("BRA".equals(countryCode)) { + language = "POR"; + cdIndex = "21"; + } + + if ("SAU".equals(countryCode) || "ARE".equals(countryCode) + || "EGY".equals(countryCode) + || "MEX".equals(countryCode) + || "SGP".equals(countryCode) + || "PHL".equals(countryCode) + || "MYS".equals(countryCode) + || "KHM".equals(countryCode) + ) { + existence = false; + language = "ENG"; + } + // 、 • 7中°~^8英文、心‘9繁体、• ~‘14 越南°~17泰国°~‘21 葡萄牙‘~‘22 印尼 + if ("IDN".equals(countryCode)) { + language = "IDN"; + cdIndex = "22"; + } + if ("THA".equals(countryCode)) { + language = "THA"; + cdIndex = "17"; + } + if ("VNM".equals(countryCode)) { + language = "VIE"; + cdIndex = "14"; + } + + String country = ""; + // 日期 位置 国家 部门code + JSONArray ocDepartmentsGUOJIA = getOcDepartmentsGUOJIA(date, "1", language, departmentCode); + log.writeLog("--------------多语言是否拿到数据:"+ocDepartmentsGUOJIA.size()); + List countryList = JSONArray.parseArray(ocDepartmentsGUOJIA.toJSONString(), DepartmentDto.class); + DepartmentDto countryDto = countryList.get(0); + //对应国家的语言名称(对应国家标签里面) + String countryDepartmentName = countryDto.getDepartmentName(); + log.writeLog("---------------对应国家语言名称:" + countryDepartmentName); + + //departmentName = + if (existence) { + //需要3个标签 + retName = "~`~`7 " + deptName + "`~`8 " + countryDepartmentName + "`~`"+cdIndex+" "+countryDepartmentName+"`~`~"; + } else { + //只需要中文和英文 + retName = "~`~`7 " + deptName + "`~`8 " + countryDepartmentName + "`~`~"; + } + + log.writeLog("---------------多语言名称:" + retName); + } catch (Exception e) { + e.printStackTrace(); + } + return retName; + } + + private void writeFile(JSONArray jsonArray) { + BufferedWriter bw = null; + try { + bw = new BufferedWriter(new FileWriter("D:\\1.txt")); + //一次写一行 + bw.write(jsonArray.toJSONString()); + bw.newLine(); //换行用 + //关闭流 + bw.close(); + } catch (IOException e) { + e.printStackTrace(); + } + System.out.println("写入成功"); + } + + public static void main(String[] args) { + SyncHrmsubcompanyToOA ss = new SyncHrmsubcompanyToOA(); + ss.getSubcompanys(); + } + +// /** +// * 此方法废弃 +// */ +// public void executeInvail() { +// JSONArray subcompanys = getSubcompanys(); +// map_subcompany_code_id = getSubCodeIdMap(); +// RecordSet rs = new RecordSet(); +// log.writeLog("----------开始同步分部,条数:"+subcompanys.size()); +// log.writeLog("----------同步分部源数据:"+subcompanys.toJSONString()); +// // 处理公司同步逻辑 +// for (int i = 0; i < subcompanys.size(); i++) { +// JSONObject sub = subcompanys.getJSONObject(i); +// String Code = Util.null2String(sub.getString("companyCode"));//分部编码 +// String Name = Util.null2String(sub.getString("companyName"));//分部全称 +// String ShortName = Util.null2String(sub.getString("companyAbbreviation"));//分部简称 +// String companyLevelCode = Util.null2String(sub.getString("companyLevelCode"));//公司级别编码 +// String companyLevelName = Util.null2String(sub.getString("companyLevelName"));//公司级别描述 +// String countryCode = Util.null2String(sub.getString("countryCode"));//国家代码 +// String countryName = Util.null2String(sub.getString("countryName"));//国家名称 +// Integer canceled = Util.null2String(sub.getString("status"))== "3"?1:null;//1 新增 2 修改 3作废 +// String sql = ""; +// //判断HR分部ID是否已经存在 +// String now = TimeCommonUtil.obtainDate(0); +// if (!map_subcompany_code_id.containsKey(Code)) {//分部不存在则插入生成新分部 +// //新增数据,插入到hrmsubcompany表中 +// sql = "insert into hrmsubcompany (subcompanyname,subcompanydesc,outkey," + +// "tlevel,canceled,created,creater,modified,modifier,companyid) values(" +// + "'" + ShortName + "'," +// + "'" + Name + "'," +// + "'" + Code + "'," +// + "'" + companyLevelCode + "'," +// + canceled + "," +// + "to_date('" + now + "','yyyy-mm-dd hh24:mi:ss')," +// + "'1'," +// + "to_date('" + now + "','yyyy-mm-dd hh24:mi:ss')," +// + "'1'," +// + "'1')"; +// log.writeLog("插入分部表生成新数据sql--------->" + sql); +// rs.execute(sql); +// +// rs.execute("select max(id) from hrmsubcompany"); +// int maxSubcompanyid = 0;//新插入数据的分部ID +// if (rs.next()) { +// maxSubcompanyid = rs.getInt(1); +// } +// //将新增加的分部加入至MAP中 +// map_subcompany_code_id.put(Code, maxSubcompanyid + ""); +// +// } else {//分部存在则更新 +// sql = "update hrmsubcompany set " + +// "subcompanyname = '" + ShortName + "', " + +// "subcompanydesc = '" + Name + "', " + +// "outkey = '" + Code + "', " + +// "modified = to_date('" + now + "','yyyy-mm-dd hh24:mi:ss')," + +// "modifier = '1', "+ +// "canceled = " + canceled + " "+ +// "where outkey= '" + Code + "'"; +// log.writeLog("更新分部表中数据sql--------->" + sql); +// rs.execute(sql); +// } +// } +// } +} diff --git a/src/main/youhong_ai_jitu_src/jntchina/schedule/hrm/util/OrganizationUtil.java b/src/main/youhong_ai_jitu_src/jntchina/schedule/hrm/util/OrganizationUtil.java new file mode 100644 index 0000000..ab3d056 --- /dev/null +++ b/src/main/youhong_ai_jitu_src/jntchina/schedule/hrm/util/OrganizationUtil.java @@ -0,0 +1,492 @@ +package jntchina.schedule.hrm.util; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.JSONArray; +import com.alibaba.fastjson.JSONObject; +import com.alibaba.fastjson.serializer.SerializerFeature; +import jntchina.schedule.hrm.entity.HrmUserDto; +import jntchina.util.HttpClientToJT; +import org.apache.commons.lang3.StringUtils; +import selfdev.util.base.TimeCommonUtil; +import selfdev.util.log.LogTool; +import weaver.conn.RecordSet; +import weaver.general.Util; + +import java.util.*; +import java.util.stream.Collectors; + +/** + * 极兔集团 + * 组织架构同步通用工具类 + */ +public class OrganizationUtil { + + /** + * 当前类数据库连接 + */ + private static final RecordSet rs = new RecordSet(); + + /** + * 组织同步通用日志操作类 + */ + private static final LogTool logComm = new LogTool("/log/hrm/comm/", false); + + /** + * 组织同步 部门日志操作类 + */ + private static final LogTool logDept = new LogTool("/log/hrm/dept/", false); + + + /** + * 组织同步 人员日志操作类 + */ + private static final LogTool logHrm = new LogTool("/log/hrm/user/", false); + + + private static final String getOrganizationURL = "/dcopenedi/hrDept/pageNewHrDeptByUpdateTime"; + + /** + * 根据岗位外键编码获取其OA中的主键ID值 + * + * @param outKey 外键编码值 + * @return OA主键ID值 + */ + public static String getJobtitleIdByOutKey(String outKey) { + String jobtitleId = ""; + if (!"".equals(outKey) && rs.executeQuery("select id from hrmJobtitles where outKey = ?", new Object[]{outKey}) && rs.next()) { + jobtitleId = Util.null2String(rs.getString(1)); + } + return jobtitleId; + } + + + /** + * 获取员工的直接上级ID 先根据直接上级编码获取对应的员工,若找不到,则获取所在部门的部门负责人作为直接上级 + * + * @param managerCode 直接上级编码 + * @param departmentId 部门ID + * @return 直接上级ID + */ + public static String getEmployeeManagerId(String managerCode, String departmentId) { + String managerId = ""; + if (rs.executeQuery("select id from hrmResource where workCode = ?", new Object[]{managerCode}) && rs.next()) { + managerId = Util.null2String(rs.getString(1)); + } + if ("".equals(managerId) && rs.executeQuery("select bmfzr from hrmDepartmentDefined where deptId = ?", new Object[]{departmentId}) && rs.next()) { + managerId = Util.null2String(rs.getString(1)); + } + return managerId; + } + + /** + * 更新上级领导(原先还未同步的上级领导) + * + * @param noFindManagerMap 未同步上级领导的员工信息集合 + */ + public static void dealNoFindMangerEmployeeData(Map noFindManagerMap) { + Iterator> entries = noFindManagerMap.entrySet().iterator(); + while (entries.hasNext()) { + Map.Entry entry = entries.next(); + String userId = entry.getKey(); + String managerCode = entry.getValue(); + String sql = "select id,outKey from hrmResource where outKey= ?"; + if (rs.executeQuery(sql, new Object[]{managerCode}) && rs.next()) { + String id = Util.null2String(rs.getString("id")); + if (!"".equals(id)) { + String updateSql = "update hrmResource set managerId = ? where workCode =?"; + rs.executeUpdate(updateSql, new Object[]{id, userId}); + } + } + } + } + + + /** + * 获取当期系统中 所有的部门信息<外部主键,OA主键> + * + * @return 返回部门信息集合 + */ + public static Map getAllDepartmentCodeIdMap() { + return getDepartmentCodeIdMap(false); + } + + + /** + * 获取当期系统中 状态未封存的部门信息<外部主键,OA主键> + * + * @return 返回部门信息集合 + */ + public static Map getEffectiveDepartmentCodeIdMap() { + return getDepartmentCodeIdMap(true); + } + + /** + * 获取当期系统中 部门信息<外部主键,OA主键> + * + * @param isEffective 是否生效记录 (CANCELED = 1 表示封存) + * @return 返回部门信息集合 + */ + private static Map getDepartmentCodeIdMap(boolean isEffective) { + String selectSQL; + Map map = new HashMap<>(); + if (isEffective) { + selectSQL = "select departmentCode,outKey,id from HrmDepartment where outKey is not null and (CANCELED!=1 or CANCELED is null)"; + } else { + selectSQL = "select departmentCode,outKey,id from HrmDepartment where outKey is not null"; + } + if (rs.executeQuery(selectSQL, new Object[0])) { + while (rs.next()) { + String outKey = Util.null2String(rs.getString("outKey")); + if (!"".equals(outKey)) + map.put(outKey, rs.getString("id")); + } + } + return map; + } + + /** + * 获取当期系统中 所有的分部信息<外部主键,OA主键> + * + * @return 返回部门信息集合 + */ + public static Map getAllSubCompanyCodeIdMap() { + return getSubCompanyCodeIdMap(false); + } + + + /** + * 获取当期系统中 状态未封存的分部信息<外部主键,OA主键> + * + * @return 返回部门信息集合 + */ + public static Map getEffectiveSubCompanyCodeIdMap() { + return getSubCompanyCodeIdMap(true); + } + + /** + * 获取当期系统中 分部信息<外部主键,OA主键> + * + * @return 返回分部信息集合 + */ + private static Map getSubCompanyCodeIdMap(boolean isEffective) { + String selectSQL; + Map map = new HashMap<>(); + if (isEffective) { + selectSQL = "select outKey,id from HrmSubCompany where outKey is not null and (CANCELED!=1 or CANCELED is null)"; + } else { + selectSQL = "select outKey,id from HrmSubCompany where outKey is not null"; + } + if (rs.executeQuery(selectSQL, new Object[0])) { + while (rs.next()) { + String outKey = Util.null2String(rs.getString("outKey")); + if (!"".equals(outKey)) + map.put(outKey, Util.null2String(rs.getString("id"))); + } + } + return map; + } + + /** + * 获取当前OA系统中 未封存部门信息集合 <外键,OA部门ID^_^OA分部ID> + * + * @return 部门信息集合 + */ + public static Map getEffectiveDeptAndCompany() { + Map map = new HashMap<>(); + RecordSet recordSet = new RecordSet(); + String selectSQL = "select outKey,id,subCompanyId1 from HrmDepartment where outKey is not null and (CANCELED!=1 or CANCELED is null)"; + if (recordSet.executeQuery(selectSQL)) { + while (recordSet.next()) { + String outKey = Util.null2String(recordSet.getString("outKey")); + String keyId = Util.null2String(recordSet.getString("id")); + String subCompanyId = Util.null2String(recordSet.getString("subCompanyId1")); + if (!"".equals(outKey)) + map.put(outKey, keyId + "^_^" + subCompanyId); + } + } + return map; + } + + /** + * 获取人员处理后的姓名 (将系统中人员姓名字段中的简体中文姓名进行替换) + * + * @param oldName 系统原有的姓名 + * @param simplifiedName 默认简体中文的姓名 + * @return 返回处理后的姓名 + */ + public static String dealEmployeeName(String oldName, String simplifiedName) { + String finalName; + if (oldName.contains("~`~`") && oldName.contains("`~`~")) { + //获取第一个出现该字符串的位置 + int firstBit = oldName.indexOf("~`~`"); + //字符串 + 数字 + 空格 + String mindStr = oldName.substring(firstBit + 6); + //第一个姓名的语言 + String lang = oldName.substring(4, oldName.indexOf(" ")); + //两个语言之间分隔符位置 + int endBit = mindStr.indexOf("`~`"); + endBit = endBit < 0 ? mindStr.indexOf("`~`~") : endBit; + String balanceStr = mindStr.substring(endBit); + if ("7".equals(lang)) {//说明第一个语言为简体中文 + finalName = "~`~`7 " + simplifiedName + balanceStr; + } else {//第一个语言不为简体中文,那在其最前面加上该语言姓名 + finalName = "~`~`7 " + simplifiedName + "`~`" + oldName.substring(firstBit + 4); + } + } else { + finalName = "~`~`7 " + simplifiedName + "`~`8 `~`~"; + } + return finalName; + } + + /** + * 根据部门ID获取其对应的分部ID + * + * @param deptId 部门ID + * @return 分部ID + */ + public static String getSubCompanyIdByDeptCode(String deptId) { + String subCompanyId = ""; + RecordSet rs = new RecordSet(); + rs.executeQuery("select subcompanyid1 from HrmDepartment where id ='" + deptId + "'", new Object[0]); + if (rs.next()) { + subCompanyId = Util.null2String(rs.getString(1)); + } + return subCompanyId; + } + + + /** + * 获取部门对应的国家信息 + * + * @return 返回部门国家对应信息集合 + */ + public static Map getDeptCountryMap() { + Map deptCountryMap = new HashMap<>(); + if (rs.executeQuery("select deptId,guojia from hrmDepartmentDefined", new Object[0])) { + while (rs.next()) { + deptCountryMap.put(Util.null2String(rs.getString(1)), Util.null2String(rs.getString(2))); + } + } + return deptCountryMap; + } + + + /** + * 获取部门对应的国家和负责人信息 + * + * @return 返回部门国家和负责人对应信息集合 + */ + public static Map> getDeptCountryAndManagerMap() { + Map> deptCountryAndManagerMap = new HashMap<>(); + if (rs.executeQuery("select deptId,guojia,bmfzr from hrmDepartmentDefined", new Object[0])) { + while (rs.next()) { + String deptId = Util.null2String(rs.getString("deptId")); + Map detailMap = new HashMap<>(); + detailMap.put("guojia", Util.null2String(rs.getString("guojia"))); + detailMap.put("bmfzr", Util.null2String(rs.getString("bmfzr"))); + deptCountryAndManagerMap.put(deptId, detailMap); + } + } + return deptCountryAndManagerMap; + } + + + /** + * 调用人员接口,获取接口返回信息 + * + * @param size 每页条数 + * @param pages 页码 + * @param today 日期 + * @param languageCds 语言代码 + * @param deptCountryCodes 部门国家代码 + * @param code 员工编码 + * @return 接口响应信息 + */ + public static String callEmployeeInterface(int size, String pages, String today, List languageCds, List deptCountryCodes, String code) { + Map params = new HashMap<>(); + params.put("updateTime", today); + params.put("point", pages); + params.put("languageCds", languageCds); + params.put("size", Integer.valueOf(size)); + params.put("deptCountryCodes", deptCountryCodes); + if (!"".equals(code)) { + params.put("employeeCode", code); + } + String url = "https://jtdcapi.jtexpress.com.cn/dcopenedi/hrEmployee/pageByParam"; + String token = HttpClientToJT.getToken(); + return HttpClientToJT.sendPost(url, token, JSONObject.toJSONString(params)); + } + + + /** + * 获取该List中的外键已存在的记录信息 + * + * @param codeList 所有外键信息集合 + * @param dataType 0 - 系统表 1- 自定义表 + * @return 所有已存在的记录集合 + */ + public static Map getExitsData(List codeList, int dataType) { + String selectData; + Map existMap = new HashMap<>(); + if (dataType == 1) { + selectData = "select positionid,positionCode from uf_jobTitleDefined u where exists ( select 1 from ( select regexp_substr('" + StringUtils.join(codeList, ",") + "','[^,]+',1,LEVEL) as code from dual connect by LEVEL <= " + codeList.size() + " ) t where t.code = u.positionCode)"; + } else { + selectData = "select outKey,id from hrmJobTitles where outKey is not null and exists ( select 1 from ( select regexp_substr('" + StringUtils.join(codeList, ",") + "','[^,]+',1,LEVEL) as code from dual connect by LEVEL <= " + codeList.size() + " ) t where t.code = hrmJobTitles.outKey)"; + } + if (rs.executeQuery(selectData, new Object[0])) { + while (rs.next()) { + existMap.put(Util.null2String(rs.getString(1)), Util.null2String(rs.getString(2))); + } + } + return existMap; + } + + /** + * 插入员工自定义 - 个人 + * + * @param userId 用户ID + * @param bankInfo [bankBranchName,bankAccountId,bankName] 银行信息数组 + * @param actionInfo [action,action_describe] 操作信息 + * @param row 用户信息实体类 + * @return 执行结果 + */ + public static boolean insertEmployeeCustomizePersonal(String userId, String[] bankInfo, String[] actionInfo, HrmUserDto row) { + boolean isSuccess; + String now = TimeCommonUtil.obtainDate(0); + if (rs.executeQuery("select 1 from cus_fielddata where id = ? and scopeid = 1 and scope = 'HrmCustomFieldByInfoType'", new Object[]{userId}) && rs.next()) { + return updateEmployeeCustomizePersonal(userId, bankInfo, actionInfo, row); + } + String bankInfoCol = ""; + String bankInfoVal = ""; + if (bankInfo != null && bankInfo.length > 2) { + bankInfoCol = "field0,field1,field5,field7,"; + bankInfoVal = "'" + bankInfo[0] + "','" + bankInfo[1] + "',?,'" + bankInfo[2] + "',"; + } + if (actionInfo != null && actionInfo.length > 1) { + bankInfoCol = bankInfoCol + "field10,field11,"; + bankInfoVal = bankInfoVal + "'" + actionInfo[0] + "','" + actionInfo[1] + "',"; + } + String sql = "insert into cus_fielddata(scope,scopeid,id," + bankInfoCol + "field15,field16,field17,field18,field19,field20,field21,field14,field22,field23,field24,created1,modified1) values('HrmCustomFieldByInfoType','1','" + userId + "'," + bankInfoVal + "'" + Util.null2String(row.getEmployeeCode()) + "','" + + Util.null2String(row.getCompanyCode()) + "','" + + Util.null2String(row.getCompanyName()) + "','" + + Util.null2String(row.getDeptCode()) + "','" + + Util.null2String(row.getDeptName()) + "','" + + Util.null2String(row.getPositionCode()) + "','" + + Util.null2String(row.getPositionName()) + "','" + + Util.null2String(row.getPositionType()) + "','" + + Util.null2String(row.getPositionTypeDescr()) + "','" + + Util.null2String(row.getPositonRankCode()) + "','" + + Util.null2String(row.getPositonRankDescr()) + + "',to_date('" + now + "','yyyy-mm-dd hh24:mi:ss')," + + "to_date('" + now + "','yyyy-mm-dd hh24:mi:ss')" + ")"; + if (bankInfo != null && bankInfo.length > 2) { + isSuccess = rs.executeUpdate(sql, new Object[]{Util.null2String(row.getEmployeeName())}); + } else { + isSuccess = rs.executeUpdate(sql, new Object[0]); + } + logComm.writeLog("写入人员自定义信息:[" + sql + "],执行结果:[" + isSuccess + "]"); + return isSuccess; + } + + /** + * 更新员工自定义 - 个人 + * + * @param userId 用户ID + * @param bankInfo [bankBranchName,bankAccountId,bankName] 银行信息数组 + * @param actionInfo [action,action_describe] 操作信息 + * @param row 用户信息实体类 + * @return 执行结果 + */ + public static boolean updateEmployeeCustomizePersonal(String userId, String[] bankInfo, String[] actionInfo, HrmUserDto row) { + boolean isSuccess; + String now = TimeCommonUtil.obtainDate(0); + String cusCol = ""; + if (bankInfo != null && bankInfo.length > 2) { + cusCol = "field0 = '" + bankInfo[0] + "', field1 = '" + bankInfo[1] + "', field5 = ?, field7 = '" + bankInfo[2] + "', "; + } + if (actionInfo != null && actionInfo.length > 1) { + cusCol = cusCol + "field10 = '" + actionInfo[0] + "', field11 = '" + actionInfo[1] + "', "; + } + String updateSQL = "update cus_fielddata set " + cusCol + "field15 = '" + Util.null2String(row.getEmployeeCode()) + "', field16 = '" + Util.null2String(row.getCompanyCode()) + "', field17 = '" + Util.null2String(row.getCompanyName()) + "', field18 = '" + Util.null2String(row.getDeptCode()) + "', field19 = '" + Util.null2String(row.getDeptName()) + "', field20 = '" + Util.null2String(row.getPositionCode()) + "', field21 = '" + Util.null2String(row.getPositionName()) + "', field14 = '" + Util.null2String(row.getPositionType()) + "', field22 = '" + Util.null2String(row.getPositionTypeDescr()) + + "', field23 = '" + Util.null2String(row.getPositonRankCode()) + + "', field24 = '" + Util.null2String(row.getPositonRankDescr()) + + "', modified1 = to_date('" + now + "','yyyy-mm-dd hh24:mi:ss')" + + " where id ='" + userId + "' and scopeid='1' and scope = 'HrmCustomFieldByInfoType'"; + if (bankInfo != null && bankInfo.length > 2) { + isSuccess = rs.executeUpdate(updateSQL, new Object[]{Util.null2String(row.getEmployeeName())}); + } else { + isSuccess = rs.executeUpdate(updateSQL, new Object[0]); + } + logComm.writeLog("更新人员自定义信息:[" + updateSQL + "],执行结果:[" + isSuccess + "]"); + return isSuccess; + } + + + /** + * 处理人员昵称信息 + * + * @param userId 用户ID + * @param nickName 昵称 + */ + public static void dealEmployeeNickName(String userId, String nickName) { + String cusSql; + RecordSet rs = new RecordSet(); + rs.executeQuery("select id from cus_fielddata where scopeid='-1' and scope='HrmCustomFieldByInfoType' and id = ?", new Object[]{userId}); + if (!rs.next()) { + cusSql = "insert into cus_fielddata(scope,scopeid,id,field0) values('HrmCustomFieldByInfoType','-1','" + userId + "',?)"; + } else { + cusSql = "update cus_fielddata set scopeid = '-1',field0 = ? where id ='" + userId + "' and scopeid='-1' and scope = 'HrmCustomFieldByInfoType'"; + } + boolean b = rs.executeUpdate(cusSql, new Object[]{nickName}); + logComm.writeLog("-------------修改自定义基本信息:" + cusSql); + logComm.writeLog("-------------修改自定义基本是否成功:" + b); + } + + + /** + * 获取组织信息 + * + * @param dateTimeTs 同步时间戳 (上一次同步时间戳) + * @return 所有组织信息的JSONArray对象 + */ + @SuppressWarnings("unchecked") + public JSONArray getDepartmentsByPoint(String dateTimeTs) { + String url = "https://jtdcapi.jtexpress.com.cn/dcopenedi/hrDept/pageNewHrDeptByUpdateTime"; + logComm.writeLog("获取部门数据url-------->" + url); + JSONArray jsonArray = new JSONArray(); + boolean hasNext = true; + String token = HttpClientToJT.getToken(); + int point = 1; + Map requestMap = new HashMap<>(); + requestMap.put("updateTime", dateTimeTs); + requestMap.put("size", Integer.valueOf(1000)); + do { + try { + requestMap.put("point", Integer.valueOf(point)); + String param = JSONObject.toJSONString(requestMap, new SerializerFeature[]{SerializerFeature.DisableCircularReferenceDetect}); + logComm.writeLog("获取组织数据传入参数param------------>" + param); + String s = HttpClientToJT.sendPost(url, token, param); + logDept.writeLog("组织数据返回结果------------>" + s); + JSONObject jsonObject = JSONObject.parseObject(s); + String code = Util.null2String(jsonObject.getString("code")); + logDept.writeLog("code------------>" + code); + if ("1".equals(code)) { + JSONObject result = jsonObject.getJSONObject("data"); + hasNext = result.getBoolean("hasNextPage").booleanValue(); + point = Util.getIntValue(result.getString("maxPoint"), 0); + JSONArray records = result.getJSONArray("records"); + if (records != null) { + Object directSales = records.stream().filter(item -> { + JSONObject itemJson = JSONObject.parseObject(JSON.toJSONString(item)); + return ("CHN".equals(itemJson.getString("countryCode")) && "ZHS".equals(itemJson.getString("languageCd"))); + }).collect(Collectors.toList()); + jsonArray.addAll((Collection) JSONArray.parseArray(JSON.toJSONString(directSales))); + } + } + } catch (Exception e) { + logDept.writeLog("获取组织接口报错,错误信息:" + e.getMessage()); + } + } while (hasNext); + return jsonArray; + } +} diff --git a/src/main/youhong_ai_jitu_src/jntchina/schedule/hrmNew/InternalSync.java b/src/main/youhong_ai_jitu_src/jntchina/schedule/hrmNew/InternalSync.java new file mode 100644 index 0000000..c5befce --- /dev/null +++ b/src/main/youhong_ai_jitu_src/jntchina/schedule/hrmNew/InternalSync.java @@ -0,0 +1,577 @@ +package jntchina.schedule.hrmNew; + +import aiyh.utils.Util; +import aiyh.utils.tool.cn.hutool.core.util.StrUtil; +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.JSONArray; +import com.alibaba.fastjson.JSONObject; +import com.engine.common.service.impl.HrmCommonServiceImpl; +import jntchina.schedule.hrm.entity.DepartmentDto; +import jntchina.schedule.hrm.entity.HrmUserDto; +import selfdev.util.base.BaseUtil; +import selfdev.util.log.LogTool; +import weaver.conn.RecordSet; +import weaver.hrm.job.JobTitlesComInfo; +import weaver.hrm.resource.ResourceComInfo; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.stream.Collectors; + +/** + * 极兔集团 + * 国内架构同步操作 + */ +@SuppressWarnings("all") +public class InternalSync { + + /** + * 部门日志操作 + */ + private static final LogTool logDept = new LogTool("/log/hrm/dept/", false); + + /** + * 岗位日志操作 + */ + private static final LogTool logJob = new LogTool("/log/hrm/job/", false); + + /** + * 员工日志操作 + */ + private static final LogTool logHrm = new LogTool("/log/hrm/user/", false); + + /** + * 分部、部门同步逻辑处理 + * + * @param lastTimestamp 上一次同步时间戳 + */ + + public void syncOrganizationData(String lastTimestamp, String currentDateTime) { + // 从配置中获取自定义分部名称 + String subCompanyNames = Util.getCusConfigValue("PS_Fixed_SubCompanyNames"); + // 将分部名称转成List集合 + List fixSubCompanyList = Util.splitString2List(subCompanyNames, ","); + + // 调用接口,获取组织信息 + JSONArray dataArray = OrganizationUtil.getDepartmentsByPoint(lastTimestamp, SyncConstants.SyncDataType_Internal_Data, 1000); + + // 将JSON数组转成对象集合 + List dataList = JSONArray.parseArray(dataArray.toJSONString(), DepartmentDto.class); + + // 分部数据 + List subCompanyList = dataList.stream().filter(item -> "10".equals(item.getOrganizationClass()) || fixSubCompanyList.contains(item.getDepartmentName())).collect(Collectors.toList()); + + // 部门数据 + List departmentList = dataList.stream().filter(item -> !"10".equals(item.getOrganizationClass()) && !fixSubCompanyList.contains(item.getDepartmentName())).collect(Collectors.toList()); + + // 跳过的数据集合 + List skipList = new ArrayList<>(); + // 跳过数量 插入数量 更新数量 + int skipNum = 0, insertNum = 0, updateNum = 0; + + // 部门数据不为空 + if (!dataList.isEmpty()) { + RecordSet rs = new RecordSet(); + + // 分部数据不为空 + if (!subCompanyList.isEmpty()) { + OrganizationUtil.subCompanySyncDeal(subCompanyList, currentDateTime); + } + + if (!departmentList.isEmpty()) { + // 人员数据集合 + Map userMap = OrganizationUtil.getEmployeeMap(); + // 部门数据集合 + Map oaDeptMap = OrganizationUtil.getEffectiveDepartmentCodeIdMap(); + // 分部数据集合 + Map oaComMap = OrganizationUtil.getEffectiveSubCompanyCodeIdMap(); + // 部门分部数据集合 + Map oaDeptAndComMap = OrganizationUtil.getDepartmentCodeAndComIdMap(); + + for (DepartmentDto row : departmentList) { + // 国家编码 + String countryCode = Util.null2String(row.getCountryCode()); + // 部门编码 + String departmentCode = Util.null2String(row.getDepartmentCode()); + // 部门全称 + String departmentName = Util.null2String(row.getDepartmentName()); + // 上级部门编码 + String superiorDepartment = Util.null2String(row.getSuperiorDepartment()); + // 排序 + String departmentOrder = Util.null2String(row.getDepartmentOrder()); + // 部门负责人code + String deptManager = Util.null2String(row.getDeptManager()); + // 分管领导code + String brchLeader = Util.null2String(row.getBrchLeader()); + // 1 新增 2 修改 3作废 + int canceled = Util.null2String(row.getStatus()).equals("3") ? 1 : 0; + // 公司 + String companyCode = Util.null2String(row.getCompanyCode()); + + // 上级部门为空时,则跳过同步 + if ("".equals(superiorDepartment)) { + skipList.add(row); + skipNum++; + logDept.writeLog("---->部门编码【" + departmentCode + "】、部门名称【" + departmentName + "】的上级部门为空,跳过同步----------"); + continue; + } + + // 直接上级ID + String managerId = Util.null2String(userMap.get(deptManager)); + // 分管领导ID + String leaderId = Util.null2String(userMap.get(brchLeader)); + + // 根据上级编码找到其对应上级部门和上级分部ID + String supDeptId = Util.null2String(oaDeptMap.get(superiorDepartment)); + String subCompanyId = Util.null2String(oaComMap.get(superiorDepartment)); + + // 如果上级编码为空、所属分部,上级部门都找不到,不作处理 + if ("".equals(subCompanyId) && "".equals(supDeptId)) { + skipList.add(row); + skipNum++; + logDept.writeLog("--->部门编码【" + departmentCode + "】、部门名称【" + departmentName + "】、上级部门编码【" + superiorDepartment + "】在OA中为匹配上上级部门,或者未找到所属分部,跳过同步----------"); + continue; + } + + if (!"".equals(subCompanyId)) {// 上级部门编码为分部,则当前部门为顶级部门 + supDeptId = "0"; + } else { + // 获取该部门对应的分部信息 + subCompanyId = Util.null2String(oaDeptAndComMap.get(supDeptId)); + } + + // 只需要中文和英文 + departmentName = "~`~`7 " + departmentName + "`~`8 `~`~"; + + if (oaDeptMap.containsKey(departmentCode)) {// 该部门数据存在,执行更新操作 + String oldDeptId = Util.null2String(oaDeptMap.get(departmentCode)); + + if ("".equals(oldDeptId)) { + skipNum++; + continue; + } + + String updateStr = ""; + // 只有有值才覆盖 + updateStr += !"".equals(subCompanyId) ? "subcompanyid1 = '" + subCompanyId + "', " : ""; + updateStr += !"".equals(managerId) ? "bmfzr = '" + managerId + "', " : ""; + updateStr += !"".equals(leaderId) ? "bmfgld = '" + leaderId + "', " : ""; + String operateSQL = "update HrmDepartment set " + + "departmentName = '" + departmentName + "', " + + "departmentMark = '" + departmentName + "', " + + "supDepId = '" + supDeptId + "'," + + updateStr + + "canceled = " + canceled + ", " + + "modified = to_date('" + currentDateTime + "','yyyy-mm-dd hh24:mi:ss'), " + + "modifier = '1', " + + "showOrder = '" + departmentOrder + "' " + + "where id= '" + oldDeptId + "'"; + + logDept.writeLog("部门数据更新SQL:[" + operateSQL + "]"); + + updateNum++; + + OrganizationUtil.departmentDefinedDeal(oldDeptId, row.getIsDirectSales(), companyCode, managerId, countryCode, leaderId); + if (rs.executeUpdate(operateSQL)) { + // 人员信息伴随部门信息变化 + if (!"".equals(subCompanyId)) { + operateSQL = "update hrmResource set subCompanyId1='" + subCompanyId + "' where departmentId = '" + oldDeptId + "' "; + rs.executeUpdate(operateSQL); + + // 更新该部门的所有下级部门的所属分部 + operateSQL = "update hrmdepartment set subCompanyId1 = '" + subCompanyId + "' where exists ( \n" + + " select 1 from (" + + " select id from hrmdepartment start with id = " + oldDeptId + " connect by supDepId = prior id \n" + + " ) s where s.id = hrmdepartment.id \n" + + ")"; + + rs.executeUpdate(operateSQL); + } + } + } else { // 该部门数据不存在,执行插入操作 + String operateSQL = "insert into HrmDepartment (departmentName,departmentCode,departmentMark,outkey," + + "supDepId,canceled,created,creater,modified,modifier," + + "showOrder,subcompanyid1,bmfzr,bmfgld) values(" + + "'" + departmentName + "'," + + "'" + departmentCode + "'," + + "'" + departmentName + "'," + + "'" + departmentCode + "'," + + "'" + supDeptId + "'," + + "" + canceled + "," + + "to_date('" + currentDateTime + "','yyyy-mm-dd hh24:mi:ss')," + + "'1'," + + "to_date('" + currentDateTime + "','yyyy-mm-dd hh24:mi:ss')," + + "'1'," + + "'" + departmentOrder + "'," + + "'" + subCompanyId + "', " + + "'" + managerId + "', " + + "'" + leaderId + "')"; + + insertNum++; + logDept.writeLog("部门数据写入SQL:[" + operateSQL + "]"); + if (rs.executeUpdate(operateSQL)) { + + if (rs.executeQuery("select id from HrmDepartment where outkey = ?", departmentCode) && rs.next()) { + String newDeptId = Util.null2String(rs.getString(1)); + + oaDeptMap.put(departmentCode, newDeptId); + oaDeptAndComMap.put(departmentCode, subCompanyId); + + // 部门自定义信息处理 + OrganizationUtil.departmentDefinedDeal(newDeptId, row.getIsDirectSales(), companyCode, managerId, countryCode, leaderId); + } else { + logDept.writeLog("获取最新插入的部门记录ID失败!"); + } + } else { + logDept.writeLog("部门数据操作写入失败!"); + } + } + } + } + logDept.writeLog("此次同步部门总数为:" + departmentList.size() + ",新增部门数为:" + insertNum + + ",更新部门数为:" + updateNum + ",跳出处理部门数为:" + skipNum); + logDept.writeLog("此次同步部门跳过是数据为:" + JSON.toJSONString(skipList)); + } + } + + + /** + * 岗位同步逻辑处理 + * + * @param lastTimestamp 上一次处理时间戳 + * @param currentDateTime 当前时间 + */ + public void syncJobTitleData(String lastTimestamp, String currentDateTime) { + // 分页获取接口数据 + // JSONArray dataArray = OrganizationUtil.getJobTitleByPoint(lastTimestamp, SyncConstants.SyncDataType_Internal_Data, 5000); + Map jobTitleByPoint = OrganizationUtil.getJobTitleByPoint(lastTimestamp, SyncConstants.SyncDataType_Internal_Data, 5000); + JSONArray dataArray = jobTitleByPoint.get("filterResult"); + JSONArray allResult = jobTitleByPoint.get("allResult"); + + if (!dataArray.isEmpty()) { + logJob.writeLog("获取岗位的记录总条数:[" + dataArray.size() + "]"); + + // 当前OA系统中部门信息 + Map oaDeptMap = OrganizationUtil.getEffectiveDepartmentCodeIdMap(); + + // 已存在的岗位数据集合 + Map sysExistMap = new HashMap<>(); + // 已存在的岗位自定义数据集合 + Map definedExistMap = new HashMap<>(); + + List codeList = new ArrayList<>(); + + RecordSet rs = new RecordSet(); + + for (int m = 0; m < dataArray.size(); m++) { + JSONObject row = dataArray.getJSONObject(m); + String positionCode = Util.null2String(row.getString("positionCode"));// 岗位编码 + if (!"".equals(positionCode)) { + codeList.add(positionCode); + } + } + + if (codeList.size() > 0) { + sysExistMap = OrganizationUtil.getExitsData(codeList, 0); + definedExistMap = OrganizationUtil.getExitsData(codeList, 1); + } + + // 跳过的记录条数,插入记录条数,更新记录条数 + int skipNum = 0, insertNum = 0, updateNum = 0; + + JobTitleMultilingualUtil jobTitleMultilingualUtil = new JobTitleMultilingualUtil(); + for (int k = 0; k < dataArray.size(); k++) { + JSONObject row = dataArray.getJSONObject(k); + String positionCode = Util.null2String(row.getString("positionCode"));// 岗位编码 + // 获取多语言岗位名称 + String positionName = jobTitleMultilingualUtil.getMultilingual(allResult, + row, + item -> Util.null2String(item.get("positionCode")), + item -> Util.null2String(item.get("positionName")), + item -> Util.null2String(item.get("languageCd"))); + if (StrUtil.isBlank(positionName)) { + positionName = Util.null2String(row.getString("positionName"));// 岗位名称 + } + Integer canceled = "3".equals(Util.null2String(row.getString("status"))) ? 1 : null;// 1 新增 2 修改 3作废 + String deptCode = Util.null2String(row.getString("deptCode"));// 部门编码 + String jobDepartmentId = Util.null2String(oaDeptMap.get(deptCode));// 所属部门ID + String jobTitleId = Util.null2String(sysExistMap.get(positionCode));// OA岗位ID + + // 判断HR岗位所属部门ID是否已经存在 + if ("".equals(jobDepartmentId)) { + skipNum++; + continue; + } + + if (!"".equals(jobTitleId)) {// 说明该岗位数据已存在,需要进行更新操作 + updateNum++; + + // 新增数据,插入到hrmJobTitles表中 + String operateSQL = "insert into hrmJobTitles (jobTitleName,jobTitleMark,outkey,jobDepartmentId," + + "canceled,created,creater,modified,modifier) values(" + + "'" + positionName + "'," + + "'" + positionName + "'," + + "'" + positionCode + "'," + + "'" + jobDepartmentId + "'," + + "" + canceled + "," + + "to_date('" + currentDateTime + "','yyyy-mm-dd hh24:mi:ss')," + + "'1'," + + "to_date('" + currentDateTime + "','yyyy-mm-dd hh24:mi:ss')," + + "'1')"; + + logJob.writeLog("岗位基本信息插入操作SQL:[" + operateSQL + "]"); + if (rs.executeUpdate(operateSQL)) { + // 获取最新写入的数据ID + if (rs.executeQuery("select id from hrmJobTitles where outkey = ?", positionCode) && rs.next()) { + String newJobId = Util.null2String(rs.getString(1)); + + sysExistMap.put(positionCode, newJobId); + + // 岗位自定义信息处理 + int newCusId = OrganizationUtil.jobTitleDefinedDeal(newJobId, row); + + if (newCusId > 0) { + definedExistMap.put(positionCode, String.valueOf(newCusId)); + } + } else { + logJob.writeLog("获取最新写入的岗位ID失败!"); + } + } else { + logJob.writeLog("岗位基本信息数据写入失败!"); + } + } else {// 说明该岗位数据不存在,需要进行插入操作 + String operateSQL = "update hrmJobtitles set " + + "jobtitleName = '" + positionName + "', " + + "jobtitleMark = '" + positionName + "', " + + "jobtitleCode = '" + positionCode + "', " + + "jobDepartmentId = '" + jobDepartmentId + "', " + + "modified = to_date('" + currentDateTime + "','yyyy-mm-dd hh24:mi:ss')," + + "modifier = '1', " + + "canceled = " + canceled + " " + + "where id= '" + jobTitleId + "'"; + + logJob.writeLog("岗位基本信息更新操作SQL:[" + operateSQL + "]"); + + if (rs.executeUpdate(operateSQL)) { + OrganizationUtil.jobTitleDefinedDeal(jobTitleId, row); + } else { + logJob.writeLog("岗位基本信息数据更新失败!"); + } + + insertNum++; + } + } + + logJob.writeLog("----------同步结束岗位,新增岗位数为:" + insertNum + " ,更新岗位数为:" + updateNum + ",跳出处理岗位数为:" + skipNum + "------------"); + + // 更新岗位缓存 + JobTitlesComInfo jobTitlesComInfo = new JobTitlesComInfo(); + jobTitlesComInfo.removeJobTitlesCache(); + } + } + + /** + * 人员同步逻辑处理 + * + * @param lastTimestamp 上一次处理时间戳 + */ + @SuppressWarnings("unchecked") + public void syncEmployeeData(String lastTimestamp, String currentDateTime) { + JSONArray dataArray = OrganizationUtil.getEmployeeByPoint(lastTimestamp, SyncConstants.SyncDataType_Internal_Data, 1000); + + if (!dataArray.isEmpty()) { + HrmCommonServiceImpl hrmCommonServiceImpl = new HrmCommonServiceImpl(); + + // 获取当前系统中的人员信息 + Map oaUserMap = OrganizationUtil.getEmployeeMap(); + // 获取当前系统中有效的岗位信息 + Map oaJobTitleMap = OrganizationUtil.getEffectiveJobTitleMap(); + // 获取当前系统中有效的部门和分部信息 + // Map oaDeptAndComMap = OrganizationUtil.getEffectiveDeptAndCompany(); + // 获取当前系统中有效的部门信息 + Map> oaDeptInfoMap = OrganizationUtil.getEffectiveDepartmentInfoMap(); + // 获取当前系统中用户自定义信息 + Map userDefinedMap = OrganizationUtil.getEmployeeDefinedMap(); + + // 将查询结果放到list对象中 + List usersList = JSONArray.parseArray(dataArray.toJSONString(), HrmUserDto.class); + + // 未获取到的上级的集合 + Map noFindManagerMap = new HashMap<>(); + + RecordSet rs = new RecordSet(); + + // 从建模表中读取默认密码(默认密码Jitu@2021) + String password = BaseUtil.getBaseInfoByParm("mrmm", "uf_tbygmrdllm", "1", "1", ""); + if ("".equals(password)) { + password = "Jitu@2021"; + } + password = BaseUtil.MD5(password); + + try { + // 更新人员缓存 + ResourceComInfo resourceComInfo = new ResourceComInfo(); + for (HrmUserDto row : usersList) { + // 昵称 + String field0 = Util.null2String(row.getEmployeeEnglishName());// 员工英文姓名 + String employeeCode = Util.null2String(row.getEmployeeCode());// 员工code + String employeeName = Util.null2String(row.getEmployeeName());// 姓名 + String managerCode = Util.null2String(row.getSupervisorId());// 上级次账号code + // 获取人员姓名的拼音 + String name_pinyin = hrmCommonServiceImpl.generateQuickSearchStr(employeeName); + String hrStatus = Util.null2String(row.getHrStatus());// 状态A在职,I离职 对应OA的1正式 5离职 + int status = "A".equals(hrStatus) ? 1 : 5;// OA的在职状态 + String deptCode = Util.null2String(row.getDeptCode());// 部门 + String positionCode = Util.null2String(row.getPositionCode());// 岗位 + String bankBranchName = Util.null2String(row.getBankBranchName());// 开户行 + String bankAccountId = Util.null2String(row.getBankAccountId());// 银行卡号 + String bankName = Util.null2String(row.getBankName());// 银行类型 + String action = Util.null2String(row.getAction());// 操作编码 + String actionDesc = Util.null2String(row.getActionDescr()).replace("'", "''");// 操作名称 + String departmentid, subcompanyid1; + // 根据员工code获取员工id + String userId = Util.null2String(oaUserMap.get(employeeCode));// 员工ID + + logHrm.writeLog("员工编号:[" + employeeCode + "],状态:[" + hrStatus + "],部门:[" + deptCode + "],上级编号:[" + managerCode + "],岗位:[" + positionCode + "]"); + + if (!"".equals(userId)) { + if (status == 5) {// 离职员工 + // 更新离职状态和清空账号信息 + String sql = "update hrmresource set " + + "loginid = '', " + + "account='', " + + "modified = to_date('" + currentDateTime + "','yyyy-mm-dd hh24:mi:ss')," + + "modifier = '1', " + + "lastmoddate = '" + currentDateTime.substring(0, 10) + "', " + + "lastmodid = '1', " + + "status = '5' " + + "where id ='" + userId + "' and workcode='" + employeeCode + "'"; + logHrm.writeLog("更新员工状态为离职sql--------->" + sql); + rs.executeUpdate(sql); + continue; + } + } + + String managerId; + if ("".equals(deptCode)) { + logHrm.writeLog("部门编码为空,直接跳过!"); + continue; + } else { + if (oaDeptInfoMap.containsKey(deptCode)) { + Map detailMap = oaDeptInfoMap.get(deptCode); + + departmentid = detailMap.get("deptId"); + subcompanyid1 = detailMap.get("subCompanyId"); + + // 再次获取其部门所属的国家编码 + String countryCode = detailMap.get("countryCode"); + + if (!"".equals(countryCode) && !"CHN".equals(countryCode)) { + logHrm.writeLog("该员工所属部门的国家属性不为CHN,直接跳过!"); + continue; + } + + // 处理直接上级 + if ("".equals(managerCode)) {// 直接上级编码为空 + // 再次获取该部门的部门负责人 + managerId = detailMap.get("deptManager"); + + if (managerId.contains(",")) { + logHrm.writeLog("该员工所属部门的部门负责人存在多人,直接跳过!"); + } + } else { + managerId = Util.null2String(oaUserMap.get(managerCode)); + } + + // 未找到上级的数据存入临时的Map集合中,待后续处理 + if ("".equals(managerId) && !"".equals(managerCode)) { + noFindManagerMap.put(employeeCode, managerCode); + } + } else { + logHrm.writeLog("部门编码:[" + deptCode + "],在OA中不存在或封存状态!"); + continue; + } + } + + // 处理岗位id + String jobtitleId = ""; + if (!"".equals(positionCode)) { + jobtitleId = Util.null2String(oaJobTitleMap.get(positionCode));// 岗位ID + } + + logHrm.writeLog("处理完匹配关系后信息,部门ID:[" + departmentid + "],分部ID:[" + subcompanyid1 + "],直接上级:[" + managerId + "],岗位ID:[" + jobtitleId + "]"); + + // 操作信息 + String[] actionInfo = new String[]{action, actionDesc}; + String[] bankInfo = new String[]{bankBranchName, bankAccountId, bankName}; + + if (oaUserMap.containsKey(employeeCode)) {// 说明当前用户在OA系统中已存在 + // 人员基本信息更新操作 + boolean isSuccess = OrganizationUtil.updateEmployeeBaseInfo(userId, row, employeeName, subcompanyid1, departmentid, jobtitleId, managerId, name_pinyin, currentDateTime); + + logHrm.writeLog("人员基本信息更新结果:[" + isSuccess + "]"); + + // 基本信息处理 + OrganizationUtil.dealEmployeeNickName(userId, field0); + + if (!userDefinedMap.containsKey(userId)) {// 判断该员工的工作自定义信息是否存在 + isSuccess = OrganizationUtil.insertEmployeeCustomizePersonal(userId, bankInfo, actionInfo, row); + } else { + // 更新人员工作信息表数据 + if ("".equals(bankAccountId)) { + isSuccess = OrganizationUtil.updateEmployeeCustomizePersonal(userId, null, actionInfo, row); + } else { + isSuccess = OrganizationUtil.updateEmployeeCustomizePersonal(userId, bankInfo, actionInfo, row); + } + } + // 人员缓存信息更新 + resourceComInfo.updateResourceInfoCache(userId); + logHrm.writeLog("人员自定义工作信息更新结果:[" + isSuccess + "]"); + + } else {// 说明当前用户在OA系统中不存在,需要进行插入操作 + // 获取最新的用户ID + if (rs.executeProc("HrmResourceMaxId_Get", "") && rs.next()) { + String newUserId = Util.null2String(rs.getInt(1)); + + // 人员基本信息插入操作 + boolean isSuccess = OrganizationUtil.insertEmployeeBaseInfo(newUserId, row, employeeName, subcompanyid1, departmentid, jobtitleId, managerId, name_pinyin, password, currentDateTime); + + if (isSuccess) { + oaUserMap.put(employeeCode, newUserId); + OrganizationUtil.dealEmployeeNickName(newUserId, field0); + + if ("".equals(bankAccountId)) { + isSuccess = OrganizationUtil.insertEmployeeCustomizePersonal(newUserId, null, actionInfo, row); + } else { + isSuccess = OrganizationUtil.insertEmployeeCustomizePersonal(newUserId, bankInfo, actionInfo, row); + } + + if (isSuccess) { + userDefinedMap.put(newUserId, employeeCode); + } + logHrm.writeLog("人员自定义工作信息写入结果:[" + isSuccess + "]"); + } + + // 人员缓存处理 + resourceComInfo.addResourceInfoCache(newUserId); + } else { + logHrm.writeLog("获取新用户ID失败,请联系系统管理员检查数据库存储过程!"); + } + } + + } + } catch (Exception e) { + e.printStackTrace(); + } + + + if (!noFindManagerMap.isEmpty()) {// 待处理数据不为空 + OrganizationUtil.dealNoFindMangerEmployeeData(noFindManagerMap); + } + } + } + + +} diff --git a/src/main/youhong_ai_jitu_src/jntchina/schedule/hrmNew/JobTitleMultilingualUtil.java b/src/main/youhong_ai_jitu_src/jntchina/schedule/hrmNew/JobTitleMultilingualUtil.java new file mode 100644 index 0000000..552f87c --- /dev/null +++ b/src/main/youhong_ai_jitu_src/jntchina/schedule/hrmNew/JobTitleMultilingualUtil.java @@ -0,0 +1,194 @@ +package jntchina.schedule.hrmNew; + +import aiyh.utils.Util; +import com.alibaba.fastjson.JSONArray; +import com.alibaba.fastjson.JSONObject; + +import java.util.*; +import java.util.function.Function; +import java.util.stream.Collectors; + +/** + *

职位多语言工具类

+ * + *

create: 2023/3/24 14:14

+ * + * @author youHong.ai + */ +public class JobTitleMultilingualUtil { + private static final Map LANGUAGE_MAP = new HashMap<>(); + + private JSONArray jsonArray = null; + private Map> groupMap = null; + + private final Long updateTime = 0L; + + static { + extracted(); + } + + private static void extracted() { + try { + Map jituMultilingual = Util.readProperties2Map("JituMultilingual", "cus.multilingual"); + if (!isEmpty(jituMultilingual)) { + for (Map.Entry entry : jituMultilingual.entrySet()) { + LANGUAGE_MAP.put(entry.getKey(), Util.null2String(entry.getValue())); + } + } + } catch (Exception e) { + Util.getLogger().error("初始化多语言配置参数失败:" + e.getMessage() + "\n" + Util.getErrString(e)); + } + } + + + private static boolean isEmpty(Map map) { + return Objects.isNull(map) || map.isEmpty(); + } + + public static boolean isEmpty(Collection collection) { + return collection == null || collection.isEmpty(); + } + + public static boolean isBlankChar(int c) { + return Character.isWhitespace(c) + || Character.isSpaceChar(c) + || c == '\ufeff' + || c == '\u202a' + || c == '\u0000' + // issue#I5UGSQ,Hangul Filler + || c == '\u3164' + // Braille Pattern Blank + || c == '\u2800' + // MONGOLIAN VOWEL SEPARATOR + || c == '\u180e'; + } + + public static boolean isBlankChar(char c) { + return isBlankChar((int) c); + } + + public static boolean isBlank(CharSequence str) { + final int length; + if ((str == null) || ((length = str.length()) == 0)) { + return true; + } + + for (int i = 0; i < length; i++) { + // 只要有一个非空字符即为非空字符串 + if (!isBlankChar(str.charAt(i))) { + return false; + } + } + + return true; + } + + + public static List sub(List list, int start, int end) { + return sub(list, start, end, 1); + } + + public static List sub(List list, int start, int end, int step) { + if (list == null) { + return null; + } + + if (list.isEmpty()) { + return new ArrayList<>(0); + } + + final int size = list.size(); + if (start < 0) { + start += size; + } + if (end < 0) { + end += size; + } + if (start == size) { + return new ArrayList<>(0); + } + if (start > end) { + int tmp = start; + start = end; + end = tmp; + } + if (end > size) { + if (start >= size) { + return new ArrayList<>(0); + } + end = size; + } + + if (step < 1) { + step = 1; + } + + final List result = new ArrayList<>(); + for (int i = start; i < end; i += step) { + result.add(list.get(i)); + } + return result; + } + + /** + *

获取多语言字符串

+ * + * @param jsonArray 总数据 + * @param currentObj 当前对象 + * @param getKey 获取分组key的方法 + * @param getName 获取名称的方法 + * @param getLanguageCd 获取语言cd的方法 + * @return 最终多语言字符串 + */ + public String getMultilingual(JSONArray jsonArray, + JSONObject currentObj, + Function getKey, + Function getName, + Function getLanguageCd) { + long l = System.currentTimeMillis(); + if (l - updateTime >= 1_000 * 60 * 60 * 3) { + extracted(); + } + StringBuilder sb = new StringBuilder(); + List list = jsonArray.toJavaList(Map.class); + Map> groupMap = null; + // 对比缓存数据,如果是上一次传递进来的总数组,则不用再次分组 + if (!jsonArray.equals(this.jsonArray)) { + this.jsonArray = jsonArray; + this.groupMap = list.stream().collect(Collectors.groupingBy(getKey)); + } + String active = LANGUAGE_MAP.get("active"); + if (isBlank(active)) { + return getName.apply(JSONObject.toJavaObject(currentObj, Map.class)); + } + // 默认添加中文 + active += ",ZHS"; + String[] activeLanguageArray = active.split(","); + List activeList = Arrays.stream(activeLanguageArray).distinct().collect(Collectors.toList()); + groupMap = this.groupMap; + if (!isEmpty(groupMap)) { + List maps = groupMap.get(getKey.apply(JSONObject.toJavaObject(currentObj, Map.class))); + if (!isEmpty(maps)) { + sb.append("~`"); + for (Map map : maps) { + String name = getName.apply(map); + String languageCd = getLanguageCd.apply(map); + // 当语言转换映射map中存在并且已经开启语言同步时,将对语言进行序列化 + if (LANGUAGE_MAP.containsKey(languageCd) && activeList.contains(languageCd)) { + String languageId = LANGUAGE_MAP.get(languageCd); + sb.append("~`").append(languageId).append(" ").append(name).append("`"); + } + } + } + return sb.append("~`~").toString(); + } + // 如果没有相关分组数据,返回传入的对象的name + return getName.apply(JSONObject.toJavaObject(currentObj, Map.class)); + + } + + public void clearJsonArray() { + this.jsonArray = null; + } + +} diff --git a/src/main/youhong_ai_jitu_src/jntchina/schedule/hrmNew/OrganizationUtil.java b/src/main/youhong_ai_jitu_src/jntchina/schedule/hrmNew/OrganizationUtil.java new file mode 100644 index 0000000..7c77f61 --- /dev/null +++ b/src/main/youhong_ai_jitu_src/jntchina/schedule/hrmNew/OrganizationUtil.java @@ -0,0 +1,1317 @@ +package jntchina.schedule.hrmNew; + +import aiyh.utils.Util; +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.JSONArray; +import com.alibaba.fastjson.JSONObject; +import com.alibaba.fastjson.serializer.SerializerFeature; +import com.engine.common.service.impl.ThemeServiceImpl; +import jntchina.schedule.hrm.entity.DepartmentDto; +import jntchina.schedule.hrm.entity.HrmUserDto; +import jntchina.util.HttpClientToJT; +import org.apache.commons.lang3.StringUtils; +import selfdev.util.log.LogTool; +import weaver.conn.RecordSet; +import weaver.hrm.company.SubCompanyComInfo; +import weaver.matrix.MatrixUtil; + +import java.util.*; +import java.util.stream.Collectors; + +/** + * 极兔集团 + * 组织架构同步通用工具类 + */ +public class OrganizationUtil { + + /** + * 当前类数据库连接 + */ + private static final RecordSet rs = new RecordSet(); + + /** + * 组织同步通用日志操作类 + */ + private static final LogTool logComm = new LogTool("/log/hrm/comm/", false); + + /** + * 组织同步 部门日志操作类 + */ + private static final LogTool logDept = new LogTool("/log/hrm/dept/", false); + + + /** + * 组织同步 部门日志操作类 + */ + private static final LogTool logJob = new LogTool("/log/hrm/job/", false); + + + /** + * 组织同步 人员日志操作类 + */ + private static final LogTool logHrm = new LogTool("/log/hrm/user/", false); + + + /** + * 获取组织信息的接口地址后缀 + */ + private static final String getOrganizationURL = "/dcopenedi/hrDept/pageNewHrDeptByUpdateTime"; + + /** + * 获取岗位信息接口地址后缀 + */ + private static final String getJobTitleURL = "/dcopenedi/hrPost/pageByParam"; + + /** + * 获取人员信息接口地址后缀 + */ + private static final String getEmployeeURL = "/dcopenedi/hrEmployee/pageByParam"; + + + /** + * 岗位自定义信息对应的模块ID + */ + private static final int jobDefinedModeId = 32501; + /** + * 岗位自定义信息对应的表名称 + */ + private static final String jobDefinedTableName = "uf_jobTitleDefined"; + + + /** + * 获取上一次同步时间戳 + * + * @param dataType 数据类型 0-国内 1-海外 2-印尼 + * @return 上一次同步时间戳 + */ + public static String getSyncTimestamp(int dataType) { + rs.executeQuery("select syncTs from org_sync_ts where dataType = ?", dataType); + if (rs.next()) { + return Util.null2String(rs.getString(1)); + } + return ""; + } + + /** + * 更新上一次同步时间戳 + * + * @param dataType 数据类型 0-国内 1-海外 2-印尼 + * @param ts 时间戳 + */ + public static void updateSyncTimestamp(int dataType, String ts) { + rs.executeUpdate("update org_sync_ts set syncTs = ? where dataType = ?", ts, dataType); + } + + /** + * 根据岗位外键编码获取其OA中的主键ID值 + * + * @param outKey 外键编码值 + * @return OA主键ID值 + */ + public static String getJobtitleIdByOutKey(String outKey) { + String jobtitleId = ""; + if (!"".equals(outKey)) { + if (rs.executeQuery("select id from hrmJobtitles where outKey = ?", outKey) && rs.next()) { + jobtitleId = Util.null2String(rs.getString(1)); + } + } + + return jobtitleId; + } + + + /** + * 获取员工的直接上级ID 先根据直接上级编码获取对应的员工,若找不到,则获取所在部门的部门负责人作为直接上级 + * + * @param managerCode 直接上级编码 + * @param departmentId 部门ID + * @return 直接上级ID + * 暂时删除该方法 + */ + @Deprecated + public static String getEmployeeManagerId(String managerCode, String departmentId) { + String managerId = ""; + + if (rs.executeQuery("select id from hrmResource where workCode = ?", managerCode) && rs.next()) { + managerId = Util.null2String(rs.getString(1)); + } + if ("".equals(managerId)) { + if (rs.executeQuery("select bmfzr from hrmDepartmentDefined where deptId = ?", departmentId) && rs.next()) { + managerId = Util.null2String(rs.getString(1)); + } + } + return managerId; + } + + /** + * 更新上级领导(原先还未同步的上级领导) + * + * @param noFindManagerMap 未同步上级领导的员工信息集合 + */ + public static void dealNoFindMangerEmployeeData(Map noFindManagerMap) { + Iterator> entries = noFindManagerMap.entrySet().iterator(); + String sql, updateSql; + while (entries.hasNext()) { + Map.Entry entry = entries.next(); + // 当前用户编码 + String userId = entry.getKey(); + // 上级领导编码 + String managerCode = entry.getValue(); + // 根据上级领导编码,获取其主键ID值 + sql = "select id,outKey from hrmResource where outKey= ?"; + if (rs.executeQuery(sql, managerCode) && rs.next()) { + String id = Util.null2String(rs.getString("id")); + if (!"".equals(id)) { + updateSql = "update hrmResource set managerId = ? where workCode =?"; + rs.executeUpdate(updateSql, id, userId); + } + } + } + } + + + /** + * 获取当期系统中 所有的部门信息<外部主键,OA主键> + * + * @return 返回部门信息集合 + */ + public static Map getAllDepartmentCodeIdMap() { + return getDepartmentCodeIdMap(false); + } + + + /** + * 获取当期系统中 状态未封存的部门信息<外部主键,OA主键> + * + * @return 返回部门信息集合 + */ + public static Map getEffectiveDepartmentCodeIdMap() { + return getDepartmentCodeIdMap(true); + } + + /** + * 获取当期系统中 部门信息<外部主键,OA主键> + * + * @param isEffective 是否生效记录 (CANCELED = 1 表示封存) + * @return 返回部门信息集合 + */ + private static Map getDepartmentCodeIdMap(boolean isEffective) { + Map map = new HashMap<>(); + String selectSQL; + if (isEffective) { + selectSQL = "select departmentCode,outKey,id from HrmDepartment where outKey is not null and (CANCELED!=1 or CANCELED is null)"; + } else { + selectSQL = "select departmentCode,outKey,id from HrmDepartment where outKey is not null"; + } + if (rs.executeQuery(selectSQL)) { + while (rs.next()) { + // 外部主键值 + String outKey = Util.null2String(rs.getString("outKey")); + if (!"".equals(outKey)) {// 不为空时才存入Map中 + map.put(outKey, rs.getString("id")); + } + } + } + return map; + } + + /** + * 获取部门对应的分部ID <部门外键,分部ID> + * + * @return 返回部门对应分部ID信息集合 + */ + public static Map getDepartmentCodeAndComIdMap() { + Map map = new HashMap<>(); + + if (rs.executeQuery("select outkey,subcompanyid1 from hrmdepartment where outkey is not null")) { + while (rs.next()) { + map.put(Util.null2String(rs.getString(1)), Util.null2String(rs.getString(2))); + } + } + return map; + } + + /** + * 获取有效的部门必要信息 <部门外键,部门其他信息集合> + * + * @return 返回部门信息 + */ + public static Map> getEffectiveDepartmentInfoMap() { + Map> infoMap = new HashMap<>(); + + String selectSQL = "select h.outKey,h.id,u.bmfzr,u.guojia,h.subcompanyid1 from hrmdepartment h left join hrmDepartmentDefined u on h.id = u.deptId where h.outkey is not null and (CANCELED!=1 or CANCELED is null)"; + + if (rs.executeQuery(selectSQL)) { + while (rs.next()) { + String outKey = Util.null2String(rs.getString("outKey")); + + String subCompanyId = Util.null2String(rs.getString("subcompanyid1")); + + String deptId = Util.null2String(rs.getString("id")); + + String deptManager = Util.null2String(rs.getString("bmfzr")); + + String countryCode = Util.null2String(rs.getString("guojia")); + + Map detailMap = new HashMap<>(); + detailMap.put("deptId", deptId); + detailMap.put("deptManager", deptManager); + detailMap.put("countryCode", countryCode); + detailMap.put("outKey", outKey); + detailMap.put("subCompanyId", subCompanyId); + + infoMap.put(outKey, detailMap); + } + } + + + return infoMap; + } + + /** + * 判断某个部门对应自定义信息是否存在 + * + * @param deptId 部门ID + * @return 是否存在 + */ + private static boolean deptDefinedIsExists(String deptId) { + return rs.executeQuery("select 1 from HrmDepartmentDefined where deptId = ?", deptId) && rs.next(); + } + + + /** + * 部门自定义信息处理 + * + * @param deptId 部门ID + * @param companyCode 组织编码 + * @param countryCode 国家编码 + * @param isDirectSales 是否直属销售 + * @param managerId 部门负责人 + * @param leaderId 分管领导 + */ + public static void departmentDefinedDeal(String deptId, String isDirectSales, String companyCode, String managerId, String countryCode, String leaderId) { + String operateSQL; + if (deptDefinedIsExists(deptId)) { + String innerUpdate = ""; + innerUpdate += !"".equals(managerId) ? managerId : ""; + innerUpdate += !"".equals(leaderId) ? leaderId : ""; + operateSQL = "update HrmDepartmentDefined set " + + ",guojia = '" + countryCode + "' " + + ",sfzy = '" + isDirectSales + "' " + + ",frgs= '" + companyCode + "'" + + innerUpdate + + "where deptId = '" + deptId + "'"; + } else { // 不存在,则进行插入操作 + operateSQL = "insert into HrmDepartmentDefined(deptId,sfzy,frgs,bmfzr,guojia,bmfgld) " + + "values('" + deptId + "'," + + "'" + isDirectSales + "'," + + "'" + companyCode + "'," + + "'" + managerId + "'," + + "'" + countryCode + "'," + + "'" + leaderId + "')"; + } + + if (rs.executeUpdate(operateSQL)) { + // 部门矩阵信息更新 + MatrixUtil.updateDepartmentData(deptId); + } else { + logDept.writeLog("部门自定义信息操作失败,失败SQL:[" + operateSQL + "]"); + } + } + + /** + * 分部自定义信息处理 + * + * @param comId 分部ID + * @param countryCode 国家编码 + * @param isDirectSales 是否直营 + */ + public static void companyDefinedDeal(String comId, String countryCode, String isDirectSales) { + String operateSQL; + + if (rs.executeQuery("select id from hrmSubCompanyDefined where subComId = ?", comId) && rs.next()) { + operateSQL = "update hrmSubCompanyDefined set " + + "sfzy = '" + isDirectSales + "', " + + "guojia = '" + countryCode + "' " + + "where subComId = '" + comId + "'"; + } else { + // 自定义信息写入 + operateSQL = "insert into hrmSubCompanyDefined(subComId,guojia,sfzy) " + + "values('" + comId + "','" + countryCode + "'," + + "'" + isDirectSales + "')"; + } + + if (rs.executeQuery(operateSQL)) { + MatrixUtil.updateSubcompayData(comId); + } else { + logComm.writeLog("分部自定义信息操作失败,失败SQL:[" + operateSQL + "]"); + } + } + + /** + * 岗位自定义信息处理 + * + * @param jobTitleId 岗位ID + * @param row 接口某一条记录信息 + */ + public static int jobTitleDefinedDeal(String jobTitleId, JSONObject row) { + RecordSet rs = new RecordSet(); + + String positionName = Util.null2String(row.getString("positionName"));// 岗位名称 + String positionAbbreviation = Util.null2String(row.getString("positionAbbreviation"));// 岗位简称 + String positionType = Util.null2String(row.getString("positionType"));// 岗位类别 + String positionTypeHighest = Util.null2String(row.getString("positionTypeHighest"));// 岗位类别最高 + String positionTypeLowest = Util.null2String(row.getString("positionTypeLowest"));// 岗位类别最低 + String positionPropeCode = Util.null2String(row.getString("positionPropeCode"));// 岗位属性编码 + String positionPropeName = Util.null2String(row.getString("positionPropeName"));// 岗位属性名称 + String companyCode = Util.null2String(row.getString("companyCode"));// 公司编码 + String companyName = Util.null2String(row.getString("companyName"));// 公司名称 + String deptCode = Util.null2String(row.getString("deptCode"));// 部门编码 + String deptName = Util.null2String(row.getString("deptName"));// 部门名称 + String locationCode = Util.null2String(row.getString("locationCode"));// 地点编码 + String locationName = Util.null2String(row.getString("locationName"));// 地点描述 + String stdPositionCode = Util.null2String(row.getString("stdPositionCode"));// 标准岗位编码 + String stdPositionName = Util.null2String(row.getString("stdPositionName"));// 标准岗位名称 + String postCode = Util.null2String(row.getString("postCode"));// 岗编码 + String postName = Util.null2String(row.getString("postName"));// 岗名称 + String sequenceCode = Util.null2String(row.getString("sequenceCode"));// 序列编码 + String sequenceName = Util.null2String(row.getString("sequenceName"));// 序列名称 + String positionGroupCode = Util.null2String(row.getString("positionGroupCode"));// 岗族编码 + String positionGroupName = Util.null2String(row.getString("positionGroupName"));// 岗族名称 + String ethnicGroupCode = Util.null2String(row.getString("ethnicGroupCode"));// 族群编码 + String ethnicGroupName = Util.null2String(row.getString("ethnicGroupName"));// 族群名称 + + + boolean isNew = false; + int dataId; + + if (rs.executeQuery("select id from " + jobDefinedModeId + " where positionid = ?", jobTitleId) && rs.next()) { + dataId = Util.getIntValue(rs.getString(1), 0); + } else { + isNew = true; + // 数据ID + dataId = Util.getModeDataId(jobDefinedTableName, jobDefinedModeId, 1); + } + + String operateSQL = "update " + jobDefinedTableName + " set " + + "positionName = '" + positionName + "', " + + "positionAbbreviation = '" + positionAbbreviation + "', " + + "positionType = '" + positionType + "', " + + "positionTypeHighest = '" + positionTypeHighest + "', " + + "positionTypeLowest = '" + positionTypeLowest + "', " + + "positionPropeCode = '" + positionPropeCode + "', " + + "positionPropeName = '" + positionPropeName + "', " + + "companyCode = '" + companyCode + "', " + + "companyName = '" + companyName + "', " + + "deptCode = '" + deptCode + "', " + + "deptName = '" + deptName + "', " + + "locationCode = '" + locationCode + "', " + + "locationName = '" + locationName + "', " + + "stdPositionCode = '" + stdPositionCode + "', " + + "stdPositionName = '" + stdPositionName + "', " + + "postcode = '" + postCode + "', " + + "postName = '" + postName + "', " + + "sequenceCode = '" + sequenceCode + "', " + + "sequenceName = '" + sequenceName + "', " + + "positionGroupCode = '" + positionGroupCode + "', " + + "positionGroupName = '" + positionGroupName + "', " + + "ethnicGroupCode = '" + ethnicGroupCode + "', " + + "ethnicGroupName = '" + ethnicGroupName + "' " + + "where positionid= '" + jobTitleId + "'"; + logJob.writeLog("更新岗位建模自定义表中数据sql--------->" + operateSQL); + if (!rs.executeUpdate(operateSQL)) { + if (isNew) { + rs.executeUpdate("delete from " + jobDefinedTableName + " where id = ?", dataId); + } + dataId = -1; + } else { + if (!isNew) { + dataId = -1; + } + } + + return dataId; + } + + /** + * 获取当期系统中 所有的分部信息<外部主键,OA主键> + * + * @return 返回部门信息集合 + */ + public static Map getAllSubCompanyCodeIdMap() { + return getSubCompanyCodeIdMap(false); + } + + + /** + * 获取当期系统中 状态未封存的分部信息<外部主键,OA主键> + * + * @return 返回部门信息集合 + */ + public static Map getEffectiveSubCompanyCodeIdMap() { + return getSubCompanyCodeIdMap(true); + } + + /** + * 获取当期系统中 分部信息<外部主键,OA主键> + * + * @return 返回分部信息集合 + */ + private static Map getSubCompanyCodeIdMap(boolean isEffective) { + Map map = new HashMap<>(); + String selectSQL; + if (isEffective) { + selectSQL = "select outKey,id from HrmSubCompany where outKey is not null and (CANCELED!=1 or CANCELED is null)"; + } else { + selectSQL = "select outKey,id from HrmSubCompany where outKey is not null"; + } + if (rs.executeQuery(selectSQL)) { + while (rs.next()) { + // 外部主键值 + String outKey = Util.null2String(rs.getString("outKey")); + if (!"".equals(outKey)) {// 不为空时才存入Map中 + map.put(outKey, Util.null2String(rs.getString("id"))); + } + } + } + return map; + } + + /** + * 获取当前OA系统中 未封存部门信息集合 <外键,OA部门ID^_^OA分部ID> + * + * @return 部门信息集合 + */ + public static Map getEffectiveDeptAndCompany() { + Map map = new HashMap<>(); + + String selectSQL = "select outKey,id,subCompanyId1 from HrmDepartment where outKey is not null and (CANCELED!=1 or CANCELED is null)"; + if (rs.executeQuery(selectSQL)) { + while (rs.next()) { + // 外部主键值 + String outKey = Util.null2String(rs.getString("outKey")); + String keyId = Util.null2String(rs.getString("id")); + String subCompanyId = Util.null2String(rs.getString("subCompanyId1")); + if (!"".equals(outKey)) {// 不为空时才存入Map中 + map.put(outKey, keyId + "^_^" + subCompanyId); + } + } + } + return map; + } + + /** + * 获取人员处理后的姓名 (将系统中人员姓名字段中的简体中文姓名进行替换) + * + * @param oldName 系统原有的姓名 + * @param simplifiedName 默认简体中文的姓名 + * @return 返回处理后的姓名 + */ + public static String dealEmployeeName(String oldName, String simplifiedName) { + String finalName; + if (oldName.contains("~`~`") && oldName.contains("`~`~")) { + // 获取第一个出现该字符串的位置 + int firstBit = oldName.indexOf("~`~`"); + + // 字符串 + 数字 + 空格 + String mindStr = oldName.substring(firstBit + 6); + // 第一个姓名的语言 + String lang = oldName.substring(4, oldName.indexOf(" ")); + // 两个语言之间分隔符位置 + int endBit = mindStr.indexOf("‘~‘"); + + endBit = endBit < 0 ? mindStr.indexOf("`~`~") : endBit; + + String balanceStr = mindStr.substring(endBit); + + if ("7".equals(lang)) {// 说明第一个语言为简体中文 + finalName = "~`~`7 " + simplifiedName + balanceStr; + } else {// 第一个语言不为简体中文,那在其最前面加上该语言姓名 + finalName = "~`~`7 " + simplifiedName + "‘~‘" + oldName.substring(firstBit + 4); + } + } else { + finalName = "~`~`7 " + simplifiedName + "`~`~"; + } + return finalName; + } + + /** + * 获取人员数据集合 <外键,主键> + * + * @return 人员数据集合 + */ + public static Map getEmployeeMap() { + Map dataMap = new HashMap<>(); + if (rs.executeQuery("select outkey,id from hrmresource where outkey is not null")) { + while (rs.next()) { + dataMap.put(Util.null2String(rs.getString(1)), Util.null2String(rs.getString(2))); + } + } + return dataMap; + } + + /** + * 获取人员工作信息自定义字段 <用户ID,field15字段值> + * + * @return 用户自定义信息 + */ + public static Map getEmployeeDefinedMap() { + Map map = new HashMap<>(); + rs.executeQuery("select id,field15 from cus_fielddata where scopeid='1' and scope='HrmCustomFieldByInfoType'"); + while (rs.next()) { + map.put(rs.getString("id"), rs.getString("field15")); + } + return map; + + } + + + /** + * 获取有效的岗位数据集合 <外键,主键> + * + * @return 人员数据集合 + */ + public static Map getEffectiveJobTitleMap() { + Map dataMap = new HashMap<>(); + if (rs.executeQuery("select outkey,id from hrmJobtitles where outkey is not null and (CANCELED!=1 or CANCELED is null)")) { + while (rs.next()) { + dataMap.put(Util.null2String(rs.getString(1)), Util.null2String(rs.getString(2))); + } + } + return dataMap; + } + + /** + * 根据部门ID获取其对应的分部ID + * + * @param deptId 部门ID + * @return 分部ID + */ + public static String getSubCompanyIdByDeptCode(String deptId) { + String subCompanyId = ""; + RecordSet rs = new RecordSet(); + rs.executeQuery("select subcompanyid1 from HrmDepartment where id ='" + deptId + "'"); + if (rs.next()) { + subCompanyId = Util.null2String(rs.getString(1)); + } + return subCompanyId; + } + + + /** + * 获取部门对应的国家信息 + * + * @return 返回部门国家对应信息集合 + */ + public static Map getDeptCountryMap() { + Map deptCountryMap = new HashMap<>(); + + if (rs.executeQuery("select deptId,guojia from hrmDepartmentDefined")) { + while (rs.next()) { + deptCountryMap.put(Util.null2String(rs.getString(1)), Util.null2String(rs.getString(2))); + } + } + + return deptCountryMap; + } + + + /** + * 获取部门对应的国家和负责人信息 + * + * @return 返回部门国家和负责人对应信息集合 + */ + public static Map> getDeptCountryAndManagerMap() { + Map> deptCountryAndManagerMap = new HashMap<>(); + + if (rs.executeQuery("select deptId,guojia,bmfzr from hrmDepartmentDefined")) { + while (rs.next()) { + String deptId = Util.null2String(rs.getString("deptId")); + + Map detailMap = new HashMap<>(); + detailMap.put("guojia", Util.null2String(rs.getString("guojia"))); + detailMap.put("bmfzr", Util.null2String(rs.getString("bmfzr"))); + + deptCountryAndManagerMap.put(deptId, detailMap); + } + } + + return deptCountryAndManagerMap; + } + + + /** + * 获取该List中的外键已存在的记录信息 + * + * @param codeList 所有外键信息集合 + * @param dataType 0 - 系统表 1- 自定义表 + * @return 所有已存在的记录集合 + */ + public static Map getExitsData(List codeList, int dataType) { + Map existMap = new HashMap<>(); + String selectData; + + if (dataType == 1) { + selectData = "select positionid,positionCode from uf_jobTitleDefined u where exists (" + + " select 1 from (" + + " select regexp_substr('" + StringUtils.join(codeList, ",") + "','[^,]+',1,LEVEL) as code from dual connect by LEVEL <= " + codeList.size() + + " ) t where t.code = u.positionCode)"; + } else { + selectData = "select outKey,id from hrmJobTitles where outKey is not null and exists (" + + " select 1 from (" + + " select regexp_substr('" + StringUtils.join(codeList, ",") + "','[^,]+',1,LEVEL) as code from dual connect by LEVEL <= " + codeList.size() + + " ) t where t.code = hrmJobTitles.outKey)"; + } + + if (rs.executeQuery(selectData)) { + while (rs.next()) { + existMap.put(Util.null2String(rs.getString(1)), Util.null2String(rs.getString(2))); + } + } + + return existMap; + } + + /** + * 分部同步操作 + * + * @param subCompanyList 分部信息集合 + * @param currentDateTime 当前系统时间戳 + */ + public static void subCompanySyncDeal(List subCompanyList, String currentDateTime) { + + ThemeServiceImpl themeService = new ThemeServiceImpl(); + + // 分部数据集合 + Map oaComMap = getEffectiveSubCompanyCodeIdMap(); + + for (DepartmentDto row : subCompanyList) { + String countryCode = Util.null2String(row.getCountryCode());// 国家编码 + String departmentCode = Util.null2String(row.getDepartmentCode());// 分部编码 + String departmentName = Util.null2String(row.getDepartmentName());// 分部全称 + String superiorDepartment = Util.null2String(row.getSuperiorDepartment());// 上级分部编码 + int canceled = Util.null2String(row.getStatus()).equals("3") ? 1 : 0;// 1 新增 2 修改 3作废 + + // 只需要中文和英文 + departmentName = "~`~`7 " + departmentName + "`~`8 `~`~"; + + String supSubComId = "0"; + if (!"".equals(superiorDepartment) && oaComMap.containsKey(superiorDepartment)) { + supSubComId = Util.null2String(oaComMap.get(superiorDepartment)); + } + + String operateSQL; + if (oaComMap.containsKey(departmentCode)) {// 该编码对应的分部存在 + String oldComId = oaComMap.get(departmentCode); + + String updateStr = !"0".equals(supSubComId) ? "supSubComId= '" + supSubComId + "', " : ""; + operateSQL = "update hrmSubCompany set " + + updateStr + + "subCompanyName = '" + departmentName + "', " + + "subCompanyDesc = '" + departmentName + "', " + + "subCompanyCode = '" + departmentCode + "', " + + "modified = to_date('" + currentDateTime + "','yyyy-mm-dd hh24:mi:ss')," + + "modifier = '1', " + + "canceled = " + canceled + " " + + "where outkey= '" + departmentCode + "'"; + + logDept.writeLog("分部信息更新操作:[" + operateSQL + "]"); + + if (rs.executeUpdate(operateSQL)) { + OrganizationUtil.companyDefinedDeal(oldComId, countryCode, row.getIsDirectSales()); + } else { + logDept.writeLog("分部信息更新失败!"); + } + } else { // 该编码对应的分部不存在 + // 新增数据,插入到hrmSubCompany表中 + operateSQL = "insert into hrmSubCompany (companyId,supSubComId,subCompanyName,subCompanyDesc,outkey,subCompanyCode," + + "canceled,created,creater,modified,modifier) values(" + + "'1'," + + "'" + supSubComId + "'," + + "'" + departmentName + "'," + + "'" + departmentName + "'," + + "'" + departmentCode + "'," + + "'" + departmentCode + "'," + + canceled + "," + + "to_date('" + currentDateTime + "','yyyy-mm-dd hh24:mi:ss')," + + "'1'," + + "to_date('" + currentDateTime + "','yyyy-mm-dd hh24:mi:ss')," + + "'1')"; + + logDept.writeLog("分部信息写入操作:[" + operateSQL + "]"); + + if (rs.executeUpdate(operateSQL)) { + // 获取新写入的记录ID + if (rs.executeQuery("select id from hrmSubCompany where outkey = ?", departmentCode) && rs.next()) { + String newComId = Util.null2String(rs.getString(1)); + + // 创建分部菜单 + themeService.createSubCompanyMenu(Integer.parseInt(newComId), Integer.parseInt(supSubComId)); + + oaComMap.put(departmentCode, newComId); + + OrganizationUtil.companyDefinedDeal(newComId, countryCode, row.getIsDirectSales()); + } else { + logDept.writeLog("获取新写入分部ID失败!"); + } + } else { + logDept.writeLog("分部信息写入失败!"); + } + } + } + + // 分部缓存处理 + SubCompanyComInfo subCompanyComInfo = new SubCompanyComInfo(); + subCompanyComInfo.removeCompanyCache(); + } + + /** + * 用户基础信息写入 + * + * @param userId 用户ID + * @param row 用户信息 + * @param lastName 姓名 + * @param subCompanyId 分部ID + * @param departmentId 部门ID + * @param jobtitleId 岗位ID + * @param managerId 直接上级ID + * @param name_pinyin 姓名拼音 + * @param currentDateTime 系统时间戳 + * @return 执行结果 + */ + public static boolean insertEmployeeBaseInfo(String userId, HrmUserDto row, String lastName, String subCompanyId, String departmentId, String jobtitleId, String managerId, String name_pinyin, String password, String currentDateTime) { + + String employeeCode = Util.null2String(row.getEmployeeCode());// 员工code + String employeeSexCode = Util.null2String(row.getEmployeeSexCode());// 性别 M男 F女 对应 OA 0男 1女 + int sex = "M".equals(employeeSexCode) ? 0 : 1; + String birthdate = Util.null2String(row.getEmployeeBirthdate());// 出生年月 + String companyTel = Util.null2String(row.getCompanyTel());// 办公电话 + String personalTel = Util.null2String(row.getPersonalTel());// 手机号 + String email = Util.null2String(row.getCompanyEmail());// 邮箱 + String idNumber = Util.null2String(row.getCertificateNum());// 身份证号码 + String EntryDate = Util.null2String(row.getEmplHireDate());// 入职日期 无字段,暂用试用结束日期来替代 + String hrStatus = Util.null2String(row.getHrStatus());// 状态A在职,I离职 对应OA的1正式 5离职 + int status = "A".equals(hrStatus) ? 1 : 5;// OA的在职状态 + + String operateSQL = "insert into hrmresource(id,loginid,password,lastname,workcode,sex, " + + "mobile,email,departmentid,jobtitle,birthday,certificatenum," + + "seclevel,outkey,status,systemlanguage,createrid,createdate," + + "companystartdate,telephone,ecology_pinyin_search,pinyinlastname," + + "created,creater,modified,modifier,managerid,subcompanyid1) values( " + + "'" + userId + "'," + + "'" + row + "'," + + "'" + password + "'," + + "?," + + "'" + employeeCode + "'," + + "'" + sex + "'," + + "'" + personalTel + "'," + + "'" + email + "'," + + "'" + departmentId + "'," + + "'" + jobtitleId + "'," + + "'" + birthdate + "'," + + "'" + idNumber + "'," + + "'" + 10 + "'," + + "'" + employeeCode + "'," + + "" + status + "," + + "'7'," + + "'1'," + + "'" + currentDateTime.substring(0, 10) + "'," + + "'" + EntryDate + "'," + + "'" + companyTel + "'," + + "'" + name_pinyin + "'," + + "'" + name_pinyin + "'," + + "to_date('" + currentDateTime + "','yyyy-mm-dd hh24:mi:ss')," + + "'1'," + + "to_date('" + currentDateTime + "','yyyy-mm-dd hh24:mi:ss')," + + "'1'," + + "'" + managerId + "'," + + "'" + subCompanyId + "')"; + + + logHrm.writeLog("人员基本信息插入SQL:[" + operateSQL + "],[" + lastName + "]"); + RecordSet rs = new RecordSet(); + + return rs.executeUpdate(operateSQL, lastName); + } + + + /** + * 更新用户的基本信息 + * + * @param userId 用户ID + * @param row 用户信息 + * @param lastName 用户姓名 + * @param subCompanyId 分部ID + * @param departmentId 部门ID + * @param jobtitleId 岗位ID + * @param managerId 直接上级ID + * @param name_pinyin 姓名拼音 + * @param currentDateTime 系统时间戳 + * @return 执行结果 + */ + public static boolean updateEmployeeBaseInfo(String userId, HrmUserDto row, String lastName, String subCompanyId, String departmentId, String jobtitleId, String managerId, String name_pinyin, String currentDateTime) { + String employeeCode = Util.null2String(row.getEmployeeCode());// 员工code + String employeeSexCode = Util.null2String(row.getEmployeeSexCode());// 性别 M男 F女 对应 OA 0男 1女 + int sex = "M".equals(employeeSexCode) ? 0 : 1; + String birthdate = Util.null2String(row.getEmployeeBirthdate());// 出生年月 + String companyTel = Util.null2String(row.getCompanyTel());// 办公电话 + String personalTel = Util.null2String(row.getPersonalTel());// 手机号 + String email = Util.null2String(row.getCompanyEmail());// 邮箱 + String idNumber = Util.null2String(row.getCertificateNum());// 身份证号码 + String EntryDate = Util.null2String(row.getEmplHireDate());// 入职日期 无字段,暂用试用结束日期来替代 + String hrStatus = Util.null2String(row.getHrStatus());// 状态A在职,I离职 对应OA的1正式 5离职 + int status = "A".equals(hrStatus) ? 1 : 5;// OA的在职状态 + + RecordSet rs = new RecordSet(); + + String updateStr = !"".equals(jobtitleId) ? "jobtitle = '" + jobtitleId + "', " : ""; + updateStr += !"".equals(managerId) ? "managerid = '" + managerId + "', " : ""; + String updateSQL = "update hrmresource set " + + "workcode = '" + employeeCode + "', " + + "departmentid = '" + departmentId + "'," + + "subcompanyid1 = '" + subCompanyId + "'," + + "lastname = ?, " + + "sex = '" + sex + "', " + + "mobile = '" + personalTel + "', " + + "ecology_pinyin_search = '" + name_pinyin + "', " + + "pinyinlastname = '" + name_pinyin + "', " + + "email = '" + email + "', " + + "telephone = '" + companyTel + "', " + + "status = " + status + ", " + + "birthday = '" + birthdate + "', " + + "certificatenum = '" + idNumber + "', " + + "companystartdate = '" + EntryDate + "', " + + "modified = to_date('" + currentDateTime + "','yyyy-mm-dd hh24:mi:ss')," + + "modifier = '1', " + + "lastmoddate = '" + currentDateTime.substring(0, 10) + "', " + + updateStr + + "lastmodid = '1' " + + "where id ='" + userId + "'"; + + logHrm.writeLog("人员基本信息更新SQL:[" + updateSQL + "],[" + lastName + "]"); + + return rs.executeUpdate(updateSQL, lastName); + } + + + /** + * 插入员工自定义 - 个人 + * + * @param userId 用户ID + * @param bankInfo [bankBranchName,bankAccountId,bankName] 银行信息数组 + * @param actionInfo [action,action_describe] 操作信息 + * @param row 用户信息实体类 + * @return 执行结果 + */ + public static boolean insertEmployeeCustomizePersonal(String userId, String[] bankInfo, String[] actionInfo, HrmUserDto row) { + boolean isSuccess; + + // 插入前先判断记录是否存在 + if (rs.executeQuery("select 1 from cus_fielddata where id = ? and scopeid = 1 and scope = 'HrmCustomFieldByInfoType'", userId) && rs.next()) { + return updateEmployeeCustomizePersonal(userId, bankInfo, actionInfo, row); + } + + String bankInfoCol = ""; + String bankInfoVal = ""; + + if (bankInfo != null && bankInfo.length > 2) { + bankInfoCol = "field0,field1,field5,field7,"; + bankInfoVal = "'" + bankInfo[0] + "'," + + "'" + bankInfo[1] + "'," + + "?," + + "'" + bankInfo[2] + "',"; + } + + if (actionInfo != null && actionInfo.length > 1) { + bankInfoCol += "field10,field11,"; + bankInfoVal += "'" + actionInfo[0] + "'," + + "'" + actionInfo[1] + "',"; + } + + // 自定义信息插入SQL语句拼接 + String sql = "insert into cus_fielddata(scope,scopeid,id," + bankInfoCol + "field15,field16,field17,field18,field19,field20,field21,field14,field22,field23,field24) values(" + + "'HrmCustomFieldByInfoType'," + + "'1'," + + "'" + userId + "'," + + bankInfoVal + + "'" + Util.null2String(row.getEmployeeCode()) + "'," + + "'" + Util.null2String(row.getCompanyCode()) + "'," + + "'" + Util.null2String(row.getCompanyName()) + "'," + + "'" + Util.null2String(row.getDeptCode()) + "'," + + "'" + Util.null2String(row.getDeptName()) + "'," + + "'" + Util.null2String(row.getPositionCode()) + "'," + + "'" + Util.null2String(row.getPositionName()) + "'," + + "'" + Util.null2String(row.getPositionType()) + "'," + + "'" + Util.null2String(row.getPositionTypeDescr()) + "'," + + "'" + Util.null2String(row.getPositonRankCode()) + "'," + + "'" + Util.null2String(row.getPositonRankDescr()) + "')"; + + + if (bankInfo != null && bankInfo.length > 2) { + isSuccess = rs.executeUpdate(sql, Util.null2String(row.getEmployeeName())); + } else { + isSuccess = rs.executeUpdate(sql); + } + + logComm.writeLog("写入人员自定义信息:[" + sql + "],执行结果:[" + isSuccess + "]"); + + return isSuccess; + } + + /** + * 更新员工自定义 - 个人 + * + * @param userId 用户ID + * @param bankInfo [bankBranchName,bankAccountId,bankName] 银行信息数组 + * @param actionInfo [action,action_describe] 操作信息 + * @param row 用户信息实体类 + * @return 执行结果 + */ + public static boolean updateEmployeeCustomizePersonal(String userId, String[] bankInfo, String[] actionInfo, HrmUserDto row) { + boolean isSuccess; + + String cusCol = ""; + + if (bankInfo != null && bankInfo.length > 2) { + cusCol = "field0 = '" + bankInfo[0] + "', " + + "field1 = '" + bankInfo[1] + "', " + + "field5 = '?', " + + "field7 = '" + bankInfo[2] + "', "; + } + + if (actionInfo != null && actionInfo.length > 1) { + cusCol += "field10 = '" + actionInfo[0] + "', " + + "field11 = '" + actionInfo[1] + "', "; + } + + // 自定义信息更新SQL语句拼接 + String updateSQL = "update cus_fielddata set " + + cusCol + + "field15 = '" + Util.null2String(row.getEmployeeCode()) + "', " + + "field16 = '" + Util.null2String(row.getCompanyCode()) + "', " + + "field17 = '" + Util.null2String(row.getCompanyName()) + "', " + + "field18 = '" + Util.null2String(row.getDeptCode()) + "', " + + "field19 = '" + Util.null2String(row.getDeptName()) + "', " + + "field20 = '" + Util.null2String(row.getPositionCode()) + "', " + + "field21 = '" + Util.null2String(row.getPositionName()) + "', " + + "field14 = '" + Util.null2String(row.getPositionType()) + "', " + + "field22 = '" + Util.null2String(row.getPositionTypeDescr()) + "', " + + "field23 = '" + Util.null2String(row.getPositonRankCode()) + "', " + + "field24 = '" + Util.null2String(row.getPositonRankDescr()) + "' " + + "where id ='" + userId + "' and scopeid='1' and scope = 'HrmCustomFieldByInfoType'"; + + if (bankInfo != null && bankInfo.length > 2) { + isSuccess = rs.executeUpdate(updateSQL, Util.null2String(row.getEmployeeName())); + } else { + isSuccess = rs.executeUpdate(updateSQL); + } + + logHrm.writeLog("更新人员自定义信息:[" + updateSQL + "],执行结果:[" + isSuccess + "]"); + + return isSuccess; + } + + + /** + * 处理人员昵称信息 + * + * @param userId 用户ID + * @param nickName 昵称 + */ + public static void dealEmployeeNickName(String userId, String nickName) { + RecordSet rs = new RecordSet(); + // 基本信息处理 + String cusSql; + // 基本信息 + rs.executeQuery("select id from cus_fielddata where scopeid='-1' and scope='HrmCustomFieldByInfoType' and id = ?", userId); + if (!rs.next()) {// 若不存在该用户的自定义信息-基本信息 + cusSql = "insert into cus_fielddata(scope,scopeid,id,field0) values(" + + "'HrmCustomFieldByInfoType'," + + "'-1'," + + "'" + userId + "',?)"; + } else { + cusSql = "update cus_fielddata set scopeid = '-1',field0 = ?" + + " where id ='" + userId + "' and scopeid='-1' and scope = 'HrmCustomFieldByInfoType'"; + } + + boolean b = rs.executeUpdate(cusSql, nickName); + logComm.writeLog("-------------修改自定义基本信息:" + cusSql); + logComm.writeLog("-------------修改自定义基本是否成功:" + b); + } + + + /** + * 调用人员接口,获取接口返回信息 + * + * @param size 每页条数 + * @param pages 页码 + * @param today 日期 + * @param languageCds 语言代码 + * @param deptCountryCodes 部门国家代码 + * @param code 员工编码 + * @return 接口响应信息 + */ + public static String callEmployeeInterface(int size, String pages, String today, List languageCds, List deptCountryCodes, String code) { + Map params = new HashMap<>(); + params.put("updateTime", today); + params.put("point", pages); + params.put("languageCds", languageCds); + params.put("size", size); + params.put("deptCountryCodes", deptCountryCodes); + + if (!"".equals(code)) { + params.put("employeeCode", code); + } + + String url = HttpClientToJT.baseUrl + "/dcopenedi/hrEmployee/pageByParam"; + + String token = HttpClientToJT.getToken(); + + return HttpClientToJT.sendPost(url, token, JSONObject.toJSONString(params)); + } + + /** + * 获取人员接口数据 + * + * @param dataTimeTs 上一次同步时间戳 + * @param dataType 数据类型 0-国内数据 1-海外数据 2-印尼数据 + * @param size 每页条数 + * @return 接口数据 + */ + @SuppressWarnings("unchecked") + public static JSONArray getEmployeeByPoint(String dataTimeTs, int dataType, int size) { + String requestURL = HttpClientToJT.baseUrl + getEmployeeURL; + + logHrm.writeLog("获取人员数据接口URL:[" + requestURL + "]"); + + JSONArray dataArray = new JSONArray(); + + // 是否有下一页 + boolean hasNext = false; + + String token = Util.null2String(HttpClientToJT.getToken()); + + if (!"".equals(token)) { + String point = "1";// 数据最大位置点 默认从1开始 + + Map requestParam = new HashMap<>(); + requestParam.put("updateTime", dataTimeTs); + requestParam.put("size", size); + + List languageList = new ArrayList<>(); + if (dataType == SyncConstants.SyncDataType_Internal_Data) { + languageList.add("ZHS"); + } else if (dataType == SyncConstants.SyncDataType_Overseas_Data) { + languageList.add("ENG"); + } else if (dataType == SyncConstants.SyncDataType_Indonesia_Data) { + languageList.add("IDN"); + // 部门国家编码 + List deptCountryCodes = new ArrayList<>(); + deptCountryCodes.add("IDN"); + requestParam.put("deptCountryCodes", deptCountryCodes); + } + + requestParam.put("languageCds", languageList); + + do { + requestParam.put("point", point); + + String result = HttpClientToJT.sendPost(requestURL, token, JSONObject.toJSONString(requestParam)); + + // 接口返回信息转成JSON对象 + JSONObject jsonObject = JSONObject.parseObject(result); + + // 获取成功失败标识符 + String code = weaver.general.Util.null2String(jsonObject.get("code")); + + if ("1".equals(code)) {// 表示接口调用成功 + JSONObject data = jsonObject.getJSONObject("data"); + + // 是否有下一页 + hasNext = data.getBoolean("hasNextPage");// 是否有下一页 + + point = Util.null2String(data.getString("maxPoint"));// 下一页开始位置点 + + JSONArray records = data.getJSONArray("records"); + // 过滤未获取到数据 + if (records != null) { + Object directSales = records.stream().filter(item -> { + JSONObject itemJson = JSONObject.parseObject(JSON.toJSONString(item)); + + if (dataType == SyncConstants.SyncDataType_Internal_Data) { + return "CHN".equals(itemJson.getString("deptCountryCode")) && "ZHS".equals(itemJson.getString("languageCd")); + } else { + return true; + } + }).collect(Collectors.toList()); + dataArray.addAll(JSONArray.parseArray(JSON.toJSONString(directSales))); + } + } else { + logHrm.writeLog("人员接口调用失败,失败信息:[" + jsonObject.toJSONString() + "]"); + } + } while (hasNext); + } else { + logHrm.writeLog("获取Token信息失败!"); + } + + return dataArray; + } + + + /** + * 获取组织信息 + * + * @param dateTimeTs 同步时间戳 (上一次同步时间戳) + * @param dataType 数据类型 0:国内 1:海外 2:印尼 + * @param size 数据条数 + * @return 所有组织信息的JSONArray对象 + */ + @SuppressWarnings("all") + public static JSONArray getDepartmentsByPoint(String dateTimeTs, int dataType, int size) { + // 新接口URL + String url = HttpClientToJT.baseUrl + getOrganizationURL; + logComm.writeLog("获取部门数据url-------->" + url); + JSONArray jsonArray = new JSONArray(); + boolean hasNext = false; + // 获取token + String token = HttpClientToJT.getToken(); + // 默认起始点 + int point = 1; + // 接口请求参数集合 + Map requestMap = new HashMap<>(); + requestMap.put("updateTime", dateTimeTs);// 上次同步时间戳 + requestMap.put("size", size);// 记录条数 + + if (dataType == SyncConstants.SyncDataType_Overseas_Data) { + List languageList = new ArrayList<>(); + languageList.add("ZHS"); + requestMap.put("languageCds", languageList); + } else if (dataType == SyncConstants.SyncDataType_Indonesia_Data) { + List languageList = new ArrayList<>(); + languageList.add("ZHS"); + requestMap.put("languageCds", languageList); + requestMap.put("countryCode", "IDN"); + } + + do { + try { + requestMap.put("point", point); + // 将map转成JSON格式字符串 + String param = JSONObject.toJSONString(requestMap, SerializerFeature.DisableCircularReferenceDetect); + logComm.writeLog("获取组织数据传入参数param------------>" + param); + String s = HttpClientToJT.sendPost(url, token, param); + logDept.writeLog("组织数据返回结果------------>" + s); + JSONObject jsonObject = JSONObject.parseObject(s); + String code = Util.null2String(jsonObject.getString("code")); + logDept.writeLog("code------------>" + code); + if ("1".equals(code)) { + JSONObject result = jsonObject.getJSONObject("data"); + // 是否有下一页 + hasNext = result.getBoolean("hasNextPage");// 是否有下一页 b + point = Util.getIntValue(result.getString("maxPoint"), 0);// 下一页开始 + + JSONArray records = result.getJSONArray("records"); + // 判断不为空 + if (records != null) { + // jsonArray.addAll(records); + // 对返回的数据进行过滤(只取国家编码=CHN 且语言编码=ZHS的记录) + Object directSales = records.stream().filter(item -> { + JSONObject itemJson = JSONObject.parseObject(JSON.toJSONString(item)); + + if (dataType == SyncConstants.SyncDataType_Internal_Data) { + return "CHN".equals(itemJson.getString("countryCode")) && "ZHS".equals(itemJson.getString("languageCd")); + } else if (dataType == SyncConstants.SyncDataType_Overseas_Data) { + return !"CHN".equals(itemJson.getString("countryCode")) && !"IDN".equals(itemJson.getString("countryCode")); + } else if (dataType == SyncConstants.SyncDataType_Indonesia_Data) { + return "IDN".equals(itemJson.getString("countryCode")); + } else { + return false; + } + }).collect(Collectors.toList()); + jsonArray.addAll(JSONArray.parseArray(JSON.toJSONString(directSales))); + } + } else { + hasNext = false; + } + } catch (Exception e) { + logDept.writeLog("获取组织接口报错,错误信息:" + e.getMessage()); + } + } while (hasNext); + + return jsonArray; + } + + /** + * 调用岗位接口获取接口返回信息 + * + * @param dateTimeTs 时间戳 + * @param dataType 数据类型 0-国内 1-海外 2-印尼 + * @param size 每页数据条数 + * @return 接口返回信息 + */ + @SuppressWarnings("unchecked") + public static Map getJobTitleByPoint(String dateTimeTs, int dataType, int size) { + JSONArray jsonArray = new JSONArray(); + Map resultMap = new HashMap<>(); + // 新接口URL + String url = HttpClientToJT.baseUrl + getJobTitleURL; + // 获取token + String token = HttpClientToJT.getToken(); + + Map requestMap = new HashMap<>(); + + requestMap.put("beginTime", dateTimeTs); + requestMap.put("size", size); + boolean hasNextPage = false; + String maxPoint = "1"; + JSONArray totalResult = new JSONArray(); + + do { + requestMap.put("point", maxPoint); + + // 将map转成字符串 + String param = JSONObject.toJSONString(requestMap, SerializerFeature.DisableCircularReferenceDetect); + + // 调用接口,获取接口返回信息 + String s = HttpClientToJT.sendPost(url, token, param); + + // 接口返回信息转成JSON对象 + JSONObject jsonObject = JSONObject.parseObject(s); + + // 获取成功失败标志 + String code = Util.null2String(jsonObject.getString("code")); + if ("1".equals(code)) { + JSONObject result = jsonObject.getJSONObject("data"); + // 是否有下一页 + hasNextPage = result.getBoolean("hasNextPage"); + // 下一页开始 + maxPoint = result.getString("maxPoint"); + JSONArray records = result.getJSONArray("records"); + // 过滤未获取到数据 + if (records != null) { + totalResult.addAll(records); + // jsonArray.addAll(records); + Object directSales = jsonArray.stream().filter(item -> { + JSONObject itemJson = JSONObject.parseObject(JSON.toJSONString(item)); + if (dataType == SyncConstants.SyncDataType_Internal_Data) { + return "ZHS".equals(itemJson.getString("languageCd")); + } else if (dataType == SyncConstants.SyncDataType_Overseas_Data) { + return !"CHN".equals(itemJson.getString("countryCode")) && !"IDN".equals(itemJson.getString("countryCode")); + } else if (dataType == SyncConstants.SyncDataType_Indonesia_Data) { + return "IDN".equals(itemJson.getString("countryCode")); + } else { + return false; + } + }).collect(Collectors.toList()); + jsonArray.addAll(JSONArray.parseArray(JSON.toJSONString(directSales))); + } + } else { + hasNextPage = false; + } + } while (hasNextPage); + resultMap.put("filterResult", jsonArray); + resultMap.put("allResult", totalResult); + return resultMap; + } + +} diff --git a/src/main/youhong_ai_jitu_src/jntchina/schedule/hrmNew/OverseasSync.java b/src/main/youhong_ai_jitu_src/jntchina/schedule/hrmNew/OverseasSync.java new file mode 100644 index 0000000..e546d7f --- /dev/null +++ b/src/main/youhong_ai_jitu_src/jntchina/schedule/hrmNew/OverseasSync.java @@ -0,0 +1,68 @@ +package jntchina.schedule.hrmNew; + +import com.alibaba.fastjson.JSONArray; +import jntchina.schedule.hrm.entity.DepartmentDto; +import selfdev.util.log.LogTool; + +import java.util.List; +import java.util.stream.Collectors; + +/** + * 极兔集团 + * 海外架构同步操作 + */ +public class OverseasSync { + + /** + * 部门日志操作 + */ + private static final LogTool logDept = new LogTool("/log/hrm/deptOC/", false); + + /** + * 岗位日志操作 + */ + private static final LogTool logJob = new LogTool("/log/hrm/jobOC/", false); + + /** + * 员工日志操作 + */ + private static final LogTool logHrm = new LogTool("/log/hrm/userOC/",false); + + + /** + * 组织同步 + * @param lastTimeStamp 上一次同步时间戳 + * @param currentDateTime 当前时间戳 + */ + @SuppressWarnings("unchecked") + private void syncOrganizationData(String lastTimeStamp,String currentDateTime){ + + //调用接口,获取组织信息 + JSONArray dataArray = OrganizationUtil.getDepartmentsByPoint(lastTimeStamp,SyncConstants.SyncDataType_Overseas_Data,1000); + + + //将JSON数组转成对象集合 + List dataList = JSONArray.parseArray(dataArray.toJSONString(), DepartmentDto.class); + + + //分部数据 + List subCompanyList = dataList.stream().filter(item -> "10".equals(item.getOrganizationClass()) || "60".equals(item.getOrganizationClass())).collect(Collectors.toList()); + + //部门数据 + List departmentList = dataList.stream().filter(item -> !"10".equals(item.getOrganizationClass()) && !"60".equals(item.getOrganizationClass())).collect(Collectors.toList()); + + + if(!dataList.isEmpty()){//接口返回的数据不为空 + + if(subCompanyList.size() > 0){//分部数据 + logDept.writeLog("分部总记录条数:[" + subCompanyList.size() + "]"); + OrganizationUtil.subCompanySyncDeal(subCompanyList,currentDateTime); + } + + if(departmentList.size() > 0){//部门数据 + logDept.writeLog("部门总记录条数:[" + subCompanyList.size() + "]"); + + } + } + } +} diff --git a/src/main/youhong_ai_jitu_src/jntchina/schedule/hrmNew/SyncAllData.java b/src/main/youhong_ai_jitu_src/jntchina/schedule/hrmNew/SyncAllData.java new file mode 100644 index 0000000..6a022f0 --- /dev/null +++ b/src/main/youhong_ai_jitu_src/jntchina/schedule/hrmNew/SyncAllData.java @@ -0,0 +1,79 @@ +package jntchina.schedule.hrmNew; + +import selfdev.util.log.LogTool; +import weaver.general.TimeUtil; +import weaver.interfaces.schedule.BaseCronJob; + + +/** + * 极兔集团 + * 组织架构同步逻辑入口 + */ +public class SyncAllData extends BaseCronJob { + + /** + * 组织同步通用日志操作类 + */ + private static final LogTool logComm = new LogTool("/log/hrm/comm/", false); + + + /** + * 实现父类方法 + */ + @Override + public synchronized void execute() { + logComm.writeLog("---------------SyncAllData Begin--------------"); + //国内逻辑处理 + internalSync(); + //海外逻辑处理 + + //印尼逻辑处理 + + logComm.writeLog("---------------SyncAllData End--------------"); + } + + /** + * 国内数据同步 + */ + private synchronized void internalSync(){ + //获取上一次国内同步时间戳 + String lastTimestamp = OrganizationUtil.getSyncTimestamp(SyncConstants.SyncDataType_Internal_Data); + + //获取当前时间戳 + String currentDateTime = TimeUtil.getCurrentTimeString(); + + logComm.writeLog("国内上一次同步时间戳:[" + lastTimestamp + "],当前时间戳:[" + currentDateTime + "]"); + + InternalSync internalSync = new InternalSync(); + + //同步组织 + internalSync.syncOrganizationData(lastTimestamp,currentDateTime); + + //同步岗位 + internalSync.syncJobTitleData(lastTimestamp,currentDateTime); + + //同步人员 + internalSync.syncEmployeeData(lastTimestamp,currentDateTime); + + //将当前时间戳写入到同步记录中 + OrganizationUtil.updateSyncTimestamp(SyncConstants.SyncDataType_Internal_Data,currentDateTime); + + logComm.writeLog("国内数据同步结束:[" + TimeUtil.getCurrentTimeString() + "]"); + } + + + /** + * 海外数据同步 + */ + private synchronized void overseasSync(){ + //获取上一次海外同步时间戳 + String lastTimestamp = OrganizationUtil.getSyncTimestamp(SyncConstants.SyncDataType_Overseas_Data); + + //获取当前时间戳 + String currentDateTime = TimeUtil.getCurrentTimeString(); + + logComm.writeLog("海外上一次同步时间戳:[" + lastTimestamp + "],当前时间戳:[" + currentDateTime + "]"); + + + } +} diff --git a/src/main/youhong_ai_jitu_src/jntchina/schedule/hrmNew/SyncConstants.java b/src/main/youhong_ai_jitu_src/jntchina/schedule/hrmNew/SyncConstants.java new file mode 100644 index 0000000..cb69501 --- /dev/null +++ b/src/main/youhong_ai_jitu_src/jntchina/schedule/hrmNew/SyncConstants.java @@ -0,0 +1,22 @@ +package jntchina.schedule.hrmNew; + +/** + * 极兔集团 + * 组织架构图常量 + */ +public class SyncConstants { + /** + * 国内数据 + */ + public static final int SyncDataType_Internal_Data = 0; + + /** + * 海外数据 + */ + public static final int SyncDataType_Overseas_Data = 1; + + /** + * 印尼数据 + */ + public static final int SyncDataType_Indonesia_Data = 2; +} diff --git a/src/main/youhong_ai_jitu_src/jntchina/service/LJL/LiShiYanGeAPI.java b/src/main/youhong_ai_jitu_src/jntchina/service/LJL/LiShiYanGeAPI.java new file mode 100644 index 0000000..e3e35d2 --- /dev/null +++ b/src/main/youhong_ai_jitu_src/jntchina/service/LJL/LiShiYanGeAPI.java @@ -0,0 +1,151 @@ +package jntchina.service.LJL; + +import com.alibaba.fastjson.JSONArray; +import com.alibaba.fastjson.JSONObject; +import weaver.conn.RecordSet; + +import javax.ws.rs.FormParam; +import javax.ws.rs.POST; +import javax.ws.rs.Path; +import javax.ws.rs.Produces; +import javax.ws.rs.core.MediaType; +import java.util.Map; + +/** + * @title: LiShiYanGeAPI + * @Author LJL + * @Date: 2021/11/10 14:01 + * @Version 1.0 + */ + +@Path("/LJL") +public class LiShiYanGeAPI { + + /** + * 历史沿革 + * 判断更改前和更改后是否一致 如果全部一致 那么将不会更改 + * + * @param json + */ + @Path("/PanDuan") + @Produces(MediaType.APPLICATION_JSON) + @POST + public String judge(@FormParam("data") String json){ +// String js = "[" + +// "{'rq' : '2021-11-09','bgxm' : 'qymc','bgq':'极兔','bgh':'极兔2','fj':'','bz':'备注'}," + +// "{'rq' : '2021-11-09','bgxm' : 'gly','bgq':'1','bgh':'1','fj':'','bz':'备注'}]"; + + + + int TorF = 0; + String name = ""; + JSONArray jo = JSONArray.parseArray(json); + for (int i = 0; i < jo.size(); i++) { + Map map = JSONObject.parseObject(JSONObject.toJSONString(jo.get(i)), Map.class); + if (map.get("bgxm").equals("企业名称变更前")) { + name = name + map.get("bgq"); + } + } + + + + for (int i = 0; i < jo.size(); i++) { + Map map = JSONObject.parseObject(JSONObject.toJSONString(jo.get(i)), Map.class); + Object bgq = map.get("bgq"); + Object bgh = map.get("bgh"); + + + if(!bgq.equals(bgh)){ + RecordSet rs = new RecordSet(); + RecordSet rs2 = new RecordSet(); + String SQL = "insert into uf_jingneiqiyexinxi_dt1(rq,bgxm,bgq,bgh,fj,bz) values('" + + map.get("rq") + + "','" +map.get("bgxm")+ + "','" +bgq+ + "','" +bgh+ + "','" +map.get("fj")+ + "','" +map.get("bz")+ + "')"; + rs.executeUpdate(SQL); + String SQL2 = "update uf_jingneiqiyexinxi SET "+getChinaName(map.get("bgxm"))+" = "+bgh+" where qymc = '"+name+"'"; + rs2.executeUpdate(SQL2); + TorF++; + + } + } + if(TorF>0) { + return "1"; //1是成功 + }else{ + return "没有需要更改的数据"; //其他的就是是失败 + } + + + } + + Object getChinaName(Object s) { + if (s.equals("管理员变更前")) { + s = "gly"; + } + if (s.equals("企业名称变更前")) { + s = "qymc"; + } + if (s.equals("曾用名变更前")) { + s = "zym"; + } + if (s.equals("英文名变更前")) { + s = "ywm"; + } + if (s.equals("成立日期变更前")) { + s = "clrq"; + } + if (s.equals("社会信用代码变更前")) { + s = "shxydm"; + } + if (s.equals("注册资本变更前")) { + s = "zczb"; + } + if (s.equals("地址变更前")) { + s = "dz"; + } + if (s.equals("经营范围变更前")) { + s = "jyfw"; + } + if (s.equals("股权特殊安排变更前")) { + s = "gqtsap"; + } + if (s.equals("股权安排附件变更前")) { + s = "gqapfj"; + } + if (s.equals("法人代表变更前")) { + s = "frdb"; + } + if (s.equals("财务负责人变更前")) { + s = "cwfzr"; + } + if (s.equals("经理变更前")) { + s = "jl"; + } + if (s.equals("监事变更前")) { + s = "js"; + } + if (s.equals("董事变更前")) { + s = "ds"; + } + if (s.equals("登记状态变更前")) { + s = "djzt"; + } + if (s.equals("业务承载变更前")) { + s = "ywcz"; + } + if (s.equals("是否为并表单位变更前")) { + s = "sfwbbdw"; + } + if (s.equals("备案附件变更前")) { + s = "bafj"; + } + + + return s; + + } +} diff --git a/src/main/youhong_ai_jitu_src/jntchina/service/ncc/NCCOrderValidateAction.java b/src/main/youhong_ai_jitu_src/jntchina/service/ncc/NCCOrderValidateAction.java new file mode 100644 index 0000000..d22ae23 --- /dev/null +++ b/src/main/youhong_ai_jitu_src/jntchina/service/ncc/NCCOrderValidateAction.java @@ -0,0 +1,192 @@ +package jntchina.service.ncc; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.JSONArray; +import com.alibaba.fastjson.JSONObject; +import com.alibaba.fastjson.serializer.SerializerFeature; +import com.api.lh.port.AddJournal; +import org.apache.commons.io.IOUtils; +import selfdev.util.log.LogTool; +import weaver.conn.RecordSet; +import weaver.file.Prop; +import weaver.general.Util; + +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; +import javax.ws.rs.POST; +import javax.ws.rs.Path; +import javax.ws.rs.Produces; +import javax.ws.rs.core.Context; +import javax.ws.rs.core.HttpHeaders; +import java.io.BufferedReader; +import java.io.InputStreamReader; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +/** + * @ClassName NCCOrderValidateAction + * @Description 获取ncc采购订单号查询oa是否有在审批 + * @Author louh + * @Date 2022/2/23 9:56 + * @Version 1.0 + */ +@Path("/NCCOrder") +public class NCCOrderValidateAction { + @POST + @Path("/ValidateDocument") + @Produces({"application/json"}) + public String deleteOrder(@Context HttpServletRequest request, @Context HttpServletResponse response, @Context HttpHeaders headers) { + LogTool log = new LogTool("/log/lh/rest/ncc", false); + Map map_return = new HashMap<>(); + List> list = new ArrayList<>(); + String allmsg = ""; + String allstutas = "1"; + String body =""; + try { + //获取配置文件中的参数 + String mode = Prop.getPropValue("DevToNCC_jntchina", "mode"); + //或配置文件中维护的准入码 + String AccessCode_p = Prop.getPropValue("DevToNCC_jntchina", mode + "_AccessCode"); + //header中没有AccessCode参数 + if (headers.getRequestHeader("AccessCode") == null || headers.getRequestHeader("AccessCode").size() == 0) { + allstutas = "0";//状态 + allmsg = "请在header中传入准入码AccessCode参数";//返回信息 + map_return.put("allstatus", allstutas); + map_return.put("allmsg", allmsg); + return JSON.toJSONString(map_return); + } + List accessCode = headers.getRequestHeader("AccessCode"); + //准入码 + String AccessCode = accessCode.get(0); + log.writeLog("AccessCode------>" + AccessCode); + if ("".equals(AccessCode)) { + allstutas = "0";//状态 + allmsg = "header中准入码AccessCode参数不可为空";//返回信息 + map_return.put("allstatus", allstutas); + map_return.put("allmsg", allmsg); + return JSON.toJSONString(map_return); + } + if (!AccessCode_p.equals(AccessCode)) { + allstutas = "0";//状态 + allmsg = "header中传入的准入码【" + AccessCode + "】无效,请联系OA管理员提供正确的准入码";//返回信息 + map_return.put("allstatus", allstutas); + map_return.put("allmsg", allmsg); + return JSON.toJSONString(map_return); + } + //获取body内容,设置UTF-8格式 + BufferedReader reader = new BufferedReader(new InputStreamReader(request.getInputStream(), "UTF-8")); + //过滤前后空格 + body = IOUtils.toString(reader).trim(); + log.writeLog("body----->" + body); + if ("".equals(body)) { + allstutas = "0";//状态 + allmsg = "body中请传入JSON格式数据";//返回信息 + map_return.put("allstatus", allstutas); + map_return.put("allmsg", allmsg); + String s = JSON.toJSONString(map_return, SerializerFeature.DisableCircularReferenceDetect); + AddJournal.addInfo("获取ncc采购订单号查询oa是否有在审批", body, s, "1", "/NCCOrder/ValidateDocument", null); + return s; + } + JSONArray jsonArray = null; + try { + //解析JOSN字符串 + jsonArray = JSONObject.parseArray(body); + } catch (Exception e) { + allstutas = "0";//状态 + allmsg = "body中传入的数据格式初始化异常,请检查数据为JSON格式";//返回信息 + map_return.put("allstatus", allstutas); + map_return.put("allmsg", allmsg); + String s = JSON.toJSONString(map_return, SerializerFeature.DisableCircularReferenceDetect); + AddJournal.addInfo("获取ncc采购订单号查询oa是否有在审批", body, s, "1", "/NCCOrder/ValidateDocument", null); + return s; + } + + + RecordSet rs = new RecordSet(); + //数据条数 + int size = jsonArray.size(); + for (int k = 0; k < size; k++) { + String msg = ""; + Map map_detail = new HashMap(); + //获取每条流程的数据 + JSONObject item = jsonArray.getJSONObject(k); + String podh = item.getString(Util.null2String("Podh"));/* 采购订单号 */ + String company_code = item.getString(Util.null2String("company_code")); /* 公司编码 */ + String supplier_code = item.getString(Util.null2String("supplier_code")); /* 供应商编码 */ + String prepay = item.getString(Util.null2String("prepay")); /* 0:预付单, 1:应付单*/ + String operation_msg = item.getString(Util.null2String("operation_msg")); /* 操作信息详情 */ + if (null == podh || "".equals(podh)) { + msg = "采购单号【Podh】不允许为空!"; + map_detail.put("msg", msg); + map_detail.put("status", "0"); + allstutas = "0"; + allmsg += msg; + list.add(map_detail); + continue; + } + log.writeLog("**********podh【" + podh + "】*******************"); + map_detail.put("podh", podh); + if (null == supplier_code || "".equals(supplier_code)) { + msg = "供应商编码【supplier_code】不允许为空!"; + map_detail.put("msg", msg); + map_detail.put("status", "0"); + allstutas = "0"; + allmsg += msg; + list.add(map_detail); + continue; + } + if (null == company_code || "".equals(company_code)) { + msg = "公司编码【company_code】不允许为空!"; + map_detail.put("msg", msg); + map_detail.put("status", "0"); + allstutas = "0"; + allmsg += msg; + list.add(map_detail); + continue; + } + map_detail.put("company_code", company_code); + String sql = "select lcbh,requestid from cgddcx20220429 where cgddh = '" + podh + "' and gsmc ='" + company_code + "' and podhname = '" + prepay + "' and gysmc = '" + supplier_code + "' and stutas not in (0,3)"; + log.writeLog("查询当前单号是否在审批中sql----> " + sql); + rs.execute(sql); + String requestid = ""; + String lcbh = ""; + if (rs.next()) { + requestid = Util.null2String(rs.getString("requestid")); //获取改单号requestid + lcbh = Util.null2String(rs.getString("lcbh")); /* 流程编号 */ + } else { + msg = "该【" + company_code + "】公司【" + podh + "】此单号并未采用!"; + map_detail.put("msg", msg); + map_detail.put("status", "1"); + //allstutas = "0"; + allmsg += msg; + list.add(map_detail); + continue; + } + msg = "该【" + podh + "】单号OA在审批中,对应的审批流程requestid为【" + requestid + "】,流程编号为【" + lcbh + "】不允许操作!"; + map_detail.put("msg", msg); + map_detail.put("status", "0"); + allstutas = "0"; + allmsg += msg; + list.add(map_detail); + } + } catch (Exception e) { + log.writeLog("接口异常,错误信息: " + e.getMessage()); + allstutas = "0";//状态 + allmsg = "接口异常,错误信息:" + e.toString();//返回信息 + } + map_return.put("allstatus", allstutas); + map_return.put("allmsg", allmsg); + map_return.put("detail", list); + + //SerializerFeature.DisableCircularReferenceDetect 消除对同一对象循环引用的问题 + String result = JSON.toJSONString(map_return, SerializerFeature.DisableCircularReferenceDetect); + if(allstutas.equals("1")){ + AddJournal.addInfo("获取ncc采购订单号查询oa是否有在审批", body, result, "0", "/NCCOrder/ValidateDocument", null); + }else{ + AddJournal.addInfo("获取ncc采购订单号查询oa是否有在审批", body, result, "1", "/NCCOrder/ValidateDocument", null); + } + return result; + } +} diff --git a/src/main/youhong_ai_jitu_src/jntchina/service/ncc/NCCServiceAction.java b/src/main/youhong_ai_jitu_src/jntchina/service/ncc/NCCServiceAction.java new file mode 100644 index 0000000..5eadd3b --- /dev/null +++ b/src/main/youhong_ai_jitu_src/jntchina/service/ncc/NCCServiceAction.java @@ -0,0 +1,273 @@ +package jntchina.service.ncc; + +import java.io.BufferedReader; +import java.io.InputStreamReader; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; +import javax.ws.rs.POST; +import javax.ws.rs.Path; +import javax.ws.rs.Produces; +import javax.ws.rs.core.Context; +import javax.ws.rs.core.HttpHeaders; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.JSONArray; +import com.alibaba.fastjson.JSONObject; +import com.alibaba.fastjson.serializer.SerializerFeature; + +import weaver.conn.RecordSet; +import weaver.file.Prop; +import weaver.general.Util; +import weaver.soa.workflow.request.RequestService; + +import selfdev.util.log.LogTool; +/** + * 接收NCC状态接口 + * @author KangMD + * 2021-01-13 + */ + +@SuppressWarnings("SuspiciousMethodCalls") +@Path("/NCC") +public class NCCServiceAction { + @POST + @Path("/ReceivePaymentStatus") + @Produces({"application/json"}) + public String receivePaymentStatus(@Context HttpServletRequest request, @Context HttpServletResponse response,@Context HttpHeaders headers){ + LogTool log=new LogTool("/log/selfdev/rest/ncc", false); + String allstatus="1";//状态 + String allmsg="";//返回信息 + Map map_return=new HashMap(); + List list_detail=new ArrayList(); + try{ + //获取配置文件中的参数 + String mode = Prop.getPropValue("DevToNCC_jntchina","mode"); + //或配置文件中维护的准入码 + String AccessCode_p = Prop.getPropValue("DevToNCC_jntchina",mode+"_AccessCode"); + + //header中没有AccessCode参数 + if(headers.getRequestHeader("AccessCode")==null||headers.getRequestHeader("AccessCode").size()==0){ + allstatus="0";//状态 + allmsg="请在header中传入准入码AccessCode参数";//返回信息 + map_return.put("allstatus", allstatus); + map_return.put("allmsg", allmsg); + return JSON.toJSONString(map_return); + } + List AccessCodeList= headers.getRequestHeader("AccessCode"); + //准入码 + String AccessCode=AccessCodeList.get(0); + log.writeLog("AccessCode------>"+AccessCode); + if("".equals(AccessCode)){ + allstatus="0";//状态 + allmsg="header中准入码AccessCode参数不可为空";//返回信息 + map_return.put("allstatus", allstatus); + map_return.put("allmsg", allmsg); + return JSON.toJSONString(map_return); + } + if(!AccessCode_p.equals(AccessCode)){ + allstatus="0";//状态 + allmsg="header中传入的准入码【"+AccessCode+"】无效,请联系OA管理员提供正确的准入码";//返回信息 + map_return.put("allstatus", allstatus); + map_return.put("allmsg", allmsg); + return JSON.toJSONString(map_return); + } + + //获取body内容,设置UTF-8格式 + BufferedReader reader = new BufferedReader(new InputStreamReader(request.getInputStream(),"UTF-8")); + //过滤前后空格 + String body =org.apache.commons.io.IOUtils.toString(reader).trim(); + log.writeLog("body----->"+body); + if("".equals(body)){ + allstatus="0";//状态 + allmsg="body中请传入JSON格式数据";//返回信息 + map_return.put("allstatus", allstatus); + map_return.put("allmsg", allmsg); + return JSON.toJSONString(map_return); + } + JSONArray jsonArray=new JSONArray(); + try{ + //由于支持一次性触发多个流程,故传入的JSON格式为数组,需要以中括号[ ]开头及结尾 + if(!body.startsWith("[")){ + body="["+body; + } + if(!body.endsWith("]")){ + body=body+"]"; + } + //解析JOSN字符串 + jsonArray = JSONObject.parseArray(body); + }catch (Exception e) { + allstatus="0";//状态 + allmsg="body中传入的数据格式初始化异常,请检查数据为JSON格式";//返回信息 + map_return.put("allstatus", allstatus); + map_return.put("allmsg", allmsg); + return JSON.toJSONString(map_return); + } + RecordSet rs=new RecordSet(); + RequestService requestService=new RequestService(); + //数据条数 + int size=jsonArray.size(); + for(int k=0;k map_detail=new HashMap(); + //获取每条流程的数据 + JSONObject item=jsonArray.getJSONObject(k); + String requestid=Util.null2String(item.getString("requestid"));// + String status=Util.null2String(item.getString("status"));//1表示付款成功,0表示退单 + String paydate=Util.null2String(item.getString("paydate"));//实际付款日期 + String rejecttype=Util.null2o(item.getString("rejecttype"));//退回状态 + String msg=Util.null2String(item.getString("msg"));//提示信息 + String isOverseas = "0";//是否海外 0:否 1:是 + + if(item.containsKey("isOverseas")){ + isOverseas = Util.null2String(item.getString("isOverseas")); + } + + map_detail.put("requestid", requestid); + if("".equals(requestid)){ + msg="requestid不可为空。"; + map_detail.put("status", "0"); + map_detail.put("msg", msg); + allstatus="0";//状态 + allmsg+=msg; + list_detail.add(map_detail); + continue; + } + if(!requestid.matches("[0-9]+")){ + msg="传入requestid必须是整数数字。"; + map_detail.put("status", "0"); + map_detail.put("msg", msg); + allstatus="0";//状态 + allmsg+=msg; + list_detail.add(map_detail); + continue; + } + +// String workflowid="";// + String nodeid="";//当前节点ID + String nodename="";//当前节点名称 + String userid="";//当前节点操作者 + String tablename="";//表名 + String sql="select a.requestid,a.workflowid,a.currentnodeid,d.nodename,c.tablename "; + sql+="from workflow_requestbase a,workflow_base b,workflow_bill c,workflow_nodebase d "; + sql+="where a.workflowid=b.id and b.formid=c.id and a.currentnodeid=d.id and a.requestid="+requestid; + rs.execute(sql); + int row=rs.getCounts(); + if(row==0){ + msg="传入requestid【"+requestid+"】未找到对应的OA流程,请核对requestid是否正确。"; + map_detail.put("status", "0"); + map_detail.put("msg", msg); + allstatus="0";//状态 + allmsg+=msg; + list_detail.add(map_detail); + continue; + } + while(rs.next()){ +// workflowid=Util.null2String(rs.getString("workflowid")); + nodeid=Util.null2String(rs.getString("currentnodeid")); + tablename=Util.null2String(rs.getString("tablename")); + nodename=Util.null2String(rs.getString("nodename")); + } + if(!nodename.contains("等待")){ + msg="OA流程requestid【"+requestid+"】当前处于【"+nodename+"】节点,只有处于【等待NCC审核】的OA流程才可接收NCC接口返回数据,请联系OA管理员核实当前流程节点情况。"; + map_detail.put("status", "0"); + map_detail.put("msg", msg); + allstatus="0";//状态 + allmsg+=msg; + list_detail.add(map_detail); + continue; + } + //查询当前流程节点操作者 + String sql2="SELECT * FROM workflow_currentoperator WHERE requestid="+requestid+" AND isremark=0 AND nodeid="+nodeid; + rs.execute(sql2); + //若此节点有多个操作者时,取第一行即可,故用if + if(rs.next()){ + userid=Util.null2String(rs.getString("userid")); + } + log.writeLog("**********requestid【"+requestid+"】、nodeid【"+nodeid+"】、userid【"+userid+"】**********"); + + map_detail.put("requestid", requestid); + if("1".equals(status)||"2".equals(status)){//付款成功或者全额核销 + + String updateSQL = "update "+tablename+" set nccfkzt='"+status+"',nccsjfkrq='"+paydate+"',nccfhxx='"+msg.replace("'", "''")+"' where requestid="+requestid; + + String remark="NCC已于"+paydate+"付款成功"; + if("2".equals(status)){ + remark="NCC已核销成功"; + } + + if("1".equals(isOverseas)){//若为海外 + //1:审核完成 2:付款完成 + if("1".equals(status)){ + remark = "NCC已于" + paydate + "审核完成"; + updateSQL = "update " + tablename + " set nccAuditStatus = " + status + ",nccAuditDate = '" + paydate + "',nccAuditRemark = '" + msg.replace("'","''") + "' where requestId = " + requestid; + } else { + String paymentCode = ""; + if(item.containsKey("paymentCode")){ + paymentCode = Util.null2String(item.get("paymentCode")); + } + remark = "NCC已于" + paydate + "付款完成"; + updateSQL = "update " + tablename + " set nccfkzt='" + status + "',nccsjfkrq = '"+paydate + "',nccfhxx = '" + msg.replace("'", "''") + "',nccfkdh='" + paymentCode + "' where requestId = "+requestid; + } + } + + //将NCC结果更新至流程表单字段中 + rs.executeUpdate(updateSQL); + + boolean flag2=requestService.nextNodeBySubmit(null, Integer.parseInt(requestid), Integer.parseInt(userid), remark); + log.writeLog("**********requestid【"+requestid+"】流程提交状态**********"+flag2); + if(flag2){ + if("1".equals(isOverseas) && "1".equals(status)){ + msg = "OA已接收NCC传入的审核状态,OA流程requestid【" + requestid + "】已成功流转至下一个节点"; + }else { + msg = "OA已接收NCC传入的付款状态,OA流程requestid【" + requestid + "】已成功流转至下一个节点"; + } + map_detail.put("status", "1"); + map_detail.put("msg", msg); + }else{ + msg="OA流程requestid【"+requestid+"】流转至下一个节点失败,请联系OA管理员检查流程设置。"; + map_detail.put("status", "0"); + map_detail.put("msg", msg); + allstatus="0";//状态 + allmsg+=msg; + } + }else{ + boolean flag2=requestService.nextNodeByReject(Integer.parseInt(requestid), Integer.parseInt(userid), msg); + log.writeLog("**********requestid【"+requestid+"】流程退回状态**********"+flag2); + if(flag2){ + String updateSQL = "update "+tablename+" set nccfkzt='"+status+"',sfcgscnccfkd = null, nccfkdh = '',ncctdhzctjlz='"+rejecttype+"',nccfhxx='"+msg.replace("'", "''")+"' where requestid="+requestid; + + //将NCC结果更新至流程表单字段中(清空上一次的NCC付款单号以及付款单状态) + rs.executeUpdate(updateSQL); + map_detail.put("status", "1"); + map_detail.put("msg", "OA已接收NCC传入的付款状态,OA流程requestid【"+requestid+"】已退回至申请人补充资料节点"); + }else{ + //将NCC结果更新至流程表单字段中(清空上一次的NCC付款单号以及付款单状态) + rs.execute("update "+tablename+" set nccfkzt='"+status+"',ncctdhzctjlz='"+rejecttype+"',nccfhxx='"+msg.replace("'", "''")+"' where requestid="+requestid); + msg="OA流程requestid【"+requestid+"】退回至申请人补充资料节点失败,请联系OA管理员检查流程设置。"; + map_detail.put("status", "0"); + map_detail.put("msg", msg); + allstatus="0";//状态 + allmsg+=msg; + } + } + list_detail.add(map_detail); + } + }catch (Exception e) { + log.writeLog("接口异常,错误信息:" + e.toString()); + allstatus="0";//状态 + allmsg="接口异常,错误信息:"+e.toString();//返回信息 + } + map_return.put("allstatus", allstatus); + map_return.put("allmsg", allmsg); + map_return.put("detail", list_detail); + + String returnMsg=JSON.toJSONString(map_return, SerializerFeature.DisableCircularReferenceDetect); + + log.writeLog("**********returnMsg**********"+returnMsg); + return returnMsg; + } +} diff --git a/src/main/youhong_ai_jitu_src/jntchina/service/oa/ChangeDt1.java b/src/main/youhong_ai_jitu_src/jntchina/service/oa/ChangeDt1.java new file mode 100644 index 0000000..cbf1187 --- /dev/null +++ b/src/main/youhong_ai_jitu_src/jntchina/service/oa/ChangeDt1.java @@ -0,0 +1,459 @@ +package jntchina.service.oa; + +import com.alibaba.fastjson.JSONArray; +import com.alibaba.fastjson.JSONObject; +import com.engine.portal.entity.Select; +import jntchina.service.oa.util.ModifyDetailInfo; +import jntchina.util.DataBaseUtils; +import selfdev.util.log.LogTool; +import weaver.conn.RecordSet; +import weaver.general.Util; + +import java.util.*; + +/** + * @title: 改变明细表 + * @author ycf + * @date 2022-02-04 + */ +public class ChangeDt1 { + private final LogTool log = new LogTool("/log/api/aa/", false); + + + public void ChangeDetail(String qyid,String changeBillId) { + log.writeLog("企业id:"+qyid); + + log.writeLog("-------------------------------------登记股东---------------------------------:"); + ModifyDetailInfo modifyDetailInfo= + new ModifyDetailInfo("djgd,cgbl,cgfs,gfzl,bz", + "uf_jnqyxxbgb_dt1", + "uf_jnqyxxbgb_dt2", + Integer.parseInt(DataBaseUtils.getModelIdByName("uf_jingneiqiyexinxi")) , + Integer.parseInt(changeBillId), + qyid); + modifyDetailInfo.setDtailJson(); + + + + String sql = ""; + RecordSet recordSet = new RecordSet(); + + + Map bgMap = new TreeMap<>(String::compareTo); + JSONObject jsonObject = modifyDetailInfo.getJsonVersion(); + log.writeLog("获取的json:"+jsonObject.toString()); + +// log.writeLog("附件:"+modifyDetailInfo.getChangeFjJson()); +// +// log.writeLog("备注:"+modifyDetailInfo.getChangeRemarkJson()); + + + + + for (Object date : jsonObject.keySet()) { + JSONObject parseObject = JSONObject.parseObject(jsonObject.getString(date.toString())); + HashMap map = new HashMap<>(); + map.put("date", parseObject.getJSONArray("data")); + map.put("bgqstr", parseObject.getString("oldrowDesc")); + map.put("bghstr", parseObject.getString("rowDesc")); + map.put("fj", strNull(parseObject.getString("fj"))); + map.put("bz", strNull(parseObject.getString("bz"))); + + bgMap.put(String.valueOf(date), map); + } + + log.writeLog("变更集合:"+bgMap); + + for (String bbrq : bgMap.keySet()) { + HashMap map = (HashMap) bgMap.get(bbrq); + String bgqstr = map.get("bgqstr").toString().replace("/、","、"); + String bghstr = map.get("bghstr").toString().replace("/、","、"); + String fj = map.get("fj").toString(); + String bz = map.get("bz").toString(); + if ("".equals(bgqstr)) { + bgqstr = "无"; + } + log.writeLog("变更前:"+bgqstr); + + String versionId = SynDate(qyid, bbrq); + + String bghListStr = map.get("date").toString(); + + ArrayList> gqList = new ArrayList<>(); + JSONArray jsonArray = JSONArray.parseArray(bghListStr); + for (int i = 0; i < jsonArray.size(); i++) { + HashMap map1 = new HashMap<>(); + map1.put("cgbl", strNull(JSONObject.parseObject(String.valueOf(jsonArray.get(i))).getString("cgbl"))); + map1.put("gfzl", strNull(JSONObject.parseObject(String.valueOf(jsonArray.get(i))).getString("gfzl"))); + map1.put("mainbillid", strNull(JSONObject.parseObject(String.valueOf(jsonArray.get(i))).getString("mainbillid"))); + map1.put("bbrq", strNull(JSONObject.parseObject(String.valueOf(jsonArray.get(i))).getString("bbrq"))); + map1.put("djgd", strNull(JSONObject.parseObject(String.valueOf(jsonArray.get(i))).getString("djgd"))); + map1.put("cgfs", strNull(JSONObject.parseObject(String.valueOf(jsonArray.get(i))).getString("cgfs"))); + map1.put("bz", strNull(JSONObject.parseObject(String.valueOf(jsonArray.get(i))).getString("bz"))); + map1.put("isChange", strNull(JSONObject.parseObject(String.valueOf(jsonArray.get(i))).getString("isChange"))); + map1.put("uuid", UUID.randomUUID().toString().replace("-", "")); +// map.put("isChange", strNull(parseObject.getString("isChange"))); + gqList.add(map1); + } + +// sql = "delete from formtable_main_3055_DT1 where mainid = '"+versionId+"' and rq = '"+bbrq+"' and bgxm = '登记股东/持股比例/持股份数/股份种类'"; +// log.writeLog("删除当日的变更项目:"+sql); +// recordSet.execute(sql); + //当日版本添加历史沿革 + sql = "insert into formtable_main_3055_DT1 (MAINID, RQ, BGXM, BGQ, BGH, FJ, BZ)\n" + + "values ('"+versionId+"','"+bbrq+"','登记股东/持股比例/持股份数/股份种类','"+bgqstr+"'," + + "'"+bghstr+"','"+fj+"','"+bz+"')"; + log.writeLog("插入历史沿革:"+sql+"\n"+ recordSet.execute(sql)); + + + /* + 判断之后是否有版本 + 有版本: + 判断版本是否变更股权 + 有变更: + (更新到有变更的表,有变更的表的变更前要更新) ---历史沿革新增 + 没有变更: + (更新之后版本所有的表,企业信息表) ---历史沿革新增 + 没有版本: + (更新当前版本表,更新企业表) ---历史沿革新增 + */ + + sql = "select ID\n" + + "from formtable_main_3055 where bbrq > '" + bbrq + "' and qyid = " + qyid +" order by bbrq"; + log.writeLog("获取之后版本的id:"+sql); + ArrayList> afterIdList = DataBaseUtils.getDataList(sql); + log.writeLog("之后版本的id:"+ Arrays.toString(afterIdList.toArray())); + + boolean isupdatemaintable = true; + boolean hasbb = afterIdList.size() > 0; + +// if (!hasbb) { +// sql = "delete from uf_jingneiqiyexinxi where mainid = " + qyid; +// log.writeLog("删除股东:"+sql); +// recordSet.execute(sql); +// } + + //删除当日的所有的股东 + sql = "delete from formtable_main_3055_dt2 where mainid = " + versionId; + log.writeLog("删除当日股东:"+sql); + recordSet.execute(sql); + + + //往当前版本插入数据 + for (Map gqmap : gqList) { + + if (gqmap.get("isChange").equals("1")) { + if ("".equals(gqmap.get("mainbillid"))&&bbrq.equals(gqmap.get("bbrq"))) { + log.writeLog("mainbillid为空,新增1:"); + + sql = "insert into uf_jingneiqiyexinxi_dt2 (MAINID, CGBL, BZ, QYMC1, GFZL, DJGD, MODFLYUUID, CGFS) values " + + "('"+qyid+"','"+gqmap.get("cgbl")+"','"+gqmap.get("bz")+"','"+qyid+"'" + + ",'"+gqmap.get("gfzl")+"','"+gqmap.get("djgd")+"','"+gqmap.get("uuid")+"','"+gqmap.get("cgfs")+"') "; + log.writeLog("插入企业信息表:"+sql); + recordSet.execute(sql); + sql = "select id from uf_jingneiqiyexinxi_dt2 where MODFLYUUID = '" + gqmap.get("uuid") + "'"; + String mainbillid = DataBaseUtils.getFirstValue(sql); + sql = "insert into formtable_main_3055_dt2 (MAINID, CGBL, BZ, QYMC1, GFZL, DJGD, mainbillid, CGFS) values " + + "('"+versionId+"','"+gqmap.get("cgbl")+"','"+gqmap.get("bz")+"','"+qyid+"'" + + ",'"+gqmap.get("gfzl")+"','"+gqmap.get("djgd")+"','"+mainbillid+"','"+gqmap.get("cgfs")+"') "; + log.writeLog("添加新增的股东:"+sql); + recordSet.execute(sql); + } else if (!"".equals(gqmap.get("mainbillid"))){ + log.writeLog("mainid不为空更新:"+gqmap.get("mainbillid")); +// sql = "update formtable_main_3055_dt2 set CGBL = '"+gqmap.get("cgbl")+"' ,BZ = '"+gqmap.get("bz")+"'" + +// ", GFZL = '"+gqmap.get("gfzl")+"', DJGD = '"+gqmap.get("djgd")+"' ,CGFS = '"+gqmap.get("cgfs")+"' " + +// " where mainid = '"+versionId+"' and mainbillid = '"+gqmap.get("mainbillid")+"'"; + + + sql = "insert into formtable_main_3055_dt2 (MAINID, CGBL, BZ, QYMC1, GFZL, DJGD, MODFLYUUID, CGFS,mainbillid) values " + + "('"+versionId+"','"+gqmap.get("cgbl")+"','"+gqmap.get("bz")+"','"+qyid+"'" + + ",'"+gqmap.get("gfzl")+"','"+gqmap.get("djgd")+"','"+gqmap.get("uuid")+"','"+gqmap.get("cgfs")+"','"+gqmap.get("mainbillid")+"') "; + + log.writeLog("当前股东的mainbillid存在,更新:"+sql); + + recordSet.execute(sql); + } + } + + } + + //有之后的版本 + if (afterIdList.size() > 0) { + //判断之后版本是否变更股权 + for (Map idMap : afterIdList) { + String afterId = idMap.get("ID"); + sql = "select id from formtable_main_3055_DT1 where mainid = "+afterId+" and bgxm = '登记股东/持股比例/持股份数/股份种类'"; + log.writeLog("获取有变更股东的企业:"+sql); + + String bgid = DataBaseUtils.getFirstValue(sql); + /* + 有变更: + (更新到有变更的表,有变更的表的变更前要更新) + 没有变更: + (更新之后版本所有的表,企业信息表) + */ + if ("".equals(DataBaseUtils.strNull(bgid))) { + //重新添加 + for (Map gqmap : gqList) { + if (gqmap.get("isChange").equals("1")) { + if ("".equals(gqmap.get("mainbillid"))&&bbrq.equals(gqmap.get("bbrq"))) { + log.writeLog("mainbillid为空,版本日期相同新增2:"); + + sql = "select id from uf_jingneiqiyexinxi_dt2 where MODFLYUUID = '" + gqmap.get("uuid") + "'"; + String mainbillid = DataBaseUtils.getFirstValue(sql); + sql = "insert into formtable_main_3055_dt2 (MAINID, CGBL, BZ, QYMC1, GFZL, DJGD, mainbillid, CGFS) values " + + "('"+afterId+"','"+gqmap.get("cgbl")+"','"+gqmap.get("bz")+"','"+qyid+"'" + + ",'"+gqmap.get("gfzl")+"','"+gqmap.get("djgd")+"','"+mainbillid+"','"+gqmap.get("cgfs")+"') "; + log.writeLog("添加新增的股东:"+sql); + recordSet.execute(sql); + } else if (!"".equals(gqmap.get("mainbillid"))){ + log.writeLog("更新:"+gqmap.get("mainbillid")); +// sql = "update formtable_main_3055_dt2 set CGBL = '"+gqmap.get("cgbl")+"', BZ = '"+gqmap.get("bz")+"'," + +// " GFZL = '"+gqmap.get("gfzl")+"', DJGD = '"+gqmap.get("djgd")+"', CGFS = '"+gqmap.get("cgfs")+"' " + +// " where mainid = '"+afterId+"' and mainbillid = '"+gqmap.get("mainbillid")+"'"; + + + + sql = "insert into formtable_main_3055_dt2 (MAINID, CGBL, BZ, QYMC1, GFZL, DJGD, mainbillid, CGFS) values " + + "('"+afterId+"','"+gqmap.get("cgbl")+"','"+gqmap.get("bz")+"','"+qyid+"'" + + ",'"+gqmap.get("gfzl")+"','"+gqmap.get("djgd")+"','"+gqmap.get("mainbillid")+"','"+gqmap.get("cgfs")+"') "; + + log.writeLog("当前股东的mainbillid存在,更新:"+sql); + + recordSet.execute(sql); + } + } + + } + } else { + + log.writeLog("当前版本存在股权变更:-----===="); + + sql = "update formtable_main_3055_DT1 set bgq ='"+bghstr+"' where id = " + bgid; + log.writeLog("更新版本的历史沿革的变更前:"+sql+"\n"+recordSet.execute(sql)); + + for (Map gqMap : gqList) { + + if ("".equals(gqMap.get("mainbillid"))&&bbrq.equals(gqMap.get("bbrq"))) { + sql = "delete from uf_jingneiqiyexinxi_dt2 where modflyuuid = '" + gqMap.get("uuid") + "'"; + //更新为空 + log.writeLog("清空企业表的股权:"+sql); + + recordSet.execute(sql); + } + } + + //后续有变更,不忘企业表中添加 + isupdatemaintable = false; + break; + } + } + } + + + if (isupdatemaintable) { + //往当前版本更新数据 + for (Map gqmap : gqList) { + + if (!"".equals(gqmap.get("mainbillid"))){ + log.writeLog("mainid不为空更新:"+gqmap.get("mainbillid")); + sql = "update uf_jingneiqiyexinxi_dt2 set CGBL = '"+gqmap.get("cgbl")+"' ,BZ = '"+gqmap.get("bz")+"'" + + ", GFZL = '"+gqmap.get("gfzl")+"', DJGD = '"+gqmap.get("djgd")+"' ,CGFS = '"+gqmap.get("cgfs")+"' " + + " where id = '"+gqmap.get("mainbillid")+"'"; + log.writeLog("变更最新的企业表:"+sql); + + recordSet.execute(sql); + } + } + //如果当前id在上一个版本中不存在,那就删除这个 + sql = "select djgd from uf_jingneiqiyexinxi_dt2 where mainid = "+qyid; + ArrayList list = DataBaseUtils.getList(sql); + + + sql = "select djgd\n" + + "from FORMTABLE_MAIN_3055_dt2\n" + + "where mainid in (select *\n" + + " from (select id from FORMTABLE_MAIN_3055 where qyid = "+qyid+" order by BBRQ desc)\n" + + " where rownum < 2)"; + log.writeLog("获取最后一个版本中的股东:"+sql); + + ArrayList bbList = DataBaseUtils.getList(sql); + log.writeLog("版本list:"+bbList); + log.writeLog("企业list:"+list); + + for (String s : list) { + //如果s不存在bblist中,直接删除 + if (!bbList.contains(s)) { + sql = "delete from uf_jingneiqiyexinxi_dt2 where djgd = '" + s+"'"; + log.writeLog("当前股东不在最新版本中,直接删除:"+sql); + recordSet.execute(sql); + } + + + } + } + + } + + + + + } + + + + /** + * + * 判断当前日期是否有数据,没有就从上一个版本复制 + * @param qyid 企业id + * @param date 日期 + * @return 当天企业的id + */ + public String SynDate(String qyid, String date) { + RecordSet recordSet = new RecordSet(); + String sql = "select id from formtable_main_3055 where qyid = '"+qyid+"' and bbrq = '"+date+"' "; + String changeId = ""; + String firstValue = DataBaseUtils.getFirstValue(sql); + if ("".equals(firstValue)) { + //空,同步所有信息,同步上一个版本所有信息 ,然后在后面修改 + sql = "select * from (select * from formtable_main_3055 where " + + " BBRQ <= '"+date+"' and qyid = '"+qyid+"' order by BBRQ desc ) where rownum <2"; + + log.writeLog("找到上一个版本的信息:"+sql); + + Map hashMap = DataBaseUtils.getDataMap(sql); + + if("".equals(strNull(hashMap.get("QYMC")))){ + log.writeLog("企业名称为空:"+hashMap); + + hashMap = DataBaseUtils.getDataMap("select * from (select * from formtable_main_3055 where qyid = '"+qyid+"' order by BBRQ ) where rownum <2"); + } + + log.writeLog("上一个版本的信息:"+hashMap); + + sql = "insert into formtable_main_3055 (zczb,dz,gly,qymc,zym,ywm,clrq,shxydm,dhyj,dhej,dhsj,dhsj1,dhwj,dhlj,dhqj," + + "jyfw,gqtsap,gqapfj,frdb,cwfzr,jl,js,ds,djzt,sfwbbdw,bafj,bbrq,qyid,GBDQ,DLQ" + + " , GSLX,GS,BZ,MGMZ,DLDFLST,YYDZ,YWBK,YWMKZJTZDJS,BZ2,DYZY,FJSC,ZJFWJGMSGS,SJS,GLF,NBJZQ,FORMMODEID) values ('" + hashMap.get("ZCZB") + "', '" + hashMap.get("DZ") + "', " + + "'" + hashMap.get("GLY") + "', '" + hashMap.get("QYMC") + "', '" + hashMap.get("ZYM") + "', '" + hashMap.get("YWM") + "', " + + "'" + hashMap.get("CLRQ") + "', '" + hashMap.get("SHXYDM") + "', '" + hashMap.get("DHYJ") + "', '" + hashMap.get("DHEJ") + "', " + + "'" + hashMap.get("DHSJ") + "', '" + hashMap.get("DHSJ1") + "', '" + hashMap.get("DHWJ") + "', '" + hashMap.get("DHLJ") + "', " + + "'" + hashMap.get("DHQJ") + "', '" + hashMap.get("JYFW") + "', '" + hashMap.get("GQTSAP") + "', '" + hashMap.get("GQAPFJ") + "', " + + "'" + hashMap.get("FRDB") + "', '" + hashMap.get("CWFZR") + "', '" + hashMap.get("JL") + "', '" + hashMap.get("JS") + "', " + + "'" + hashMap.get("DS") + "', '" + hashMap.get("DJZT") + "', '" + hashMap.get("SFWBBDW") + "', " + + "'" + hashMap.get("BAFJ") + "', '" + date + "','" + qyid + "'" + + ", '" + hashMap.get("GBDQ") + "', '" + hashMap.get("DLQ") + "', '" + hashMap.get("GSLX") + "', '" + hashMap.get("GS") + "'" + + ", '" + hashMap.get("BZ") + "', '" + hashMap.get("MGMZ") + "', '" + hashMap.get("DLDFLST") + "', '" + hashMap.get("YYDZ") + "'" + + ", '" + hashMap.get("YWBK") + "', '" + hashMap.get("YWMKZJTZDJS") + "', '" + hashMap.get("BZ2") + "', '" + hashMap.get("DYZY") + "'" + + ", '" + hashMap.get("FJSC") + "', '" + hashMap.get("ZJFWJGMSGS") + "', '" + hashMap.get("SJS") + "','"+ hashMap.get("GLF") +"','"+ + hashMap.get("NBJZQ") +"','"+DataBaseUtils.getModelIdByName("formtable_main_3055")+"')"; + log.writeLog("插入版本表的sql:" + sql); + recordSet.execute(sql); + + changeId = DataBaseUtils.getFirstValue("select id from formtable_main_3055 where qyid = '"+qyid+"' and bbrq = '"+date+"' "); + + + + sql = "select * from formtable_main_3055_dt2 where MAINID = (select * from (select id from formtable_main_3055 where " + + " BBRQ < '"+date+"' and qyid = '"+qyid+"' order by BBRQ desc ) where rownum <2) " ; + log.writeLog("获取股东:"+sql); + + ArrayList> dt2List = DataBaseUtils.getDataList(sql); + for (Map map : dt2List) { + sql = "insert into formtable_main_3055_dt2 (MAINID,DJGD,CGBL,BZ,QYMC1,rq,CGFS,gfzl,mainbillid) values ('" + changeId + "'" + + ",'" + map.get("DJGD") + "','" + map.get("CGBL") + "','" + map.get("BZ") + "','" + map.get("QYMC1") + "'," + + "'" + date + "','" + map.get("CGFS") + "','" + map.get("GFZL") + "','"+map.get("MAINBILLID")+"')"; + recordSet.execute(sql); + log.writeLog("插入股东:" + sql); + } + + + //同步资质证照 + sql = "select * from formtable_main_3055_dt3 where MAINID = (select * from (select id from formtable_main_3055 where " + + " BBRQ < '"+date+"' and qyid = '"+qyid+"' order by BBRQ desc ) where rownum <2) " ; + log.writeLog("同步资质证照的SQL:"+sql); + + ArrayList> dt3List = DataBaseUtils.getDataList(sql); + log.writeLog("同步资质证照的list:"+dt3List.size()); + + for (Map map : dt3List) { + sql = "insert into formtable_main_3055_dt3 (MAINID,zzzz,fjsc,BZ,QYMC,MAINBILLID) values ('" + changeId + "'" + + ",'" + map.get("ZZZZ") + "','" + map.get("FJSC") + "','" + map.get("BZ") + "','" + map.get("QYMC") + "','"+strNull(map.get("MAINBILLID"))+"')"; + log.writeLog("插入资质证照信息sql:" + sql); + recordSet.execute(sql); + } + + + } + //返回刚刚那张表的id + + sql = "select id from formtable_main_3055 where qyid = '"+qyid+"' and bbrq = '"+date+"' "; + firstValue = DataBaseUtils.getFirstValue(sql); + log.writeLog("之后的firstvalue:" + firstValue); + + return firstValue; + } + + /** + * 股东变更前后 + * @param list 股东集合 + * @return 内容 + */ + public String getGdBg(ArrayList> list) { + + String value = ""; + for (Map map : list) { + + value += "\n"+getQyOrRy(Util.null2String(map.get("DJGD")))+"/"+map.get("CGBL")+ + "%/"+map.get("CGFS")+"/"+getCgzl(Util.null2String(map.get("GFZL")))+"、"; + } + log.writeLog("value:"+value); + return "".equals(value)?value:value.substring(0,value.length()-1); + } + + /** + * 获取持股种类 + * @param id id + * @return 种类内容 + */ + public String getCgzl(String id) { + if (Util.null2String(id).equals("")) { + return ""; + } + RecordSet recordSet = new RecordSet(); + recordSet.execute("select GFZL from uf_gufenzhonglei where id = " + id); + recordSet.next(); + return Util.null2String(recordSet.getString("GFZL")); + } + + /** + * 获取企业或人员姓名 + * @param str id + * @return name + */ + private String getQyOrRy(String str) { + String[] strs = str.split("_"); + + String sql = ""; + if ("qy".equals(strs[0])) { + sql = "select qymc name from uf_jingneiqiyexinxi where id = " + strs[1]; + } else { + sql = "select xm name from UF_RENYUANXINXIKU where id = " + strs[1]; + + } + RecordSet recordSet = new RecordSet(); + recordSet.execute(sql); + recordSet.next(); + + log.writeLog("查找新的股东:"+sql); + return recordSet.getString("name"); + } + + + public static String strNull(String str) { + return (null == str) ? "" : str; + } + + + + +} diff --git a/src/main/youhong_ai_jitu_src/jntchina/service/oa/ChangeDt2.java b/src/main/youhong_ai_jitu_src/jntchina/service/oa/ChangeDt2.java new file mode 100644 index 0000000..76d360e --- /dev/null +++ b/src/main/youhong_ai_jitu_src/jntchina/service/oa/ChangeDt2.java @@ -0,0 +1,292 @@ +package jntchina.service.oa; + +import jntchina.util.DataBaseUtils; +import selfdev.util.log.LogTool; +import weaver.conn.RecordSet; +import weaver.general.Util; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.Map; +import java.util.UUID; + +/** + * @title: 改变明细表 + * @author ycf + * @date 2022-02-04 + */ +public class ChangeDt2 { + private final LogTool log = new LogTool("/log/api/aa/", false); + public void changeDt2(String qyId, String changeBillId) { + log.writeLog("-------------------------------------资质证照---------------------------------:"); + log.writeLog("企业id:"+qyId); + + + //先找到所有变更明细表中的有变更日期的数据 + String sql = ""; + RecordSet recordSet = new RecordSet(); + String qymc = qyId; + + //只考虑新增 + sql = "select * from uf_jnqyxxbgb_dt4 where mainid = '" + changeBillId + "' and rq is not null and zbid is null "; + log.writeLog("获取新增的资质证照:"+sql); + + log.writeLog("通过SQL获取数据集:"+sql); + ArrayList> addList = new ArrayList<>(); + + recordSet.execute(sql); + while (recordSet.next()) { + HashMap map = new HashMap<>(); + for (String s : recordSet.getColumnName()) { + map.put(s, (recordSet.getString(s))); + } + map.put("uuid", UUID.randomUUID().toString().replace("-", "")); + addList.add(map); + } + for (Map bgMap : addList) { + /* + 变更插入两张表 + 历史沿革插入两张表 + 往之后版本更新 + */ + String bgrq = bgMap.get("RQ"); + + //插入两张表 + sql = "insert into uf_jingneiqiyexinxi_dt3 (zzzz,fjsc,bz,mainid,qymc,MODFLYUUID) values ('"+bgMap.get("ZZZZ")+"','"+bgMap.get("FJSC")+"','"+bgMap.get("BZ")+"','"+qyId+"','"+qymc+"','"+bgMap.get("uuid")+"') "; + log.writeLog("插入企业信息的明细表" + sql); + recordSet.execute(sql); + + sql = "select id from uf_jingneiqiyexinxi_dt3 where MODFLYUUID = '"+bgMap.get("uuid")+"' "; + log.writeLog("通过新增的list中的UUID取变更主表的id:"+sql); + + String qiyeMainId = DataBaseUtils.getFirstValue(sql); + log.writeLog("获取插入企业表中的资质证照的ID:"+qiyeMainId); + + + + String versionId = SynDate(qyId, bgrq); + + sql = "insert into formtable_main_3055_dt3 (zzzz,fjsc,bz,mainbillid,mainid) values" + + " ('"+bgMap.get("ZZZZ")+"','"+bgMap.get("FJSC")+"','"+bgMap.get("BZ")+"','"+qiyeMainId+"','"+versionId+"') "; + log.writeLog("将新增的资质证照插入版本的明细表" + sql); + recordSet.execute(sql); + + + + + + sql = "insert into formtable_main_3055_dt1 (rq,mainid,bgxm,bgq,bgh,fj,bz) values" + + "('"+bgrq+"','"+versionId+"','资质证照','无','"+bgMap.get("ZZZZ")+"','"+bgMap.get("FJ")+"','"+bgMap.get("BZ1")+"') "; + log.writeLog("插入历史沿革" + sql); + recordSet.execute(sql); + + //找到之后是否有版本信息 + sql = "select id from formtable_main_3055 where qyid = '" + qyId + "' and bbrq > '" + bgrq + "' "; + log.writeLog("找到变更资质证照之后所有的版本"+sql); + ArrayList> idList = DataBaseUtils.getDataList(sql); + + //之后所有的版本都要插入当前的资质证照 + for (Map bbMap : idList) { + sql = "insert into formtable_main_3055_dt3 (zzzz,fjsc,bz,mainbillid,mainid) values" + + " ('"+bgMap.get("ZZZZ")+"','"+bgMap.get("FJSC")+"','"+bgMap.get("BZ")+"','"+qiyeMainId+"','"+bbMap.get("ID")+"') "; + log.writeLog("插入之后所有的版本"+sql); + recordSet.execute(sql); + } + } + + //所有需要更新的 + sql = "select * from uf_jnqyxxbgb_dt4 where mainid = '" + changeBillId + "' and rq is not null and zbid is not null "; + log.writeLog("获取更新的资质证照:"+sql); + + ArrayList> changeList = DataBaseUtils.getDataList(sql); + for (Map bghMap : changeList) { + String bgrq = bghMap.get("RQ"); + String zbid = bghMap.get("ZBID"); + String versionId = SynDate(qyId, bgrq); + + //获取原本的资质证照---改成上一个版本的 + sql = "select *\n" + + "from formtable_main_3055_DT3 where MAINID = '"+versionId+"' and MAINBILLID = "+bghMap.get("ZBID"); + log.writeLog("获取上一个版本的资质证照:"+sql); + + Map bgqMap = DataBaseUtils.getDataMap(sql); + + + + log.writeLog("主表id:"+zbid); + log.writeLog("上一版本的mainbillid:"+bgqMap.get("MAINBILLID")); + + + //主表id相同的情况下 + if (zbid.equals(bgqMap.get("MAINBILLID"))) { + log.writeLog("主表id相同的情况下"); + + //当前编辑版本的ID + String versionID = SynDate(qyId, bgrq); + //判断后面 是否有版本 + + sql = "select id from formtable_main_3055 where bbrq>'"+bgrq+"' and qyid = '"+qyId+"'"; + //获取之后版本的id + ArrayList> afterVersionId = DataBaseUtils.getDataList(sql); + + log.writeLog("变更前资质证照:"+bgqMap.get("ZZZZ")); + log.writeLog("变更后资质证照:"+bghMap.get("ZZZZ")); + + //资质证照名称变更 + if (!Util.null2String(bghMap.get("ZZZZ")).equals(Util.null2String(bgqMap.get("ZZZZ")))){ + //修改明细表中的字段(版本表,企业表) + sql = "update uf_jingneiqiyexinxi_dt3 set zzzz = '"+bghMap.get("ZZZZ")+"' where id = '"+zbid+"'"; + log.writeLog("修改资质证照的sql:"+sql); + recordSet.execute(sql); + //修改所有的id为xx,并且变更前为XXX 的版本表的明细表 + sql = "update formtable_main_3055_dt3 set zzzz = '"+bghMap.get("ZZZZ")+"' where MAINBILLID = '"+zbid+"' and mainid in" + + " (select id from formtable_main_3055 where bbrq >= '"+bgrq+"' and qyid = '"+qyId+"' ) and zzzz = '"+bgqMap.get("ZZZZ")+"' "; + log.writeLog("修改所有的id为xx,并且变更前为XXX 的版本表的明细表:"+sql); + recordSet.execute(sql); + + + + + + sql = "insert into formtable_main_3055_dt1 (rq,mainid,bgxm,bgq,bgh,fj,bz) values " + + "('"+bgrq+"','"+versionID+"','资质证照','"+bgqMap.get("ZZZZ")+"','"+bghMap.get("ZZZZ")+"','"+ bghMap.get("FJ")+"','"+ bghMap.get("BZ1")+"')"; + log.writeLog("插入企业版本表中的历史沿革:"+sql); + recordSet.execute(sql); + + + + //修改之后历史沿革的变更前为xx的信息变成当前版本的变更后的 + sql = "update formtable_main_3055_dt1 set bgq = '" + bghMap.get("ZZZZ") + "' " + + "where mainid in (select id from formtable_main_3055 where qyid = '" + qyId + "') and bgxm = '资质证照' and bgq = '" + bgqMap.get("ZZZZ") + "' and rq > '" + bgrq + "' "; + log.writeLog("修改之后历史沿革的变更前为xx的信息变成当前版本的变更后的:" + sql); + recordSet.execute(sql); + + } + + log.writeLog("变更前资质证照FJSC:"+bgqMap.get("FJSC")); + log.writeLog("变更后资质证照FJSC:"+bghMap.get("FJSC")); + if (!Util.null2String(bghMap.get("FJSC")).equals(Util.null2String(bgqMap.get("FJSC")))){ + sql = "update uf_jingneiqiyexinxi_dt3 set FJSC = '"+bghMap.get("FJSC")+"' where id = '"+zbid+"' "; + log.writeLog("修改资质证照附件的sql:"+sql); + recordSet.execute(sql); + + sql = "update formtable_main_3055_dt3 set FJSC = '"+bghMap.get("FJSC")+"' where MAINBILLID = '"+zbid+"' and mainid = "+versionID; + log.writeLog("修改资质证照附件的sql:"+sql); + recordSet.execute(sql); + + //修改所有的id为xx,并且变更前为XXX 的版本表的明细表 + sql = "update formtable_main_3055_dt3 set FJSC = '"+bghMap.get("FJSC")+"' where MAINBILLID = '"+zbid+"' and mainid in" + + " (select id from formtable_main_3055 where bbrq >= '"+bgrq+"' and qyid = '"+qyId+"' ) and (FJSC = '"+bgqMap.get("FJSC")+"' or fjsc is null) "; + log.writeLog("变更所有的之后版本的数据:"+sql); + recordSet.execute(sql); + } + + log.writeLog("变更前资质证照BZ:"+bgqMap.get("BZ")); + log.writeLog("变更后资质证照BZ:"+bghMap.get("BZ")); + if (!Util.null2String(bghMap.get("BZ")).equals(Util.null2String(bgqMap.get("BZ")))){ + sql = "update uf_jingneiqiyexinxi_dt3 set BZ = '"+bghMap.get("BZ")+"' where id = '"+zbid+"'"; + log.writeLog("修改资质证照备注的sql:"+sql); + recordSet.execute(sql); + + sql = "update formtable_main_3055_dt3 set BZ = '"+bghMap.get("BZ")+"' where id = '"+zbid+"' and id = "+versionID; + log.writeLog("修改资质证照备注的sql:"+sql); + recordSet.execute(sql); + + //修改所有的id为xx,并且变更前为XXX 的版本表的明细表 + sql = "update formtable_main_3055_dt3 set BZ = '"+bghMap.get("BZ")+"' where MAINBILLID = '"+zbid+"' and mainid in" + + " (select id from formtable_main_3055 where bbrq >= '"+bgrq+"' and qyid = '"+qyId+"' ) and BZ = '"+bgqMap.get("BZ")+"' "; + log.writeLog("变更所有的之后版本的备注数据:"+sql); + recordSet.execute(sql); + } + } + } + } + /** + * + * 判断当前日期是否有数据,没有就从上一个版本复制 + * @param qyid 企业id + * @param date 日期 + * @return 当天企业的id + */ + public String SynDate(String qyid, String date) { + RecordSet recordSet = new RecordSet(); + String sql = "select id from formtable_main_3055 where qyid = '"+qyid+"' and bbrq = '"+date+"' "; + String changeId = ""; + String firstValue = DataBaseUtils.getFirstValue(sql); + if ("".equals(firstValue)) { + //空,同步所有信息,同步上一个版本所有信息 ,然后在后面修改 + sql = "select * from (select * from formtable_main_3055 where " + + " BBRQ <= '"+date+"' and qyid = '"+qyid+"' order by BBRQ desc ) where rownum <2"; + + log.writeLog("找到上一个版本的信息:"+sql); + + Map hashMap = DataBaseUtils.getDataMap(sql); + + if("".equals(DataBaseUtils.strNull(hashMap.get("QYMC")))){ + log.writeLog("企业名称为空:"+hashMap); + + hashMap = DataBaseUtils.getDataMap("select * from (select * from formtable_main_3055 where qyid = '"+qyid+"' order by BBRQ ) where rownum <2"); + } + + log.writeLog("上一个版本的信息:"+hashMap); + + sql = "insert into formtable_main_3055 (zczb,dz,gly,qymc,zym,ywm,clrq,shxydm,dhyj,dhej,dhsj,dhsj1,dhwj,dhlj,dhqj," + + "jyfw,gqtsap,gqapfj,frdb,cwfzr,jl,js,ds,djzt,sfwbbdw,bafj,bbrq,qyid,GBDQ,DLQ" + + " , GSLX,GS,BZ,MGMZ,DLDFLST,YYDZ,YWBK,YWMKZJTZDJS,BZ2,DYZY,FJSC,ZJFWJGMSGS,SJS,GLF,NBJZQ,FORMMODEID) values ('" + hashMap.get("ZCZB") + "', '" + hashMap.get("DZ") + "', " + + "'" + hashMap.get("GLY") + "', '" + hashMap.get("QYMC") + "', '" + hashMap.get("ZYM") + "', '" + hashMap.get("YWM") + "', " + + "'" + hashMap.get("CLRQ") + "', '" + hashMap.get("SHXYDM") + "', '" + hashMap.get("DHYJ") + "', '" + hashMap.get("DHEJ") + "', " + + "'" + hashMap.get("DHSJ") + "', '" + hashMap.get("DHSJ1") + "', '" + hashMap.get("DHWJ") + "', '" + hashMap.get("DHLJ") + "', " + + "'" + hashMap.get("DHQJ") + "', '" + hashMap.get("JYFW") + "', '" + hashMap.get("GQTSAP") + "', '" + hashMap.get("GQAPFJ") + "', " + + "'" + hashMap.get("FRDB") + "', '" + hashMap.get("CWFZR") + "', '" + hashMap.get("JL") + "', '" + hashMap.get("JS") + "', " + + "'" + hashMap.get("DS") + "', '" + hashMap.get("DJZT") + "', '" + hashMap.get("SFWBBDW") + "', " + + "'" + hashMap.get("BAFJ") + "', '" + date + "','" + qyid + "'" + + ", '" + hashMap.get("GBDQ") + "', '" + hashMap.get("DLQ") + "', '" + hashMap.get("GSLX") + "', '" + hashMap.get("GS") + "'" + + ", '" + hashMap.get("BZ") + "', '" + hashMap.get("MGMZ") + "', '" + hashMap.get("DLDFLST") + "', '" + hashMap.get("YYDZ") + "'" + + ", '" + hashMap.get("YWBK") + "', '" + hashMap.get("YWMKZJTZDJS") + "', '" + hashMap.get("BZ2") + "', '" + hashMap.get("DYZY") + "'" + + ", '" + hashMap.get("FJSC") + "', '" + hashMap.get("ZJFWJGMSGS") + "', '" + hashMap.get("SJS") + "','"+ hashMap.get("GLF") +"','"+ + hashMap.get("NBJZQ") +"','"+DataBaseUtils.getModelIdByName("formtable_main_3055")+"')"; + log.writeLog("插入版本表的sql:" + sql); + recordSet.execute(sql); + + changeId = DataBaseUtils.getFirstValue("select id from formtable_main_3055 where qyid = '"+qyid+"' and bbrq = '"+date+"' "); + + + + sql = "select * from formtable_main_3055_dt2 where MAINID = (select * from (select id from formtable_main_3055 where " + + " BBRQ < '"+date+"' and qyid = '"+qyid+"' order by BBRQ desc ) where rownum <2) " ; + log.writeLog("获取股东:"+sql); + + ArrayList> dt2List = DataBaseUtils.getDataList(sql); + for (Map map : dt2List) { + sql = "insert into formtable_main_3055_dt2 (MAINID,DJGD,CGBL,BZ,QYMC1,rq,CGFS,gfzl,mainbillid) values ('" + changeId + "'" + + ",'" + map.get("DJGD") + "','" + map.get("CGBL") + "','" + map.get("BZ") + "','" + map.get("QYMC1") + "'," + + "'" + date + "','" + map.get("CGFS") + "','" + map.get("GFZL") + "','" + map.get("MAINBILLID") + "')"; + recordSet.execute(sql); + log.writeLog("插入股东:" + sql); + } + //同步资质证照 + sql = "select * from formtable_main_3055_dt3 where MAINID = (select * from (select id from formtable_main_3055 where " + + " BBRQ < '"+date+"' and qyid = '"+qyid+"' order by BBRQ desc ) where rownum <2) " ; + log.writeLog("同步资质证照的SQL:"+sql); + + ArrayList> dt3List = DataBaseUtils.getDataList(sql); + log.writeLog("同步资质证照的list:"+dt3List.size()); + + for (Map map : dt3List) { + sql = "insert into formtable_main_3055_dt3 (MAINID,zzzz,fjsc,BZ,QYMC,MAINBILLID) values ('" + changeId + "'" + + ",'" + map.get("ZZZZ") + "','" + map.get("FJSC") + "','" + map.get("BZ") + "','" + map.get("QYMC") + "','"+map.get("MAINBILLID")+"')"; + log.writeLog("插入资质证照信息sql:" + sql); + recordSet.execute(sql); + } + + + } + //返回刚刚那张表的id + + sql = "select id from formtable_main_3055 where qyid = '"+qyid+"' and bbrq = '"+date+"' "; + firstValue = DataBaseUtils.getFirstValue(sql); + log.writeLog("之后的firstvalue:" + firstValue); + + return firstValue; + } +} diff --git a/src/main/youhong_ai_jitu_src/jntchina/service/oa/DeleteQiye.java b/src/main/youhong_ai_jitu_src/jntchina/service/oa/DeleteQiye.java new file mode 100644 index 0000000..4eb6fe7 --- /dev/null +++ b/src/main/youhong_ai_jitu_src/jntchina/service/oa/DeleteQiye.java @@ -0,0 +1,68 @@ +package jntchina.service.oa; + +import java.util.HashMap; +import java.util.Map; + +import selfdev.util.log.LogTool; +import weaver.conn.RecordSet; +import weaver.formmode.customjavacode.AbstractModeExpandJavaCodeNew; +import weaver.general.Util; +import weaver.hrm.User; +import weaver.soa.workflow.request.RequestInfo; + + +/** + * 说明 + * 修改时 + * 类名要与文件名保持一致 + * class文件存放位置与路径保持一致。 + * 请把编译后的class文件,放在对应的目录中才能生效 + * 注意 同一路径下java名不能相同。 + * @author Administrator + * + */ +public class DeleteQiye extends AbstractModeExpandJavaCodeNew { + private final LogTool log = new LogTool("/log/api/qiye/", false); + /** + * 执行模块扩展动作 + * @param param + * param包含(但不限于)以下数据 + * user 当前用户 + * importtype 导入方式(仅在批量导入的接口动作会传输) 1 追加,2覆盖,3更新,获取方式(int)param.get("importtype") + * 导入链接中拼接的特殊参数(仅在批量导入的接口动作会传输),比如a=1,可通过param.get("a")获取参数值 + * 页面链接拼接的参数,比如b=2,可以通过param.get("b")来获取参数 + * @return + */ + public Map doModeExpand(Map param) { + Map result = new HashMap(); + try { + User user = (User)param.get("user"); + int billid = -1;//数据id + int modeid = -1;//模块id + RequestInfo requestInfo = (RequestInfo)param.get("RequestInfo"); + if(requestInfo!=null){ + billid = Util.getIntValue(requestInfo.getRequestid()); + modeid = Util.getIntValue(requestInfo.getWorkflowid()); + if(billid>0&&modeid>0){ + //------请在下面编写业务逻辑代码------ + + + String sql = ""; + RecordSet recordSet = new RecordSet(); + sql = "delete from formtable_main_3055 where qyid = " + billid; + log.writeLog("从信息卡片中删除:" + sql); + recordSet.executeUpdate(sql); + + + + + } + } + } catch (Exception e) { + result.put("errmsg","自定义出错信息"); + result.put("flag", "false"); + } + return result; + } + +} \ No newline at end of file diff --git a/src/main/youhong_ai_jitu_src/jntchina/service/oa/EnterpriseAPI.java b/src/main/youhong_ai_jitu_src/jntchina/service/oa/EnterpriseAPI.java new file mode 100644 index 0000000..1d506b3 --- /dev/null +++ b/src/main/youhong_ai_jitu_src/jntchina/service/oa/EnterpriseAPI.java @@ -0,0 +1,1009 @@ +package jntchina.service.oa; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.JSONArray; +import com.alibaba.fastjson.JSONObject; +import jntchina.entity.ChangeInfo; +import jntchina.util.DataBaseUtils; +import selfdev.util.log.LogTool; +import weaver.conn.RecordSet; + +import weaver.front.tablestring.Sql; +import weaver.general.Util; +import weaver.hrm.HrmUserVarify; +import weaver.hrm.User; + +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; +import javax.ws.rs.*; +import javax.ws.rs.core.Context; +import javax.ws.rs.core.HttpHeaders; +import java.io.BufferedReader; +import java.io.InputStreamReader; +import java.math.BigDecimal; +import java.text.DecimalFormat; +import java.time.LocalDate; +import java.util.*; + +/** + * @title: EnterpriseAPI企业信息api + * @Author ycf + * @Date: 2021/11/1 15:32 + * @Version 1.0 + */ +@Path("/EnterpriseAPI") +public class EnterpriseAPI { + private final LogTool log = new LogTool("/log/api/qiye/", false); + + + @POST + @Path("/getEquityInfo") + @Produces({"application/json"}) + public String getEquityInfo(@Context HttpServletRequest request, @Context HttpServletResponse response) { + + String qymc = request.getParameter("name"); + RecordSet recordSet = new RecordSet(); + String sql = ""; + + OAUtils oaUtils = new OAUtils(); + + recordSet.execute("select id from UF_JINGNEIQIYEXINXI where qymc = '" + qymc + "' "); + log.writeLog("寻找企业id:" + "select id from UF_JINGNEIQIYEXINXI where qymc = '" + qymc + "'"); + + recordSet.next(); + + + //处理的企业id + String cxqyid = recordSet.getString("id"); + //当前企业id + String dqqyid = cxqyid; + + log.writeLog("qiye id:" + cxqyid); + + + String qyurl = "/jntchina/workflow/jsp/JumpEnterprise.jsp?id="; + + String json = "{\n" + + " \"label\": \"" + qymc + "\",\n" + + " \"url\": \"qyurl\",\n" + + " \"ratio\": \"bili% \",\n" + + " \"children\": []\n" + + "}"; + + String gudong = "{\n" + + " \"label\": \"chigu\",\n" + + " \"url\": \" qyurl \",\n" + + " replacereplace," + + " \"children\": []" + + " }ens"; + + String chigu = "{\n" + + " \"label\": \"chigu\",\n" + + " \"url\": \" qyurl \",\n" + + " \"ratio\": \" bili% \",\n" + + " \"children\": []" + + " }ens"; + json = json.replace("qyurl", qyurl + cxqyid); + log.writeLog("json:" + json); + List list3 = new ArrayList<>(); + cxqyid = "qy_" + cxqyid; + + //通过企业id获取 + while (!cxqyid.equals("")) { + String[] gd = cxqyid.split("_"); + log.writeLog("股东cxqyid:" + cxqyid); + if ("qy".equals(gd[0])) { + + sql = "select mainid, (select name from V_CHIGU where IDS = a.djgd) djgdC,djgd,cgbl from uf_jingneiqiyexinxi_dt2 a where mainid = '" + gd[1] + "' and" + + " cgbl is not null and (select DJZT from UF_JINGNEIQIYEXINXI b where b.id = a.MAINID) != 5 order by CGBL desc,CGFS desc,DJGD desc "; + + log.writeLog("获取股东的sql:" + sql); + if (list3.contains(recordSet.getString("djgd"))) { + log.writeLog("list3中存在:" + list3); + break; + } else { + list3.add(recordSet.getString("djgd")); + } + recordSet.execute(sql); + recordSet.next(); + cxqyid = Util.null2String(recordSet.getString("djgd")).trim(); + log.writeLog("获取的股东:" + cxqyid); + + if (!(cxqyid.trim()).equals("")) { + json = gudong.replace("[]", "[" + json + "]"); + + json = json.replace("chigu", recordSet.getString("DJGDC")); + json = json.replace("bili", recordSet.getString("CGBL")); + json = json.replace("replacereplace,", "\"ratio\": \" bili% \",\n"); + json = json.replace("qyurl", qyurl + cxqyid); + json = json.replace("ens", " "); + } + } else { + sql = "select ids,name from V_CHIGU where ids = '" + cxqyid + "'"; + log.writeLog("获取股东人员的sql:" + sql); + + recordSet.execute(sql); + recordSet.next(); + + cxqyid = ""; + + +// json = gudong.replace("[]","["+json+"]"); + + json = json.replace("\"label\": \"\",", "\"label\": \"" + recordSet.getString("name") + "\","); +// json = json.replace("bili", recordSet.getString("CGBL")); +// json = json.replace("replacereplace,", "\"ratio\": \" bili% \",\n"); +// json = json.replace("qyurl", qyurl + recordSet.getString("ids")); + json = json.replace("ens", " "); + + } + + } + + json = json.replace("bili%", ""); + log.writeLog("股东json:" + json); +//往下追溯,找股东 + + list3.clear(); + //用来遍历 + List list = new ArrayList<>(); + list.add(dqqyid); + //用来缓存 + List list2 = new ArrayList<>(); + //所有企业的合集 + log.writeLog("list长度:" + list.size()); + for (String s : list) { + sql = "select * from UF_JINGNEIQIYEXINXI_DT2 a where DJGD = 'qy_" + s + "' " + + "and cgbl is not null and (select DJZT from UF_JINGNEIQIYEXINXI b where b.id = a.MAINID) != 5 order by CGBL desc,CGFS desc,DJGD desc "; + log.writeLog("找股东:" + sql); + + recordSet.execute(sql); + int i = 0; + + while (recordSet.next()) { + list2.add(recordSet.getString("mainid")); + if (list3.contains(recordSet.getString("mainid"))) { + log.writeLog("list3中存在:" + list3); + break; + } + i++; + list3.add(recordSet.getString("mainid")); + + if (i == 1) { + json = json.replace("[]", "[" + chigu + "]"); + } else { + json = json.replace("ens", "," + chigu); + } + String qy = Util.null2String(oaUtils.getQymc(recordSet.getString("mainid"))); + + + json = json.replace("chigu", qy); + json = json.replace("qyurl", qyurl + recordSet.getString("mainid")); + json = json.replace("bili", recordSet.getString("cgbl")); + String a = ("index" + recordSet.getString("mainid") + " "); + log.writeLog("要替换的值:" + a); + json = json.replace("[]", a); + } + + + json = json.replace("ens", ""); + log.writeLog("22222222222:" + json); + } + json = json.replace("ens", ""); + log.writeLog("股东一级:" + list); + list.clear(); + log.writeLog("股东二级:" + list2); + //持股二级如果有值 + + list.addAll(list2); + log.writeLog("11111111111111111111111:" + 1); + + log.writeLog("list.size:" + list.size()); + + while (list.size() > 0) { + log.writeLog("遍历list1:" + list); + list2.clear(); + for (String s : list) { + + sql = "select * from UF_JINGNEIQIYEXINXI_DT2 a where DJGD = 'qy_" + s + "' and cgbl is not null" + + " and (select DJZT from UF_JINGNEIQIYEXINXI b where b.id = a.MAINID) != 5 order by CGBL desc,CGFS desc,DJGD desc "; + log.writeLog("寻找下一级:" + sql); + recordSet.execute(sql); + int i = 0; + log.writeLog("前:" + json); + + while (recordSet.next()) { + list2.add(recordSet.getString("mainid")); + if (list3.contains(recordSet.getString("mainid"))) { + log.writeLog("list3中存在:" + list3); + break; + } + i++; + list3.add(recordSet.getString("mainid")); + + if (i == 1) { + json = json.replace("index" + s + " ", "[" + chigu + "]"); + } else { + json = json.replace("ens", "," + chigu); + } + json = json.replace("chigu", oaUtils.getQymc(recordSet.getString("mainid"))); + json = json.replace("qyurl", qyurl + recordSet.getString("mainid")); + json = json.replace("bili", recordSet.getString("cgbl")); + + String a = ("index" + recordSet.getString("mainid") + " "); + + json = json.replace("[]", a); + log.writeLog("json:" + i + json); + + + } + json = json.replace("ens", ""); + log.writeLog("后:" + json); + + } + + log.writeLog("寻找下一级公司:" + list2); + list.clear(); + list.addAll(list2); + list2.clear(); + + + } + + + for (String s : list3) { + json = json.replace("index" + s + " ", "\"\""); + } + + json = json.replace("bili%", ""); + json = json.replace("ens", ""); + json = json.replace("replacereplace,", ""); + json = json.replace("[]", "\"\""); + + log.writeLog("endjson:" + json); + + + return json; + + + } + + + public String getDjgd() { + + + return ""; + } + + + /** + * 获取下一级目录 + * + * @param request 请求的参数 + * @return 企业信息和目录信息 + */ + @POST + @Path("/getDirs") + @Produces({"application/json"}) + public String getDir(@Context HttpServletRequest request, @Context HttpServletResponse response, @Context HttpHeaders headers) { + + + String code = request.getParameter("id"); +// code = "1a2a1a2a1a2a3"; + + log.writeLog("获取的id:" + code); + String[] daohang = code.split("a"); + +// String[] cgbls = request.getParameterValues("query[cgbl][]"); +// log.writeLog("cgbl:"+Arrays.toString(cgbls)); + + + String search = Util.null2String(request.getParameter("search")); + + StringBuilder sqls = new StringBuilder(); + String[] deleteIds = request.getParameterValues("deleteId[]"); + log.writeLog("删除:" + Arrays.toString(deleteIds)); + + String[] clrq = request.getParameterValues("query[clrq][]"); + log.writeLog("获取的成立日期:" + Arrays.toString(clrq)); + + + String dateSql = new OAUtils().getDateSql(clrq); + log.writeLog("成立日期助理后:" + dateSql); + sqls.append(dateSql); + + + //浏览按钮人员信息库 + String gly = Util.null2String(request.getParameter("query[gly][id]")); + log.writeLog("gly:" + gly); + + String qymc = Util.null2String(request.getParameter("query[qymc]")); + log.writeLog("qymc:" + qymc); + + String zym = Util.null2String(request.getParameter("query[zym]")); + String ywm = Util.null2String(request.getParameter("query[ywm]")); + + String shxydm = Util.null2String(request.getParameter("query[shxydm]")); + String zczb = Util.null2String(request.getParameter("query[zczb]")); + String dz = Util.null2String(request.getParameter("query[dz]")); + String jyfw = Util.null2String(request.getParameter("query[jyfw]")); + //浏览按钮企业名称 + String bz = Util.null2String(request.getParameter("query[bz][id]")); + String gqtsap = Util.null2String(request.getParameter("query[gqtsap]")); + //浏览按钮人员信息库 + String frdb = Util.null2String(request.getParameter("query[frdb][id]")); + //浏览按钮人员信息库 + String cwfzr = Util.null2String(request.getParameter("query[cwfzr][id]")); + //浏览按钮人员信息库 + String jl = Util.null2String(request.getParameter("query[jl][id]")); + //浏览按钮人员信息库 + String js = Util.null2String(request.getParameter("query[js][id]")); + //浏览按钮人员信息库 + String ds = Util.null2String(request.getParameter("query[ds][id]")); + //选择框 + String djzt = Util.null2String(request.getParameter("query[djzt][id]")); + //选择框 + + //选择框 + String sfwbbdw = Util.null2String(request.getParameter("query[sfwbbdw][id]")); + String dhyj = Util.null2String(request.getParameter("query[dhyj][id]")); + String dhej = Util.null2String(request.getParameter("query[dhej][id]")); + String dhsj = Util.null2String(request.getParameter("query[dhsj][id]")); + String dhsj1 = Util.null2String(request.getParameter("query[dhsj1][id]")); + String dhwj = Util.null2String(request.getParameter("query[dhwj][id]")); + String dhlj = Util.null2String(request.getParameter("query[dhlj][id]")); + String dhqj = Util.null2String(request.getParameter("query[dhqj][id]")); + String gbdq = Util.null2String(request.getParameter("query[gbdq][id]")); + String dlq = Util.null2String(request.getParameter("query[dlq][id]")); + String gslx = Util.null2String(request.getParameter("query[gslx][id]")); + String dldflst = Util.null2String(request.getParameter("query[dldflst]")); + String ywbk = Util.null2String(request.getParameter("query[ywbk][id]")); + String ywmkzjtzdjs = Util.null2String(request.getParameter("query[ywmkzjtzdjs][id]")); + String bafj = Util.null2String(request.getParameter("query[bafj][id]")); + String yydz = Util.null2String(request.getParameter("query[yydz]")); + String bz2 = Util.null2String(request.getParameter("query[bz2]")); + String fjsc = Util.null2String(request.getParameter("query[fjsc][id]")); + String fjsc2 = Util.null2String(request.getParameter("query[fjsc2][id]")); + String dyzy = Util.null2String(request.getParameter("query[dyzy]")); + String sjs = Util.null2String(request.getParameter("query[sjs]")); + String mgmz = Util.null2String(request.getParameter("query[mgmz]")); + String gqapfj = Util.null2String(request.getParameter("query[gqapfj][id]")); + String gs = Util.null2String(request.getParameter("query[gs]")); + String zjfwjgmsgs = Util.null2String(request.getParameter("query[zjfwjgmsgs]")); + String glf = Util.null2String(request.getParameter("query[glf]")); + + String djgd = Util.null2String(request.getParameter("query[djgd][id]")); + String djgds = Util.null2String(request.getParameter("query[djgd]")); + String cgbl = Util.null2String(request.getParameter("query[cgbl]")); + + + //浏览按钮 + String[] str = {djzt, sfwbbdw, + dhyj, dhej, dhsj, dhsj1, dhwj, dhlj, dhqj, gbdq, dlq, gslx, dldflst, + ywbk, ywmkzjtzdjs, ywbk, bz, dyzy, glf}; + String[] strzd = {"djzt", "sfwbbdw", + "dhyj", "dhej", "dhsj", "dhsj1", "dhwj", "dhlj", "dhqj", "gbdq", "dlq", "gslx", "dldflst", + "ywbk", "ywmkzjtzdjs", "ywbk", "bz", "dyzy", "glf"}; + //文本框 + String[] str1 = {gly, qymc, zym, ywm, shxydm, zczb, dz, jyfw, bz2, gqtsap, + sjs, yydz, gs, zjfwjgmsgs, gqapfj, fjsc, fjsc2, bafj, mgmz}; + String[] str1zd = {"gly", "qymc", "zym", "ywm", "shxydm", "zczb", "dz", "jyfw", "bz2", "gqtsap", + "sjs", "yydz", "gs", "zjfwjgmsgs", "gqapfj", "fjsc", "fjsc2", "bafj", "mgmz"}; + + //人力,多选 + String[] str2 = {frdb, cwfzr, jl, js, ds}; + String[] str2zd = {"frdb", "cwfzr", "jl", "js", "ds"}; + + + log.writeLog("str:" + Arrays.toString(str)); + log.writeLog("str1:" + Arrays.toString(str1)); + + + //浏览按钮 + for (int i = 0; i < str.length; i++) { + if (!"null".equals(str[i]) && !"".equals(str[i]) && str[i] != null) { + sqls.append(" and ").append(strzd[i]).append(" = '").append(str[i]).append("' "); + + } + } + + log.writeLog("sqls1:" + sqls); + //文本框,模糊搜索 + for (int i = 0; i < str1.length; i++) { + if (!"null".equals(str1[i]) && !"".equals(str1[i]) && str[i] != null) { + sqls.append(" and ").append(str1zd[i]).append(" like '%").append(str1[i]).append("%' "); + + } + } + + for (int i = 0; i < str2.length; i++) { + if (!"null".equals(str2[i]) && !"".equals(str2[i]) && str2[i] != null) { + sqls.append(" and ','||a.").append(str2zd[i]).append("||',' like '%,").append(str2[i]).append(",%' "); + + } + } + + + if (!"".equals(djgd)) { + sqls.append(" and id in (select MAINID from UF_JINGNEIQIYEXINXI_DT2 where DJGD= '").append(djgd).append("') "); + } + if (!"".equals(cgbl)) { + sqls.append(" and id in (select MAINID from UF_JINGNEIQIYEXINXI_DT2 where cgbl like '%").append(cgbl).append("%') "); + } + + //登记股东 张三有限责任公司/50% + if (!"".equals(djgds)) { + + String[] strs = djgds.replace("%", "").split("/"); + sqls.append(" and id in (select MAINID from UF_JINGNEIQIYEXINXI_DT2 where DJGD in (select ids from V_CHIGU where name like '%").append(strs[0]).append("%') "); + if (strs.length == 2) { + sqls.append(" and CGBL like '%").append(strs[1]).append("%') "); + } + } + + + String cc = search; + if ("yes".contains(search.toLowerCase())) { + cc = "%0%"; + } + if ("no".contains(search.toLowerCase())) { + cc = "%1%"; + } + log.writeLog("sqls:" + sqls); + + //当模糊搜索不为空时,拼接 + if (!"".equals(search.trim())) { + sqls.append(" and ( \n" + + " lower(qymc) like lower('%" + search + "%') or lower(clrq) like lower('%" + search + "%') or lower(ZYM) like lower('%" + search + "%') or\n" + + " lower(YWM) like lower('%" + search + "%') or lower(SHXYDM) like lower('%" + search + "%') or lower(ZCZB) like lower('%" + search + "%') or\n" + + " lower(GS) like lower('%" + search + "%') or lower(MGMZ) like lower('%" + search + "%') or lower(DZ) like lower('%" + search + "%') or\n" + + " lower(YYDZ) like lower('%" + search + "%') or lower(dyzy) like lower('%" + search + "%') or lower(JYFW) like lower('%" + search + "%') or " + + " lower(BZ) like lower('%" + search + "%') or lower(NBJZQ) like lower('%" + search + "%') or \n" + + + " GBDQ in (select b.id from uf_guojiadiquku b where lower(GJDQK) like lower('%" + search + "%')) or\n" + + " DLQ in (select b.ID from uf_dailiqu b where lower(b.DLQ) like lower('%" + search + "%')) or\n" + + " GSLX in (select b.id from uf_gongsileixing b where lower(b.GSLX) like lower('%" + search + "%')) or\n" + + " DJZT in (select b.ID from uf_dengjizhuangtai b where lower(b.DJZT) like lower('%" + search + "%')) or\n" + + " BZ in (select b.id from uf_bizhong b where lower(b.BZ) like lower('%" + search + "%')) or\n" + + " DLDFLST like '" + cc + "' or\n" + + " glf like '" + cc + "' or\n" + + " YWBK in (select b.id from uf_yewubankuai b where lower(b.YWBK) like lower('%" + search + "%')) or\n" + + " YWMKZJTZDJS in (select b.id from uf_jituanzhongdejue b where lower(b.YWMKZJTZDJS) like lower('%" + search + "%')) or\n" + + " SFWBBDW in (select b.id from uf_shifouweibingbia b where lower(b.SFWBBDW) like lower('%" + search + "%')) " + +// "or\n" + +//// " FJSC in (select b.DOCID from docimagefile b where b.IMAGEFILENAME like '%"+search+"%') or\n" + +// " GQAPFJ in (select b.DOCID from docimagefile b where b.IMAGEFILENAME like '%"+search+"%') or\n" + +// " BAFJ in (select b.DOCID from docimagefile b where b.IMAGEFILENAME like '%"+search+"%')\n" + + " or GLY in (select b.id from UF_GUANLIYUANKUXIN b where lower(SFZXM) like lower('%" + search + "%'))" + +// " or\n" + +// " CWFZR in (select b.id from UF_RENYUANXINXIKU b where lower(XM) like lower('%"+search+"%')) or\n" + +// " FRDB in (select b.id from UF_RENYUANXINXIKU b where lower(XM) like lower('%"+search+"%')) or\n" + +// " JS in (select b.id from UF_RENYUANXINXIKU b where lower(XM) like lower('%"+search+"%')) or\n" + +// " DS in (select b.id from UF_RENYUANXINXIKU b where lower(XM) like lower('%"+search+"%')) or\n" + +// " JL in (select b.id from UF_RENYUANXINXIKU b where lower(XM) like lower('%"+search+"%')) " + + " "); + ArrayList list = DataBaseUtils.getList("select id from UF_RENYUANXINXIKU where xm like '%" + search + "%' "); + for (String s : list) { + sqls.append(" or ','||CWFZR||',' like '%," + s + ",%' " + + " or ','||FRDB||',' like '%," + s + ",%' " + + " or ','||JS||',' like '%," + s + ",%' " + + " or ','||DS||',' like '%," + s + ",%' " + + " or ','||JL||',' like '%," + s + ",%' "); + } + + } + + //登记股东 张三有限责任公司/50% + if (!"".equals(search)) { + + String[] strs = search.replace("%", "").split("/"); + sqls.append(" or id in (select MAINID from UF_JINGNEIQIYEXINXI_DT2 where DJGD in (select ids from V_CHIGU where name like '%").append(strs[0]).append("%') "); + if (strs.length == 2) { + sqls.append(" and CGBL like '%").append(strs[1]).append("%') "); + } else { + sqls.append(" ) "); + } + } + + + log.writeLog("sqls:" + sqls); + log.writeLog("参数code:" + code); + //导航 + String sql = ""; + //企业个数 + String sql2 = ""; + //企业 + String sql3 = ""; + //是否为父节点 + String sql4 = ""; + RecordSet recordSet = new RecordSet(); + + //删除企业 + if (null != deleteIds && deleteIds.length >= 1 && !"".equals(deleteIds[0])) { + for (String deleteId : deleteIds) { + if (!"".equals(deleteId)) { + sql = "delete from uf_jingneiqiyexinxi where id = " + deleteId; + log.writeLog("删除企业:" + sql); + recordSet.execute(sql); + sql = "delete from uf_jingneiqiyexinxi_dt2 where mainid = " + deleteId; + log.writeLog("删除持股:" + sql); + recordSet.execute(sql); + sql = "delete from uf_jingneiqiyexinxi_dt2 where djgd = 'qy_" + deleteId + "' "; + log.writeLog("删除dt股东:" + sql); + recordSet.execute(sql); + } + + } + + sql = "delete \n" + + "from formtable_main_3055 where qyid not in (select id from UF_JINGNEIQIYEXINXI)"; + recordSet.execute(sql); + log.writeLog("删除历史表的数据:" + sql); + + } + + + if (sqls.toString().contains("and ( ")) { + sqls.append(" ) "); + } + String gl = ""; + + User user1 = HrmUserVarify.getUser(request, response); + int uid1 = user1.getUID(); + if (uid1 != 1) { + String username = DataBaseUtils.getFirstValue("select LASTNAME from HRMRESOURCE where id = " + user1.getUID()); + Map glyMap = DataBaseUtils.getDataMap("select type,id from uf_guanliyuankuxin where sfzxm = '" + username + "' "); + log.writeLog("用户名:" + username); + log.writeLog("glytype:" + glyMap); + + ArrayList> maps = new ArrayList<>(); + //判断当前用户是否为超级管理员 + if (!glyMap.get("TYPE").equals("0")) { + //判断管理员是否为本人 + gl = " and (gly = '" + glyMap.get("ID") + "' or ','||gxry||',' like '%," + uid1 + ",%' )"; + } + + + } + + + switch (daohang.length) { + case 1: + if ("".equals(code)) { + + //默认中国大陆 + sql = "select (select DHYJZDXX from uf_daohangyijizidua b where a.dhyj=b.id) name,count(1) num,dhyj code from uf_jingneiqiyexinxi a where 1= 1 " + sqls + gl + " group by dhyj order by dhyj "; + sql2 = "select count(1) from uf_jingneiqiyexinxi a where 1=1 " + sqls; + sql3 = " select (select DHYJZDXX from uf_daohangyijizidua where id = a.dhyj) dhyj,(select dhej from uf_daohangerji where id = a.dhej) dhej,(select dhsj from uf_saohangsanji where id = a.dhsj) dhsj\n" + + " ,(select dhsj from uf_daohangsiji where id = a.dhsj1) dhsj1,id\n" + + " ,(select dhwj from uf_daohangwuji where id = a.dhwj) dhwj,(select dhlj from uf_daohangliuji where id = a.dhlj) dhlj,(select dhqj from uf_daohangqiji where id = a.dhqj) dhqj\n" + + " ,(select GJDQK from uf_guojiadiquku where id = a.gbdq) gbdq,(select DLQ from uf_dailiqu where id=a.dlq) dlq,(select gslx from uf_gongsileixing where id=a.gslx) gslx,(select bz from uf_bizhong where id=a.bz) bz,\n" + + " dldflst,(select YWBK from uf_yewubankuai where id=a.ywbk) ywbk,(select YWMKZJTZDJS from uf_jituanzhongdejue where id=a.ywmkzjtzdjs) ywmkzjtzdjs,\n" + + " gly, frdb, cwfzr, jl,js,ds,(select DJZT from uf_dengjizhuangtai where id=a.djzt) djzt,(select SFWBBDW from uf_shifouweibingbia where id = a.sfwbbdw) sfwbbdw,gs,mgmz,yydz,bz2,dyzy\n" + + " ,zjfwjgmsgs,sjs,zczb,dz,qymc,zym,ywm,clrq,shxydm,jyfw,gqtsap, fjsc,gqapfj,bafj,GLF,NBJZQ from uf_jingneiqiyexinxi a where 1=1 " + sqls; + sql4 = "select a.*,rownum num from uf_jingneiqiyexinxi a where dhej is not null " + sqls; + + } else { + sql = "select (select DHEJ from uf_daohangerji b where a.dhej=b.id) name,count(1) num,dhej code from uf_jingneiqiyexinxi a where a.DHYJ=" + daohang[0] + sqls + gl + " group by dhej "; + sql2 = "select count(1) from uf_jingneiqiyexinxi a where dhyj = " + daohang[0] + sqls; + sql3 = " select (select DHYJZDXX from uf_daohangyijizidua where id = a.dhyj) dhyj,(select dhej from uf_daohangerji where id = a.dhej) dhej,(select dhsj from uf_saohangsanji where id = a.dhsj) dhsj\n" + + " ,(select dhsj from uf_daohangsiji where id = a.dhsj1) dhsj1,id\n" + + " ,(select dhwj from uf_daohangwuji where id = a.dhwj) dhwj,(select dhlj from uf_daohangliuji where id = a.dhlj) dhlj,(select dhqj from uf_daohangqiji where id = a.dhqj) dhqj\n" + + " ,(select GJDQK from uf_guojiadiquku where id = a.gbdq) gbdq,(select DLQ from uf_dailiqu where id=a.dlq) dlq,(select gslx from uf_gongsileixing where id=a.gslx) gslx,(select bz from uf_bizhong where id=a.bz) bz,\n" + + " dldflst,(select YWBK from uf_yewubankuai where id=a.ywbk) ywbk,(select YWMKZJTZDJS from uf_jituanzhongdejue where id=a.ywmkzjtzdjs) ywmkzjtzdjs,\n" + + " gly, frdb, cwfzr, jl,js,ds,(select DJZT from uf_dengjizhuangtai where id=a.djzt) djzt,(select SFWBBDW from uf_shifouweibingbia where id = a.sfwbbdw) sfwbbdw,gs,mgmz,yydz,bz2,dyzy\n" + + " ,zjfwjgmsgs,sjs,zczb,dz,qymc,zym,ywm,clrq,shxydm,jyfw,gqtsap, fjsc,gqapfj,bafj,GLF,NBJZQ from uf_jingneiqiyexinxi a where dhyj = " + daohang[0] + " " + sqls; + + } + break; + case 2: + sql = "select (select DHSJ from uf_saohangsanji b where a.DHSJ =b.id) name,count(2) num,dhsj code from uf_jingneiqiyexinxi a where a.dhyj=" + daohang[0] + " and a.dhej=" + daohang[1] + " and dhsj is not null " + sqls + gl + " group by dhsj "; + sql2 = "select count(1) from uf_jingneiqiyexinxi a where dhej = " + daohang[1] + " and dhyj = " + daohang[0] + " " + sqls; + sql3 = " select (select DHYJZDXX from uf_daohangyijizidua where id = a.dhyj) dhyj,(select dhej from uf_daohangerji where id = a.dhej) dhej,(select dhsj from uf_saohangsanji where id = a.dhsj) dhsj\n" + + " ,(select dhsj from uf_daohangsiji where id = a.dhsj1) dhsj1,id\n" + + " ,(select dhwj from uf_daohangwuji where id = a.dhwj) dhwj,(select dhlj from uf_daohangliuji where id = a.dhlj) dhlj,(select dhqj from uf_daohangqiji where id = a.dhqj) dhqj\n" + + " ,(select GJDQK from uf_guojiadiquku where id = a.gbdq) gbdq,(select DLQ from uf_dailiqu where id=a.dlq) dlq,(select gslx from uf_gongsileixing where id=a.gslx) gslx,(select bz from uf_bizhong where id=a.bz) bz,\n" + + " dldflst,(select YWBK from uf_yewubankuai where id=a.ywbk) ywbk,(select YWMKZJTZDJS from uf_jituanzhongdejue where id=a.ywmkzjtzdjs) ywmkzjtzdjs,\n" + + " gly, frdb, cwfzr, jl,js,ds,(select DJZT from uf_dengjizhuangtai where id=a.djzt) djzt,(select SFWBBDW from uf_shifouweibingbia where id = a.sfwbbdw) sfwbbdw,gs,mgmz,yydz,bz2,dyzy\n" + + " ,zjfwjgmsgs,sjs,zczb,dz,qymc,zym,ywm,clrq,shxydm,jyfw,gqtsap, fjsc,gqapfj,bafj,GLF,NBJZQ from uf_jingneiqiyexinxi a where dhej = " + daohang[1] + " and dhyj = " + daohang[0] + " " + sqls; + + break; + case 3: + sql = "select (select DHSJ from uf_daohangsiji b where a.DHSJ1 =b.id) name,count(2) num ,dhsj1 code from uf_jingneiqiyexinxi a where a.dhyj=" + daohang[0] + " and a.dhej=" + daohang[1] + " and a.dhsj=" + daohang[2] + " and dhsj1 is not null " + sqls + gl + " group by dhsj1"; + sql2 = "select count(1) from uf_jingneiqiyexinxi a where dhsj = " + daohang[2] + " and dhej = " + daohang[1] + " and dhyj = " + daohang[0] + " " + sqls; + sql3 = " select (select DHYJZDXX from uf_daohangyijizidua where id = a.dhyj) dhyj,(select dhej from uf_daohangerji where id = a.dhej) dhej,(select dhsj from uf_saohangsanji where id = a.dhsj) dhsj\n" + + " ,(select dhsj from uf_daohangsiji where id = a.dhsj1) dhsj1,id\n" + + " ,(select dhwj from uf_daohangwuji where id = a.dhwj) dhwj,(select dhlj from uf_daohangliuji where id = a.dhlj) dhlj,(select dhqj from uf_daohangqiji where id = a.dhqj) dhqj\n" + + " ,(select GJDQK from uf_guojiadiquku where id = a.gbdq) gbdq,(select DLQ from uf_dailiqu where id=a.dlq) dlq,(select gslx from uf_gongsileixing where id=a.gslx) gslx,(select bz from uf_bizhong where id=a.bz) bz,\n" + + " dldflst,(select YWBK from uf_yewubankuai where id=a.ywbk) ywbk,(select YWMKZJTZDJS from uf_jituanzhongdejue where id=a.ywmkzjtzdjs) ywmkzjtzdjs,\n" + + " gly, frdb, cwfzr, jl,js,ds,(select DJZT from uf_dengjizhuangtai where id=a.djzt) djzt,(select SFWBBDW from uf_shifouweibingbia where id = a.sfwbbdw) sfwbbdw,gs,mgmz,yydz,bz2,dyzy\n" + + " ,zjfwjgmsgs,sjs,zczb,dz,qymc,zym,ywm,clrq,shxydm,jyfw,gqtsap, fjsc,gqapfj,bafj,GLF,NBJZQ from uf_jingneiqiyexinxi a where dhsj = " + daohang[2] + " and dhej = " + daohang[1] + " and dhyj = " + daohang[0] + " " + sqls; + + break; + case 4: + sql = "select (select DHWJ from uf_daohangwuji b where a.DHWJ = b.id) name, count(2) num,DHWJ code from uf_jingneiqiyexinxi a where dhyj = " + daohang[0] + " and dhej = " + daohang[1] + " and dhsj = " + daohang[2] + " and dhsj1 = " + daohang[3] + " and DHWJ is not null " + sqls + gl + " group by DHWJ"; + sql2 = "select count(1) from uf_jingneiqiyexinxi a where dhsj1 = " + daohang[3] + " and dhsj = " + daohang[2] + " and dhej = " + daohang[1] + " and dhyj = " + daohang[0] + " " + sqls; + sql3 = " select (select DHYJZDXX from uf_daohangyijizidua where id = a.dhyj) dhyj,(select dhej from uf_daohangerji where id = a.dhej) dhej,(select dhsj from uf_saohangsanji where id = a.dhsj) dhsj\n" + + " ,(select dhsj from uf_daohangsiji where id = a.dhsj1) dhsj1,id\n" + + " ,(select dhwj from uf_daohangwuji where id = a.dhwj) dhwj,(select dhlj from uf_daohangliuji where id = a.dhlj) dhlj,(select dhqj from uf_daohangqiji where id = a.dhqj) dhqj\n" + + " ,(select GJDQK from uf_guojiadiquku where id = a.gbdq) gbdq,(select DLQ from uf_dailiqu where id=a.dlq) dlq,(select gslx from uf_gongsileixing where id=a.gslx) gslx,(select bz from uf_bizhong where id=a.bz) bz,\n" + + " dldflst,(select YWBK from uf_yewubankuai where id=a.ywbk) ywbk,(select YWMKZJTZDJS from uf_jituanzhongdejue where id=a.ywmkzjtzdjs) ywmkzjtzdjs,\n" + + " gly, frdb, cwfzr, jl,js,ds,(select DJZT from uf_dengjizhuangtai where id=a.djzt) djzt,(select SFWBBDW from uf_shifouweibingbia where id = a.sfwbbdw) sfwbbdw,gs,mgmz,yydz,bz2,dyzy\n" + + " ,zjfwjgmsgs,sjs,zczb,dz,qymc,zym,ywm,clrq,shxydm,jyfw,gqtsap, fjsc,gqapfj,bafj,GLF,NBJZQ from uf_jingneiqiyexinxi a where dhsj1 = " + daohang[3] + " and dhsj = " + daohang[2] + " and dhej = " + daohang[1] + " and dhyj = " + daohang[0] + " " + sqls; + + break; + case 5: + sql = "select (select dhlj from uf_daohangliuji b where a.dhlj = b.id) name, count(2) num,dhlj code from uf_jingneiqiyexinxi a where dhyj = " + daohang[0] + " and dhej = " + daohang[1] + " and dhsj = " + daohang[2] + " and dhsj1 = " + daohang[3] + " and dhwj=" + daohang[4] + " and dhlj is not null " + sqls + gl + " group by dhlj "; + sql2 = "select count(1) from uf_jingneiqiyexinxi a where dhwj = " + daohang[4] + " and dhsj1 = " + daohang[3] + " and dhsj = " + daohang[2] + " and dhej = " + daohang[1] + " and dhyj = " + daohang[0] + " " + sqls; + sql3 = " select (select DHYJZDXX from uf_daohangyijizidua where id = a.dhyj) dhyj,(select dhej from uf_daohangerji where id = a.dhej) dhej,(select dhsj from uf_saohangsanji where id = a.dhsj) dhsj\n" + + " ,(select dhsj from uf_daohangsiji where id = a.dhsj1) dhsj1,id\n" + + " ,(select dhwj from uf_daohangwuji where id = a.dhwj) dhwj,(select dhlj from uf_daohangliuji where id = a.dhlj) dhlj,(select dhqj from uf_daohangqiji where id = a.dhqj) dhqj\n" + + " ,(select GJDQK from uf_guojiadiquku where id = a.gbdq) gbdq,(select DLQ from uf_dailiqu where id=a.dlq) dlq,(select gslx from uf_gongsileixing where id=a.gslx) gslx,(select bz from uf_bizhong where id=a.bz) bz,\n" + + " dldflst,(select YWBK from uf_yewubankuai where id=a.ywbk) ywbk,(select YWMKZJTZDJS from uf_jituanzhongdejue where id=a.ywmkzjtzdjs) ywmkzjtzdjs,\n" + + " gly, frdb, cwfzr, jl,js,ds,(select DJZT from uf_dengjizhuangtai where id=a.djzt) djzt,(select SFWBBDW from uf_shifouweibingbia where id = a.sfwbbdw) sfwbbdw,gs,mgmz,yydz,bz2,dyzy\n" + + " ,zjfwjgmsgs,sjs,zczb,dz,qymc,zym,ywm,clrq,shxydm,jyfw,gqtsap, fjsc,gqapfj,bafj,GLF,NBJZQ from uf_jingneiqiyexinxi a where dhwj = " + daohang[4] + " and dhsj1 = " + daohang[3] + " and dhsj = " + daohang[2] + " and dhej = " + daohang[1] + " and dhyj = " + daohang[0] + " " + sqls; + + break; + case 6: + sql = "select (select dhqj from uf_daohangqiji b where a.dhqj= b.id) name, count(2) num,dhqj code from uf_jingneiqiyexinxi a where dhyj = " + daohang[0] + " and dhej = " + daohang[1] + " and dhsj = " + daohang[2] + " and dhsj1 = " + daohang[3] + " and dhwj=" + daohang[4] + " and dhlj=" + daohang[5] + " and dhqj is not null " + sqls + gl + " group by dhqj"; + sql2 = "select count(1) from uf_jingneiqiyexinxi a where dhlj = " + daohang[5] + " and dhwj = " + daohang[4] + " and dhsj1 = " + daohang[3] + " and dhsj = " + daohang[2] + " and dhej = " + daohang[1] + " and dhyj = " + daohang[0] + " " + sqls; + sql3 = " select (select DHYJZDXX from uf_daohangyijizidua where id = a.dhyj) dhyj,(select dhej from uf_daohangerji where id = a.dhej) dhej,(select dhsj from uf_saohangsanji where id = a.dhsj) dhsj\n" + + " ,(select dhsj from uf_daohangsiji where id = a.dhsj1) dhsj1,id\n" + + " ,(select dhwj from uf_daohangwuji where id = a.dhwj) dhwj,(select dhlj from uf_daohangliuji where id = a.dhlj) dhlj,(select dhqj from uf_daohangqiji where id = a.dhqj) dhqj\n" + + " ,(select GJDQK from uf_guojiadiquku where id = a.gbdq) gbdq,(select DLQ from uf_dailiqu where id=a.dlq) dlq,(select gslx from uf_gongsileixing where id=a.gslx) gslx,(select bz from uf_bizhong where id=a.bz) bz,\n" + + " dldflst,(select YWBK from uf_yewubankuai where id=a.ywbk) ywbk,(select YWMKZJTZDJS from uf_jituanzhongdejue where id=a.ywmkzjtzdjs) ywmkzjtzdjs,\n" + + " gly, frdb, cwfzr, jl,js,ds,(select DJZT from uf_dengjizhuangtai where id=a.djzt) djzt,(select SFWBBDW from uf_shifouweibingbia where id = a.sfwbbdw) sfwbbdw,gs,mgmz,yydz,bz2,dyzy\n" + + " ,zjfwjgmsgs,sjs,zczb,dz,qymc,zym,ywm,clrq,shxydm,jyfw,gqtsap, fjsc,gqapfj,bafj,GLF,NBJZQ from uf_jingneiqiyexinxi a where dhlj = " + daohang[5] + " and dhwj = " + daohang[4] + " and dhsj1 = " + daohang[3] + " and dhsj = " + daohang[2] + " and dhej = " + daohang[1] + " and dhyj = " + daohang[0] + " " + sqls; + + break; + case 7: +// sql = "select (select dhqj from uf_daohangqiji b where a.dhqj= b.id) name, count(2) num,dhqj code from uf_jingneiqiyexinxi a where dhyj = "+daohang[0]+" and dhej = "+daohang[1]+" and dhsj = "+daohang[2]+" and dhsj1 = "+daohang[3]+" and dhwj="+daohang[4]+" and dhlj="+daohang[5]+" and dhqj is not null group by dhqj"; + sql2 = "select count(1) from uf_jingneiqiyexinxi a where dhqj = " + daohang[6] + " and dhlj = " + daohang[5] + " and dhwj = " + daohang[4] + " and dhsj1 = " + daohang[3] + " and dhsj = " + daohang[2] + " and dhej = " + daohang[1] + " and dhyj = " + daohang[0] + " " + sqls; + sql3 = " select (select DHYJZDXX from uf_daohangyijizidua where id = a.dhyj) dhyj,(select dhej from uf_daohangerji where id = a.dhej) dhej,(select dhsj from uf_saohangsanji where id = a.dhsj) dhsj\n" + + " ,(select dhsj from uf_daohangsiji where id = a.dhsj1) dhsj1,id\n" + + " ,(select dhwj from uf_daohangwuji where id = a.dhwj) dhwj,(select dhlj from uf_daohangliuji where id = a.dhlj) dhlj,(select dhqj from uf_daohangqiji where id = a.dhqj) dhqj\n" + + " ,(select GJDQK from uf_guojiadiquku where id = a.gbdq) gbdq,(select DLQ from uf_dailiqu where id=a.dlq) dlq,(select gslx from uf_gongsileixing where id=a.gslx) gslx,(select bz from uf_bizhong where id=a.bz) bz,\n" + + " dldflst,(select YWBK from uf_yewubankuai where id=a.ywbk) ywbk,(select YWMKZJTZDJS from uf_jituanzhongdejue where id=a.ywmkzjtzdjs) ywmkzjtzdjs,\n" + + " gly, frdb, cwfzr, jl,js,ds,(select DJZT from uf_dengjizhuangtai where id=a.djzt) djzt,(select SFWBBDW from uf_shifouweibingbia where id = a.sfwbbdw) sfwbbdw,gs,mgmz,yydz,bz2,dyzy\n" + + " ,zjfwjgmsgs,sjs,zczb,dz,qymc,zym,ywm,clrq,shxydm,jyfw,gqtsap, fjsc,gqapfj,bafj,GLF,NBJZQ from uf_jingneiqiyexinxi a where dhqj = " + daohang[6] + " and dhlj = " + daohang[5] + " and dhwj = " + daohang[4] + " and dhsj1 = " + daohang[3] + " and dhsj = " + daohang[2] + " and dhej = " + daohang[1] + " and dhyj = " + daohang[0] + " " + sqls; + + + break; + + } + HashMap hashMap = new HashMap<>(); + sql2 = sql2 + gl; + sql3 = sql3 + gl; + log.writeLog("sql1:" + sql); + log.writeLog("sql2:" + sql2); + log.writeLog("sql3:" + sql3); + //查询导航 + ArrayList> daohangList = new ArrayList<>(); + if (daohang.length == 7 || daohang.length == 6) { + recordSet.execute(sql); + while (recordSet.next()) { + HashMap map = new HashMap<>(); + map.put("name", recordSet.getString("name") + "(" + recordSet.getString("num") + ")"); + map.put("number", recordSet.getString("num")); + map.put("nodeid", code + "a" + recordSet.getString("code")); + map.put("id", code + "a" + recordSet.getString("code")); + map.put("isParent", false); + map.put("canClick", true); + map.put("dragDisabled", true); + + + daohangList.add(map); +// log.writeLog("导航查询map:" + map.toString()); + } + } else { + recordSet.execute(sql); + + while (recordSet.next()) { + + + HashMap map = new HashMap<>(); + map.put("name", recordSet.getString("name") + "(" + recordSet.getString("num") + ")"); + map.put("number", recordSet.getString("num")); + map.put("canClick", true); + map.put("dragDisabled", true); + + if ("".equals(code)) { + + map.put("nodeid", recordSet.getString("code")); + map.put("id", recordSet.getString("code")); + } else { + map.put("nodeid", code + "a" + recordSet.getString("code")); + map.put("id", code + "a" + recordSet.getString("code")); + + } + switch (daohang.length) { + case 1: + if (!"".equals(code)) { + sql4 = sql3 + " and dhej = " + recordSet.getString("code") + " and dhsj is not null"; + } + break; + case 2: + sql4 = sql3 + " and dhsj = " + recordSet.getString("code") + " and dhsj1 is not null"; + break; + case 3: + sql4 = sql3 + " and dhsj1 = " + recordSet.getString("code") + " and dhwj is not null "; + break; + case 4: + sql4 = sql3 + " and dhwj = " + recordSet.getString("code") + " and dhlj is not null "; + break; + case 5: + sql4 = sql3 + " and dhlj = " + recordSet.getString("code") + " and dhqj is not null "; + break; + } + + map.put("isParent", new OAUtils().isHaveNext(sql4 + gl)); + daohangList.add(map); +// log.writeLog("导航查询map:" + map.toString()); + } + } + hashMap.put("datas", daohangList); + + log.writeLog("sql4:" + sql4); + + + //查询企业个数 + recordSet.execute(sql2); + while (recordSet.next()) { + hashMap.put("number", recordSet.getString(1)); + log.writeLog("企业个数:" + recordSet.getString(1)); + } + + + //获取管理员模块id + sql = "select id from modeinfo where formid = (select id from workflow_bill where tablename = 'uf_guanliyuankuxin')"; + recordSet.execute(sql); + recordSet.next(); + String glymodeId = recordSet.getString("ID"); + + //获取管理员表单id + sql = "select id from workflow_bill where tablename = 'uf_guanliyuankuxin'"; + recordSet.execute(sql); + recordSet.next(); + String glyformId = recordSet.getString("ID"); + + + ArrayList> qiyeList = new ArrayList<>(); + //查询企业 + recordSet.execute(sql3 + " order by to_date(clrq,'yyyy-MM-dd') "); + + int i = 0; + while (recordSet.next()) { + + i++; + HashMap map = new HashMap<>(); + for (String s : recordSet.getColumnName()) { + map.put(s, recordSet.getString(s)); + } + + + if ("0".equals(map.get("DLDFLST"))) { + map.put("DLDFLST", "Yes"); + } else if ("1".equals(map.get("DLDFLST"))) { + map.put("DLDFLST", "No"); + } else { + map.put("DLDFLST", ""); + } + + //信息卡片的URL + map.put("QYMCURL", "/jntchina/workflow/jsp/JumpEnterprise.jsp?id=" + map.get("ID")); + map.put("GLYURL", "/spa/cube/index.html#/main/cube/card?type=0&modeId=" + glymodeId + "&formId=" + glyformId + "&billid=" + map.get("GLY")); + + OAUtils oaUtils = new OAUtils(); + map.put("GLYID", map.get("GLY")); + map.put("GLY", oaUtils.getGlyName(map.get("GLY").toString())); + + + try { + map.put("FRDB", oaUtils.getUrl((String) map.get("FRDB"))); + map.put("CWFZR", oaUtils.getUrl((String) map.get("CWFZR"))); + map.put("JL", oaUtils.getUrl((String) map.get("JL"))); + map.put("DS", oaUtils.getUrl((String) map.get("DS"))); + map.put("JS", oaUtils.getUrl((String) map.get("JS"))); + +// map.put("BAFJ", oaUtils.getWenJianUrl((String) map.get("BAFJ"))); +// map.put("FJSC", oaUtils.getWenJianUrl((String) map.get("FJSC"))); +// map.put("GQAPFJ", oaUtils.getWenJianUrl((String) map.get("GQAPFJ"))); + + + } catch (Exception e) { + log.writeLog("错误:" + e); + + } + + map.put("DJGD", oaUtils.gdStr(map.get("ID").toString(), "uf_jingneiqiyexinxi")); + + //查询出来的数据千分位展示,并保留三位小数 + DecimalFormat df = new DecimalFormat(",###,##0.000"); //保留二位小数 + try { + BigDecimal GS = new BigDecimal(String.valueOf(map.get("GS"))); +// BigDecimal MGMZ = new BigDecimal(String.valueOf(map.get("MGMZ"))); + + map.put("GS", df.format(GS)); +// map.put("MGMZ", df.format(MGMZ)); + + } catch (Exception e) { +// log.writeLog("格式化错误:"+e); + } + try { + + BigDecimal ZCZB = new BigDecimal(String.valueOf(map.get("ZCZB"))); + map.put("ZCZB", df.format(ZCZB)); + } catch (Exception e) { + log.writeLog("格式化错误:" + e); + } + qiyeList.add(map); + + } + + qiyeList.sort(Comparator.comparing((Map o) -> ((String) o.get("QYMC")))); + qiyeList.sort(Comparator.comparing((Map o) -> ((String) o.get("CLRQ")))); + + //获取当前用户 +// User user = HrmUserVarify.getUser (request , response) ; +// int uid = user.getUID(); +// if (uid != 1) { +// String username = DataBaseUtils.getFirstValue("select LASTNAME from HRMRESOURCE where id = " + user.getUID()); +// Map glyMap = DataBaseUtils.getDataMap("select type,id from uf_guanliyuankuxin where sfzxm = '" + username + "' "); +// log.writeLog("用户名:"+username); +// log.writeLog("glytype:"+glyMap); +// +// ArrayList> maps = new ArrayList<>(); +// //判断当前用户是否为超级管理员 +// if (!glyMap.get("TYPE").equals("0")) { +// //判断管理员是否为本人 +// for (Map map : qiyeList) { +// if ((map.get("GLYID")).toString().equals(glyMap.get("ID"))) { +// maps.add(map); +// } +// } +// +// qiyeList = maps; +// } +// +// +// +// } + + + hashMap.put("dataSource", qiyeList); + + + return JSON.toJSONString(hashMap); + } + + + @POST + @Path("/getUserByqyid") + @Produces({"application/json"}) + public String getUserByQYID(@Context HttpServletRequest request) { + String qyid = request.getParameter("qyid"); + log.writeLog("qyid:" + qyid); + + String sql = "select id,lastname name from HRMRESOURCE where ','|| (select gxry from UF_JINGNEIQIYEXINXI where id = " + qyid + ") ||',' like '%,'|| id ||',%' "; + log.writeLog("获取共享人员的sql:" + sql); + + ArrayList> dataList = DataBaseUtils.getDataList(sql); + for (Map stringMap : dataList) { + stringMap.put("id", stringMap.get("ID")); + stringMap.put("name", stringMap.get("NAME")); + + } + HashMap map = new HashMap<>(); + map.put("data", dataList); + return JSON.toJSONString(map); + + } + + @POST + @Path("/updGxry") + @Produces({"application/json"}) + public String updGxry(@Context HttpServletRequest request, @Context HttpServletResponse response, @Context HttpHeaders headers) { + String msg = "成功"; + String code = "1"; + try { + log.writeLog("更新共享人员数据"); + + //获取body内容,设置UTF-8格式 + BufferedReader reader = new BufferedReader(new InputStreamReader(request.getInputStream(), "UTF-8")); + //过滤前后空格 + String body = org.apache.commons.io.IOUtils.toString(reader).trim(); + log.writeLog("body:" + body); + + + String value = ""; + + JSONObject json = JSON.parseObject(body); + JSONArray gxry = json.getJSONArray("gxry"); + for (int i = 0; i < gxry.size(); i++) { + String id = gxry.getJSONObject(i).getString("id"); + System.out.println("人员" + id); + value = value + id + ","; + + } + System.out.println("企业" + json.getString("id")); + + String qyid = json.getString("id"); + + + log.writeLog("value分割前:" + value); + + if (value.contains(",")) { + value = value.substring(0, value.length() - 1); + } + + log.writeLog("value分割后:" + value); + + String sql = "update uf_jingneiqiyexinxi set gxry = '" + value + "' where id = " + qyid; + log.writeLog("更新共享人员的sql:" + sql); + + RecordSet recordSet = new RecordSet(); + recordSet.execute(sql); + } catch (Exception e) { + msg = "错误" + e; + code = "1"; + } + + + HashMap map = new HashMap<>(); + map.put("msg", msg); + map.put("code", code); + return JSON.toJSONString(map); + + } + + + @POST + @Path("/isGly") + @Produces({"application/json"}) + public String isGly(@Context HttpServletRequest request, @Context HttpServletResponse response, @Context HttpHeaders headers) { + + User user1 = HrmUserVarify.getUser(request, response); + + String username = DataBaseUtils.getFirstValue("select LASTNAME from HRMRESOURCE where id = " + user1.getUID()); + Map glyMap = DataBaseUtils.getDataMap("select count(id) num from uf_guanliyuankuxin where sfzxm = '" + username + "' "); + log.writeLog("管理员:"+glyMap); + + HashMap map = new HashMap<>(); + if ("0".equals(glyMap.get("NUM"))&&user1.getUID() != 1) { + map.put("status", "1"); + map.put("role", "普通用户"); + } else { + map.put("status", "0"); + map.put("role", "管理员"); + } + + return JSON.toJSONString(map); + + } + + @GET + @Path("/isGlyGet") + @Produces({"application/json"}) + public String isGlyget(@Context HttpServletRequest request, @Context HttpServletResponse response, @Context HttpHeaders headers) { + + User user1 = HrmUserVarify.getUser(request, response); + + String username = DataBaseUtils.getFirstValue("select LASTNAME from HRMRESOURCE where id = " + user1.getUID()); + Map glyMap = DataBaseUtils.getDataMap("select count(id) num from uf_guanliyuankuxin where sfzxm = '" + username + "' "); + log.writeLog("管理员:"+glyMap); + + HashMap map = new HashMap<>(); + if ("0".equals(glyMap.get("NUM"))&&user1.getUID() != 1) { + map.put("status", "1"); + map.put("role", "普通用户"); + } else { + map.put("status", "0"); + map.put("role", "管理员"); + } + + return JSON.toJSONString(map); + + } + + +} \ No newline at end of file diff --git a/src/main/youhong_ai_jitu_src/jntchina/service/oa/HisEnterpriseAPI.java b/src/main/youhong_ai_jitu_src/jntchina/service/oa/HisEnterpriseAPI.java new file mode 100644 index 0000000..72f8f0c --- /dev/null +++ b/src/main/youhong_ai_jitu_src/jntchina/service/oa/HisEnterpriseAPI.java @@ -0,0 +1,475 @@ +package jntchina.service.oa; + +import com.alibaba.fastjson.JSON; +import jntchina.util.DataBaseUtils; +import selfdev.util.log.LogTool; +import weaver.conn.RecordSet; +import weaver.general.Util; +import weaver.hrm.HrmUserVarify; +import weaver.hrm.User; + + +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; +import javax.ws.rs.*; +import javax.ws.rs.core.Context; +import java.math.BigDecimal; +import java.text.DecimalFormat; +import java.time.LocalDate; +import java.util.*; + +/** + * @title: EnterpriseAPI企业版本信息api + * @Author ycf + * @Date: 2021/11/1 15:32 + * @Version 1.0 + */ +@Path("/HisEnterpriseAPI") +public class HisEnterpriseAPI { + private final LogTool log = new LogTool("/log/api/lqiye/", false); + + + @POST + @Path("/getHisEquityInfo") + @Produces({"application/json"}) + public String getHisEquityInfo(@Context HttpServletRequest request) { + String name = request.getParameter("name"); + String bbrq = request.getParameter("bbrq"); + RecordSet recordSet = new RecordSet(); + String sql = ""; + sql = "select qyid from formtable_main_3055 where qymc = '" + name + "'"; + recordSet.execute(sql); + recordSet.next(); + String qyid = recordSet.getString("qyid"); + sql = "select json from uf_gqjgbb where qyid = " + qyid + " and bbrq = " + bbrq; + recordSet.execute(sql); + recordSet.next(); + String json = recordSet.getString("json"); + log.writeLog("json:" + json); + + + return json; + } + + + /** + * 获取下一级目录 (历史) + * + * @param request 请求的参数 + * code 导航树id + * date 日期 + * @return 企业信息和目录信息 + */ + @POST + @Path("/getHisDirs") + @Produces({"application/json"}) + public String getHisDir(@Context HttpServletRequest request, @Context HttpServletResponse response) { + + String code = request.getParameter("id"); +// code = "1a2a1a2a1a2a3"; + String search = Util.null2String(request.getParameter("search")); + String date = request.getParameter("date"); + log.writeLog("获取的id:" + code); + String[] daohang = code.split("a"); + + StringBuilder sqls = new StringBuilder(); + String cc = search; + if ("yes".contains(search.toLowerCase())) { + cc = "%0%"; + } + if ("no".contains(search.toLowerCase())) { + cc = "%1%"; + } + //当模糊搜索不为空时,拼接 + if (!"".equals(search.trim())) { + sqls.append(" and ( \n" + + " lower(qymc) like lower('%" + search + "%') or lower(clrq) like lower('%" + search + "%') or lower(ZYM) like lower('%" + search + "%') or\n" + + " lower(YWM) like lower('%" + search + "%') or lower(SHXYDM) like lower('%" + search + "%') or lower(ZCZB) like lower('%" + search + "%') or\n" + + " lower(GS) like lower('%" + search + "%') or lower(MGMZ) like lower('%" + search + "%') or lower(DZ) like lower('%" + search + "%') or\n" + + " lower(YYDZ) like lower('%" + search + "%') or lower(dyzy) like lower('%" + search + "%') or lower(JYFW) like lower('%" + search + "%') or " + + " lower(BZ) like lower('%" + search + "%') or lower(NBJZQ) like lower('%" + search + "%') or \n" + + + " GBDQ in (select b.id from uf_guojiadiquku b where lower(GJDQK) like lower('%" + search + "%')) or\n" + + " DLQ in (select b.ID from uf_dailiqu b where lower(b.DLQ) like lower('%" + search + "%')) or\n" + + " GSLX in (select b.id from uf_gongsileixing b where lower(b.GSLX) like lower('%" + search + "%')) or\n" + + " DJZT in (select b.ID from uf_dengjizhuangtai b where lower(b.DJZT) like lower('%" + search + "%')) or\n" + + " BZ in (select b.id from uf_bizhong b where lower(b.BZ) like lower('%" + search + "%')) or\n" + + " DLDFLST like '" + cc + "' or\n" + + " glf like '" + cc + "' or\n" + + " YWBK in (select b.id from uf_yewubankuai b where lower(b.YWBK) like lower('%" + search + "%')) or\n" + + " YWMKZJTZDJS in (select b.id from uf_jituanzhongdejue b where lower(b.YWMKZJTZDJS) like lower('%" + search + "%')) or\n" + + " SFWBBDW in (select b.id from uf_shifouweibingbia b where lower(b.SFWBBDW) like lower('%" + search + "%')) " + +// "or\n" + +//// " FJSC in (select b.DOCID from docimagefile b where b.IMAGEFILENAME like '%"+search+"%') or\n" + +// " GQAPFJ in (select b.DOCID from docimagefile b where b.IMAGEFILENAME like '%"+search+"%') or\n" + +// " BAFJ in (select b.DOCID from docimagefile b where b.IMAGEFILENAME like '%"+search+"%')\n" + + " or GLY in (select b.id from UF_GUANLIYUANKUXIN b where lower(SFZXM) like lower('%" + search + "%'))" + +// " or\n" + +// " ','||UF_JINGNEIQIYEXINXI.CWFZR||',' like '%,"+search+",%' or\n" + +// " ','||UF_JINGNEIQIYEXINXI.CWFZR||',' like '%,"+search+",%' or\n" + +// " ','||UF_JINGNEIQIYEXINXI.CWFZR||',' like '%,"+search+",%' or\n" + +// " ','||UF_JINGNEIQIYEXINXI.CWFZR||',' like '%,"+search+",%' or\n" + +// " ','||UF_JINGNEIQIYEXINXI.CWFZR||',' like '%,"+search+",%' " + + " "); + + ArrayList list = DataBaseUtils.getList("select id from UF_RENYUANXINXIKU where xm like '%" + search + "%' "); + for (String s : list) { + sqls.append(" or ','||CWFZR||',' like '%," + s + ",%' " + + " or ','||FRDB||',' like '%," + s + ",%' " + + " or ','||JS||',' like '%," + s + ",%' " + + " or ','||DS||',' like '%," + s + ",%' " + + " or ','||JL||',' like '%," + s + ",%' "); + } + } + + //登记股东 张三有限责任公司/50% + if (!"".equals(search)) { + + String[] strs = search.replace("%", "").split("/"); + sqls.append(" or id in (select MAINID from formtable_main_3055_DT2 where DJGD in (select ids from V_CHIGU where name like '%").append(strs[0]).append("%') "); + if (strs.length == 2) { + sqls.append(" and CGBL like '%").append(strs[1]).append("%') "); + } else { + sqls.append(" ) "); + } + + } + + if (date.equals("")) { + date = LocalDate.now().toString(); + } + + + if (sqls.toString().contains(" and ( ")) { + sqls.append(" ) "); + } + + + + String gl = ""; + + //过滤管理员和三方权限 + User user1 = HrmUserVarify.getUser (request , response) ; + int uid1 = user1.getUID(); + if (uid1 != 1) { + String username = DataBaseUtils.getFirstValue("select LASTNAME from HRMRESOURCE where id = " + user1.getUID()); + Map glyMap = DataBaseUtils.getDataMap("select type,id from uf_guanliyuankuxin where sfzxm = '" + username + "' "); + log.writeLog("用户名:"+username); + log.writeLog("glytype:"+glyMap); + + ArrayList> maps = new ArrayList<>(); + //判断当前用户是否为超级管理员 + if (!glyMap.get("TYPE").equals("0")) { + //判断管理员是否为本人 + gl = " and gly = '"+glyMap.get("ID")+"' "; + } + } + + + + + + + + + log.writeLog("参数code:" + code); + //导航 + String sql = ""; + //企业个数 + String sql2 = ""; + //企业 + String sql3 = ""; + //是否为父节点 + String sql4 = ""; + RecordSet recordSet = new RecordSet(); + + log.writeLog("进入第:" + daohang.length + "层"); + + String s = "(select DHYJZDXX from uf_daohangyijizidua where id = a.dhyj) dhyj,(select dhej from uf_daohangerji where id = a.dhej) dhej,(select dhsj from uf_saohangsanji where id = a.dhsj) dhsj\n" + + " ,(select dhsj from uf_daohangsiji where id = a.dhsj1) dhsj1,id,qyid \n" + + " ,(select dhwj from uf_daohangwuji where id = a.dhwj) dhwj,(select dhlj from uf_daohangliuji where id = a.dhlj) dhlj,(select dhqj from uf_daohangqiji where id = a.dhqj) dhqj\n" + + ",(select GJDQK from uf_guojiadiquku where id = a.gbdq) gbdq,(select DLQ from uf_dailiqu where id=a.dlq) dlq,(select gslx from uf_gongsileixing where id=a.gslx) gslx,(select bz from uf_bizhong where id=a.bz) bz,\n" + + " dldflst,(select YWBK from uf_yewubankuai where id=a.ywbk) ywbk,(select YWMKZJTZDJS from uf_jituanzhongdejue where id=a.ywmkzjtzdjs) ywmkzjtzdjs,\n" + + " gly, frdb, cwfzr,jl, fjsc,bafj,gqapfj, \n" + + " js,\n" + + " ds,(select DJZT from uf_dengjizhuangtai where id=a.djzt) djzt,(select SFWBBDW from uf_shifouweibingbia where id = a.sfwbbdw) sfwbbdw,gs,mgmz,yydz,bz2,dyzy\n" + + ",zjfwjgmsgs,sjs,zczb,dz,qymc,zym,ywm,clrq,shxydm,jyfw,gqtsap,GLF,NBJZQ,"; + switch (daohang.length) { + case 1: + if ("".equals(code)) { + + //默认中国大陆 + sql = "select (select DHYJZDXX from uf_daohangyijizidua c where b.dhyj=c.id) name,count(1) num,dhyj code from( select a.*, rank() over(partition by a.qyid order by to_date(bbrq,'yyyy-MM-dd') desc) rn from formtable_main_3055 a where to_date(clrq, 'YYYY-MM-DD') <=to_date('" + date + "', 'YYYY-MM-DD') " + sqls+gl + " ) b where b.rn=1 group by dhyj order by dhyj "; + sql2 = "select count(1) nums from( select a.*, rank() over(partition by a.qyid order by to_date(bbrq,'yyyy-MM-dd') desc) rn from formtable_main_3055 a where to_date(bbrq, 'YYYY-MM-DD') <=to_date('" + date + "', 'YYYY-MM-DD') and to_date(clrq, 'YYYY-MM-DD') <=to_date('" + date + "', 'YYYY-MM-DD') " + sqls + " ) b where b.rn=1 "; + sql3 = "select * from( select " + s + " rank() over(partition by a.qyid order by to_date(bbrq,'yyyy-MM-dd') desc) rn from formtable_main_3055 a where to_date(bbrq, 'YYYY-MM-DD') <=to_date('" + date + "', 'YYYY-MM-DD') and to_date(clrq, 'YYYY-MM-DD') <=to_date('" + date + "', 'YYYY-MM-DD') " + sqls + " ) b where b.rn=1 "; + sql4 = "select * from( select a.*, rank() over(partition by a.qyid order by to_date(bbrq,'yyyy-MM-dd') desc) rn from formtable_main_3055 a where to_date(clrq, 'YYYY-MM-DD') <=to_date('" + date + "', 'YYYY-MM-DD')) b where b.rn=1 and dhej is not null "; + + + } else { + sql = "select (select DHEJ from uf_daohangerji c where b.dhej=c.id) name,count(1) num,dhej code from ( select a.*, rank() over(partition by a.qyid order by to_date(bbrq,'yyyy-MM-dd')) rn from formtable_main_3055 a where to_date(clrq, 'YYYY-MM-DD') <=to_date('" + date + "', 'YYYY-MM-DD') " + sqls+gl + " ) b where b.rn=1 and DHYJ=" + daohang[0] + " group by dhej "; + sql2 = "select count(1) nums from ( select a.*, rank() over(partition by a.qyid order by to_date(bbrq,'yyyy-MM-dd') desc) rn from formtable_main_3055 a where to_date(bbrq, 'YYYY-MM-DD') <=to_date('" + date + "', 'YYYY-MM-DD') and to_date(clrq, 'YYYY-MM-DD') <=to_date('" + date + "', 'YYYY-MM-DD') " + sqls + " ) b where b.rn=1 and dhyj = " + daohang[0]; + sql3 = " select * from ( select " + s + " rank() over(partition by a.qyid order by to_date(bbrq,'yyyy-MM-dd') desc) rn from formtable_main_3055 a where to_date(bbrq, 'YYYY-MM-DD') <=to_date('" + date + "', 'YYYY-MM-DD') and dhyj = " + daohang[0] + " and to_date(clrq, 'YYYY-MM-DD') <=to_date('" + date + "', 'YYYY-MM-DD') " + sqls + " ) b where b.rn=1 "; + + } + break; + case 2: + sql = "select (select DHSJ from uf_saohangsanji c where b.DHSJ =c.id) name,count(2) num,dhsj code from ( select a.*, rank() over(partition by a.qyid order by to_date(bbrq,'yyyy-MM-dd') desc) rn from formtable_main_3055 a where to_date(clrq, 'YYYY-MM-DD') <=to_date('" + date + "', 'YYYY-MM-DD') " + sqls+gl + " ) b where b.rn=1 and dhyj=" + daohang[0] + " and dhej=" + daohang[1] + " and dhsj is not null group by dhsj"; + sql2 = "select count(1) nums from ( select a.*, rank() over(partition by a.qyid order by to_date(bbrq,'yyyy-MM-dd') desc) rn from formtable_main_3055 a where to_date(bbrq, 'YYYY-MM-DD') <=to_date('" + date + "', 'YYYY-MM-DD') and to_date(clrq, 'YYYY-MM-DD') <=to_date('" + date + "', 'YYYY-MM-DD') " + sqls + " ) b where b.rn=1 and dhej = " + daohang[1] + " and dhyj = " + daohang[0] + ""; + sql3 = " select * from ( select " + s + " rank() over(partition by a.qyid order by to_date(bbrq,'yyyy-MM-dd') desc) rn from formtable_main_3055 a where to_date(bbrq, 'YYYY-MM-DD') <=to_date('" + date + "', 'YYYY-MM-DD') and dhej = " + daohang[1] + " and dhyj = " + daohang[0] + " and to_date(clrq, 'YYYY-MM-DD') <=to_date('" + date + "', 'YYYY-MM-DD') " + sqls + " ) b where b.rn=1 "; + + break; + case 3: + sql = "select (select DHSJ from uf_daohangsiji c where b.DHSJ1 =c.id) name,count(2) num ,dhsj1 code from ( select a.*, rank() over(partition by a.qyid order by to_date(bbrq,'yyyy-MM-dd') desc) rn from formtable_main_3055 a where to_date(clrq, 'YYYY-MM-DD') <=to_date('" + date + "', 'YYYY-MM-DD') " + sqls+gl + " ) b where b.rn=1 and dhyj=" + daohang[0] + " and dhej=" + daohang[1] + " and dhsj=" + daohang[2] + " and dhsj1 is not null group by dhsj1"; + sql2 = "select count(1) nums from ( select a.*, rank() over(partition by a.qyid order by to_date(bbrq,'yyyy-MM-dd') desc) rn from formtable_main_3055 a where to_date(bbrq, 'YYYY-MM-DD') <=to_date('" + date + "', 'YYYY-MM-DD') and to_date(clrq, 'YYYY-MM-DD') <=to_date('" + date + "', 'YYYY-MM-DD') " + sqls + " ) b where b.rn=1 and dhsj = " + daohang[2] + " and dhej = " + daohang[1] + " and dhyj = " + daohang[0] + ""; + sql3 = " select * from ( select " + s + " rank() over(partition by a.qyid order by to_date(bbrq,'yyyy-MM-dd') desc) rn from formtable_main_3055 a where to_date(bbrq, 'YYYY-MM-DD') <=to_date('" + date + "', 'YYYY-MM-DD') and dhsj = " + daohang[2] + " and dhej = " + daohang[1] + " and dhyj = " + daohang[0] + " and to_date(clrq, 'YYYY-MM-DD') <=to_date('" + date + "', 'YYYY-MM-DD') " + sqls + " ) b where b.rn=1 "; + + break; + case 4: + sql = "select (select DHWJ from uf_daohangwuji c where b.DHWJ = c.id) name, count(2) num,DHWJ code from ( select a.*, rank() over(partition by a.qyid order by to_date(bbrq,'yyyy-MM-dd') desc) rn from formtable_main_3055 a where to_date(clrq, 'YYYY-MM-DD') hashMap = new HashMap<>(); + + sql3 = sql3 + gl; + log.writeLog("sql1:" + sql); + log.writeLog("sql2:" + sql2); + log.writeLog("sql3:" + sql3); + + + //查询导航,每个树节点对应一个id 例如1a2a2a1,通过id拼接 + ArrayList> daohangList = new ArrayList<>(); + if (daohang.length == 7 || daohang.length == 6) { + recordSet.execute(sql); + while (recordSet.next()) { + + HashMap map = new HashMap<>(); + map.put("name", recordSet.getString("name") + "(" + recordSet.getString("num") + ")"); + map.put("number", recordSet.getString("num")); + map.put("nodeid", code + "a" + recordSet.getString("code")); + map.put("id", code + "a" + recordSet.getString("code")); + map.put("isParent", false); + map.put("canClick", true); + map.put("dragDisabled", true); + + daohangList.add(map); + } + } else { + recordSet.execute(sql); + + while (recordSet.next()) { + + HashMap map = new HashMap<>(); + map.put("name", recordSet.getString("name") + "(" + recordSet.getString("num") + ")"); + map.put("number", recordSet.getString("num")); + map.put("canClick", true); + map.put("dragDisabled", true); + + if ("".equals(code)) { + + map.put("nodeid", recordSet.getString("code")); + map.put("id", recordSet.getString("code")); + } else { + map.put("nodeid", code + "a" + recordSet.getString("code")); + map.put("id", code + "a" + recordSet.getString("code")); + + } + + //判断是否为父节点的SQL + switch (daohang.length) { + case 1: + if (!"".equals(code)) { + sql4 = " select * from ( select a.*, rank() over(partition by a.qyid order by to_date(bbrq,'yyyy-MM-dd') desc) rn from formtable_main_3055 a where to_date(clrq, 'YYYY-MM-DD') <=to_date('" + date + "', 'YYYY-MM-DD')) b where b.rn=1 and dhyj = " + daohang[0] + " and dhej = " + recordSet.getString("code") + " and dhsj is not null"; + } + break; + case 2: + sql4 = " select * from ( select a.*, rank() over(partition by a.qyid order by to_date(bbrq,'yyyy-MM-dd') desc) rn from formtable_main_3055 a where to_date(clrq, 'YYYY-MM-DD') <=to_date('" + date + "', 'YYYY-MM-DD')) b where b.rn=1 and dhej = " + daohang[1] + " and dhyj = " + daohang[0] + " and dhsj = " + recordSet.getString("code") + " and dhsj1 is not null"; + break; + case 3: + sql4 = " select * from ( select a.*, rank() over(partition by a.qyid order by to_date(bbrq,'yyyy-MM-dd') desc) rn from formtable_main_3055 a where to_date(clrq, 'YYYY-MM-DD') <=to_date('" + date + "', 'YYYY-MM-DD')) b where b.rn=1 and dhsj = " + daohang[2] + " and dhej = " + daohang[1] + " and dhyj = " + daohang[0] + " and dhsj1 = " + recordSet.getString("code") + " and dhwj is not null "; + break; + case 4: + sql4 = " select * from ( select a.*, rank() over(partition by a.qyid order by to_date(bbrq,'yyyy-MM-dd') desc) rn from formtable_main_3055 a where to_date(clrq, 'YYYY-MM-DD') <=to_date('" + date + "', 'YYYY-MM-DD')) b where b.rn=1 and dhsj1 = " + daohang[3] + " and dhsj = " + daohang[2] + " and dhej = " + daohang[1] + " and dhyj = " + daohang[0] + " and dhwj = " + recordSet.getString("code") + " and dhlj is not null "; + break; + case 5: + sql4 = " select * from ( select a.*, rank() over(partition by a.qyid order by to_date(bbrq,'yyyy-MM-dd') desc) rn from formtable_main_3055 a where to_date(clrq, 'YYYY-MM-DD') <=to_date('" + date + "', 'YYYY-MM-DD')) b where b.rn=1 and dhwj = " + daohang[4] + " and dhsj1 = " + daohang[3] + " and dhsj = " + daohang[2] + " and dhej = " + daohang[1] + " and dhyj = " + daohang[0] + " and dhlj = " + recordSet.getString("code") + " and dhqj is not null "; + break; + } + + log.writeLog("查询sql4:" + sql4); + map.put("isParent", new OAUtils().isHaveNext(sql4+gl)); + daohangList.add(map); + } + } + hashMap.put("datas", daohangList); + + log.writeLog("sql4:" + sql4+gl); + + +// //查询企业个数 +// recordSet.execute(sql2); +// while (recordSet.next()) { +// hashMap.put("number", recordSet.getString("nums")); +// log.writeLog("企业个数:" + recordSet.getString("nums")); +// } + + + recordSet = new RecordSet(); + //找到各个模块id和表单id拼接url,用于跳转url + //获取模块id + sql = "select id from modeinfo where formid = (select id from workflow_bill where tablename = 'formtable_main_3055')"; + log.writeLog("获取模块id:" + sql); + + recordSet.execute(sql); + recordSet.next(); + String modeId = recordSet.getString("ID"); + //获取表单id + sql = "select id from workflow_bill where tablename = 'formtable_main_3055'"; + log.writeLog("获取表单id:" + sql); + recordSet.execute(sql); + recordSet.next(); + String formId = recordSet.getString("ID"); + //获取管理员模块id + sql = "select id from modeinfo where formid = (select id from workflow_bill where tablename = 'uf_guanliyuankuxin')"; + recordSet.execute(sql); + recordSet.next(); + String glymodeId = recordSet.getString("ID"); + + //获取管理员表单id + sql = "select id from workflow_bill where tablename = 'uf_guanliyuankuxin'"; + recordSet.execute(sql); + recordSet.next(); + String glyformId = recordSet.getString("ID"); + + + ArrayList> qiyeList = new ArrayList<>(); + //获取所有企业 + + + //查询架构表中企业,从所有企业的集合中剔除 + recordSet.execute(sql3); + while (recordSet.next()) { + + + HashMap map = new HashMap<>(); + for (String s1 : recordSet.getColumnName()) { + map.put(s1, recordSet.getString(s1)); + } + + if ("0".equals(map.get("DLDFLST"))) { + map.put("DLDFLST", "Yes"); + } else if ("1".equals(map.get("DLDFLST"))) { + map.put("DLDFLST", "No"); + } else { + map.put("DLDFLST", ""); + } + + + map.put("QYMCURL", "/spa/cube/index.html#/main/cube/card?type=0&modeId=" + modeId + "&formId=" + formId + "&billid=" + map.get("ID")); + map.put("GLYURL", "/spa/cube/index.html#/main/cube/card?type=0&modeId=" + glymodeId + "&formId=" + glyformId + "&billid=" + map.get("GLY")); + + + OAUtils oaUtils = new OAUtils(); + + map.put("GLY", oaUtils.getGlyName(map.get("GLY").toString())); + map.put("GLYID", Util.null2String(map.get("GLY"))); + //因为会存在多个人员的情况,还得重新包装成集合 + try { + map.put("FRDB", oaUtils.getUrl((String) map.get("FRDB"))); + map.put("CWFZR", oaUtils.getUrl((String) map.get("CWFZR"))); + map.put("JL", oaUtils.getUrl((String) map.get("JL"))); + map.put("DS", oaUtils.getUrl((String) map.get("DS"))); + + map.put("JS", oaUtils.getUrl((String) map.get("JS"))); + + map.put("BAFJ", oaUtils.getWenJianUrl((String) map.get("BAFJ"))); + map.put("FJSC", oaUtils.getWenJianUrl((String) map.get("FJSC"))); + map.put("GQAPFJ", oaUtils.getWenJianUrl((String) map.get("GQAPFJ"))); + + + } catch (Exception e) { + log.writeLog("错误:" + e); + + } + //拼接登记股东 + map.put("DJGD", oaUtils.gdStr(map.get("ID").toString(), "formtable_main_3055")); + //查询出来的数据千分位展示,并保留三位小数,注册资本可能为中文会报错 + DecimalFormat df = new DecimalFormat(",###,##0.000"); //保留三位小数 + try { + BigDecimal GS = new BigDecimal(String.valueOf(map.get("GS"))); +// BigDecimal MGMZ = new BigDecimal(String.valueOf(map.get("MGMZ"))); + + map.put("GS", df.format(GS)); +// map.put("MGMZ", df.format(MGMZ)); + } catch (Exception e) { + log.writeLog("格式化错误:" + e); + + } + try { + BigDecimal ZCZB = new BigDecimal(String.valueOf(map.get("ZCZB"))); + map.put("ZCZB", df.format(ZCZB)); + } catch (Exception e) { + log.writeLog("格式化错误:" + e); + } + + qiyeList.add(map); + + } + //所有企业根据list》map中的成立日期排序,从小到大 + + qiyeList.sort(Comparator.comparing((Map o) -> ((String) o.get("QYMC")))); + qiyeList.sort(Comparator.comparing((Map o) -> ((String) o.get("CLRQ")))); + + +// //获取当前用户 +// User user = HrmUserVarify.getUser (request , response) ; +// int uid = user.getUID(); +// if (uid != 1) { +// String username = DataBaseUtils.getFirstValue("select LASTNAME from HRMRESOURCE where id = " + user.getUID()); +// Map glyMap = DataBaseUtils.getDataMap("select type,id from uf_guanliyuankuxin where sfzxm = '" + username + "' "); +// log.writeLog("用户名:"+username); +// log.writeLog("glytype:"+glyMap); +// +// ArrayList> maps = new ArrayList<>(); +// //判断当前用户是否为超级管理员 +// if (!glyMap.get("TYPE").equals("0")) { +// //判断管理员是否为本人 +// for (Map map : qiyeList) { +// if ((map.get("GLYID")).toString().equals(glyMap.get("ID"))) { +// maps.add(map); +// } +// } +// +// qiyeList = maps; +// } +// } + hashMap.put("dataSource", qiyeList); + return JSON.toJSONString(hashMap); + } + +} + + diff --git a/src/main/youhong_ai_jitu_src/jntchina/service/oa/HisInfoChangeJiekou.java b/src/main/youhong_ai_jitu_src/jntchina/service/oa/HisInfoChangeJiekou.java new file mode 100644 index 0000000..14e7077 --- /dev/null +++ b/src/main/youhong_ai_jitu_src/jntchina/service/oa/HisInfoChangeJiekou.java @@ -0,0 +1,598 @@ +package jntchina.service.oa; + + +import jntchina.util.DataBaseUtils; +import selfdev.util.log.LogTool; +import weaver.conn.RecordSet; +import weaver.formmode.customjavacode.AbstractModeExpandJavaCodeNew; +import weaver.general.Util; +import weaver.hrm.User; +import weaver.soa.workflow.request.RequestInfo; + +import java.util.*; + + +/** + * 说明 + * 修改时 + * 类名要与文件名保持一致 + * class文件存放位置与路径保持一致。 + * 请把编译后的class文件,放在对应的目录中才能生效 + * 注意 同一路径下java名不能相同。 + * + * @author Administrator + */ +public class HisInfoChangeJiekou extends AbstractModeExpandJavaCodeNew { + private final LogTool log = new LogTool("/log/api/aa/", false); + + /** + * 执行模块扩展动作 + * + * @param param param包含(但不限于)以下数据 + * user 当前用户 + * importtype 导入方式(仅在批量导入的接口动作会传输) 1 追加,2覆盖,3更新,获取方式(int)param.get("importtype") + * 导入链接中拼接的特殊参数(仅在批量导入的接口动作会传输),比如a=1,可通过param.get("a")获取参数值 + * 页面链接拼接的参数,比如b=2,可以通过param.get("b")来获取参数 + * @return + */ + public Map doModeExpand(Map param) { + Map result = new HashMap(); + try { + User user = (User) param.get("user"); + int billid = -1;//数据id + int modeid = -1;//模块id + RequestInfo requestInfo = (RequestInfo) param.get("RequestInfo"); + if (requestInfo != null) { + billid = Util.getIntValue(requestInfo.getRequestid()); + modeid = Util.getIntValue(requestInfo.getWorkflowid()); + if (billid > 0 && modeid > 0) { + //------请在下面编写业务逻辑代码------ + log.writeLog("【【【【【【【【【【【【【【【【【【【【【【【【【【【企业修改】】】】】】】】】】】】】】】】】】】】】】】】"); + + log.writeLog("模块id:" + billid); + this.changeInfo(String.valueOf(billid)); + log.writeLog("param:"+param); + } + } + + } catch (Exception e) { + result.put("errmsg", "自定义出错信息"); + result.put("flag", "false"); + } + return result; + } + + + /** + * 修改企业信息 + * + * @param id 流程id + */ + public void changeInfo(String id) { + /* + 当企业变更后, + insert > 境内企业版本表 table: formtable_main_3055 + update > 境内企业信息表 table: uf_jingneiqiyexinxi + insert > 历史沿革表 table: uf_jingneiqiyexinxi_dt1 + */ + log.writeLog("表单id:" + id); + + RecordSet recordSet = new RecordSet(); + //变更的项目 + HashMap bghMap = new HashMap<>(); + //变更的集合 + + + //首先从 变更表(uf_jnqyxxbgb)找出所有变更数据, + String sql = "select * from uf_jnqyxxbgb where id = " + id; + recordSet.execute(sql); + while (recordSet.next()) { + for (String s : recordSet.getColumnName()) { + bghMap.put(s, recordSet.getString(s)); + } + } + log.writeLog("变更表信息:" + bghMap); + + String qyid = bghMap.get("QYID"); + + log.writeLog("企业名称变更前:" + bghMap.get("QYMCBGQ")); + //找出所有的变更项目 + String[] xm = {"GLY", "QYMC", "ZYM", "YWM", "CLRQ", "SHXYDM" + , "ZCZB", "DZ", "JYFW", "GQTSAP", "GQAPFJ", "FRDB", "CWFZR", "JL" + , "JS", "DS", "DJZT", "SFWBBDW", "BAFJ", "GBDQ", "DLQ", + "DHYJ", "DHEJ", "DHSJ", "DHSJ1", "DHWJ", "DHLJ", "DHQJ" + , "GSLX", "GS", "BZ", "MGMZ", "DLDFLST", "YYDZ", "YWBK", "YWMKZJTZDJS" + , "BZ2", "DYZY", "DYZYFJSC", "ZJFWJGMSGS", "SJS","GLF","NBJZQ"}; + + //判断变更表的变更前后是否一样 + log.writeLog("企业名称变更后:" + bghMap.get("QYMCBGH")); + + log.writeLog(":"+bghMap.get("CLRQBGH")); + log.writeLog(":"+bghMap.get("CLRQBGQ")); + + if (!bghMap.get("CLRQBGH").equals(bghMap.get("CLRQBGQ"))) { + + + recordSet.execute(sql); + sql = "update formtable_main_3055 set clrq = '"+bghMap.get("CLRQBGH")+"' where qyid = " + qyid + " "; + log.writeLog("更新所有企业:"+sql); + recordSet.execute(sql); + sql = "update uf_jingneiqiyexinxi set clrq = '"+bghMap.get("CLRQBGH")+"' where id = " + qyid + " "; + recordSet.execute(sql); + log.writeLog("更新企业表:"+sql); + + } + + + + //变更主表 + for (String key : xm) { + String date = bghMap.get(key + "RQ"); + //如果日期不为空,那么该项目有变更 + if (!"".equals(Util.null2String(date))) { + //获取日期,当日之前的一个企业版本做对比 + sql = "select *from (select * from formtable_main_3055 where " + + " BBRQ <= '"+date+"' and qyid = '"+qyid+"' order by BBRQ desc ) where rownum <2"; + log.writeLog("找到变更前的:"+sql); + + Map bgqMap = DataBaseUtils.getDataMap(sql); + log.writeLog("变更前map:"+bgqMap); + + //判断版本的前后数据是否一致 + if (!strNull(bghMap.get(key+"BGH")).equals(strNull( bgqMap.get(key)))) { + //不一致时,直接修改 + String VersionId = SynDate(qyid, date); + log.writeLog("返回的versionid:"+VersionId); + sql = "update formtable_main_3055 set " + key + " = '" + bghMap.get(key+"BGH") + "' where id = " + VersionId; + log.writeLog("直接版本表:"+sql); + recordSet.execute(sql); + + + sql = "delete from formtable_main_3055_dt1 where mainid = '" + VersionId + "' " + + "and rq = '" + date + "' and bgxm = '" + this.getBgxms(key) + "' "; + log.writeLog("删除当日的变更项目:"+sql); +// recordSet.execute(sql); + sql = "insert into formtable_main_3055_dt1 (MAINID,RQ,BGXM,BGQ,BGH,FJ,BZ) values " + + "('" + VersionId + "','" + date + "','" + this.getBgxms(key) + "'" + + ",'" + this.getBianGeng(key, bgqMap.get(key)) + "','" + this.getBianGeng(key, bghMap.get(key+"BGH")) + "','" + bghMap.get(key+"FJ") + "','" + bghMap.get(key+"BZ") + "')"; + log.writeLog("插入版本表的历史沿革:"+sql); + recordSet.execute(sql); + + //判断之后是否有版本; + sql = "select bbrq from formtable_main_3055 where BBRQ > '"+date+"' and qyid = '"+qyid+"' order by BBRQ desc"; + if (DataBaseUtils.dataIsExists(sql)) { + log.writeLog("有之后的版本:-----------"); + + //如果之后没有修改过这个字段,就要修改 + sql = "select id from formtable_main_3055 where qyid = '" + qyid + "' " + + "and to_date(BBRQ,'YYYY-MM-DD')>to_date('" + date + "','YYYY-MM-DD') order by bbrq"; + ArrayList> idList = DataBaseUtils.getDataList(sql); + boolean isUpdateQiYe = true; + //遍历之后版本 + for (Map map : idList) { + String id1 = map.get("ID"); + //如果没有变更此项目,直接更新 + sql = "select bgxm from formtable_main_3055_dt1 where mainid = '" + id1 + "' "; + ArrayList list = DataBaseUtils.getList(sql); + log.writeLog("list:"+list); + log.writeLog("bgxm:"+getBgxms(key)); + if (!list.contains(getBgxms(key))) { + //之后版本所有的字段都要修改 + sql = "update formtable_main_3055 set "+key+" = '" + bghMap.get(key+"BGH") + "' where id = "+id1; + log.writeLog("修改之后所有版本的字段:"+sql); + recordSet.execute(sql); + } else { + //有更新过,跳出更新,不更新企业表 + //设置变更前 + sql = "update formtable_main_3055_dt1 set bgq = '"+this.getBianGeng(key, bghMap.get(key+"BGH"))+"' where mainid = '" + id1 + "' and bgxm = '"+getBgxms(key)+"' "; + log.writeLog("设置变更前:" + sql); + recordSet.execute(sql); + isUpdateQiYe = false; + break; + } + } + //之后没修改过该项目,要修改主表 + if (isUpdateQiYe) { + + sql = "update uf_jingneiqiyexinxi set " + key + " = '" + bghMap.get(key+"BGH") + "' where id = " + qyid +" "; + log.writeLog("之后版本没有修改该项目,直接企业信息表:"+sql); + recordSet.execute(sql); + } + } else { + log.writeLog("没有之后的版本:"); + sql = "update uf_jingneiqiyexinxi set " + key + " = '" + bghMap.get(key+"BGH") + "' where id = " + qyid; + log.writeLog("不存在日期后的企业,直接修改企业表:"+sql); + recordSet.execute(sql); + + } + } + } + } + //变更明细表3资质证照 + new ChangeDt2().changeDt2(qyid,id); + try { + + new ChangeDt1().ChangeDetail(qyid,id); + + sql = "update uf_jingneiqiyexinxi_dt2 set qymc1 = mainid where id = "+qyid; + recordSet.execute(sql); + } catch (Exception e) { + log.writeLog(":"+DataBaseUtils.getExceptionDetail(e)); + ; + } + + log.writeLog("删除持股比例和持股份数的股东:"); + + sql = "delete from UF_JINGNEIQIYEXINXI_DT2 where (CGBL = '0.00' or CGBL is null ) and (cgfs = '0.00' or CGFS is null ) and GFZL is null"; + recordSet.execute(sql); + sql = "delete from formtable_main_3055_DT2 where (CGBL = '0.00' or CGBL is null ) and (cgfs = '0.00' or CGFS is null ) and GFZL is null "; + recordSet.execute(sql); + } + + /** + * + * 判断当前日期是否有数据,有的话就删除,没有就从上一个版本复制 + * @param qyid 企业id + * @param date 日期 + * @return 当天企业的id + */ + public String SynDate(String qyid, String date) { + RecordSet recordSet = new RecordSet(); + String sql = "select id from formtable_main_3055 where qyid = '"+qyid+"' and bbrq = '"+date+"' "; + String changeId; + String firstValue = DataBaseUtils.getFirstValue(sql); + if ("".equals(firstValue)) { + //空,同步所有信息,同步上一个版本所有信息 ,然后在后面修改 + sql = "select * from (select * from formtable_main_3055 where " + + " BBRQ <= '"+date+"' and qyid = '"+qyid+"' order by BBRQ desc ) where rownum <2"; + + log.writeLog("找到上一个版本的信息:"+sql); + + Map hashMap = DataBaseUtils.getDataMap(sql); + + if("".equals(strNull(hashMap.get("QYMC")))){ + log.writeLog("企业名称为空:"+hashMap); + + hashMap = DataBaseUtils.getDataMap("select * from (select * from formtable_main_3055 where qyid = '"+qyid+"' order by BBRQ ) where rownum <2"); + } + + log.writeLog("上一个版本的信息:"+hashMap); + + sql = "insert into formtable_main_3055 (zczb,dz,gly,qymc,zym,ywm,clrq,shxydm,dhyj,dhej,dhsj,dhsj1,dhwj,dhlj,dhqj," + + "jyfw,gqtsap,gqapfj,frdb,cwfzr,jl,js,ds,djzt,sfwbbdw,bafj,bbrq,qyid,GBDQ,DLQ" + + " , GSLX,GS,BZ,MGMZ,DLDFLST,YYDZ,YWBK,YWMKZJTZDJS,BZ2,DYZY,FJSC,ZJFWJGMSGS,SJS,GLF,NBJZQ,FORMMODEID) values ('" + hashMap.get("ZCZB") + "', '" + hashMap.get("DZ") + "', " + + "'" + hashMap.get("GLY") + "', '" + hashMap.get("QYMC") + "', '" + hashMap.get("ZYM") + "', '" + hashMap.get("YWM") + "', " + + "'" + hashMap.get("CLRQ") + "', '" + hashMap.get("SHXYDM") + "', '" + hashMap.get("DHYJ") + "', '" + hashMap.get("DHEJ") + "', " + + "'" + hashMap.get("DHSJ") + "', '" + hashMap.get("DHSJ1") + "', '" + hashMap.get("DHWJ") + "', '" + hashMap.get("DHLJ") + "', " + + "'" + hashMap.get("DHQJ") + "', '" + hashMap.get("JYFW") + "', '" + hashMap.get("GQTSAP") + "', '" + hashMap.get("GQAPFJ") + "', " + + "'" + hashMap.get("FRDB") + "', '" + hashMap.get("CWFZR") + "', '" + hashMap.get("JL") + "', '" + hashMap.get("JS") + "', " + + "'" + hashMap.get("DS") + "', '" + hashMap.get("DJZT") + "', '" + hashMap.get("SFWBBDW") + "', " + + "'" + hashMap.get("BAFJ") + "', '" + date + "','" + qyid + "'" + + ", '" + hashMap.get("GBDQ") + "', '" + hashMap.get("DLQ") + "', '" + hashMap.get("GSLX") + "', '" + hashMap.get("GS") + "'" + + ", '" + hashMap.get("BZ") + "', '" + hashMap.get("MGMZ") + "', '" + hashMap.get("DLDFLST") + "', '" + hashMap.get("YYDZ") + "'" + + ", '" + hashMap.get("YWBK") + "', '" + hashMap.get("YWMKZJTZDJS") + "', '" + hashMap.get("BZ2") + "', '" + hashMap.get("DYZY") + "'" + + ", '" + hashMap.get("FJSC") + "', '" + hashMap.get("ZJFWJGMSGS") + "', '" + hashMap.get("SJS") + "','"+ hashMap.get("GLF") +"','"+ + hashMap.get("NBJZQ") +"','"+DataBaseUtils.getModelIdByName("formtable_main_3055")+"')"; + log.writeLog("插入版本表的sql:" + sql); + recordSet.execute(sql); + + changeId = DataBaseUtils.getFirstValue("select id from formtable_main_3055 where qyid = '"+qyid+"' and bbrq = '"+date+"' "); + + +// //同步历史沿革 +// sql = "select * from uf_jingneiqiyexinxi_dt1 where MAINID = '" + qyid + "' and to_date(rq,'yyyy-MM-dd') <=to_date('" + date + "','yyyy-MM-dd') "; +// log.writeLog("同步历史沿革的SQL:" + sql); +// ArrayList> dt1List = DataBaseUtils.getDataList(sql); +// for (Map map : dt1List) { +// sql = "insert into formtable_main_3055_dt1 (MAINID,RQ,BGXM,BGQ,BGH,FJ,BZ,mainbillid) values ('" + changeId + "','" + map.get("RQ") + "','" + map.get("BGXM") + "'" + +// ",'" + map.get("BGQ") + "','" + map.get("BGH") + "','" + map.get("FJ") + "','" + map.get("BZ") + "','"+map.get("ID")+"')"; +// recordSet.execute()(sql); +// log.writeLog("插入版本表的变更表:" + sql); +// } + //同步股权信息 + + sql = "select * from formtable_main_3055_dt2 where MAINID = (select * from (select id from formtable_main_3055 where " + + " BBRQ < '"+date+"' and qyid = '"+qyid+"' order by BBRQ desc ) where rownum <2) " ; + ArrayList> dt2List = DataBaseUtils.getDataList(sql); + for (Map map : dt2List) { + sql = "insert into formtable_main_3055_dt2 (MAINID,DJGD,CGBL,BZ,QYMC1,rq,CGFS,gfzl,MAINBILLID) values ('" + changeId + "'" + + ",'" + map.get("DJGD") + "','" + map.get("CGBL") + "','" + map.get("BZ") + "','" + map.get("QYMC1") + "'," + + "'" + date + "','" + map.get("CGFS") + "','" + map.get("GFZL") + "','"+map.get("MAINBILLID")+"')"; + recordSet.execute(sql); + log.writeLog("插入股东:" + sql); + } + //同步资质证照 + sql = "select * from formtable_main_3055_dt3 where MAINID = (select * from (select id from formtable_main_3055 where " + + " BBRQ <= '"+date+"' and qyid = '"+qyid+"' order by BBRQ desc ) where rownum <2) " ; + ArrayList> dt3List = DataBaseUtils.getDataList(sql); + for (Map map : dt3List) { + sql = "insert into formtable_main_3055_dt3 (MAINID,zzzz,fjsc,BZ,QYMC,MAINBILLID) values ('" + changeId + "'" + + ",'" + map.get("ZZZZ") + "','" + map.get("FJSC") + "','" + map.get("BZ") + "','" + map.get("QYMC") + "','"+map.get("MAINBILLID")+"')"; + log.writeLog("插入股权信息sql:" + sql); + recordSet.execute(sql); + } + + } + //返回刚刚那张表的id + + sql = "select id from formtable_main_3055 where qyid = '"+qyid+"' and bbrq = '"+date+"' "; + firstValue = DataBaseUtils.getFirstValue(sql); + log.writeLog("之后的firstvalue:" + firstValue); + + return firstValue; + } + + public static String strNull(String str) { + return (null == str) ? "" : str; + } + /** + * 字段转换(通过字符找到变更项目) + * @param bg 变更的字符串 + * @return 变更项目 + */ + public String getBgxms(String bg) { + //设置变更项目的对应字段 + Map cors = new HashMap<>(); + cors.put("QYMC", "企业名称"); + cors.put("ZYM", "曾用名"); + cors.put("YWM", "英文名"); + cors.put("CLRQ", "成立日期"); + cors.put("SHXYDM", "社会信用代码"); + cors.put("GQTSAP", "股权特殊安排"); + cors.put("FRDB", "法人代表"); + cors.put("CWFZR", "财务负责人"); + cors.put("JL", "经理"); + cors.put("JS", "监事"); + cors.put("DS", "董事"); + cors.put("DJZT", "登记状态"); + cors.put("YWCZ", "业务承载"); + cors.put("SFWBBDW", "是否为并表单位"); + cors.put("ZCZB", "注册资本"); + cors.put("DZ", "注册地址"); + cors.put("JYFW", "经营范围"); + cors.put("DJGD", "登记股东"); + cors.put("CGBL", "持股比例"); + cors.put("GLY", "管理员"); + cors.put("DHYJ", "导航一级"); + cors.put("DHEJ", "导航二级"); + cors.put("DHSJ", "导航三级"); + cors.put("DHSJ1", "导航四级"); + cors.put("DHWJ", "导航五级"); + cors.put("DHLJ", "导航六级"); + cors.put("DHQJ", "导航七级"); + cors.put("BAFJ", "备案附件"); + + cors.put("GBDQ", "国别/地区"); + cors.put("DLQ", "代理区"); + cors.put("GSLX", "公司类型"); + cors.put("GS", "股数"); + cors.put("BZ", "币种"); + cors.put("MGMZ", "每股面值"); + cors.put("DLDFLST", "独立的法律实体"); + cors.put("YYDZ", "营业地址"); + cors.put("YWBK", "业务板块"); + cors.put("YWMKZJTZDJS", "业务模块/在集团中的角色"); + cors.put("BZ2", "备注"); + cors.put("DYZY", "抵押/质押"); + cors.put("FJSC", "附件上传"); + cors.put("ZJFWJGMSGS", "中介服务机构/秘书公司"); + cors.put("SJS", "审计师"); + cors.put("GQAPFJ", "股权安排附件"); + cors.put("DYZYFJSC", "抵押/质押附件上传"); + cors.put("GLF", "关联方"); + cors.put("NBJZQ", "年报截止期"); + + + //判断 + if (Util.null2String(cors.get(bg)).equals("")) { + + log.writeLog("bgx---------------------------------------------:" + bg); + return Util.null2String(bg); + } else { + log.writeLog("bgx---------------------------------------------:" + cors.get(bg)); + + return Util.null2String(cors.get(bg)); + } + } + + /** + * 找到浏览按钮的变更项目 + * @param bgxm filedName + * @param value value + * @return 变更内容 + */ + public String getBianGeng(String bgxm, String value) { + this.log.writeLog("接收参数bgxm:" + bgxm); + this.log.writeLog("接收参数value:" + value); + + String sql = ""; + if ("FRDB,CWFZR,JL,JS,DS".contains(bgxm)) { + sql = "select xm returnvalue from uf_renyuanxinxiku where id = "; + + log.writeLog("bgxm value:" + value); + if (!value.equals("")) { + RecordSet recordSet = new RecordSet(); + String[] values = value.split(","); + log.writeLog(bgxm + "人员:" + values.length); + + StringBuilder res = new StringBuilder(); + for (String s : values) { + sql = "select xm from uf_renyuanxinxiku where id = " + s; + recordSet.execute(sql); + recordSet.next(); + res.append(recordSet.getString("xm")).append(";\n"); + } + log.writeLog("res:" + res); + return Util.null2String(res.toString()); + } + } + if ("GLY".equals(bgxm)) { + sql = "select sfzxm returnvalue from uf_guanliyuankuxin where id ="; + + } + if ("GLF".equals(bgxm)) { + return "0".equals(value) ? "YES" : "NO"; + + } + if ("GBDQ".equals(bgxm)) { + sql = "select GJDQK returnvalue from uf_guojiadiquku where id ="; + } + + if ("DLQ".equals(bgxm)) { + sql = "select DLQ returnvalue from uf_dailiqu where id ="; + } + + if ("GSLX".equals(bgxm)) { + sql = "select gslx returnvalue from uf_gongsileixing where id = "; + } + + if ("DJZT".equals(bgxm)) { + sql = "select DJZT returnvalue from uf_dengjizhuangtai where id ="; + } + + if ("DHYJ".equals(bgxm)) { + sql = "select DHYJZDXX returnvalue from uf_daohangyijizidua where id ="; + } + + if ("DHEJ".equals(bgxm)) { + sql = "select dhej returnvalue from uf_daohangerji where id = "; + } + + if ("DHSJ".equals(bgxm)) { + sql = "select dhsj returnvalue from uf_saohangsanji where id ="; + } + + if ("DHSJ1".equals(bgxm)) { + sql = "select dhsj returnvalue from uf_daohangsiji where id ="; + } + + if ("DHWJ".equals(bgxm)) { + sql = "select dhwj returnvalue from uf_daohangwuji where id ="; + } + + if ("DHLJ".equals(bgxm)) { + sql = "select dhlj returnvalue from uf_daohangliuji where id ="; + } + if ("BZ".equals(bgxm)) { + sql = "select bz returnvalue from UF_BIZHONG where id = "; + } + + if ("DHQJ".equals(bgxm)) { + sql = "select dhqj returnvalue from uf_daohangqiji where id ="; + } + + if ("DLDFLST".equals(bgxm)) { + return "0".equals(value) ? "YES" : "NO"; + } + + + + if ("YWBK".equals(bgxm)) { + sql = "select YWBK returnvalue from uf_yewubankuai where id ="; + } + + if ("YWMKZJTZDJS".equals(bgxm)) { + sql = "select YWMKZJTZDJS returnvalue from uf_jituanzhongdejue where id ="; + } + + if ("QYMC".equals(bgxm)) { + return value; + } + + if ("SFWBBDW".equals(bgxm)) { + sql = "select SFWBBDW returnvalue from uf_shifouweibingbia where id ="; + } + if ("BAFJ".equals(bgxm) || "GQAPFJ".equals(bgxm) || "DYZYFJSC".equals(bgxm) || "FJSC".equals(bgxm)) { + log.writeLog("bgxm value:" + value); + if (!value.equals("")) { + RecordSet recordSet = new RecordSet(); + String[] values = value.split(","); + log.writeLog(bgxm + "附件的个数:" + values.length); + + StringBuilder res = new StringBuilder(); + for (String s : values) { + sql = "select IMAGEFILENAME from docimagefile where docid= " + s; + recordSet.execute(sql); + recordSet.next(); + res.append(recordSet.getString("IMAGEFILENAME")).append(";\n"); + } + return Util.null2String(res.toString()); + } + } + + if ("".equals(sql)) { + return Util.null2String(value); + } else if ("".equals(Util.null2String(value))) { + return Util.null2String(value); + } else { + RecordSet recordSet = new RecordSet(); + this.log.writeLog("查找中文字段的SQL:" + sql + value); + recordSet.execute(sql + value); + recordSet.next(); + return Util.null2String(recordSet.getString("returnvalue")); + } + } + + + /** + * 获取企业或人员姓名 + * @param str id + * @return name + */ + private String getQyOrRy(String str) { + String[] strs = str.split("_"); + + String sql ; + if ("qy".equals(strs[0])) { + sql = "select qymc name from uf_jingneiqiyexinxi where id = " + strs[1]; + } else { + sql = "select xm name from UF_RENYUANXINXIKU where id = " + strs[1]; + + } + RecordSet recordSet = new RecordSet(); + recordSet.execute(sql); + recordSet.next(); + + log.writeLog("查找新的股东:"+sql); + return recordSet.getString("name"); + } + + + /** + * 股东变更前后 + * @param list 股东集合 + * @return 内容 + */ + public String getGdBg(ArrayList> list) { + + String value = ""; + for (Map map : list) { + + value += "\n"+getQyOrRy(Util.null2String(map.get("DJGD")))+"/"+map.get("CGBL")+ + "%/"+map.get("CGFS")+"/"+getCgzl(Util.null2String(map.get("GFZL")))+"、"; + } + log.writeLog("value:"+value); + return "".equals(value)?value:value.substring(0,value.length()-1); + } + + /** + * 获取持股种类 + * @param id id + * @return 种类内容 + */ + public String getCgzl(String id) { + if (Util.null2String(id).equals("")) { + return ""; + } + RecordSet recordSet = new RecordSet(); + recordSet.execute("select GFZL from uf_gufenzhonglei where id = " + id); + recordSet.next(); + return Util.null2String(recordSet.getString("GFZL")); + } + + + + + + +} \ No newline at end of file diff --git a/src/main/youhong_ai_jitu_src/jntchina/service/oa/HistoryInfoAPI.java b/src/main/youhong_ai_jitu_src/jntchina/service/oa/HistoryInfoAPI.java new file mode 100644 index 0000000..a4fb954 --- /dev/null +++ b/src/main/youhong_ai_jitu_src/jntchina/service/oa/HistoryInfoAPI.java @@ -0,0 +1,445 @@ +package jntchina.service.oa; + +import com.alibaba.fastjson.JSON; +import jntchina.entity.ChangeInfo; +import selfdev.util.log.LogTool; +import weaver.conn.RecordSet; +import weaver.general.Util; + +import java.util.*; + +/** + * @title: 历史信息 + * @Author ycf + * @Date: 2021/11/18 17:15 + * @Version 1.0 + */ +public class HistoryInfoAPI { + private final LogTool log = new LogTool("/log/api/aa/", false); + + /** + * 修改企业信息 + * @param id 流程id + */ + public void changeInfo(String id) { + /* + 当企业变更后, + insert > 境内企业版本表 table: formtable_main_3055 + update > 境内企业信息表 table: uf_jingneiqiyexinxi + insert > 历史沿革表 table: uf_jingneiqiyexinxi_dt1 + */ + log.writeLog("表单id:" + id); + + RecordSet recordSet = new RecordSet(); + //变更的项目 + HashMap bgMap = new HashMap<>(); + //变更的集合 + ArrayList changeInfosList = new ArrayList<>(); + + //首先从 变更表(uf_jnqyxxbgb)找出所有变更数据, + String sql = "select * from uf_jnqyxxbgb where id = " + id; + recordSet.execute(sql); + while (recordSet.next()) { + for (String s : recordSet.getColumnName()) { + bgMap.put(s, recordSet.getString(s)); + } + } + log.writeLog("变更表信息:" + bgMap.toString()); + + log.writeLog("企业名称变更前:" + bgMap.get("QYMCBGH")); + //找出所有的变更项目 + String[] xm = {"GLY", "QYMC", "ZYM", "YWM", "CLRQ", "SHXYDM" + , "ZCZB", "DZ", "JYFW", "GQTSAP", "GQAPFJ", "FRDB", "CWFZR", "JL" + , "JS", "DS", "DJZT", "SFWBBDW", "BAFJ", "GBDQ", "DLQ" + , "GSLX", "GS","BZ","MGMZ","DLDFLST","YYDZ","YWBK","YWBKZJTZDJS" + ,"BZ2","DYZY","FJSC","ZJFWJGMSGS","SJS","DHYJ","DHEJ","DHSJ","DHSJ1","DHWJ","DHLJ","DHQJ"}; + + //判断变更表的变更前后是否一yydz样 + log.writeLog("企业名称变更后:" + bgMap.get("QYMCBGH")); + + for (String value : xm) { + + + log.writeLog(value + "BGQ:--" + bgMap.get(value + "BGQ")); + log.writeLog(value + "BGH:--" + bgMap.get(value + "BGH")); + + + if (!bgMap.get(value + "BGQ").equals(bgMap.get(value + "BGH"))) { + //当做出了改变,先把改变的值存到list中 + ChangeInfo changeInfo = new ChangeInfo(); + changeInfo.setMainid(bgMap.get("QYID")); + changeInfo.setRq(bgMap.get(value + "RQ")); + changeInfo.setBgxm(value); + changeInfo.setBgq(bgMap.get(value + "BGQ")); + changeInfo.setBgh(bgMap.get(value + "BGH")); + changeInfo.setFj(bgMap.get(value + "FJ")); + changeInfo.setBz(bgMap.get(value + "BZ")); + changeInfosList.add(changeInfo); + log.writeLog("变更的:" + changeInfo); + } + } + + log.writeLog("所有变更项目集合:" + changeInfosList.toString()); + + //变更企业的股权架构 + + //changeInfosList里面加上股权变更 + ArrayList> bgqList = new ArrayList<>(); + ArrayList> bghList = new ArrayList<>(); + sql = "select * from uf_jnqyxxbgb_dt1 where mainid = " + id; + + log.writeLog("查询股权变更前的sql:" + sql); + + //判断股权前后是否相等, + recordSet.execute(sql); + while (recordSet.next()) { + HashMap bgqMap = new HashMap<>(); + for (String s : recordSet.getColumnName()) { + bgqMap.put(s, Util.null2String(recordSet.getString(s))); + } + bgqList.add(bgqMap); + } + + sql = "select * from uf_jnqyxxbgb_dt2 where mainid = " + id; + log.writeLog("查询股权变更后的sql:" + sql); + + //判断股权前后是否相等, + recordSet.execute(sql); + while (recordSet.next()) { + HashMap bghMap = new HashMap<>(); + for (String s : recordSet.getColumnName()) { + bghMap.put(s, Util.null2String(recordSet.getString(s))); + } + bghList.add(bghMap); + } + + log.writeLog("bgq:"+bgqList.toString()); + log.writeLog("bgh:"+bghList.toString()); + + for (HashMap bgqMap : bgqList) { + for (HashMap bghMap : bghList) { + if (bgqMap.get("DJGD").equals(bghMap.get("DJGD"))) { + if (!bghMap.get("CGBL").equals(bgqMap.get("CGBL"))||!bghMap.get("CGFS").equals(bgqMap.get("CGFS"))) { + //股权改变 + log.writeLog("股权发生改变:"); + + ChangeInfo changeInfo = new ChangeInfo(); + changeInfo.setMainid(bgMap.get("QYID")); + changeInfo.setBgq("持股比例"+bgqMap.get("CGBL")+" 持股份数"+bgqMap.get("CGFS")); + changeInfo.setBgh("持股比例"+bghMap.get("CGBL")+" 持股份数"+bghMap.get("CGFS")); + changeInfo.setBz(bghMap.get("BZ")); + changeInfo.setFj(bghMap.get("FJ")); + changeInfo.setRq(bghMap.get("RQ")); + sql = "select qymc from uf_jingneiqiyexinxi where id =" + bghMap.get("DJGD"); + log.writeLog("找到改变的企业名称sql:"+sql); + + recordSet.execute(sql); + recordSet.next(); + + log.writeLog("改变的企业名称:"+recordSet.getString("QYMC")); + + changeInfo.setBgxm(recordSet.getString("QYMC")); + log.writeLog("改变的信息:"+changeInfo.toString()); + changeInfosList.add(changeInfo); + + } + } + + } + } + if (bghList.size() > bgqList.size()) { + for (int i = 0; i < (bghList.size())- bgqList.size(); i++) { + log.writeLog("添加股东:"); + + HashMap map = bghList.get(bgqList.size() + i); + ChangeInfo changeInfo = new ChangeInfo(); + changeInfo.setMainid(bgMap.get("QYID")); + changeInfo.setBgq("持股比例0 持股份数0"); + changeInfo.setBgh("持股比例"+map.get("CGBL")+" 持股份数"+map.get("CGFS")); + changeInfo.setBz(map.get("BZ")); + changeInfo.setRq(map.get("RQ")); + + changeInfo.setFj(map.get("FJ")); + sql = "select qymc from uf_jingneiqiyexinxi where id =" + bgMap.get("QYID"); + recordSet.execute(sql); + recordSet.next(); + + changeInfo.setBgxm(recordSet.getString("QYMC")); + log.writeLog("添加的股东:"+changeInfo.toString()); + changeInfosList.add(changeInfo); + + } + } + if (bghList.size() < bgqList.size()) { + //删除股东信息 + for (HashMap bgqMap : bgqList) { + for (HashMap bghMap : bghList) { + //当变更后的企业被删除,变更后则为0 + + } + } + + } + log.writeLog("changeInfosList1111:"+changeInfosList.toString()); + log.writeLog("changeInfosList1111:"+changeInfosList.size()); + + + + + + //所有改变信息 + + + //把修改信息根据日期排序 map.(date,info) + // 根据日期降序排序 + Map> paixuMapBydate = new TreeMap<>(String::compareTo); + + for (ChangeInfo info : changeInfosList) { + + ArrayList changeInfos = new ArrayList<>(); + + changeInfos.add(info); + + if (!Util.null2String(paixuMapBydate.get(info.getRq())).equals("")) { + + changeInfos.addAll(paixuMapBydate.get(info.getRq())); + + } + paixuMapBydate.put(info.getRq(), changeInfos); + + } + + log.writeLog("map排序:" + paixuMapBydate.toString()); + + //先把境内企业信息表同步到企业信息版本表formtable_main_3055,按照日期修改 + for (String key : paixuMapBydate.keySet()) { + ArrayList changeInfos = paixuMapBydate.get(key); + + //获取企业表的数据同步到版本表 + log.writeLog("获取企业表的数据同步到版本表:"); + + sql = "select * from uf_jingneiqiyexinxi where id = " + bgMap.get("QYID"); + HashMap hashMap = new HashMap<>(); + recordSet.execute(sql); + while (recordSet.next()) { + for (String s : recordSet.getColumnName()) { + hashMap.put(s, recordSet.getString(s)); + } + } + log.writeLog("境内企业信息表的数据:" + hashMap.toString()); + log.writeLog("境内企业信息表的sql:" + sql); + + + //获取模块id + sql = "select id from modeinfo where formid = (select id from workflow_bill where tablename = 'formtable_main_3055')"; + recordSet.execute(sql); + recordSet.next(); + String modeId = recordSet.getString("ID"); + + //先判断是否存在当天日期的版本表 + sql = "select * from formtable_main_3055 where bbrq='"+key+"' and qyid = "+bgMap.get("QYID"); + recordSet.execute(sql); + recordSet.next(); + if (!"".equals(recordSet.getString("ID"))) { + + log.writeLog("当前日期的企业已经存在,不做更新:"); + } else { + + sql = "insert into formtable_main_3055 (zczb,dz,gly,qymc,zym,ywm,clrq,shxydm,dhyj,dhej,dhsj,dhsj1,dhwj,dhlj,dhqj," + + "jyfw,gqtsap,gqapfj,frdb,cwfzr,jl,js,ds,djzt,sfwbbdw,bafj,bbrq,qyid,FORMMODEID,GBDQ,DLQ" + + " , GSLX,GS,BZ,MGMZ,DLDFLST,YYDZ,YWBK,YWBKZJTZDJS,BZ2,DYZY,FJSC,ZJFWJGMSGS,SJS) values ('" + hashMap.get("ZCZB") + "', '" + hashMap.get("DZ") + "', " + + "'" + hashMap.get("GLY") + "', '" + hashMap.get("QYMC") + "', '" + hashMap.get("ZYM") + "', '" + hashMap.get("YWM") + "', " + + "'" + hashMap.get("CLRQ") + "', '" + hashMap.get("SHXYDM") + "', '" + hashMap.get("DHYJ") + "', '" + hashMap.get("DHEJ") + "', " + + "'" + hashMap.get("DHSJ") + "', '" + hashMap.get("DHSJ1") + "', '" + hashMap.get("DHWJ") + "', '" + hashMap.get("DHLJ") + "', " + + "'" + hashMap.get("DHQJ") + "', '" + hashMap.get("JYFW") + "', '" + hashMap.get("GQTSAP") + "', '" + hashMap.get("GQAPFJ") + "', " + + "'" + hashMap.get("FRDB") + "', '" + hashMap.get("CWFZR") + "', '" + hashMap.get("JL") + "', '" + hashMap.get("JS") + "', " + + "'" + hashMap.get("DS") + "', '" + hashMap.get("DJZT") + "', '" + hashMap.get("SFWBBDW") + "', " + + "'" + hashMap.get("BAFJ") + "', '" + key + "','"+bgMap.get("QYID")+"',"+modeId+"" + + ", '" + hashMap.get("GBDQ") + "', '" + hashMap.get("DLQ") + "', '" + hashMap.get("GSLX") + "', '" + hashMap.get("GS") + "'" + + ", '" + hashMap.get("BZ") + "', '" + hashMap.get("MGMZ") + "', '" + hashMap.get("DLDFLST") + "', '" + hashMap.get("YYDZ") + "'" + + ", '" + hashMap.get("YWBK") + "', '" + hashMap.get("YWBKZJTZDJS") + "', '" + hashMap.get("BZ2") + "', '" + hashMap.get("DYZY") + "'" + + ", '" + hashMap.get("FJSC") + "', '" + hashMap.get("ZJFWJGMSGS") + "', '" + hashMap.get("SJS") + "')"; + log.writeLog("插入版本表的sql:"+sql); + + recordSet.executeUpdate(sql); + log.writeLog("当日版本的企业不存在,只更新sql:" + sql); + + } + + + sql = "select max(id) QYID from formtable_main_3055 where qyid ="+bgMap.get("QYID")+" and bbrq = '"+key+"'"; +// sql = "select max(id) from formtable_main_3055 order by id desc "; + + log.writeLog("找表的的ID的sql:"+sql); + + recordSet.execute(sql); + recordSet.next(); + String mxbId = recordSet.getString("QYID"); + log.writeLog("主表的id:"+mxbId); + + + //同步历史沿革dt1 + ArrayList arrayList = new ArrayList<>(); + sql = "select * from uf_jingneiqiyexinxi_dt1 where MAINID = " + bgMap.get("QYID"); + recordSet.execute(sql); + while (recordSet.next()) { + ChangeInfo changeInfo = new ChangeInfo(); + changeInfo.setMainid(recordSet.getString("MAINID")); + changeInfo.setRq(recordSet.getString("RQ")); + changeInfo.setBgxm(recordSet.getString("BGXM")); + changeInfo.setBgq(recordSet.getString("BGQ")); + changeInfo.setBgh(recordSet.getString("BGH")); + changeInfo.setFj(recordSet.getString("FJ")); + changeInfo.setBz(recordSet.getString("BZ")); + arrayList.add(changeInfo); + } + for (ChangeInfo changeInfo : arrayList) { + sql = "insert into formtable_main_3055_dt1 (MAINID,RQ,BGXM,BGQ,BGH,FJ,BZ) values ('" + mxbId + "','" + changeInfo.getRq() + "','" + changeInfo.getBgxm() + "'" + + ",'" + changeInfo.getBgq() + "','" + changeInfo.getBgh() + "','" + changeInfo.getFj() + "','" + changeInfo.getBz() + "')"; + recordSet.executeUpdate(sql); + log.writeLog("插入版本表的变更表:" + sql); + } + + //同步股权信息dt2 + sql = "select * from uf_jingneiqiyexinxi_dt2 where MAINID = " + bgMap.get("QYID"); + recordSet.execute(sql); + ArrayList> dt2 = new ArrayList<>(); + log.writeLog("获取股权sql:" + sql); + + while (recordSet.next()) { + HashMap map = new HashMap<>(); + for (String s : recordSet.getColumnName()) { + map.put(s, recordSet.getString(s)); + } + dt2.add(map); + } + log.writeLog("股权list:" + dt2); + log.writeLog("股权的行数:" + dt2.size()); + + //更新境内企业信息(uf_jingneiqiyexinxi)股权信息(dt2) + for (HashMap map : dt2) { + + sql = "insert into formtable_main_3055_dt2 (MAINID,DJGD,CGBL,BZ,QYMC1,rq,CGFS,gfzl) values ('" + mxbId + "'" + + ",'" + map.get("DJGD") + "','" + map.get("CGBL") + "','" + map.get("BZ") + "','" + map.get("QYMC1") + "','"+key+"','"+map.get("CGFS")+"','"+map.get("GFZL")+"')"; + log.writeLog("插入股权信息sql:" + sql); + recordSet.executeUpdate(sql); + + + + + } + log.writeLog("同步股权信息sql:" + sql); + + //changeInfos,更新境内企业信息(uf_jingneiqiyexinxi) + for (ChangeInfo changeInfo : changeInfos) { +// if (!changeInfo.getBgxm().trim().substring(0, 1).matches("^[a-zA-Z]*")) { +// +// } else { + sql = "update uf_jingneiqiyexinxi set " + changeInfo.getBgxm() + " = '" + changeInfo.getBgh() + "' where id = " + bgMap.get("QYID"); + log.writeLog("更新境内企业信息:" + sql); + recordSet.execute(sql); +// } + + } + + //插入修改信息到包括历史沿革uf_jingneiqiyexinxi_dt1 + + for (ChangeInfo changeInfo : changeInfos) { + sql = "insert into uf_jingneiqiyexinxi_dt1 (MAINID,RQ,BGXM,BGQ,BGH,FJ,BZ) values " + + "('" + changeInfo.getMainid() + "','" + changeInfo.getRq() + "','" + new HistoryInfoAPI().getBgxms(changeInfo.getBgxm()) + "'" + + ",'" + changeInfo.getBgq() + "','" + changeInfo.getBgh() + "','" + changeInfo.getFj() + "','" + changeInfo.getBz() + "')"; + log.writeLog("插入修改信息到包括历史沿革uf_jingneiqiyexinxi_dt1:" + sql); + recordSet.executeUpdate(sql); + + } + + //先删除相关的股权 + sql = "delete uf_jingneiqiyexinxi_dt2 where mainid= " + bgMap.get("QYID"); + recordSet.execute(sql); + log.writeLog("删除股权的sql:" + sql); + + //更新股权 dt2 + for (HashMap map : bghList) { + //把变更后的股权插入到jingneiqiyexinxi_dt2中 + sql = "insert into uf_jingneiqiyexinxi_dt2 (MAINID,DJGD,CGBL,BZ,CGFS,GFZL) values " + + "('" + bgMap.get("QYID") + "','" + map.get("DJGD") + "','" + map.get("CGBL") + "','" + map.get("BZ") + "','"+map.get("CFFS")+"','"+ map.get("GFZL")+"')"; + log.writeLog("添加境内企业信息的sql:" + sql); + recordSet.execute(sql); + } + //更新企业表中的股权信息 +// update uf_jingneiqiyexinxi_dt2 set qymc1='用于测试的企业11' where qymc1= '用于测试的企业22' + sql = "update uf_jingneiqiyexinxi_dt2 set qymc1='" + bgMap.get("QYMCBGH") + "' where mainid = '" + bgMap.get("QYID") + "'"; + log.writeLog("更新股权表的qymc1:" + sql); + recordSet.executeUpdate(sql); + } + } + + /** + * 字段转换(通过字符找到变更项目) + * @param bg 变更的字符串 + * @return 变更项目 + */ + + public String getBgxms(String bg) { + //设置变更项目的对应字段 + Map cors = new HashMap<>(); + cors.put("QYMC", "企业名称"); + cors.put("ZYM", "曾用名"); + cors.put("YWM", "英文名"); + cors.put("CLRQ", "成立日期"); + cors.put("SHXYDM", "社会信用代码"); + cors.put("GQTSAP", "股权特殊安排"); + cors.put("FRDB", "法人代表"); + cors.put("CWFZR", "财务负责人"); + cors.put("JL", "经理"); + cors.put("JS", "监事"); + cors.put("DS", "董事"); + cors.put("DJZT", "登记状态"); + cors.put("YWCZ", "业务承载"); + cors.put("SFWBBDW", "是否为并表单位"); + cors.put("ZCZB", "注册资本"); + cors.put("DZ", "地址"); + cors.put("JYFW", "经营范围"); + cors.put("DJGD", "登记股东"); + cors.put("CGBL", "持股比例"); + cors.put("GLY", "管理员"); + cors.put("DHYJ", "导航一级"); + cors.put("DHEJ", "导航二级"); + cors.put("DHSJ", "导航三级"); + cors.put("DHSJ1", "导航四级"); + cors.put("DHWJ", "导航五级"); + cors.put("DHLJ", "导航六级"); + cors.put("DHQJ", "导航七级"); + cors.put("BAFJ", "备案附件"); + + cors.put("GBDQ", "国别/地区"); + cors.put("DLQ", "代理区"); + cors.put("GSLX", "公司类型"); + cors.put("GS", "股数"); + cors.put("BZ", "币种"); + cors.put("MGMZ", "每股面值"); + cors.put("DLDFLST", "独立的法律实体"); + cors.put("YYDZ", "营业地址"); + cors.put("YWBK", "业务板块"); + cors.put("YWBKZJTZDJS", "业务模块/在集团中的角色"); + cors.put("BZ2", "备注"); + cors.put("DYZY", "抵押/质押"); + cors.put("FJSC", "附件上传"); + cors.put("ZJFWJGMSGS", "中介服务机构/秘书公司"); + cors.put("SJS", "审计师"); + + //判断 + if (Util.null2String(cors.get(bg)).equals("")) { + + log.writeLog("bgx---------------------------------------------:" + bg); + return bg; + } else { + log.writeLog("bgx---------------------------------------------:" + cors.get(bg)); + + return cors.get(bg); + } + } + + + +} diff --git a/src/main/youhong_ai_jitu_src/jntchina/service/oa/NewQiye.java b/src/main/youhong_ai_jitu_src/jntchina/service/oa/NewQiye.java new file mode 100644 index 0000000..755676b --- /dev/null +++ b/src/main/youhong_ai_jitu_src/jntchina/service/oa/NewQiye.java @@ -0,0 +1,136 @@ +package jntchina.service.oa; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.Map; + +import jntchina.util.DataBaseUtils; +import selfdev.util.log.LogTool; +import weaver.conn.RecordSet; +import weaver.formmode.customjavacode.AbstractModeExpandJavaCodeNew; +import weaver.general.Util; +import weaver.hrm.User; +import weaver.soa.workflow.request.RequestInfo; + + +/** + * 说明 + * 修改时 + * 类名要与文件名保持一致 + * class文件存放位置与路径保持一致。 + * 请把编译后的class文件,放在对应的目录中才能生效 + * 注意 同一路径下java名不能相同。 + * @author Administrator + * + */ +public class NewQiye extends AbstractModeExpandJavaCodeNew { + private final LogTool log = new LogTool("/log/api/aa/", false); + + /** + * 执行模块扩展动作 + * @param param + * param包含(但不限于)以下数据 + * user 当前用户 + * importtype 导入方式(仅在批量导入的接口动作会传输) 1 追加,2覆盖,3更新,获取方式(int)param.get("importtype") + * 导入链接中拼接的特殊参数(仅在批量导入的接口动作会传输),比如a=1,可通过param.get("a")获取参数值 + * 页面链接拼接的参数,比如b=2,可以通过param.get("b")来获取参数 + * @return + */ + public Map doModeExpand(Map param) { + Map result = new HashMap(); + try { + User user = (User)param.get("user"); + int billid = -1;//数据id + int modeid = -1;//模块id + RequestInfo requestInfo = (RequestInfo)param.get("RequestInfo"); + if(requestInfo!=null){ + billid = Util.getIntValue(requestInfo.getRequestid()); + modeid = Util.getIntValue(requestInfo.getWorkflowid()); + if(billid>0&&modeid>0){ + //------请在下面编写业务逻辑代码------ + + + RecordSet recordSet = new RecordSet(); + String sql = "select * from uf_jingneiqiyexinxi where id = "+billid; + HashMap hashMap = new HashMap<>(); + recordSet.execute(sql); + while (recordSet.next()) { + for (String s : recordSet.getColumnName()) { + hashMap.put(s, recordSet.getString(s)); + } + } + log.writeLog("创建企业查询语句:"+sql); +//获取模块id + sql = "select id from modeinfo where formid = (select id from workflow_bill where tablename = 'formtable_main_3055')"; + recordSet.execute(sql); + recordSet.next(); + String modeId = recordSet.getString("ID"); + + sql = "insert into formtable_main_3055 (zczb,dz,gly,qymc,zym,ywm,clrq,shxydm,dhyj,dhej,dhsj,dhsj1,dhwj,dhlj,dhqj," + + "jyfw,gqtsap,gqapfj,frdb,cwfzr,jl,js,ds,djzt,sfwbbdw,bafj,bbrq,qyid,FORMMODEID,GBDQ,DLQ" + + " , GSLX,GS,BZ,MGMZ,DLDFLST,YYDZ,YWBK,YWMKZJTZDJS,BZ2,DYZY,FJSC,ZJFWJGMSGS,SJS,GLF,NBJZQ) values ('" + hashMap.get("ZCZB") + "', '" + hashMap.get("DZ") + "', " + + "'" + hashMap.get("GLY") + "', '" + hashMap.get("QYMC") + "', '" + hashMap.get("ZYM") + "', '" + hashMap.get("YWM") + "', " + + "'" + hashMap.get("CLRQ") + "', '" + hashMap.get("SHXYDM") + "', '" + hashMap.get("DHYJ") + "', '" + hashMap.get("DHEJ") + "', " + + "'" + hashMap.get("DHSJ") + "', '" + hashMap.get("DHSJ1") + "', '" + hashMap.get("DHWJ") + "', '" + hashMap.get("DHLJ") + "', " + + "'" + hashMap.get("DHQJ") + "', '" + hashMap.get("JYFW") + "', '" + hashMap.get("GQTSAP") + "', '" + hashMap.get("GQAPFJ") + "', " + + "'" + hashMap.get("FRDB") + "', '" + hashMap.get("CWFZR") + "', '" + hashMap.get("JL") + "', '" + hashMap.get("JS") + "', " + + "'" + hashMap.get("DS") + "', '" + hashMap.get("DJZT") + "', '" + hashMap.get("SFWBBDW") + "', " + + "'" + hashMap.get("BAFJ") + "', '" + hashMap.get("CLRQ") + "','"+billid+"',"+modeId+"" + + ", '" + hashMap.get("GBDQ") + "', '" + hashMap.get("DLQ") + "', '" + hashMap.get("GSLX") + "', '" + hashMap.get("GS") + "'" + + ", '" + hashMap.get("BZ") + "', '" + hashMap.get("MGMZ") + "', '" + hashMap.get("DLDFLST") + "', '" + hashMap.get("YYDZ") + "'" + + ", '" + hashMap.get("YWBK") + "', '" + hashMap.get("YWMKZJTZDJS") + "', '" + hashMap.get("BZ2") + "', '" + hashMap.get("DYZY") + "'" + + ", '" + hashMap.get("FJSC") + "', '" + hashMap.get("ZJFWJGMSGS") + "', '" + hashMap.get("SJS") + "', '" + hashMap.get("GLF") + "', '" + hashMap.get("NBJZQ") + "')"; + log.writeLog("插入版本表的sql:"+sql); + + recordSet.execute(sql); + + + sql = "select id from formtable_main_3055 where qyid = " + billid; + String versionId = DataBaseUtils.getFirstValue(sql); + + sql = "select * from uf_jingneiqiyexinxi_dt2 where MAINID = "+billid ; + log.writeLog("获取股东:"+sql); + + ArrayList> dt2List = DataBaseUtils.getDataList(sql); + for (Map map : dt2List) { + sql = "insert into formtable_main_3055_dt2 (MAINID,DJGD,CGBL,BZ,QYMC1,CGFS,gfzl,MAINBILLID) values ('" + versionId + "'" + + ",'" + map.get("DJGD") + "','" + map.get("CGBL") + "','" + map.get("BZ") + "','" + map.get("QYMC1") + "'," + + "'','" + map.get("CGFS") + "','" + map.get("GFZL") + "','"+map.get("ID")+"')"; + recordSet.execute(sql); + log.writeLog("插入股东:" + sql); + } + //同步资质证照 + sql = "select * from uf_jingneiqiyexinxi_dt3 where MAINID = " + billid; + log.writeLog("同步资质证照的SQL:"+sql); + + ArrayList> dt3List = DataBaseUtils.getDataList(sql); + log.writeLog("同步资质证照的list:"+dt3List.size()); + + + + for (Map map : dt3List) { + sql = "insert into formtable_main_3055_dt3 (MAINID,zzzz,fjsc,BZ,QYMC,MAINBILLID) values ('" + versionId + "'" + + ",'" + map.get("ZZZZ") + "','" + map.get("FJSC") + "','" + map.get("BZ") + "','" + map.get("QYMC") + "','"+map.get("ID")+"')"; + log.writeLog("插入资质证照信息sql:" + sql); + recordSet.execute(sql); + } + + sql = "update uf_jingneiqiyexinxi_dt2 set qymc1 = '" + billid + "' where mainid = '"+billid+"'"; + log.writeLog("修改:"+sql); + recordSet.execute(sql); + sql = "update uf_jingneiqiyexinxi_dt3 set qymc = '" + billid + "' where mainid = '"+billid+"'"; + log.writeLog("修改:"+sql); + recordSet.execute(sql); + + + + } + } + } catch (Exception e) { + result.put("errmsg","自定义出错信息"); + result.put("flag", "false"); + } + return result; + } + +} \ No newline at end of file diff --git a/src/main/youhong_ai_jitu_src/jntchina/service/oa/OAUtils.java b/src/main/youhong_ai_jitu_src/jntchina/service/oa/OAUtils.java new file mode 100644 index 0000000..fa297b9 --- /dev/null +++ b/src/main/youhong_ai_jitu_src/jntchina/service/oa/OAUtils.java @@ -0,0 +1,1013 @@ +package jntchina.service.oa; + +import com.alibaba.excel.ExcelWriter; +import com.alibaba.excel.metadata.Sheet; +import com.alibaba.excel.metadata.Table; +import com.alibaba.excel.support.ExcelTypeEnum; +import com.alibaba.fastjson.JSON; +import jntchina.schedule.hrm.SynShangBiao; +import jntchina.util.DataBaseUtils; +import selfdev.util.log.LogTool; +import weaver.conn.RecordSet; + +import weaver.general.Util; +import weaver.hrm.User; + + +import javax.servlet.http.HttpServletRequest; +import javax.ws.rs.*; +import javax.ws.rs.core.Context; +import javax.ws.rs.core.MediaType; +import javax.ws.rs.core.Response; +import java.io.*; +import java.time.LocalDate; +import java.util.*; + +import static jntchina.service.oa.ChangeDt1.strNull; + +/** + * @title: OAUtils 工具处理类 + * @Author ycf + * @Date: 2021/12/7 17:03 + * @Version 1.0 + */ +@Path("/UtilsAPI") +public class OAUtils { + private final LogTool log = new LogTool("/log/api/qiye/", false); + + + + @POST + @Path("/changeDate") + public String changeDate(@Context HttpServletRequest request) { + HashMap map = new HashMap<>(); + RecordSet recordSet = new RecordSet(); + String sql = ""; + try { + + + String[] bgq = request.getParameterValues("bgq[]"); + String[] bgh = request.getParameterValues("bgh[]"); + String id = request.getParameter("id"); + log.writeLog("变更前日期:"+ Arrays.toString(bgq)); + log.writeLog("变更hou日期:"+ Arrays.toString(bgh)); + log.writeLog("id:"+id); + + if (bgq.length == bgh.length) { + for (int i = 0; i < bgq.length; i++) { + if (!bgq[i].equals(bgh[i])) { + //更新历史沿革日期 + sql = "update formtable_main_3055_DT1\n" + + "set rq = '"+bgh[i]+"'\n" + + "where mainid = (select id from formtable_main_3055 where bbRQ = '"+bgq[i]+"' and qyid = "+id+") "; + recordSet.execute(sql); + log.writeLog("更新企业的历史沿革sql:" + sql); + + + //更新版本日期 + sql = "update formtable_main_3055\n" + + "set BBRQ = '"+bgh[i]+"'\n" + + "where BBRQ = '"+bgq[i]+"' and QYID = "+id; + recordSet.execute(sql); + log.writeLog("更新企业的版本日期sql:"+sql); + } + } + } + + map.put("msg","修改成功"); + } catch (Exception e) { + log.writeLog("e:"+e); + + + map.put("msg","修改失败"+e.toString()); + } + log.writeLog("msg:"+JSON.toJSONString(map)); + + return JSON.toJSONString(map); + + } + + + @GET + @Path("/synShangBiao") + public String synShangBiao() { + + HashMap map = new HashMap<>(); + try { + new SynShangBiao().execute(); + map.put("code", "1"); + map.put("msg", "成功"); + } catch (Exception e) { + map.put("code", "0"); + map.put("msg", "失败,失败原因请通过后台日志查看"); + } + return JSON.toJSONString(map); + + } + + @POST + @Path("/getDetailValue") + public String getDetailValue(@Context HttpServletRequest request) { + String id = Util.null2String(request.getParameter("id")); + String isinfo = Util.null2String(request.getParameter("isinfo")); + String sql = ""; + + if ("0".equals(isinfo)) { + sql = "select *\n" + + "from formtable_main_3055_DT1 where mainid in (select id\n" + + "from formtable_main_3055 where qyid = "+id+" ) order by RQ, id"; + } else { + + sql = "select *\n" + + "from formtable_main_3055_DT1 where mainid in (select id\n" + + "from formtable_main_3055 where BBRQ<=(select BBRQ\n" + + "from formtable_main_3055 where id = "+id+") and qyid = (select QYID\n" + + "from formtable_main_3055 where id = "+id+") ) order by RQ, id "; + } + + + log.writeLog("获取明细字段的sql:"+sql); + + + RecordSet recordSet = new RecordSet(); + sql = strNull(sql); + log.writeLog("通过SQL获取数据集:"+sql); + ArrayList> maps = new ArrayList<>(); + recordSet.execute(sql); + while (recordSet.next()) { + HashMap map = new HashMap<>(); + for (String s : recordSet.getColumnName()) { + map.put(s, strNull(recordSet.getString(s))); + } + maps.add(map); + } + + log.writeLog("maps:"+maps); + + + int i = 0; + for (Map map : maps) { + i++; + map.put("FJS", getWenJianUrl(map.get("FJ").toString())); + + map.put("ID", i+""); + } + + HashMap map = new HashMap<>(); + map.put("data", maps); + + + + return JSON.toJSONString(map); + } + + /** + * 获取系统语言 + * @return 是否为中文 + */ + @GET + @Path("/getLanguage") + public String getLanguage() { + + RecordSet recordSet = new RecordSet(); + recordSet.execute(" select id from modeinfo where formid = (select id from workflow_bill where tablename = 'uf_jingneiqiyexinxi') "); + recordSet.next(); + String id = recordSet.getString("ID"); + HashMap map = new HashMap<>(); + map.put("language", (User.getUser(1, 0).getLanguage() + "").equals("7")); + map.put("path", "/spa/cube/engine.html#/cubeengine/app/modebatchimport?modeid="+id+"&customid="+id+"&_key=2dcq42"); + return JSON.toJSONString(map); + } + + /** + * 获取创建企业的url + * @return url + */ + @GET + @Path("/getCreateQiyeURL") + public String getCreateQiyeURL() { + RecordSet recordSet = new RecordSet(); + recordSet.execute("select id from modeinfo where formid = (select id from workflow_bill where tablename = 'uf_jingneiqiyexinxi')"); + recordSet.next(); + String modelId = recordSet.getString("ID"); + recordSet.execute("select id from workflow_bill where tablename = 'uf_jingneiqiyexinxi'"); + recordSet.next(); + String fromId = recordSet.getString("ID"); + + HashMap map = new HashMap<>(); + map.put("path", "/spa/cube/index.html#/main/cube/card?type=1&modeId=" + modelId + "&formId=" + fromId); + return JSON.toJSONString(map); + } + + /** + * 检查企业名是否重名 + * + * @param name 企业名 + * @return 状态:0:可用,1:不可 + */ + @GET + @Path("/checkName") + public String checkName(@QueryParam("name") String name) { + + RecordSet recordSet = new RecordSet(); + String sql = "select count(1) from uf_jingneiqiyexinxi where qymc = '" + name + "'"; + log.writeLog("检查:" + sql); + recordSet.execute(sql); + recordSet.next(); + int anInt = recordSet.getInt(1); + log.writeLog("是否有重名;+" + anInt); + if (anInt == 0) { + return "0"; + } else { + return "1"; + } + + } + + + + /** + * 判断是否含有下一级 + * + * @param sql 判断的SQL + * @return boolean true/false + */ + public boolean isHaveNext(String sql) { + log.writeLog("isHaveNextsql4:" + sql); + + RecordSet recordSet = new RecordSet(); + recordSet.execute(sql); + recordSet.next(); + String a = recordSet.getString("ID"); + return !"".equals(a); + + + } + + /** + * 根据参数获取日期的SQL + * @param str str + * @return sql + */ + public String getDateSql(String[] str) { + String sql = ""; + //开始时间 + String date1 = ""; + //结束时间 + String date2 = ""; + //当前时间 + String date = String.valueOf(LocalDate.now()); + String year = date.substring(0, 4); + String month = date.substring(5, 7); + String day = date.substring(8, 10); + log.writeLog("date:"+date); + log.writeLog("date1:"+date1); + log.writeLog("date2:"+date2); + + + + if (null != str) { + switch (str[0]) { + case "1": + //昨天 + if (!day.equals("01")) { + sql += " and to_date(clrq,'yyyy-MM-dd') = to_date('" + year + "-" + month + "-" + (Integer.parseInt(day) - 1) + "','yyyy-MM-dd') "; + } else { + //获取上个月的最后一天 + String day2 = String.valueOf(LocalDate.of(Integer.parseInt(year), Integer.parseInt(month) - 1, Integer.parseInt(day)).lengthOfMonth()); + sql += " and to_date(clrq,'yyyy-MM-dd') = to_date('" + year + "-" + (Integer.parseInt(month) - 1) + "-" + day2 + "','yyyy-MM-dd') "; + } + break; + case "2": + //今天 + sql += " and to_date(clrq,'yyyy-MM-dd') = to_date('" + year + "-" + month + "-" + day + "','yyyy-MM-dd') "; + break; + case "3": + //明天 + //判断是否为本月最后一天 + if (day.equals(String.valueOf(LocalDate.of(Integer.parseInt(year), Integer.parseInt(month), Integer.parseInt(day)).lengthOfMonth()))) { + if (month.equals("12")) { + sql += " and to_date(clrq,'yyyy-MM-dd') = to_date('" + (Integer.parseInt(year) + 1) + "-01-01','yyyy-MM-dd') "; + } else { + sql += " and to_date(clrq,'yyyy-MM-dd') = to_date('" + year + "-" + (Integer.parseInt(month) + 1) + "-01','yyyy-MM-dd') "; + } + } else { + sql += " and to_date(clrq,'yyyy-MM-dd') = to_date('" + year + "-" + month + "-"+(Integer.parseInt(day) + 1)+"','yyyy-MM-dd') "; + } + break; + case "4": + //上周 + break; + case "5": + //本周 + break; + case "6": + //指定日期范围 + if (null != str[1]) { + if (!"".equals(str[1])) { + sql += " and to_date(clrq,'yyyy-MM-dd') >= to_date('"+str[1]+"','yyyy-MM-dd') "; + } + } + if (null != str[2]) { + if (!"".equals(str[2])) { + sql += " and to_date(clrq,'yyyy-MM-dd') <= to_date('"+str[2]+"','yyyy-MM-dd') "; + } + } + + break; + case "7": + //下周 + + break; + case "8": + //本月 + + sql += " and to_date(clrq,'yyyy-MM-dd') <= to_date('"+year+"-"+month+"-"+LocalDate.of(Integer.parseInt(year), Integer.parseInt(month), Integer.parseInt(day)).lengthOfMonth()+"','yyyy-MM-dd') "; + sql += " and to_date(clrq,'yyyy-MM-dd') >= to_date('"+year+"-"+month+"-01','yyyy-MM-dd') "; + break; + case "9": + //本季度 + switch (Integer.parseInt(month)) { + case 1: + case 2: + case 3 : + sql += " and to_date(clrq,'yyyy-MM-dd') <= to_date('" + year + "-03-31','yyyy-MM-dd') "; + sql += " and to_date(clrq,'yyyy-MM-dd') >= to_date('" + year + "-01-01','yyyy-MM-dd') "; + break; + case 4: + case 5: + case 6 : + + sql += " and to_date(clrq,'yyyy-MM-dd') <= to_date('" + year + "-06-31','yyyy-MM-dd') "; + sql += " and to_date(clrq,'yyyy-MM-dd') >= to_date('" + year + "-04-01','yyyy-MM-dd') "; + break; + case 7: + case 8: + case 9 : + + sql += " and to_date(clrq,'yyyy-MM-dd') <= to_date('" + year + "-09-31','yyyy-MM-dd') "; + sql += " and to_date(clrq,'yyyy-MM-dd') >= to_date('" + year + "-07-01','yyyy-MM-dd') "; + break; + + case 10: + case 11: + case 12 : + sql += " and to_date(clrq,'yyyy-MM-dd') <= to_date('" + year + "-12-31','yyyy-MM-dd') "; + sql += " and to_date(clrq,'yyyy-MM-dd') >= to_date('" + year + "-10-01','yyyy-MM-dd') "; + break; + + } + break; + case "10": + //本年 + sql += " and to_date(clrq,'yyyy-MM-dd') <= to_date('"+year+"-12-31','yyyy-MM-dd') "; + sql += " and to_date(clrq,'yyyy-MM-dd') >= to_date('"+year+"-01-01','yyyy-MM-dd') "; + + break; + case "11": + //上个月 + if (month.equals("01")) { + sql += " and to_date(clrq,'yyyy-MM-dd') < to_date('"+(Integer.parseInt(year)-1)+"-12-01','yyyy-MM-dd') "; + sql += " and to_date(clrq,'yyyy-MM-dd') >= to_date('"+(Integer.parseInt(year)-1)+"-12-31','yyyy-MM-dd') "; + } else { + String month2 = Integer.parseInt(month) - 1+""; + sql += " and to_date(clrq,'yyyy-MM-dd') < to_date('"+year+"-"+month+"-1','yyyy-MM-dd') "; + sql += " and to_date(clrq,'yyyy-MM-dd') >= to_date('"+year+"-"+month2+"-01','yyyy-MM-dd') "; + } + + break; + case "12": + //上一年 + + sql += " and to_date(clrq,'yyyy-MM-dd') <= to_date('"+(Integer.parseInt(year)-1)+"-12-31','yyyy-MM-dd') "; + sql += " and to_date(clrq,'yyyy-MM-dd') >= to_date('"+(Integer.parseInt(year)-1)+"-01-01','yyyy-MM-dd') "; + + break; + } + + } + return sql; + } + + + /** + * 导出列表 Excel表格 + * @param request 导出的企业id + * @return Excel + * @throws IOException io流异常 + */ + @Path("/exportToExcel") + @POST + public String exportToExcel(@Context HttpServletRequest request) throws IOException { + log.writeLog("进入导出:"); + String[] qyid = request.getParameterValues("params[]"); + log.writeLog("导出企业的id:"+ Arrays.toString(qyid)); + RecordSet recordSet = new RecordSet(); + List> bodyList = new ArrayList<>(); + for (String str : qyid) { + String sql = "select (select DHYJZDXX from uf_daohangyijizidua where id = a.dhyj) dhyj" + + ",(select dhej from uf_daohangerji where id = a.dhej) dhej" + + ",(select dhsj from uf_saohangsanji where id = a.dhsj) dhsj " + + " ,(select dhsj from uf_daohangsiji where id = a.dhsj1) dhsj1 " + + " ,(select dhwj from uf_daohangwuji where id = a.dhwj) dhwj" + + ",(select dhlj from uf_daohangliuji where id = a.dhlj) dhlj" + + ",(select dhqj from uf_daohangqiji where id = a.dhqj) dhqj " + + ", (select sfzxm from uf_guanliyuankuxin where id =a.gly) gly" + + ",qymc" + + ",(select GJDQK from uf_guojiadiquku where id = a.gbdq) gbdq" + + ",(select DLQ from uf_dailiqu where id=a.dlq) dlq" + + ",(select gslx from uf_gongsileixing where id=a.gslx) gslx" + + ",zym" + + ",ywm" + + ",clrq" + + ",shxydm" + + ",(select DJZT from uf_dengjizhuangtai where id=a.djzt) djzt" + + ",zczb" + + ",gs" + + ",(select bz from uf_bizhong where id=a.bz) bz" + + ",mgmz" + + ", dldflst" + + ",dz" + + ",yydz" + + ",jyfw" + + ",(select YWBK from uf_yewubankuai where id=a.ywbk) ywbk" + + ",(select YWMKZJTZDJS from uf_jituanzhongdejue where id=a.ywmkzjtzdjs) ywmkzjtzdjs" + + ",bz2" + + ",(select SFWBBDW from uf_shifouweibingbia where id = a.sfwbbdw) sfwbbdw" + + ", frdb" + + ",cwfzr" + + ", jl" + + ", js" + + ", ds" + + ",gqtsap" + + ",dyzy " + + ",zjfwjgmsgs" + + ",sjs,GLF,NBJZQ,id" + + " from uf_jingneiqiyexinxi a where id = "+str; + + log.writeLog("导出 查找企业的SQL:"+sql); + + recordSet.execute(sql); +// ArrayList> mapArrayList = new ArrayList<>(); + + while (recordSet.next()) { + List list = new ArrayList<>(); + for (String s : recordSet.getColumnName()) { + log.writeLog("s:"+s); + if (!"ID".equals(s)){ + if ( "DS".equals(s) || "JS".equals(s) || "JL".equals(s) || "CWFZR".equals(s) || "FRDB".equals(s)) { + list.add(Util.null2String(this.getRenYuan(recordSet.getString(s)))); + }else if ("GLF".equals(s)){ + list.add(Util.null2String("0".equals(recordSet.getString(s))?"YES":"NO")); + }else if ("DLDFLST".equals(s)){ + log.writeLog("独立的法律实体:"+recordSet.getString(s)); + if ("0".equals(recordSet.getString(s))) { + list.add("Yes"); + } else if ("1".equals(recordSet.getString(s))) { + list.add("No"); + } else { + list.add(" "); + } + }else if ("CLRQ".equals(s)){ + list.add(Util.null2String(recordSet.getString(s))); + list.add(gdStr(recordSet.getString("ID"),"uf_jingneiqiyexinxi")); + } else { + list.add(Util.null2String(recordSet.getString(s))); + + } + } + + + } + log.writeLog("获取的企业:"+list); + + bodyList.add(list); + } + } + List> titleList = new ArrayList<>(); + titleList.add(Arrays.asList("导航一级")); titleList.add(Arrays.asList("导航二级"));titleList.add(Arrays.asList("导航三级"));titleList.add(Arrays.asList("导航四级"));titleList.add(Arrays.asList("导航五级"));titleList.add(Arrays.asList("导航六级"));titleList.add(Arrays.asList("导航七级"));titleList.add(Arrays.asList("管理员"));titleList.add(Arrays.asList("企业名称"));titleList.add(Arrays.asList("国别地区"));titleList.add(Arrays.asList("代理区"));titleList.add(Arrays.asList("公司类型"));titleList.add(Arrays.asList("曾用名"));titleList.add(Arrays.asList("外文名"));titleList.add(Arrays.asList("成立日期"));titleList.add(Arrays.asList("登记股东/持股比例"));titleList.add(Arrays.asList("社会信用代码"));titleList.add(Arrays.asList("登记状态"));titleList.add(Arrays.asList("注册资本"));titleList.add(Arrays.asList("股数"));titleList.add(Arrays.asList("币种"));titleList.add(Arrays.asList("每股面值"));titleList.add(Arrays.asList("独立的法律实体"));titleList.add(Arrays.asList("注册地址"));titleList.add(Arrays.asList("营业地址"));titleList.add(Arrays.asList("经营范围"));titleList.add(Arrays.asList("业务板块"));titleList.add(Arrays.asList("业务模块在集团中的角色"));titleList.add(Arrays.asList("备注"));titleList.add(Arrays.asList("是否为并表单位"));titleList.add(Arrays.asList("法人代表"));titleList.add(Arrays.asList("财务负责人"));titleList.add(Arrays.asList("经理"));titleList.add(Arrays.asList("监事"));titleList.add(Arrays.asList("董事"));titleList.add(Arrays.asList("股权特殊安排"));titleList.add(Arrays.asList("抵押质押"));titleList.add(Arrays.asList("中介服务机构/秘书公司"));titleList.add(Arrays.asList("审计师")); + titleList.add(Arrays.asList("关连方")); + titleList.add(Arrays.asList("年报截止期")); + + + String fileName = UUID.randomUUID().toString().replace("-", "") + "excel.xlsx"; + File file = new File("/usr/weaver/ecology/filesystem/excel/"+fileName); + OutputStream out = new FileOutputStream(file); + //往文件写入数据 + ExcelWriter writer = new ExcelWriter(out, ExcelTypeEnum.XLSX); + Sheet sheet = new Sheet(1, 0); + sheet.setSheetName("sheet1"); + Table table = new Table(1); + //设置表头 + table.setHead(titleList); + //写入数据 + writer.write0(bodyList, sheet, table); + writer.finish(); + + + HashMap map = new HashMap<>(); + map.put("url", fileName); + return JSON.toJSONString(map); + + } + + + @GET + @Path("/getFile") + @Produces(MediaType.APPLICATION_OCTET_STREAM)//返回方式为流 + public Response getFile(@Context HttpServletRequest request) throws Exception { + + File file = new File("/usr/weaver/ecology/filesystem/excel/"+request.getParameter("fileName")); + return Response + .ok(new FileInputStream(file),MediaType.APPLICATION_OCTET_STREAM) + .header("content-disposition","attachment; filename = "+ java.net.URLEncoder.encode("企业信息列表.xlsx", "UTF-8")) + .build(); + } + + + + /** + * 导出架构表列表 + * @param request 企业ID + * @return Excel + * @throws IOException io流 + */ + @Path("/exportHisToExcel") + @POST + public String exportHisToExcel(@Context HttpServletRequest request) throws IOException { + log.writeLog("进入导出:"); + String[] qyid = request.getParameterValues("params[]"); + log.writeLog("导出企业的id:"+ Arrays.toString(qyid)); + RecordSet recordSet = new RecordSet(); + List> bodyList = new ArrayList<>(); + for (String str : qyid) { + String table = ""; + if ("c".equals(str.substring(0, 1))) { + str = str.replace("c", ""); + table = "uf_jingneiqiyexinxi"; + } else { + table = "formtable_main_3055"; + } + String sql = "select (select DHYJZDXX from uf_daohangyijizidua where id = a.dhyj) dhyj" + + ",(select dhej from uf_daohangerji where id = a.dhej) dhej" + + ",(select dhsj from uf_saohangsanji where id = a.dhsj) dhsj " + + " ,(select dhsj from uf_daohangsiji where id = a.dhsj1) dhsj1 " + + " ,(select dhwj from uf_daohangwuji where id = a.dhwj) dhwj" + + ",(select dhlj from uf_daohangliuji where id = a.dhlj) dhlj" + + ",(select dhqj from uf_daohangqiji where id = a.dhqj) dhqj " + + ", (select sfzxm from uf_guanliyuankuxin where id =a.gly) gly" + + ",qymc" + + ",(select GJDQK from uf_guojiadiquku where id = a.gbdq) gbdq" + + ",(select DLQ from uf_dailiqu where id=a.dlq) dlq" + + ",(select gslx from uf_gongsileixing where id=a.gslx) gslx" + + ",zym" + + ",ywm" + + ",clrq" + + ",shxydm" + + ",(select DJZT from uf_dengjizhuangtai where id=a.djzt) djzt" + + ",zczb" + + ",gs" + + ",(select bz from uf_bizhong where id=a.bz) bz" + + ",mgmz" + + ", dldflst" + + ",dz" + + ",yydz" + + ",jyfw" + + ",(select YWBK from uf_yewubankuai where id=a.ywbk) ywbk" + + ",(select YWMKZJTZDJS from uf_jituanzhongdejue where id=a.ywmkzjtzdjs) ywmkzjtzdjs" + + ",bz2" + + ",(select SFWBBDW from uf_shifouweibingbia where id = a.sfwbbdw) sfwbbdw" + + ", frdb" + + ", cwfzr" + + ", jl" + + ", js" + + ", ds" + + ",gqtsap" + + ",dyzy " + + ",zjfwjgmsgs" + + ",sjs,GLF,NBJZQ,id" + + " from "+table+" a where id = "+str; + + log.writeLog("导出 查找企业的SQL:"+sql); + + recordSet.execute(sql); +// ArrayList> mapArrayList = new ArrayList<>(); + + while (recordSet.next()) { + List list = new ArrayList<>(); + for (String s : recordSet.getColumnName()) { + if (!"ID".equals(s)){ + if ( "DS".equals(s) || "JS".equals(s) || "JL".equals(s) || "CWFZR".equals(s) || "FRDB".equals(s)) { + + list.add(Util.null2String(this.getRenYuan(recordSet.getString(s)))); + }else if ("GLF".equals(s)){ + list.add(Util.null2String("0".equals(recordSet.getString(s))?"YES":"NO")); + }else if ("DLDFLST".equals(s)){ + log.writeLog("独立的法律实体:"+recordSet.getString(s)); + if ("0".equals(recordSet.getString(s))) { + list.add("Yes"); + } else if ("1".equals(recordSet.getString(s))) { + list.add("No"); + } else { + list.add(" "); + } + }else if ("CLRQ".equals(s)){ + list.add(Util.null2String(recordSet.getString(s))); + list.add(gdStr(recordSet.getString("ID"),table)); + }else { + list.add(Util.null2String(recordSet.getString(s))); + } + } + } + bodyList.add(list); + } + } + List> titleList = new ArrayList<>(); + titleList.add(Arrays.asList("导航一级")); titleList.add(Arrays.asList("导航二级")); + titleList.add(Arrays.asList("导航三级")); + titleList.add(Arrays.asList("导航四级"));titleList.add(Arrays.asList("导航五级")); + titleList.add(Arrays.asList("导航六级"));titleList.add(Arrays.asList("导航七级")); + titleList.add(Arrays.asList("管理员"));titleList.add(Arrays.asList("企业名称")); + titleList.add(Arrays.asList("国别地区"));titleList.add(Arrays.asList("代理区")); + titleList.add(Arrays.asList("公司类型"));titleList.add(Arrays.asList("曾用名")); + titleList.add(Arrays.asList("外文名"));titleList.add(Arrays.asList("成立日期")); + titleList.add(Arrays.asList("登记股东/持股比例")); + titleList.add(Arrays.asList("社会信用代码"));titleList.add(Arrays.asList("登记状态")); + titleList.add(Arrays.asList("注册资本"));titleList.add(Arrays.asList("股数")); + titleList.add(Arrays.asList("币种"));titleList.add(Arrays.asList("每股面值")); + titleList.add(Arrays.asList("独立的法律实体"));titleList.add(Arrays.asList("注册地址")); + titleList.add(Arrays.asList("营业地址"));titleList.add(Arrays.asList("经营范围")); + titleList.add(Arrays.asList("业务板块"));titleList.add(Arrays.asList("业务模块在集团中的角色")); + titleList.add(Arrays.asList("备注"));titleList.add(Arrays.asList("是否为并表单位")); + + + + titleList.add(Arrays.asList("法人代表")); + titleList.add(Arrays.asList("财务负责人")); + titleList.add(Arrays.asList("经理")); + titleList.add(Arrays.asList("监事"));titleList.add(Arrays.asList("董事")); + titleList.add(Arrays.asList("股权特殊安排")); + titleList.add(Arrays.asList("抵押质押"));titleList.add(Arrays.asList("中介服务机构/秘书公司")); + titleList.add(Arrays.asList("审计师")); + titleList.add(Arrays.asList("关连方")); + titleList.add(Arrays.asList("年报截止期")); + + + String fileName = UUID.randomUUID().toString().replace("-", "") + "excel.xlsx"; + File file = new File("/usr/weaver/ecology/filesystem/excel/"+fileName); + OutputStream out = new FileOutputStream(file); + //往文件写入数据 + ExcelWriter writer = new ExcelWriter(out, ExcelTypeEnum.XLSX); + Sheet sheet = new Sheet(1, 0); + sheet.setSheetName("sheet1"); + Table table = new Table(1); + //设置表头 + table.setHead(titleList); + //写入数据 + writer.write0(bodyList, sheet, table); + writer.finish(); + + + HashMap map = new HashMap<>(); + map.put("url", fileName); + return JSON.toJSONString(map); + + + } + + + @Path("/getUserName") + @GET + public String getUserByUserName(@Context HttpServletRequest request) { + RecordSet recordSet = new RecordSet(); + String name = request.getParameter("name"); + + String sql = "select id,xm from uf_renyuanxinxiku where xm = '" + name+"'"; + log.writeLog("查找:"+name+"的id的SQL"+sql); + + recordSet.execute(sql); + recordSet.next(); + HashMap map = new HashMap<>(); + map.put("id", recordSet.getString("ID")); + map.put("name", recordSet.getString("xm")); + + if (recordSet.getString("ID").equals("")) { + map.put("status", "1"); + + } else { + map.put("msg", (User.getUser(1, 0).getLanguage() + "").equals("7") ? "请管理员到人员信息库创建此登录用户" : "Ask the administrator to create this login user in the personnel information base"); + map.put("status", "0"); + } + return JSON.toJSONString(map); + } + + + /** + * 导出明细表 + * @param request 企业id + * @return Excel + * @throws IOException io流异常 + */ + @Path("/exportDetailToExcel") + @GET + @Produces(MediaType.APPLICATION_OCTET_STREAM)//返回方式为流 + public Response exportDetailToExcel(@Context HttpServletRequest request) throws IOException { + String qyid = request.getParameter("id"); + RecordSet recordSet = new RecordSet(); + List> bodyList = new ArrayList<>(); + String sql = "select rq,bgxm,bgq,bgh,bz from uf_jingneiqiyexinxi_dt1 where mainid ="+qyid+" order by rq"; + sql = "select rq,bgxm,bgq,bgh,bz \n" + + "from formtable_main_3055_DT1 where mainid in (select id\n" + + "from formtable_main_3055 where qyid = "+qyid+" ) order by RQ, id"; + recordSet.execute(sql); + int i = 0; + while (recordSet.next()) { + i++; + List list = new ArrayList<>(); + list.add(Util.null2String(i)); + for (String s : recordSet.getColumnName()) { + list.add(Util.null2String(recordSet.getString(s))); + } + bodyList.add(list); + + } + List> titleList = new ArrayList<>(); + titleList.add(Arrays.asList("序号")); + titleList.add(Arrays.asList("变更日期")); + titleList.add(Arrays.asList("变更项目")); + titleList.add(Arrays.asList("变更前")); + titleList.add(Arrays.asList("变更后")); + titleList.add(Arrays.asList("备注")); + + File file = new File("/usr/weaver/ecology/filesystem/excel/"+UUID.randomUUID().toString().replace("-","")+"excel.xlsx"); + OutputStream out = new FileOutputStream(file); + //往文件写入数据 + ExcelWriter writer = new ExcelWriter(out, ExcelTypeEnum.XLSX); + Sheet sheet = new Sheet(1, 0); + sheet.setSheetName("sheet1"); + Table table = new Table(1); + //设置表头 + table.setHead(titleList); + //写入数据 + writer.write0(bodyList, sheet, table); + writer.finish(); + + return Response + .ok(new FileInputStream(file),MediaType.APPLICATION_OCTET_STREAM) + .header("content-disposition","attachment; filename = "+ java.net.URLEncoder.encode("企业信息变更表.xlsx", "UTF-8")) + .build(); + + } + + + + /** + * 导出架构表明细表 + * @param request 企业id + * @return Excel + * @throws IOException io流异常 + */ + @Path("/exportHisDetailToExcel") + @GET + @Produces(MediaType.APPLICATION_OCTET_STREAM)//返回方式为流 + public Response exportHisDetailToExcel(@Context HttpServletRequest request) throws IOException { + String qyid = request.getParameter("id"); + RecordSet recordSet = new RecordSet(); + List> bodyList = new ArrayList<>(); + String sql = "select rq,bgxm,bgq,bgh,bz from formtable_main_3055_dt1 where mainid ="+qyid+" order by ID"; + sql = "select rq,bgxm,bgq,bgh,bz \n" + + "from formtable_main_3055_DT1 where mainid in (select id\n" + + "from formtable_main_3055 where BBRQ<=(select BBRQ\n" + + "from formtable_main_3055 where id = "+qyid+") and qyid = (select QYID\n" + + "from formtable_main_3055 where id = "+qyid+") ) order by RQ , id"; + + recordSet.execute(sql); + int i = 0; + while (recordSet.next()) { + List list = new ArrayList<>(); + i++; + list.add(Util.null2String(i)); + for (String s : recordSet.getColumnName()) { + list.add(Util.null2String(recordSet.getString(s))); + } + bodyList.add(list); + } + List> titleList = new ArrayList<>(); + titleList.add(Arrays.asList("序号")); + titleList.add(Arrays.asList("变更日期")); + titleList.add(Arrays.asList("变更项目")); + titleList.add(Arrays.asList("变更前")); + titleList.add(Arrays.asList("变更后")); + titleList.add(Arrays.asList("备注")); + + File file = new File("/usr/weaver/ecology/filesystem/excel/"+UUID.randomUUID().toString().replace("-","")+"excel.xlsx"); + OutputStream out = new FileOutputStream(file); + //往文件写入数据 + ExcelWriter writer = new ExcelWriter(out, ExcelTypeEnum.XLSX); + Sheet sheet = new Sheet(1, 0); + sheet.setSheetName("sheet1"); + Table table = new Table(1); + //设置表头 + table.setHead(titleList); + //写入数据 + writer.write0(bodyList, sheet, table); + writer.finish(); + + return Response + .ok(new FileInputStream(file),MediaType.APPLICATION_OCTET_STREAM) + .header("content-disposition","attachment; filename = "+ java.net.URLEncoder.encode("企业信息变更表.xlsx", "UTF-8")) + .build(); + + } + + + + + public String getQymc(String qyid) { + qyid = DataBaseUtils.strNull(qyid); + RecordSet recordSet = new RecordSet(); + recordSet.execute("select qymc from uf_jingneiqiyexinxi where id = " + qyid); +// log.writeLog("寻找企业名称:"+"select qymc from uf_jingneiqiyexinxi where id = " + qyid); + + recordSet.next(); + String qymc = recordSet.getString("qymc"); + log.writeLog("qymc:"+qymc); + + return qymc; + } + public String getQyid(String qymc) { + RecordSet recordSet = new RecordSet(); + recordSet.execute("select id from uf_jingneiqiyexinxi where qymc = '"+qymc+"'" ); + recordSet.next(); + return recordSet.getString("id"); + } + + + public String getRenYuan(String value) { +// log.writeLog("获取的人员:"+value); + + String sql = ""; + String res = ""; + if (!value.equals("")) { + RecordSet recordSet = new RecordSet(); + String[] values = value.split(","); + + for (String s : values) { + if (!"".equals(s.trim())) { + + sql = "select xm from uf_renyuanxinxiku where id = " + s; + recordSet.execute(sql); + recordSet.next(); + res += recordSet.getString("xm")+" "; + } + } + + + } + log.writeLog("res:"+res); + + return res; + } + public String getFileNames(String value) { + log.writeLog("获取的文件名:"+value); + + String sql = ""; + String res = ""; + if (!value.equals("")) { + RecordSet recordSet = new RecordSet(); + String[] values = value.split(","); + + for (String s : values) { + if (!"".equals(s.trim())) { + + sql = "select IMAGEFILENAME from docimagefile where docid= " + s; + recordSet.execute(sql); + recordSet.next(); + res += recordSet.getString("IMAGEFILENAME")+";"; + } + } + } + log.writeLog("返回的文件:"+res); + + return res; + } + + public List> getUrl(String value) { + List> list = new ArrayList<>(); + RecordSet recordSet = new RecordSet(); + String sql = ""; + //人员信息库id + sql = "select id from modeinfo where formid = (select id from workflow_bill where tablename = 'uf_renyuanxinxiku')"; + recordSet.execute(sql); + recordSet.next(); + String rymodeId = recordSet.getString("ID"); + //获取表单id + sql = "select id from workflow_bill where tablename = 'uf_renyuanxinxiku'"; + recordSet.execute(sql); + recordSet.next(); + String ryformId = recordSet.getString("ID"); +// map.put("JLURL", "/spa/cube/index.html#/main/cube/card?type=0&modeId=" + rymodeId + "&formId=" + ryformId + "&billid=" + map.get("JL")); + String url = "/spa/cube/index.html#/main/cube/card?type=0&modeId=" + rymodeId + "&formId=" + ryformId + "&billid="; + + if (!value.equals("")) { + String[] values = value.split(","); + for (String s : values) { + if (!"".equals(s.trim())) { + sql = "select id,xm from uf_renyuanxinxiku where id = " + s; + recordSet.execute(sql); + recordSet.next(); + HashMap map = new HashMap<>(); + map.put("value", recordSet.getString("xm")); + map.put("url", url+recordSet.getString("id")); + list.add(map); + } + } + } + return list; + } + + public List> getWenJianUrl(String value) { + + + List> list = new ArrayList<>(); + RecordSet recordSet = new RecordSet(); + String sql = ""; + String url = "/spa/document/index2file.jsp?id="; + + if (!value.equals("")) { + String[] values = value.split(","); + for (String s : values) { + if (!"".equals(s.trim())) { + sql = "select IMAGEFILENAME,docid from docimagefile where docid= " + s; + recordSet.execute(sql); + recordSet.next(); + HashMap map = new HashMap<>(); + map.put("value", Util.null2String(recordSet.getString("IMAGEFILENAME"))); + map.put("url", Util.null2String(url+recordSet.getString("docid"))); + list.add(map); + } + } + } + return list; + } + + public String getGlyName(String id) { + RecordSet recordSet = new RecordSet(); + String sql = "select sfzxm from UF_GUANLIYUANKUXIN where id = " + Util.null2String(id); + + recordSet.execute(sql); + recordSet.next(); + return recordSet.getString("sfzxm"); + } + + /** + * 获取股东str + * @param id 企业id + * @param tableName 表名 + * @return str + */ + public String gdStr(String id,String tableName) { + String value = ""; + String sql = "select * from "+tableName+"_dt2 where mainid = "+id +" order by djgd"; +// log.writeLog("获取股东:"+sql); + + RecordSet recordSet = new RecordSet(); + recordSet.execute(sql); + while (recordSet.next()) { + value += "\n"+getGdName(recordSet.getString("djgd"))+"/"+recordSet.getString("CGBL")+"%、"; + } + + + return "".equals(value)?value:value.substring(0,value.length()-1); + } + + + /** + * 获取股东名字 企业、人员 + * @param gdname 股东 + * @return 名字 + */ + private String getGdName(String gdname) { + String s = DataBaseUtils.strNull(gdname); + String[] strs = s.split("_"); + + String sql = ""; + if (strs.length > 1) { + if ("qy".equals(strs[0])) { + sql = "select qymc name from uf_jingneiqiyexinxi where id = " + strs[1]; + } else { + sql = "select xm name from UF_RENYUANXINXIKU where id = " + strs[1]; + + } + } + + RecordSet recordSet = new RecordSet(); + recordSet.execute(sql); + recordSet.next(); + +// log.writeLog("查找新的股东:"+sql); + + + return recordSet.getString("name"); + } +} diff --git a/src/main/youhong_ai_jitu_src/jntchina/service/oa/OnetimeSalaryPaySearchAPI.java b/src/main/youhong_ai_jitu_src/jntchina/service/oa/OnetimeSalaryPaySearchAPI.java new file mode 100644 index 0000000..dbe3468 --- /dev/null +++ b/src/main/youhong_ai_jitu_src/jntchina/service/oa/OnetimeSalaryPaySearchAPI.java @@ -0,0 +1,115 @@ +package jntchina.service.oa; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.JSONArray; +import com.alibaba.fastjson.JSONObject; +import com.alibaba.fastjson.serializer.SerializerFeature; +import jntchina.util.HttpClientToDC; +import jntchina.util.JTHrmApiUtil; +import selfdev.util.log.LogTool; +import weaver.general.Util; + +import javax.servlet.http.HttpServletRequest; +import javax.ws.rs.POST; +import javax.ws.rs.Path; +import javax.ws.rs.Produces; +import javax.ws.rs.core.Context; +import java.util.*; + +/** + * @title: 一次性薪资发放查询接口api + * @Author KangMD + * @Date: 2022/04/09 + */ +@Path("/oa/OnetimeSalaryPaySearchAPI") +public class OnetimeSalaryPaySearchAPI { + private final LogTool log = new LogTool("/log/selfdev/rest/oa", false); + + + /** + * 获取申请人有权限的薪资组 + * @param request + * @return + */ + @POST + @Path("/getPayGroupList") + @Produces({"application/json"}) + public String getPayGroupList(@Context HttpServletRequest request) { + String workcode = Util.null2String(request.getParameter("workcode"));//工号 + log.writeLog("前端获取薪资组传入workcode------>"+workcode); + String str="[]";//返回结果 + //工号为空时返回空结果 + if("".equals(workcode)){ + return str; + } + try{ + Map map=new HashMap(); + map.put("LANGUAGE_CD","ZHS");//默认中国-ZHS + map.put("FIELDNAME","EMPL_PAYGP_"+workcode);//字段名 + //将传入参数map转成字符串 + String strParm = JSONObject.toJSONString(map, SerializerFeature.DisableCircularReferenceDetect); + log.writeLog("获取薪资组传入中台参数----------------->"+strParm); + //获取Token + String token = HttpClientToDC.getToken(); + log.writeLog("转换接口token------>" + token); + //调用接口获取数据 + JSONArray jsonArray = JTHrmApiUtil.translateValue(token, strParm); + if(jsonArray!=null){ + //转成字符串 + str=JSON.toJSONString(jsonArray, SerializerFeature.DisableCircularReferenceDetect); + } + log.writeLog("获取一次性薪酬发放薪资组返回结果--->"+str); + }catch (Exception e){ + log.writeLog("调用一次性薪酬发放薪资组接口异常,错误信息:"+e.toString()); + str="[]"; + } + return str; + } + + /** + * 获取日历ID + * @param request + * @return + */ + @POST + @Path("/getCalendarIDList") + @Produces({"application/json"}) + public String getCalendarIDList(@Context HttpServletRequest request) { + String workcode = Util.null2String(request.getParameter("workcode"));//工号 + String paygroup = Util.null2String(request.getParameter("paygroup"));//薪资组 + log.writeLog("前端获取日历传入workcode------>"+workcode); + log.writeLog("前端获取日历传入paygroup------>"+paygroup); + String str="[]";//返回结果 + //工号为空时返回空结果 + if("".equals(workcode)||"".equals(paygroup)){ + return str; + } + + try{ + Map map=new HashMap(); + map.put("LANGUAGE_CD","ZHS");//默认中国-ZHS + map.put("FIELDNAME","EMPL_PAYGP_CAL_ID_"+workcode+"_"+paygroup);//字段名 + //将传入参数map转成字符串 + String strParm = JSONObject.toJSONString(map, SerializerFeature.DisableCircularReferenceDetect); + log.writeLog("获取日历传入中台参数----------------->"+strParm); + //获取Token + String token = HttpClientToDC.getToken(); + log.writeLog("转换接口token------>" + token); + //调用接口获取数据 + JSONArray jsonArray = JTHrmApiUtil.translateValue(token, strParm); + if(jsonArray!=null){ + //转成字符串 + str=JSON.toJSONString(jsonArray, SerializerFeature.DisableCircularReferenceDetect); + } + log.writeLog("获取一次性薪酬发放日历ID返回结果--->"+str); + }catch (Exception e){ + log.writeLog("调用一次性薪酬发放日历ID接口异常,错误信息:"+e.toString()); + str="[]"; + } + return str; + } + + +} + + diff --git a/src/main/youhong_ai_jitu_src/jntchina/service/oa/ShangbiaoTemplate.java b/src/main/youhong_ai_jitu_src/jntchina/service/oa/ShangbiaoTemplate.java new file mode 100644 index 0000000..fcc3e7f --- /dev/null +++ b/src/main/youhong_ai_jitu_src/jntchina/service/oa/ShangbiaoTemplate.java @@ -0,0 +1,230 @@ +package jntchina.service.oa; + + +import com.alibaba.fastjson.JSON; +import selfdev.util.log.LogTool; +import weaver.conn.RecordSet; +import weaver.docs.webservices.DocAttachment; +import weaver.docs.webservices.DocInfo; +import weaver.docs.webservices.DocServiceImpl; + +import weaver.formmode.customjavacode.AbstractModeExpandJavaCodeNew; +import weaver.general.Util; +import weaver.hrm.User; +import weaver.soa.workflow.request.RequestInfo; + +import javax.imageio.ImageIO; +import java.awt.*; +import java.awt.image.BufferedImage; +import java.io.ByteArrayOutputStream; +import java.io.IOException; +import java.util.Base64; +import java.util.HashMap; +import java.util.Map; + +/** + * @title: ShangbiaoTemplate + * @Author ycf + * @Date: 2021/11/8 10:09 + * @Version 1.0 + */ +public class ShangbiaoTemplate extends AbstractModeExpandJavaCodeNew { + private final LogTool log = new LogTool("/log/api/shangB/", false); + + /** + * 执行模块扩展动作 + * @param param + * param包含(但不限于)以下数据 + * user 当前用户 + * importtype 导入方式(仅在批量导入的接口动作会传输) 1 追加,2覆盖,3更新,获取方式(int)param.get("importtype") + * 导入链接中拼接的特殊参数(仅在批量导入的接口动作会传输),比如a=1,可通过param.get("a")获取参数值 + * 页面链接拼接的参数,比如b=2,可以通过param.get("b")来获取参数 + * @return + */ + public Map doModeExpand(Map param) { + Map result = new HashMap(); + log.writeLog("参数:"+param); + + try { + User user = (User)param.get("user"); + log.writeLog("user:"+user); + + int billid = -1;//数据id + int modeid = -1;//模块id + RequestInfo requestInfo = (RequestInfo)param.get("RequestInfo"); + log.writeLog("param:"+param.toString()); + + if(requestInfo!=null){ + log.writeLog("requestInfo:"+requestInfo.toString()); + billid = Util.getIntValue(requestInfo.getRequestid()); + modeid = Util.getIntValue(requestInfo.getWorkflowid()); + log.writeLog("billid:"+billid); + log.writeLog("modeid:"+modeid); + + if(billid>0&&modeid>0){ + log.writeLog("requestInfo:"+requestInfo.toString()); + log.writeLog("param:"+ JSON.toJSONString(param)); + + String name = ""; + String by = ""; + RecordSet recordSet = new RecordSet(); + String sql = "select a.by1,sbmc qymc from uf_shangbiao a where a.id = " + billid ; + recordSet.execute(sql); + log.writeLog("sql:"+sql); + + while (recordSet.next()) { + by = Util.null2String(recordSet.getString("by1")); + log.writeLog("标样:"+by); + name = recordSet.getString("qymc"); + log.writeLog("企业名:"+name); + } + //如果标样是空,则自动生成 + if (by.equals("null") || by.equals("")) { + String base64 = this.getBase64(name); + log.writeLog("base64:"+base64); + DocServiceImpl docService=new DocServiceImpl();//OA知识接口 + DocInfo docInfo=new DocInfo(); //知识文档实体bean + docInfo.setMaincategory(0);//文档主目录 + docInfo.setSubcategory(0);//文档分目录 + recordSet.execute("select id from docseccategory where CATEGORYNAME= '标样'"); + recordSet.next(); + docInfo.setSeccategory(recordSet.getInt("ID")); + docInfo.setDocSubject(name+"商标");//文档标题 + //附件(一个附件创建一篇文档) + DocAttachment[] da =new DocAttachment[1]; + da[0]=new DocAttachment(); + da[0].setDocid(0); + da[0].setImagefileid(0); + recordSet.execute("select needzip,needzipencrypt from systemset"); + while (recordSet.next()) { + da[0].setIszip(recordSet.getInt("NEEDZIP"));//是否压缩 + da[0].setIsencrype(recordSet.getInt("NEEDZIPENCRYPT"));//是否加密 + log.writeLog("是否压缩:"+recordSet.getInt("NEEDZIP")); + log.writeLog("是否加密:"+recordSet.getInt("NEEDZIPENCRYPT")); + } + da[0].setFilename(name+".jpeg");//附件名 + da[0].setFilecontent(base64); + //将附件添加到文档中 + docInfo.setAttachments(da); + User localUser = User.getUser(1,0); + //创建文档 + try { + int docid=docService.createDocByUser(docInfo, localUser); + String sql2 = "update uf_shangbiao set by1 = "+docid+" where id = "+billid; + log.writeLog("sql2:"+sql2); + recordSet.execute(sql2); + } catch (Exception e) { + e.printStackTrace(); + } + } + } + } + } catch (Exception e) { + result.put("errmsg",e.toString()); + log.writeLog("错误:"+e.toString()); + + result.put("flag", "false"); + } + return result; + } + + public String getBase64(String name) { + + BufferedImage bufImg = null; + + int nameL = name.length(); + log.writeLog("公司名长度:"+nameL); + + //生成中文的公司标样 + if (!name.trim().substring(0, 1).matches("^[a-zA-Z]*")) { + bufImg = new BufferedImage(500, 500, BufferedImage.TYPE_INT_RGB); + Graphics2D g2 = (Graphics2D) bufImg.getGraphics(); + g2.setColor(new Color(255, 255, 255)); + g2.fillRect(0, 0, 500, 500); + g2.setColor(new Color(0, 0, 0)); + //2*3布局 + if (nameL <= 3) { + g2.setFont(new Font("宋体", Font.BOLD, 100)); + g2.drawString(name, 100, 200); + System.out.println(nameL % 2); + }else if (nameL <= 6) { + g2.setFont(new Font("宋体", Font.BOLD, 100)); + g2.drawString(name.substring(0, 3), 100, 200); + g2.drawString(name.substring(3, nameL), nameL == 6 ? 100 : 500 / 2 - nameL % 3 * 50, 350); + System.out.println(nameL % 2); + } else if (nameL <= 9) { + //3*3布局 + g2.setFont(new Font("宋体", Font.BOLD, 100)); + g2.drawString(name.substring(0, 3), 100, 150); + g2.drawString(name.substring(3, 6), 100, 270); + g2.drawString(name.substring(6, nameL), nameL == 9 ? 100 : 500 / 2 - nameL % 3 * 50, 390); + System.out.println(nameL % 2); + } else if (nameL <= 12) { + //3*4布局 + g2.setFont(new Font("宋体", Font.BOLD, 80)); + g2.drawString(name.substring(0, 4), 80, 150); + g2.drawString(name.substring(4, 8), 80, 270); + g2.drawString(name.substring(8, nameL), nameL == 12 ? 80 : 500 / 2 - nameL % 4 * 40, 390); + System.out.println(nameL % 2); + } else if (nameL <= 16) { +// 4*4布局 + g2.setFont(new Font("宋体", Font.BOLD, 80)); + g2.drawString(name.substring(0, 4), 80, 120); + g2.drawString(name.substring(4, 8), 80, 230); + g2.drawString(name.substring(8, 12), 80, 340); + g2.drawString(name.substring(12, nameL), nameL == 16 ? 80 : 500 / 2 - nameL % 4 * 40, 450); + System.out.println(nameL % 2); + } else if (nameL <= 20) { + g2.setFont(new Font("宋体", Font.BOLD, 72)); + g2.drawString(name.substring(0, 5), 62, 120); + g2.drawString(name.substring(5, 10), 62, 230); + g2.drawString(name.substring(10, 15), 62, 340); + g2.drawString(name.substring(15, nameL), nameL == 20 ? 62 : 500 / 2 - nameL % 5 * 36, 450); + System.out.println(500 / 2 - nameL % 4 * 30); + } else if (nameL <= 25) { + g2.setFont(new Font("宋体", Font.BOLD, 72)); + g2.drawString(name.substring(0, 5), 62, 100); + g2.drawString(name.substring(5, 10), 62, 190); + g2.drawString(name.substring(10, 15), 62, 280); + g2.drawString(name.substring(15, 20), 62, 370); + g2.drawString(name.substring(20, nameL), nameL == 25 ? 62 : 500 / 2 - nameL % 5 * 36, 460); + + } else if (nameL <= 30) { + g2.setFont(new Font("宋体", Font.BOLD, 72)); + g2.drawString(name.substring(0, 5), 62, 80); + g2.drawString(name.substring(5, 10), 62, 160); + g2.drawString(name.substring(10, 15), 62, 240); + g2.drawString(name.substring(15, 20), 62, 320); + g2.drawString(name.substring(20, 25), 62, 400); + g2.drawString(name.substring(25, nameL), nameL == 30 ? 62 : 500 / 2 - nameL % 5 * 36, 480); + System.out.println(500 / 2 - nameL % 4 * 30); + } + } else { + + int wid = name.length() * 28 + 80; + + bufImg = new BufferedImage(wid, 200, BufferedImage.TYPE_INT_RGB); + Graphics2D g2 = (Graphics2D) bufImg.getGraphics(); + g2.setColor(new Color(255, 255, 255)); + g2.fillRect(0, 0, wid, 200); + g2.setColor(new Color(0, 0, 0)); + //英文 + g2.setFont(new Font("Times New Roma", Font.BOLD, 50)); + g2.drawString(name, 50, 100); + + } + String base64 = ""; + ByteArrayOutputStream stream = new ByteArrayOutputStream(); + try { + ImageIO.write(bufImg, "JPEG", stream); + base64 = Base64.getEncoder().encodeToString(stream.toByteArray()); + + } catch (IOException e) { + e.printStackTrace(); + } + + return base64; + + + } +} diff --git a/src/main/youhong_ai_jitu_src/jntchina/service/oa/ShangbiaoTemplateChange.java b/src/main/youhong_ai_jitu_src/jntchina/service/oa/ShangbiaoTemplateChange.java new file mode 100644 index 0000000..9361cf1 --- /dev/null +++ b/src/main/youhong_ai_jitu_src/jntchina/service/oa/ShangbiaoTemplateChange.java @@ -0,0 +1,233 @@ +package jntchina.service.oa; + + +import com.alibaba.fastjson.JSON; +import selfdev.util.log.LogTool; +import weaver.conn.RecordSet; +import weaver.docs.webservices.DocAttachment; +import weaver.docs.webservices.DocInfo; +import weaver.docs.webservices.DocServiceImpl; +import weaver.formmode.customjavacode.AbstractModeExpandJavaCodeNew; +import weaver.general.Util; +import weaver.hrm.User; +import weaver.soa.workflow.request.RequestInfo; + +import javax.imageio.ImageIO; +import java.awt.*; +import java.awt.image.BufferedImage; +import java.io.ByteArrayOutputStream; +import java.io.IOException; +import java.util.Base64; +import java.util.HashMap; +import java.util.Map; + +; + +/** + * @title: ShangbiaoTemplate + * @Author ycf + * @Date: 2021/11/8 10:09 + * @Version 1.0 + */ +public class ShangbiaoTemplateChange extends AbstractModeExpandJavaCodeNew { + private final LogTool log = new LogTool("/log/api/shangB/", false); + + /** + * 执行模块扩展动作 + * @param param + * param包含(但不限于)以下数据 + * user 当前用户 + * importtype 导入方式(仅在批量导入的接口动作会传输) 1 追加,2覆盖,3更新,获取方式(int)param.get("importtype") + * 导入链接中拼接的特殊参数(仅在批量导入的接口动作会传输),比如a=1,可通过param.get("a")获取参数值 + * 页面链接拼接的参数,比如b=2,可以通过param.get("b")来获取参数 + * @return r + */ + public Map doModeExpand(Map param) { + Map result = new HashMap(); + log.writeLog("参数:"+param); + + try { + User user = (User)param.get("user"); + log.writeLog("user:"+user); + + int billid = -1;//数据id + int modeid = -1;//模块id + RequestInfo requestInfo = (RequestInfo)param.get("RequestInfo"); + log.writeLog("param:"+param.toString()); + + if(requestInfo!=null){ + log.writeLog("requestInfo:"+requestInfo.toString()); + billid = Util.getIntValue(requestInfo.getRequestid()); + modeid = Util.getIntValue(requestInfo.getWorkflowid()); + log.writeLog("billid:"+billid); + log.writeLog("modeid:"+modeid); + + if(billid>0&&modeid>0){ + log.writeLog("requestInfo:"+requestInfo.toString()); + log.writeLog("param:"+ JSON.toJSONString(param)); + + String name = ""; + String by = ""; + RecordSet recordSet = new RecordSet(); + String sql = "select a.by1,sbmc qymc from uf_shangbiao a where a.id = " + billid ; + recordSet.execute(sql); + log.writeLog("sql:"+sql); + + while (recordSet.next()) { + by = Util.null2String(recordSet.getString("by1")); + log.writeLog("标样:"+by); + name = recordSet.getString("qymc"); + log.writeLog("企业名:"+name); + } + + String base64 = this.getBase64(name); + log.writeLog("base64:"+base64); + + DocServiceImpl docService=new DocServiceImpl();//OA知识接口 + DocInfo docInfo=new DocInfo(); //知识文档实体bean + docInfo.setMaincategory(0);//文档主目录 + docInfo.setSubcategory(0);//文档分目录 + recordSet.execute("select id from docseccategory where CATEGORYNAME= '标样'"); + recordSet.next(); + docInfo.setSeccategory(recordSet.getInt("ID")); + docInfo.setDocSubject(name+"商标");//文档标题 + //附件(一个附件创建一篇文档) + DocAttachment da[]=new DocAttachment[1]; + da[0]=new DocAttachment(); + da[0].setDocid(0); + da[0].setImagefileid(0); + recordSet.execute("select needzip,needzipencrypt from systemset"); + while (recordSet.next()) { + da[0].setIszip(recordSet.getInt("NEEDZIP"));//是否压缩 + da[0].setIsencrype(recordSet.getInt("NEEDZIPENCRYPT"));//是否加密 + log.writeLog("是否压缩:"+recordSet.getInt("NEEDZIP")); + log.writeLog("是否加密:"+recordSet.getInt("NEEDZIPENCRYPT")); + } + da[0].setFilename(name+".jpeg");//附件名 + da[0].setFilecontent(base64); + //将附件添加到文档中 + docInfo.setAttachments(da); + User localUser = User.getUser(1,0); + //创建文档 + try { + int docid=docService.createDocByUser(docInfo, localUser); + String sql2 = "update uf_shangbiao set by1 = "+docid+" where id = "+billid; + log.writeLog("sql2:"+sql2); + + recordSet.execute(sql2); + + + } catch (Exception e) { + e.printStackTrace(); + } + } + + } + } catch (Exception e) { + result.put("errmsg",e.toString()); + log.writeLog("错误:"+e.toString()); + + result.put("flag", "false"); + } + return result; + } + + public String getBase64(String name) { + + BufferedImage bufImg = null; + + int nameL = name.length(); + log.writeLog("公司名长度:"+nameL); + + //生成中文的公司标样 + if (!name.trim().substring(0, 1).matches("^[a-zA-Z]*")) { + bufImg = new BufferedImage(500, 500, BufferedImage.TYPE_INT_RGB); + Graphics2D g2 = (Graphics2D) bufImg.getGraphics(); + g2.setColor(new Color(255, 255, 255)); + g2.fillRect(0, 0, 500, 500); + g2.setColor(new Color(0, 0, 0)); + //2*3布局 + if (nameL <= 3) { + g2.setFont(new Font("宋体", Font.BOLD, 100)); + g2.drawString(name, 100, 200); + System.out.println(nameL % 2); + }else if (nameL <= 6) { + g2.setFont(new Font("宋体", Font.BOLD, 100)); + g2.drawString(name.substring(0, 3), 100, 200); + g2.drawString(name.substring(3, nameL), nameL == 6 ? 100 : 500 / 2 - nameL % 3 * 50, 350); + System.out.println(nameL % 2); + } else if (nameL <= 9) { + //3*3布局 + g2.setFont(new Font("宋体", Font.BOLD, 100)); + g2.drawString(name.substring(0, 3), 100, 150); + g2.drawString(name.substring(3, 6), 100, 270); + g2.drawString(name.substring(6, nameL), nameL == 9 ? 100 : 500 / 2 - nameL % 3 * 50, 390); + System.out.println(nameL % 2); + } else if (nameL <= 12) { + //3*4布局 + g2.setFont(new Font("宋体", Font.BOLD, 80)); + g2.drawString(name.substring(0, 4), 80, 150); + g2.drawString(name.substring(4, 8), 80, 270); + g2.drawString(name.substring(8, nameL), nameL == 12 ? 80 : 500 / 2 - nameL % 4 * 40, 390); + System.out.println(nameL % 2); + } else if (nameL <= 16) { +// 4*4布局 + g2.setFont(new Font("宋体", Font.BOLD, 80)); + g2.drawString(name.substring(0, 4), 80, 120); + g2.drawString(name.substring(4, 8), 80, 230); + g2.drawString(name.substring(8, 12), 80, 340); + g2.drawString(name.substring(12, nameL), nameL == 16 ? 80 : 500 / 2 - nameL % 4 * 40, 450); + System.out.println(nameL % 2); + } else if (nameL <= 20) { + g2.setFont(new Font("宋体", Font.BOLD, 72)); + g2.drawString(name.substring(0, 5), 62, 120); + g2.drawString(name.substring(5, 10), 62, 230); + g2.drawString(name.substring(10, 15), 62, 340); + g2.drawString(name.substring(15, nameL), nameL == 20 ? 62 : 500 / 2 - nameL % 5 * 36, 450); + System.out.println(500 / 2 - nameL % 4 * 30); + } else if (nameL <= 25) { + g2.setFont(new Font("宋体", Font.BOLD, 72)); + g2.drawString(name.substring(0, 5), 62, 100); + g2.drawString(name.substring(5, 10), 62, 190); + g2.drawString(name.substring(10, 15), 62, 280); + g2.drawString(name.substring(15, 20), 62, 370); + g2.drawString(name.substring(20, nameL), nameL == 25 ? 62 : 500 / 2 - nameL % 5 * 36, 460); + + } else if (nameL <= 30) { + g2.setFont(new Font("宋体", Font.BOLD, 72)); + g2.drawString(name.substring(0, 5), 62, 80); + g2.drawString(name.substring(5, 10), 62, 160); + g2.drawString(name.substring(10, 15), 62, 240); + g2.drawString(name.substring(15, 20), 62, 320); + g2.drawString(name.substring(20, 25), 62, 400); + g2.drawString(name.substring(25, nameL), nameL == 30 ? 62 : 500 / 2 - nameL % 5 * 36, 480); + System.out.println(500 / 2 - nameL % 4 * 30); + } + } else { + System.out.println(name.length()); + bufImg = new BufferedImage(name.length()*27+45, 200, BufferedImage.TYPE_INT_RGB); + Graphics2D g2 = (Graphics2D) bufImg.getGraphics(); + g2.setColor(new Color(255, 255, 255)); + g2.fillRect(0, 0, name.length()*27+45, 200); + g2.setColor(new Color(0, 0, 0)); + //英文 + g2.setFont(new Font("Times New Roma", Font.BOLD, 50)); + g2.drawString(name, 50, 100); + + } + String base64 = ""; + ByteArrayOutputStream stream = new ByteArrayOutputStream(); + try { + ImageIO.write(bufImg, "JPEG", stream); + base64 = Base64.getEncoder().encodeToString(stream.toByteArray()); + log.writeLog("base64:"+base64); + + } catch (IOException e) { + e.printStackTrace(); + } + + return base64; + + + } +} diff --git a/src/main/youhong_ai_jitu_src/jntchina/service/oa/util/ModifyDetailInfo.java b/src/main/youhong_ai_jitu_src/jntchina/service/oa/util/ModifyDetailInfo.java new file mode 100644 index 0000000..7d34e7a --- /dev/null +++ b/src/main/youhong_ai_jitu_src/jntchina/service/oa/util/ModifyDetailInfo.java @@ -0,0 +1,680 @@ +package jntchina.service.oa.util; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.JSONArray; +import com.alibaba.fastjson.JSONObject; +import com.engine.demo.impl.BaseUtil; +import com.engine.demo.impl.CubeSaveInterccept; +import com.engine.demo.impl.TransField; +import selfdev.util.log.LogTool; +import weaver.conn.RecordSet; +import weaver.general.Util; +import weaver.hrm.User; + +import java.text.SimpleDateFormat; +import java.util.ArrayList; +import java.util.List; +import java.util.Set; + +/** + * + * 明细数据修改 + * 修改日期当做key 也就是一个版本 + * 按照日期 降序 排列 + * 版本包含了 新增以及修改以前的历史版本 数据 + * + * + */ +public class ModifyDetailInfo { + private final static LogTool log = new LogTool("/log/ModifyDetailInfo/",false); + private List dateVersion=new ArrayList<>();//日期版本数据 + private static final String remarkField="";//备注字段 + private static final String imageField="";//日期字段 + private JSONObject jsonVersion=new JSONObject();//版本JSON + private String field="";//明细表字段信息 + private String fromtableName="";//表名称 + private String totableName="";//表名称 + private int modeid=0;//模块ID + private int billid=0;//数据ID + private int formid=-3054;//数据ID uat -1793 prd -3054 + private String qyid="";//企业ID + private String changeFj="";//变更附件 + private String changeRemark="";//变更备注 + private JSONObject changeFjJson=new JSONObject();//变更附件 + private JSONObject changeRemarkJson=new JSONObject();//变更备注 + private String detailtabledesc="";//明细字段 + private int newVersionDateIndex=-1;//最新的版本日期 + + public ArrayList sortDate=new ArrayList();//存储版本时间的数据 + public ArrayList addsortDate=new ArrayList();//新增版本 存储版本时间的数据 + public JSONObject fieldJson=new JSONObject(); + + public ModifyDetailInfo(String field,String fromtableName,String totableName,int modeid,int billid,String qyid){ + this.field=field; + this.fromtableName=fromtableName; + this.totableName=totableName; + this.modeid=modeid; + this.billid=billid; + this.qyid=qyid; + + } + + public JSONObject getChangeFjJson() { + return changeFjJson; + } + + public void setChangeFjJson(JSONObject changeFjJson) { + this.changeFjJson = changeFjJson; + } + + public JSONObject getChangeRemarkJson() { + return changeRemarkJson; + } + + public void setChangeRemarkJson(JSONObject changeRemarkJson) { + this.changeRemarkJson = changeRemarkJson; + } + + public JSONObject getJsonVersion() { + return jsonVersion; + } + + public void setJsonVersion(JSONObject jsonVersion) { + this.jsonVersion = jsonVersion; + } + + public ModifyDetailInfo(){ + } + + public String getChangeFj() { + return changeFj; + } + + public void setChangeFj(String changeFj) { + this.changeFj = changeFj; + } + + public String getChangeRemark() { + return changeRemark; + } + + public void setChangeRemark(String changeRemark) { + this.changeRemark = changeRemark; + } + + public String getDetailtabledesc() { + return detailtabledesc; + } + + public void setDetailtabledesc(String detailtabledesc) { + this.detailtabledesc = detailtabledesc; + } + + public int getNewVersionDate() { + return newVersionDateIndex; + } + + public void setNewVersionDate(int newVersionDate) { + this.newVersionDateIndex = newVersionDate; + } + + public void setDtailJson(){ + iniVersionDate();//初始化版本日期 + log.writeLog(this.sortDate.toString()); + //this.newVersionDateIndex=this.sortDate.size(); + if(this.sortDate.size()>0){ + this.newVersionDateIndex=this.sortDate.size()-1;//最新的版本位置 + } + TransField transField=new TransField(); + detailtabledesc=transField.getFeildnameByNames(replaceStr(field,"bz"), totableName, 1); + RecordSet recordSet=new RecordSet(); + String sql="select * from "+totableName+" where mainid="+this.billid+" and length(nvl(rq,''))>0 order by rq"; + log.writeLog(sql); + recordSet.execute(sql); + while(recordSet.next()){ + int type=0;//0新增 1修改 + JSONObject checkJson=new JSONObject(); + String detailid=Util.null2String(recordSet.getString("detailid")).trim(); + String fj=Util.null2String(recordSet.getString("fj")).trim();//变更附件 + String rq=Util.null2String(recordSet.getString("rq")).trim(); + if(!"".equals(fj)){ + if(changeFjJson.containsKey(rq)){ + changeFj=changeFj+fj+","; + String fjStr=Util.null2String(changeFjJson.getString(rq)).trim() ; + fjStr=fjStr+fj+","; + changeFjJson.put(rq,fjStr); + }else{ + changeFjJson.put(rq,fj); + } + } + String bz1=Util.null2String(recordSet.getString("bz1")).trim();//变更备注 + if(!"".equals(bz1)){ + changeRemark=changeRemark+bz1+"\n"; + if(changeRemarkJson.containsKey(rq)){ + String remarkStr=Util.null2String(changeRemarkJson.getString(rq)).trim() ; + remarkStr=remarkStr+fj+"\n"; + changeRemarkJson.put(rq,remarkStr); + }else{ + changeRemarkJson.put(rq,bz1); + } + } + for(String str:field.split(",")){ + str= Util.null2String(str).trim(); + if(str.equals("")){ + continue; + } + checkJson.put(str,Util.null2String(recordSet.getString(str))); + } + checkJson.put("isChange","1"); + if("".equals(detailid)){//新增 + type=0; + }else{ + JSONObject oldJSONObject= getDetailData(detailid); + log.writeLog(oldJSONObject.toJSONString()); + boolean flag=fastJsonDiff.compareJsons(checkJson,oldJSONObject,null); + if(flag){//代表有改变 + log.writeLog("data not modify!"); + continue;//开启下一次的循环 + }else{ + log.writeLog("data modify!"); + } + type=1; + } + JSONObject rqversion= jsonVersion.getJSONObject(rq);//日期版本 (需要) + if(rqversion==null||rqversion.size()<=0){ + //获取日期的版本 信息 需要加日期数据进行版本的叠加 + JSONObject endDateVersionData=new JSONObject(); + JSONArray olddata=new JSONArray(); + /** 先判断 版本日期是否存在 初始化的版本里面 **/ + String oldversiondate="";//getVersionDate(rq);//最新版本 或者是 前一个版本的日期 + String historyVersionDate=getVersionDate(rq);//判断日期 是否是最新的 修改版本 为空则是 + + if("".equals(historyVersionDate)){//当前最新 修改版本 如果日期是最新的第二个版本以及之后的版本 则主要 拿前一个版本的数据 + int versionIndex=sortDateArray(rq,this.sortDate); + if(versionIndex-newVersionDateIndex>=2){ + oldversiondate=this.sortDate.get(versionIndex-1);//获取上一个版本的数据 + }else{ + if(versionIndex>0){ + oldversiondate=this.sortDate.get(versionIndex); + }else{ + oldversiondate=rq; + } + } + }else{ + int versionIndex=sortDateArray(rq,this.sortDate); + if(versionIndex>0){ + int newindex= getAddSortDateAbove(addsortDate,historyVersionDate); + if(newindex>-1){ + oldversiondate=addsortDate.get(newindex);//this.sortDate.get(versionIndex-1); + }else{ + oldversiondate=historyVersionDate; + } + }else{ + oldversiondate=historyVersionDate; + } + + } + JSONArray DateVersionData=null; +// if(versionIndex>0){ +// oldversiondate=this.sortDate.get(versionIndex-1); +// } + checkJson.put("type",type);//0 新增 1 修改 + checkJson.put("bbrq",rq); + log.writeLog("oldversiondate-->"+oldversiondate); + if("".equals(oldversiondate)){ + DateVersionData=checkDateVersion(oldversiondate);//获取修改前的版本数据 + }else{ + if(addsortDate.contains(oldversiondate)){ + + } + if(addsortDate.contains(oldversiondate)&&jsonVersion.containsKey(oldversiondate)){ + log.writeLog("isvali"); + DateVersionData=CopyJSONArray(jsonVersion.getJSONObject(oldversiondate).getJSONArray("data")); + //relpaceJSONArray(DateVersionData,CopyJSONObject(checkJson),detailid);//添加或者修改 + }else{ + log.writeLog("is not vali"); + DateVersionData=checkDateVersion(oldversiondate); + log.writeLog("DateVersionData-->"+DateVersionData.toJSONString()); + } + } + olddata=CopyJSONArray(DateVersionData); + if(type==0){ + DateVersionData.add(CopyJSONObject(checkJson)); + }else{ + //修改 通过 detailid 去替换 + log.writeLog(DateVersionData.toJSONString()+"replace-->"+detailid+" "+CopyJSONObject(checkJson).toJSONString()); + relpaceJSONArray(DateVersionData,CopyJSONObject(checkJson),detailid); + } + //JSONArray DateVersionData=checkDateVersion(rq);//获取修改前的版本数据 + endDateVersionData.put("data",DateVersionData); + endDateVersionData.put("olddata",olddata);//复制一下 保存起来 当做变更前的数据 + endDateVersionData.put("rq",rq); + if(!addsortDate.contains(rq)){ + addsortDate.add(rq);//保存 新增的 版本信息 + } + jsonVersion.put(rq,endDateVersionData); + }else{ + JSONArray DateVersionData=rqversion.getJSONArray("data"); + if(type==0){ + checkJson.put("bbrq",rq); + DateVersionData.add(checkJson); + }else{ + //修改 通过 detailid 去替换 + log.writeLog(" replace -->"+DateVersionData.toJSONString()); + relpaceJSONArray(DateVersionData,CopyJSONObject(checkJson),detailid); + } + } + } + //数据转换 + if(this.jsonVersion!=null&&this.jsonVersion.size()>0){ + Set keys=this.jsonVersion.keySet(); + for(String key:keys){ + JSONObject jsonVersionSingle= this.jsonVersion.getJSONObject(key); + if(jsonVersionSingle!=null&&jsonVersionSingle.size()>0){ + String rowDesc=getStrByJSON(jsonVersionSingle.getJSONArray("data"),true); + jsonVersionSingle.put("rowDesc",rowDesc); + jsonVersionSingle.put("fj",changeFjJson.getString(key)); + jsonVersionSingle.put("bz",changeRemarkJson.getString(key)); + String oldrowDesc=getStrByJSON(jsonVersionSingle.getJSONArray("olddata"),false); + jsonVersionSingle.put("oldrowDesc",oldrowDesc); + } + + } + } + log.writeLog("jsonVersion"+jsonVersion.toJSONString()); + log.writeLog("jsonVersion"+this.toString()); + } + + public JSONObject getDetailData(String detailid){ + JSONObject json=new JSONObject(); + RecordSet recordSet=new RecordSet(); + String sql="select * from "+fromtableName+" where mainid="+this.billid+" and detailid="+detailid; + recordSet.execute(sql); + if(recordSet.next()){ + for(String str:field.split(",")){ + str= Util.null2String(str).trim(); + if(str.equals("")){ + continue; + } + json.put(str,Util.null2String(recordSet.getString(str))); + } + } + return json; + } + + /** + * 获取日期的版本数据 + * @param date + * @return + */ + public JSONArray checkDateVersion( String date){ + JSONArray jsons=new JSONArray(); + JSONObject json=new JSONObject(); + RecordSet re=new RecordSet(); + boolean flag=false; + String sql="select * from "+ CubeSaveInterccept.CompanyVersionMaintable+" where qyid='"+this.qyid+"' and bbrq='"+date+"'"; + re.execute(sql); + if(re.next()){ + flag =true; + } + log.writeLog("CubeSaveInterccept.CompanyVersionMaintable==>"+CubeSaveInterccept.CompanyVersionMaintable); + if(flag){//存在修改的版本 + sql="select b.mainbillid,"+getSqlField("b")+" ,-1 leve from "+CubeSaveInterccept.CompanyVersionMaintable+" a,"+CubeSaveInterccept.CompanyVersionMaintable+"_dt2 b where a.id=b.mainid and a.qyid='"+this.qyid+"' and a.bbrq='"+date+"'"; + }else{//不存在取最新的数据(获取 ) + sql="select * from (" + + " select * from (select a.bbrq,b.mainbillid,"+getSqlField("b")+",0 ver,row_number() over(partition by a.bbrq ORDER BY a.bbrq ASC ) leve from "+CubeSaveInterccept.CompanyVersionMaintable+" a,"+CubeSaveInterccept.CompanyVersionMaintable+"_dt2 b where a.id=b.mainid and a.qyid='"+this.qyid+"' and a.bbrq<'"+date+"' order by a.bbrq desc) " + + //" union all " + + //"select b.mainbillid,b."+field+",1 ver,row_number() over(partition by a.bbrq ORDER BY a.bbrq ASC ) leve from "+CubeSaveInterccept.CompanyVersionMaintable+" a,"+CubeSaveInterccept.CompanyVersionMaintable+"_dt2 b where a.id=b.mainid and a.qyid='"+this.qyid+"' and leve=1 "+ + //" union all " + + //"select id mainbillid,"+field+",1 ver,99 leve from "+CubeSaveInterccept.CompanyMaintable+"_dt2 where mainid='"+this.qyid+"' " + + ") g order by ver asc "; + } + log.writeLog(sql); + String leve=""; + re.executeQuery(sql); + int i=0; + while(re.next()){ + log.writeLog(i); + i++; + json=new JSONObject(); + if("".equals(leve)){ + leve=Util.null2String(re.getString("bbrq")); + }else{ + if(!leve.equals(Util.null2String(re.getString("bbrq")))){ + break; + } + } + for(String str:(field+",mainbillid").split(",")){ + str= Util.null2String(str).trim(); + if(str.equals("")){ + continue; + } + json.put(str,Util.null2String(re.getString(str))); + } + jsons.add(json); + } + + return jsons; + } + + public JSONArray CopyJSONArray(JSONArray jsons){ + if(jsons==null||jsons.size()<=0){ + return new JSONArray(); + } + String newjson=JSON.toJSONString(jsons); + return JSONObject.parseArray(newjson); + } + public JSONObject CopyJSONObject(JSONObject jsons){ + if(jsons==null||jsons.size()<=0){ + return new JSONObject(); + } + String newjson=JSON.toJSONString(jsons); + return JSONObject.parseObject(newjson); + } + public void relpaceJSONArray(JSONArray fromjsons,JSONObject tojson,String detailid){ + if(tojson==null||tojson.size()<=0){ + fromjsons=new JSONArray(); + } + if(tojson.containsKey("mainbillid")){ + detailid=Util.null2String(tojson.getString("mainbillid")) ; + } + if(fromjsons==null||fromjsons.size()<=0){ + if(fromjsons==null){ + fromjsons=new JSONArray(); + } + tojson.put("mainbillid",detailid); + fromjsons.add(tojson); + return; + } + JSONArray newfromjsons=new JSONArray(); + boolean isVali=false; + for(int i=0;i0){ + fromjsons.clear(); + fromjsons.addAll(newfromjsons); + } + } + + /** + * 获取版本日期 + * @param date + * @return + */ + public String getVersionDate(String date){ + RecordSet re=new RecordSet(); + String versiondate=""; + String sql="select * from "+ CubeSaveInterccept.CompanyVersionMaintable+" where qyid='"+this.qyid+"' and bbrq='"+date+"'"; + re.execute(sql); + if(re.next()){ + return date; + } +// sql="select * from (select a.bbrq,0 ver,row_number() over(partition by a.bbrq ORDER BY a.bbrq ASC ) leve from "+CubeSaveInterccept.CompanyVersionMaintable+" a,"+CubeSaveInterccept.CompanyVersionMaintable+"_dt2 b where a.id=b.mainid and a.qyid='"+this.qyid+"' and a.bbrq<'"+date+"' order by a.bbrq desc ) where leve=1" ; +// log.writeLog(sql); +// re.execute(sql); +// if(re.next()){ +// return Util.null2String(re.getString("bbrq")).trim(); +// } + return ""; + } + + /** + * 初始化版本信息 + */ + public void iniVersionDate(){ + RecordSet re=new RecordSet(); + String versiondate=""; + String sql="select * from "+ CubeSaveInterccept.CompanyVersionMaintable+" where qyid='"+this.qyid+"' order by bbrq"; + + re.execute(sql); + while(re.next()){ + String bbrq=Util.null2String(re.getString("bbrq")).trim(); + if("".equals(bbrq)){ + continue; + } + sortDate.add(bbrq); + } + } + public int sortDateArray(String date,List sortDatedemo){ + SimpleDateFormat simpleDateFormat=new SimpleDateFormat("yyyy-MM-dd"); + int inxex=-1; + date=Util.null2String(date).trim(); + if("".equals(date)){ + return inxex; + } + if(sortDatedemo.size()<=0){ + sortDatedemo.add(date); + return 0; + } + try{ + int listindex=-1; + boolean isadd=false; + for(String str:sortDatedemo){ + str=Util.null2String(str).trim(); + if("".equals(str)){ + //continue; + } + listindex++; + inxex++; + if(simpleDateFormat.parse(date).getTime()==simpleDateFormat.parse(str).getTime()){ + break; + } + if(simpleDateFormat.parse(date).getTime()<=simpleDateFormat.parse(str).getTime()){ + isadd=true; + break; + } + } + if((listindex+1)==sortDatedemo.size()){//最后了 + listindex++; + inxex++; + sortDatedemo.add(listindex,date); + } + + if(listindex>-1&&isadd){ + sortDatedemo.add(listindex,date); + } + }catch(Exception e){ + return -1; + } + return inxex; + } + + public String getStrByJSON(JSONArray jsons,boolean isgl){ + String str=""; + if(jsons==null||jsons.size()<=0){ + return str; + } + TransField transField=new TransField(this.formid,this.billid+"",new User(1)); + + //getFieldIdByName(this.totableName,); + for(int i=0;i"+fieldJSON.toJSONString()); + String newfieldvalue=""; + try { + + newfieldvalue= BaseUtil.Html2Text(transField.transFieldValue(singleJson.getString(demo), fieldJSON)) ; + } catch (Exception e) { + e.printStackTrace(); + log.writeLog(e.getMessage()); + } + strSungle=strSungle+newfieldvalue+"/"; + + } + if(strSungle.endsWith("/")){ + strSungle.substring(0,strSungle.length()-1); + } + str=str+strSungle+"、\n"; + } + return str; + } + + @Override + public String toString() { + return "ModifyDetailInfo{" + + "dateVersion=" + dateVersion + + ", jsonVersion=" + jsonVersion + + ", field='" + field + '\'' + + ", fromtableName='" + fromtableName + '\'' + + ", totableName='" + totableName + '\'' + + ", modeid=" + modeid + + ", billid=" + billid + + ", qyid='" + qyid + '\'' + + ", changeFj='" + changeFjJson.toJSONString() + '\'' + + ", changeRemark='" + changeFjJson.toJSONString() + '\'' + + ", detailtabledesc='" + detailtabledesc + '\'' + + '}'; + } + public String getSqlField(String split){ + String sqlfield=""; + for(String str:this.field.split(",")){ + str=Util.null2String(str).trim(); + if("".equals(str)){ + continue; + } + sqlfield=sqlfield+split+"."+str+","; + } + if(sqlfield.endsWith(",")){ + sqlfield=sqlfield.substring(0,sqlfield.length()-1); + } + return sqlfield; + } + + /** + * 获取上一个 日期的下标 + * @return + */ + public int getAddSortDateAbove(List data,String date){ + int index=-1; + if(data==null||data.size()<=0||"".equals(Util.null2String(date))){ + return index; + } + try{ + int indexdemo=-1; + SimpleDateFormat sim=new SimpleDateFormat("yyyy-MM-dd"); + for(String key:data){ + indexdemo++; + key=Util.null2String(key).trim(); + if("".equals(key)){ + continue; + } + if((indexdemo+1)==data.size()){//最后一个 + if(sim.parse(key).getTime()<=sim.parse(date).getTime()){ + index=indexdemo; + break; + } + }else{ + if(sim.parse(key).getTime()<=sim.parse(date).getTime()&&sim.parse(data.get(indexdemo+1)).getTime()>=sim.parse(date).getTime()){ + index=indexdemo; + break; + } + } + + } + }catch(Exception e){ + index=-1; + } + return index; + } + + public static void main(String[] arge){ + ModifyDetailInfo modifyDetailInfo=new ModifyDetailInfo(); + modifyDetailInfo.sortDate.add("2021-12-01"); + modifyDetailInfo.sortDate.add("2021-12-07"); + //modifyDetailInfo.sortDate.add("2021-12-03"); + //modifyDetailInfo.sortDate.add("2021-12-05"); + //modifyDetailInfo.sortDate.add("2021-12-06"); + //getAddSortDateAbove + //System.out.println(modifyDetailInfo.sortDateArray("2021-12-17",modifyDetailInfo.sortDate)); + System.out.println(modifyDetailInfo.getAddSortDateAbove(modifyDetailInfo.sortDate,"2021-12-05")); + System.out.println(modifyDetailInfo.sortDate.toString()); + + JSONArray jsons=new JSONArray(); + JSONObject json=new JSONObject(); + JSONObject json1=new JSONObject(); + JSONObject json2=new JSONObject(); + json.put("de","de"); + json.put("de2","de2"); + json.put("mainbillid","123"); + jsons.add(json); + json1.put("de","de11"); + json1.put("de2","de222"); + jsons.add(json1); + + json2.put("de","de11"); + json2.put("de2","de222"); + json2.put("mainbillid","123"); + //System.out.println(modifyDetailInfo.CopyJSONArray(jsons).toJSONString()); + + //System.out.println(modifyDetailInfo.replaceStr("sdsd,dsd,sds,ds","dsdw")); + modifyDetailInfo.relpaceJSONArray(jsons,json2,"123"); + System.out.println(jsons.toJSONString()); + + } + + public String replaceStr(String tarStr,String str){ + String newtarStr=""; + tarStr=Util.null2String(tarStr); + str=Util.null2String(str); + if(!"".equals(str)){ + for(String demo:tarStr.split(",")){ + if(str.equals(demo)){ + continue; + } + newtarStr=newtarStr+demo+","; + } + }else{ + newtarStr=tarStr; + } + if(newtarStr.endsWith(",")){ + newtarStr=newtarStr.substring(0,newtarStr.length()-1); + } + return newtarStr; + } + + + +} diff --git a/src/main/youhong_ai_jitu_src/jntchina/service/oa/util/fastJsonDiff.java b/src/main/youhong_ai_jitu_src/jntchina/service/oa/util/fastJsonDiff.java new file mode 100644 index 0000000..4a8685f --- /dev/null +++ b/src/main/youhong_ai_jitu_src/jntchina/service/oa/util/fastJsonDiff.java @@ -0,0 +1,110 @@ +package jntchina.service.oa.util; + +import com.alibaba.fastjson.JSONArray; +import com.alibaba.fastjson.JSONObject; + +import java.util.Arrays; +import java.util.Iterator; +import java.util.List; + +/** + * 比较json 是否一致 + */ +public class fastJsonDiff { + public static boolean compareJsons(JSONObject json1, JSONObject json2,String key){ + if(!commonCompare(json1,json2,key)){ + return false; + } + Iterator json1Keys = json1.keySet().iterator(); + while (json1Keys.hasNext()){ + key = json1Keys.next(); + if(!compareJsons(json1.get(key), json2.get(key),key)){ + return false; + } + } + return true; + } + + public static boolean compareJsons(Object json1,Object json2, String key){ + if(!commonCompare(json1,json2,key)){ + return false; + } + if (json1 instanceof JSONObject){ + //如果是JSONObject则继续递归比较。 + return compareJsons((JSONObject) json1,(JSONObject) json2, key); + } else if (json1 instanceof JSONArray){ + //如果是JSONArray,则进行数组类比较。 + return compareJsons((JSONArray) json1,(JSONArray) json2,key); + } else { + //其余全部为字符串比较,非字符串的也转换为字符串比较。 + return compareJsons(json1.toString(),json2.toString(),key); + } + //return true; + } + + public static boolean compareJsons(JSONArray jsonArray1, JSONArray jsonArray2, String key){ + if(!commonCompare(jsonArray1,jsonArray2,key)){ + return false; + } + + //数组存在无序的情况,所以需要将1中的每一个元素,跟2中的所有元素进行比较。 + //两种方案:1.先对两个jsonArray进行排序,然后再依次比较。 2.对1中的每一个元素,判断是否在2中存在。(有重复元素的可能会有问题。) + //方案2的实现: + Iterator iterator1 = jsonArray1.iterator(); + while (iterator1.hasNext()){ + Object o1 = iterator1.next(); + if (jsonArray2.indexOf(o1) == -1){ + System.err.println("不一致:key "+ key +" json1中的 jsonArray其中的value : " + JSONObject.toJSONString(o1) + " 仅在json1中存在,不在json2中存在"); + return false; + } else { + System.out.println("一致:key " + key +" json1中的 jsonArray其中的value :" + JSONObject.toJSONString(o1)); + } + } + Iterator iterator2 = jsonArray2.iterator(); + while (iterator2.hasNext()){ + Object o2 = iterator2.next(); + if (jsonArray1.indexOf(o2) == -1){ + System.err.println("不一致:key " + key +" json2中的 jsonArray其中的value : " + JSONObject.toJSONString(o2) + " 仅在json2中存在,不在json1中存在"); + return false; + } + } + return true; + } + + public static boolean compareJsons(String json1,String json2,String key){ + if(!commonCompare(json1,json2,key)){ + return false; + } + if (json1.equals(json2)){ + System.out.println("一致:key " + key + " , json1 value = " + json1 + " json2 value = " + json2); + + } else { + System.err.println("不一致: key " + key + " , json1 value = " + json1 + " json2 value = " + json2 ); + return false; + } + return true; + } + + public static boolean commonCompare(Object json1,Object json2,String key){ + if (json1 == null && json2 == null){ + //System.err.println("不一致: key " + key + " 在两者中均不存在"); + return false; + } + if (json1 == null){ + System.err.println("不一致: key " + key + " 在json1中不存在,在json2中为 " + JSONObject.toJSONString(json2) ); + return false; + } + if (json2 == null){ + System.err.println("不一致: key " + key + " 在json1中为 " + JSONObject.toJSONString(json2) + " 在json2中不存在" ); + return false; + } + return true; + } + public static void main(String[] args) { + //String str1 = "{\"username\":\"tom\",\"age\":18,\"address\":[{\"province\":\"上海市\"},{\"city\":\"上海市\"},{\"city\":\"上海市政府\"},{\"disrtict\":\"静安区\"}],\"aihao\":[\"打球\",\"唱歌\",\"读书\"]}"; + String str1 = "{\"username\":\"andy\",\"age\":18,\"address\":[{\"province\":\"上海市\"},{\"city\":\"上海市\"},{\"disrtict\":\"静安区\"}],\"aihao\":[\"写作\",\"唱歌\",\"打球\"]}"; + String str2 = "{\"username1\":\"andy\",\"age\":18,\"address\":[{\"province\":\"上海市\"},{\"city\":\"上海市\"},{\"disrtict\":\"静安区\"}],\"aihao\":[\"写作\",\"唱歌\",\"打球\"]}"; + boolean flag=compareJsons(JSONObject.parseObject(str1),JSONObject.parseObject(str2),null); + System.out.println("de"+flag) ; + } +} diff --git a/src/main/youhong_ai_jitu_src/jntchina/test/DC_Test.java b/src/main/youhong_ai_jitu_src/jntchina/test/DC_Test.java new file mode 100644 index 0000000..0db57ea --- /dev/null +++ b/src/main/youhong_ai_jitu_src/jntchina/test/DC_Test.java @@ -0,0 +1,84 @@ +package jntchina.test; + +import java.util.HashMap; +import java.util.Map; + +import org.apache.http.HttpEntity; +import org.apache.http.client.methods.CloseableHttpResponse; +import org.apache.http.client.methods.HttpPost; +import org.apache.http.entity.ContentType; +import org.apache.http.entity.StringEntity; +import org.apache.http.impl.client.CloseableHttpClient; +import org.apache.http.impl.client.HttpClients; +import org.apache.http.util.EntityUtils; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.JSONObject; +import com.weaver.general.Util; + +import jntchina.util.HttpClientToDC; +import jntchina.util.MD5Utils; +import selfdev.util.base.TimeCommonUtil; + +public class DC_Test { + + public static void main(String[] args) { + // TODO Auto-generated method stub + String userName="oa003"; + String password="123456"; + String systemCode="oa"; + String secretkey="5362448sd132d241e5ae27e318qws11d"; + String token=getToken(userName,password,secretkey,systemCode); + System.out.println(token); + } + + /** + * 获取token + * @return + * @throws Exception + */ + public static String getToken(String userName,String password,String secretkey,String systemCode) { + String token = null; + try { + //获取当前系统日期 + String today= TimeCommonUtil.obtainDate(0).substring(0,10).replace("-", ""); + //加密串 + String encryptionKey= MD5Utils.encrypt(userName+":"+password+":"+today+":"+secretkey); + System.out.println(encryptionKey); + CloseableHttpClient client = HttpClients.createDefault(); + HttpPost post = new HttpPost("https://uat-jtdcapi.jtexpress.com.cn/dcoauthedi/oauth/getToken"); + JSONObject param=new JSONObject(); + param.put("userName",userName);//用户名 + param.put("password",password);//密码 + param.put("systemCode",systemCode);//系统标识 + param.put("encryptionKey",encryptionKey);//授权类型 + + System.out.println(param.toString()); + + StringEntity requestentity=new StringEntity(param.toString(),"utf-8"); + requestentity.setContentType(ContentType.APPLICATION_JSON.toString()); + post.setEntity(requestentity); + String responseContent = null; // 响应内容 + CloseableHttpResponse response = client.execute(post); + if (response.getStatusLine().getStatusCode() == 200) { + HttpEntity entity = response.getEntity(); + responseContent = EntityUtils.toString(entity, "UTF-8"); + } + System.out.println("调用getToken接口返回结果----->"+responseContent); + if(!"".equals(responseContent)){ + JSONObject object_return= JSON.parseObject(responseContent); + //接口返回状态 + String succ= Util.null2String(object_return.getString("succ")); + if("true".equals(succ)){ + token= Util.null2String(object_return.getString("data")); + } + } + }catch (Exception e) { + e.printStackTrace(); + } + System.out.println(token); + return token; + } + + +} diff --git a/src/main/youhong_ai_jitu_src/jntchina/test/DeptTest.java b/src/main/youhong_ai_jitu_src/jntchina/test/DeptTest.java new file mode 100644 index 0000000..9c921d3 --- /dev/null +++ b/src/main/youhong_ai_jitu_src/jntchina/test/DeptTest.java @@ -0,0 +1,206 @@ +package jntchina.test; + +import com.alibaba.fastjson.JSONObject; +import org.apache.http.client.entity.UrlEncodedFormEntity; +import org.apache.http.client.methods.CloseableHttpResponse; +import org.apache.http.client.methods.HttpPost; +import org.apache.http.impl.client.CloseableHttpClient; +import org.apache.http.impl.client.HttpClients; +import org.apache.http.message.BasicNameValuePair; +import org.apache.http.util.EntityUtils; + +import java.math.BigInteger; +import java.security.MessageDigest; +import java.security.NoSuchAlgorithmException; +import java.sql.Timestamp; +import java.util.*; + +/** + * @Author Administrator + * @Description + * @Date 2021/2/22 17:32 + */ +public class DeptTest { + + public static void main(String[] args) { + DeptTest restfulDemo = new DeptTest(); + restfulDemo.doAction(); + } + + /** + * restful接口调用案例 + * 以getModeDataPageList为例 + */ + public void doAction() { + + CloseableHttpResponse response;// 响应类, + CloseableHttpClient httpClient = HttpClients.createDefault(); + + //restful接口url + HttpPost httpPost = new HttpPost("http://159.138.82.156:8088/api/cube/restful/interface/saveOrUpdateModeData/insertOrUpdateDept"); + + //当前日期 + String currentDate = getCurrentDate(); + //当前时间 + String currentTime = getCurrentTime(); + //获取时间戳 + String currentTimeTamp = getTimestamp(); + + Map params = new HashMap<>(); + Map paramDatajson = new HashMap<>(); + + //header + Map header = new HashMap<>(); + + //系统标识 + String systemid = "hr"; + //密码 + String d_password = "A038A0555B424DE1A869CBB664A093C9"; + //封装header里的参数 + header.put("systemid", systemid); + header.put("currentDateTime", currentTimeTamp); + String md5Source = systemid + d_password + currentTimeTamp; + String md5OfStr = getMD5Str(md5Source).toLowerCase(); + //Md5是:系统标识+密码+时间戳 并且md5加密的结果 + header.put("Md5", md5OfStr); + paramDatajson.put("header", header); + + //封装pageinfo +// JSONObject pageInfo = new JSONObject(); +// pageInfo.put("pageNo", 1); +// pageInfo.put("pageSize", 10); +// paramDatajson.put("pageInfo",pageInfo); + + List list = new ArrayList<>(); + Map map = new HashMap<>(); + + //封装mainTable参数 + JSONObject mainTable = new JSONObject(); + mainTable.put("id", 11); + mainTable.put("nc_dept_code", 11); // NCC部门编码 + mainTable.put("nc_dept_name", "网络管理部"); // NCC部门名称 文本 + mainTable.put("parent_dept_code", 123); // NCC上级部门 传id + mainTable.put("dept_id", 22); // OA部门ID 传id + mainTable.put("dept_code", "OAtest"); // OA部门编码 + mainTable.put("dept_name", "OA的测试部门"); // OA部门名称 + mainTable.put("type", "极兔管理"); // 业务板块 + mainTable.put("property", "管理"); // 部门属性 + mainTable.put("unit", "重庆纭庆供应链管理有限公司"); //所属业务单元 +// paramDatajson.put("mainTable",mainTable); + + //封装operationinfo参数 + JSONObject operationinfo = new JSONObject(); + operationinfo.put("operationDate", ""); + operationinfo.put("operator", "1"); + operationinfo.put("operationTime", ""); + + map.put("mainTable", mainTable); + map.put("operationinfo", operationinfo); + + list.add(map); + + paramDatajson.put("data", list); + + params.put("datajson", paramDatajson); + + System.out.println("===请求参数datajson===" + paramDatajson); + + //装填参数 + List nvps = new ArrayList(); + if (params != null) { + params.forEach((k, v) -> { + nvps.add(new BasicNameValuePair((String) k, JSONObject.toJSONString(v))); + }); + } + try { + httpPost.addHeader("Content-Type", "application/x-www-form-urlencoded; charset=utf-8"); + httpPost.setEntity(new UrlEncodedFormEntity(nvps, "UTF-8")); + response = httpClient.execute(httpPost); + if (response != null && response.getEntity() != null) { + //返回信息 + String resultString = EntityUtils.toString(response.getEntity()); + //todo这里处理返回信息 + System.out.println("返回的结果信息为:" + resultString); + } else { + System.out.println("获取数据失败,请查看日志" + currentDate + " " + currentTime); + } + } catch (Exception e) { + System.out.println("请求失败" + currentDate + " " + currentTime + "====errormsg:" + e.getMessage()); + } + } + + public String getMD5Str(String plainText) { + //定义一个字节数组 + byte[] secretBytes = null; + try { + // 生成一个MD5加密计算摘要 + MessageDigest md = MessageDigest.getInstance("MD5"); + //对字符串进行加密 + md.update(plainText.getBytes()); + //获得加密后的数据 + secretBytes = md.digest(); + } catch (NoSuchAlgorithmException e) { + throw new RuntimeException("没有md5这个算法!"); + } + //将加密后的数据转换为16进制数字 + String md5code = new BigInteger(1, secretBytes).toString(16); + // 如果生成数字未满32位,需要前面补0 + for (int i = 0; i < 32 - md5code.length(); i++) { + md5code = "0" + md5code; + } + return md5code; + } + + public static String getCurrentTime() { + Date newdate = new Date(); + long datetime = newdate.getTime(); + Timestamp timestamp = new Timestamp(datetime); + String currenttime = (timestamp.toString()).substring(11, 13) + ":" + (timestamp.toString()).substring(14, 16) + ":" + + (timestamp.toString()).substring(17, 19); + return currenttime; + } + + public static String getCurrentDate() { + Date newdate = new Date(); + long datetime = newdate.getTime(); + Timestamp timestamp = new Timestamp(datetime); + String currentdate = (timestamp.toString()).substring(0, 4) + "-" + (timestamp.toString()).substring(5, 7) + "-" + + (timestamp.toString()).substring(8, 10); + return currentdate; + } + + /** + * 获取当前日期时间。 YYYY-MM-DD HH:MM:SS + * + * @return 当前日期时间 + */ + public static String getCurDateTime() { + Date newdate = new Date(); + long datetime = newdate.getTime(); + Timestamp timestamp = new Timestamp(datetime); + return (timestamp.toString()).substring(0, 19); + } + + /** + * 获取时间戳 格式如:19990101235959 + * + * @return + */ + public static String getTimestamp() { + return getCurDateTime().replace("-", "").replace(":", "").replace(" ", ""); + } + + public static int getIntValue(String v, int def) { + try { + return Integer.parseInt(v); + } catch (Exception ex) { + return def; + } + } + + + public static String null2String(Object s) { + return s == null ? "" : s.toString(); + } + +} diff --git a/src/main/youhong_ai_jitu_src/jntchina/test/DeptTest2.java b/src/main/youhong_ai_jitu_src/jntchina/test/DeptTest2.java new file mode 100644 index 0000000..c7aa76a --- /dev/null +++ b/src/main/youhong_ai_jitu_src/jntchina/test/DeptTest2.java @@ -0,0 +1,188 @@ +package jntchina.test; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.JSONObject; +import org.apache.http.client.entity.UrlEncodedFormEntity; +import org.apache.http.client.methods.CloseableHttpResponse; +import org.apache.http.client.methods.HttpPost; +import org.apache.http.impl.client.CloseableHttpClient; +import org.apache.http.impl.client.HttpClients; +import org.apache.http.message.BasicNameValuePair; +import org.apache.http.util.EntityUtils; + +import java.math.BigInteger; +import java.security.MessageDigest; +import java.security.NoSuchAlgorithmException; +import java.sql.Timestamp; +import java.util.*; + +/** + * @Author Administrator + * @Description + * @Date 2021/2/22 17:32 + */ +public class DeptTest2 { + + public static void main(String[] args) { + DeptTest2 restfulDemo = new DeptTest2(); + restfulDemo.doAction(); + } + + /** + * restful接口调用案例 + * 以getModeDataPageList为例 + */ + public void doAction() { + + CloseableHttpResponse response;// 响应类, + CloseableHttpClient httpClient = HttpClients.createDefault(); + + //restful接口url + HttpPost httpPost = new HttpPost("http://124.71.198.239:8088/api/cube/restful/interface/getModeDataPageList/listDepartmentInfo"); + + //当前日期 + String currentDate = getCurrentDate(); + //当前时间 + String currentTime = getCurrentTime(); + //获取时间戳 + String currentTimeTamp = getTimestamp(); + + Map params = new HashMap<>(); + Map paramDatajson = new HashMap<>(); + + //header + Map header = new HashMap<>(); + + //系统标识 + String systemid = "oa"; + //密码 + String d_password = "BE598342ABA04FAFBB2C20ABD1C33F6B"; + //封装header里的参数 + header.put("systemid", systemid); + header.put("currentDateTime", currentTimeTamp); + String md5Source = systemid + d_password + currentTimeTamp; + String md5OfStr = getMD5Str(md5Source).toLowerCase(); + //Md5是:系统标识+密码+时间戳 并且md5加密的结果 + header.put("Md5", md5OfStr); + paramDatajson.put("header", header); + + //封装pageinfo + JSONObject pageInfo = new JSONObject(); + pageInfo.put("pageNo", 1); + pageInfo.put("pageSize", 10); + paramDatajson.put("pageInfo", pageInfo); + + //封装mainTable参数 + JSONObject mainTable = new JSONObject(); + mainTable.put("MODIFIED", "2021-03-02 02:03"); + paramDatajson.put("mainTable", mainTable); + + //封装operationinfo参数 + JSONObject operationinfo = new JSONObject(); + operationinfo.put("operator", "1"); + paramDatajson.put("operationinfo", operationinfo); + + params.put("datajson", paramDatajson); + + System.out.println("===请求参数datajson===" + JSON.toJSON(paramDatajson)); + + //装填参数 + List nvps = new ArrayList(); + if (params != null) { + params.forEach((k, v) -> { + nvps.add(new BasicNameValuePair((String) k, JSONObject.toJSONString(v))); + }); + } + try { + httpPost.addHeader("Content-Type", "application/x-www-form-urlencoded; charset=utf-8"); + httpPost.setEntity(new UrlEncodedFormEntity(nvps, "UTF-8")); + response = httpClient.execute(httpPost); + if (response != null && response.getEntity() != null) { + //返回信息 + String resultString = EntityUtils.toString(response.getEntity()); + //todo这里处理返回信息 + System.out.println("返回的结果信息为:" + resultString); + } else { + System.out.println("获取数据失败,请查看日志" + currentDate + " " + currentTime); + } + } catch (Exception e) { + System.out.println("请求失败" + currentDate + " " + currentTime + "====errormsg:" + e.getMessage()); + } + } + + public String getMD5Str(String plainText) { + //定义一个字节数组 + byte[] secretBytes = null; + try { + // 生成一个MD5加密计算摘要 + MessageDigest md = MessageDigest.getInstance("MD5"); + //对字符串进行加密 + md.update(plainText.getBytes()); + //获得加密后的数据 + secretBytes = md.digest(); + } catch (NoSuchAlgorithmException e) { + throw new RuntimeException("没有md5这个算法!"); + } + //将加密后的数据转换为16进制数字 + String md5code = new BigInteger(1, secretBytes).toString(16); + // 如果生成数字未满32位,需要前面补0 + for (int i = 0; i < 32 - md5code.length(); i++) { + md5code = "0" + md5code; + } + return md5code; + } + + public static String getCurrentTime() { + Date newdate = new Date(); + long datetime = newdate.getTime(); + Timestamp timestamp = new Timestamp(datetime); + String currenttime = (timestamp.toString()).substring(11, 13) + ":" + (timestamp.toString()).substring(14, 16) + ":" + + (timestamp.toString()).substring(17, 19); + return currenttime; + } + + public static String getCurrentDate() { + Date newdate = new Date(); + long datetime = newdate.getTime(); + Timestamp timestamp = new Timestamp(datetime); + String currentdate = (timestamp.toString()).substring(0, 4) + "-" + (timestamp.toString()).substring(5, 7) + "-" + + (timestamp.toString()).substring(8, 10); + return currentdate; + } + + /** + * 获取当前日期时间。 YYYY-MM-DD HH:MM:SS + * + * @return 当前日期时间 + */ + public static String getCurDateTime() { + Date newdate = new Date(); + long datetime = newdate.getTime(); + Timestamp timestamp = new Timestamp(datetime); + return (timestamp.toString()).substring(0, 19); + } + + /** + * 获取时间戳 格式如:19990101235959 + * + * @return + */ + public static String getTimestamp() { + return getCurDateTime().replace("-", "").replace(":", "").replace(" ", ""); + } + + public static int getIntValue(String v, int def) { + try { + return Integer.parseInt(v); + } catch (Exception ex) { + return def; + } + } + + + public static String null2String(Object s) { + return s == null ? "" : s.toString(); + } + + +} diff --git a/src/main/youhong_ai_jitu_src/jntchina/test/HrTest.java b/src/main/youhong_ai_jitu_src/jntchina/test/HrTest.java new file mode 100644 index 0000000..0ab1a97 --- /dev/null +++ b/src/main/youhong_ai_jitu_src/jntchina/test/HrTest.java @@ -0,0 +1,204 @@ +package jntchina.test; + +import com.alibaba.fastjson.JSONObject; + +import org.apache.http.client.entity.UrlEncodedFormEntity; +import org.apache.http.client.methods.CloseableHttpResponse; +import org.apache.http.client.methods.HttpPost; +import org.apache.http.impl.client.CloseableHttpClient; +import org.apache.http.impl.client.HttpClients; +import org.apache.http.message.BasicNameValuePair; +import org.apache.http.util.EntityUtils; + + +import java.math.BigInteger; +import java.security.MessageDigest; +import java.security.NoSuchAlgorithmException; +import java.sql.Timestamp; +import java.util.*; + +/** + * @Author Administrator + * @Description + * @Date 2021/2/22 17:32 + */ +public class HrTest { + + public static void main(String[] args) { + HrTest restfulDemo = new HrTest(); + restfulDemo.doAction(); + } + + public void doAction() { + + CloseableHttpResponse response;// 响应类, + CloseableHttpClient httpClient = HttpClients.createDefault(); + + //restful接口url + HttpPost httpPost = new HttpPost("http://159.138.82.156:8088/api/cube/restful/interface/saveOrUpdateModeData/insertOrUpdateHr"); + + //当前日期 + String currentDate = getCurrentDate(); + //当前时间 + String currentTime = getCurrentTime(); + //获取时间戳 + String currentTimeTamp = getTimestamp(); + + Map params = new HashMap<>(); + Map paramDatajson = new HashMap<>(); + + //header + Map header = new HashMap<>(); + + //系统标识 + String systemid = "hr"; + //密码 + String d_password = "A038A0555B424DE1A869CBB664A093C9"; + //封装header里的参数 + header.put("systemid", systemid); + header.put("currentDateTime", currentTimeTamp); + String md5Source = systemid + d_password + currentTimeTamp; + String md5OfStr = getMD5Str(md5Source).toLowerCase(); + //Md5是:系统标识+密码+时间戳 并且md5加密的结果 + header.put("Md5", md5OfStr); + paramDatajson.put("header", header); + + //封装pageinfo +// JSONObject pageInfo = new JSONObject(); +// pageInfo.put("pageNo", 1); +// pageInfo.put("pageSize", 10); +// paramDatajson.put("pageInfo",pageInfo); + + List list = new ArrayList<>(); + Map map = new HashMap<>(); + + //封装mainTable参数 + JSONObject mainTable = new JSONObject(); + mainTable.put("id", "1"); + mainTable.put("name", "张三啊"); // 姓名 传文本 + mainTable.put("unit_code", "123"); // 所属业务单元 id + mainTable.put("code", "123"); // 人员编码 传id + mainTable.put("group_code", "123"); // 任职集团 传id 默认01 + mainTable.put("post_unit_code", "123"); // 任职业务单元 id + mainTable.put("type", "2"); // 人员类别 枚举:[1:合同工,2:外包员工] + mainTable.put("dept_code", "123"); // 所在部门编码 id + mainTable.put("is_principal", "1"); // 状态 枚举:[1:正式,2:试用,3:离职] + mainTable.put("work_date", "2021-02-26"); // 任职开始日期 日期 yyyy-MM-dd +// paramDatajson.put("mainTable",mainTable); + + //封装operationinfo参数 + JSONObject operationinfo = new JSONObject(); + operationinfo.put("operationDate", ""); + operationinfo.put("operator", "1"); + operationinfo.put("operationTime", ""); + + map.put("mainTable", mainTable); + map.put("operationinfo", operationinfo); + + list.add(map); + + paramDatajson.put("data", list); + + params.put("datajson", paramDatajson); + + System.out.println("===请求参数datajson===" + paramDatajson); + + //装填参数 + List nvps = new ArrayList(); + if (params != null) { + params.forEach((k, v) -> { + nvps.add(new BasicNameValuePair((String) k, JSONObject.toJSONString(v))); + }); + } + try { + httpPost.addHeader("Content-Type", "application/x-www-form-urlencoded; charset=utf-8"); + httpPost.setEntity(new UrlEncodedFormEntity(nvps, "UTF-8")); + response = httpClient.execute(httpPost); + if (response != null && response.getEntity() != null) { + //返回信息 + String resultString = EntityUtils.toString(response.getEntity()); + //todo这里处理返回信息 + System.out.println("返回的结果信息为:" + resultString); + } else { + System.out.println("获取数据失败,请查看日志" + currentDate + " " + currentTime); + } + } catch (Exception e) { + System.out.println("请求失败" + currentDate + " " + currentTime + "====errormsg:" + e.getMessage()); + } + } + + public String getMD5Str(String plainText) { + //定义一个字节数组 + byte[] secretBytes = null; + try { + // 生成一个MD5加密计算摘要 + MessageDigest md = MessageDigest.getInstance("MD5"); + //对字符串进行加密 + md.update(plainText.getBytes()); + //获得加密后的数据 + secretBytes = md.digest(); + } catch (NoSuchAlgorithmException e) { + throw new RuntimeException("没有md5这个算法!"); + } + //将加密后的数据转换为16进制数字 + String md5code = new BigInteger(1, secretBytes).toString(16); + // 如果生成数字未满32位,需要前面补0 + for (int i = 0; i < 32 - md5code.length(); i++) { + md5code = "0" + md5code; + } + return md5code; + } + + public static String getCurrentTime() { + Date newdate = new Date(); + long datetime = newdate.getTime(); + Timestamp timestamp = new Timestamp(datetime); + String currenttime = (timestamp.toString()).substring(11, 13) + ":" + (timestamp.toString()).substring(14, 16) + ":" + + (timestamp.toString()).substring(17, 19); + return currenttime; + } + + public static String getCurrentDate() { + Date newdate = new Date(); + long datetime = newdate.getTime(); + Timestamp timestamp = new Timestamp(datetime); + String currentdate = (timestamp.toString()).substring(0, 4) + "-" + (timestamp.toString()).substring(5, 7) + "-" + + (timestamp.toString()).substring(8, 10); + return currentdate; + } + + /** + * 获取当前日期时间。 YYYY-MM-DD HH:MM:SS + * + * @return 当前日期时间 + */ + public static String getCurDateTime() { + Date newdate = new Date(); + long datetime = newdate.getTime(); + Timestamp timestamp = new Timestamp(datetime); + return (timestamp.toString()).substring(0, 19); + } + + /** + * 获取时间戳 格式如:19990101235959 + * + * @return + */ + public static String getTimestamp() { + return getCurDateTime().replace("-", "").replace(":", "").replace(" ", ""); + } + + public static int getIntValue(String v, int def) { + try { + return Integer.parseInt(v); + } catch (Exception ex) { + return def; + } + } + + + public static String null2String(Object s) { + return s == null ? "" : s.toString(); + } + +} diff --git a/src/main/youhong_ai_jitu_src/jntchina/test/HttpClientToNCC_Test.java b/src/main/youhong_ai_jitu_src/jntchina/test/HttpClientToNCC_Test.java new file mode 100644 index 0000000..cb18cfe --- /dev/null +++ b/src/main/youhong_ai_jitu_src/jntchina/test/HttpClientToNCC_Test.java @@ -0,0 +1,374 @@ +package jntchina.test; + +import java.io.BufferedReader; +import java.io.IOException; +import java.io.InputStream; +import java.io.InputStreamReader; +import java.io.OutputStream; +import java.lang.reflect.Type; +import java.net.HttpURLConnection; +import java.net.URL; +import java.net.URLEncoder; +import java.nio.charset.Charset; +import java.util.HashMap; +import java.util.Map; + +import org.apache.commons.lang3.StringUtils; + +import com.google.gson.Gson; + +import jntchina.util.CompressUtil; +import jntchina.util.Decryption; +import jntchina.util.Encryption; +import jntchina.util.ResultMessageUtil; +import jntchina.util.SHA256Util; +import jntchina.util.Test; +import selfdev.util.log.LogTool; + +/** + * @Author Administrator + * @Description + * @Date 2021/2/19 11:21 + */ +public class HttpClientToNCC_Test { + // app_secret + private static final String client_secret = "7f4960d6de4a42bebfc4"; + // 公钥 + private static final String pubKey = "MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCbAEDvatjhVymfI2gubZ72iYaOtbcmLZljJOEfKtl0v3rkwoify8o1qBjqOYkvAh8a7iER/lWzMZgg5iHpbUqS1Plejx4fvUvslQt59B+1gzruLbW+4jDEY9Cl2f7vj7J1HYp9K7OBY0oM2GvzFJzLWnpDnJVjgNNyuEqlqYY5kQIDAQAB"; + // app_id + private static final String client_id = "oa"; + // ncc用户名 + private static final String username = null; + // ncc用户名密码 + private static final String pwd = null; + // ncc账套 + private static final String busi_center = "jtsd"; + // 获取token方式:client_credentials、password + private static final String grant_type = "client_credentials"; + // 服务器ip:port + private static final String baseUrl = "http://180.169.229.37:9333"; + // 返回值压缩加密级别 + private static final String secret_level = "L0"; + // openapi请求路径 +// private static String apiUrl = "/nccloud/api/jitu/erm/bxbill/insert"; + // 访问api获取到的access_token + public static String token = null; + // 重复调用检查 + public static String repeat_check = null; + // 接口调用业务标识 + public static String busi_id = null; + + public static LogTool log = new LogTool("/log/selfdev/action", false); + + public static void main(String[] args) { + try { + System.out.println(getToken()); + } catch (Exception e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + } + + /** + * 获取access_token + * + * @return + * @throws Exception + */ + public static String getToken() throws Exception { + String token = null; + if ("password".equals(grant_type)) { + // 密码模式 + token = getTokenByPWD(); + log.writeLog("--------密码模式----获取access_token"); + } else if ("client_credentials".equals(grant_type)) { + // 客户端模式 + token = getTokenByClient(); + log.writeLog("--------客户端模式----获取access_token"); + } + return token; + } + + /** + * 客户端模式获取token + * + * @return + * @throws Exception + */ + private static String getTokenByClient() throws Exception { + Map paramMap = new HashMap(); + // 密码模式认证 + paramMap.put("grant_type", "client_credentials"); + // 第三方应用id + paramMap.put("client_id", client_id); + // 第三方应用secret 公钥加密 + paramMap.put("client_secret", URLEncoder.encode(Encryption.pubEncrypt(pubKey, client_secret), "utf-8")); + // 账套编码 + paramMap.put("biz_center", busi_center); + // 传递数据源和ncc登录用户 + // paramMap.put("dsname", "TM_0614"); + // paramMap.put("usercode", "1"); + + // 签名 + String sign = SHA256Util.getSHA256(client_id + client_secret + pubKey); + paramMap.put("signature", sign); + + String url = baseUrl + "/nccloud/opm/accesstoken"; + String mediaType = "application/x-www-form-urlencoded"; + + log.writeLog("--------客户端模式获取token-----"); + + return doPost(url, paramMap, mediaType, null, ""); + } + + /** + * 密码模式获取token + * + * @return + * @throws Exception + */ + private static String getTokenByPWD() throws Exception { + Map paramMap = new HashMap(); + // 密码模式认证 + paramMap.put("grant_type", "password"); + // 第三方应用id + paramMap.put("client_id", client_id); + // 第三方应用secret 公钥加密 + paramMap.put("client_secret", URLEncoder.encode(Encryption.pubEncrypt(pubKey, client_secret), "utf-8")); + // ncc用户名 + paramMap.put("username", username); + // 密码 公钥加密 + paramMap.put("password", URLEncoder.encode(Encryption.pubEncrypt(pubKey, pwd), "utf-8")); + // 账套编码 + paramMap.put("biz_center", busi_center); + // 签名 + String sign = SHA256Util.getSHA256(client_id + client_secret + username + pwd + pubKey); + paramMap.put("signature", sign); + + String url = baseUrl + "/nccloud/opm/accesstoken"; + String mediaType = "application/x-www-form-urlencoded"; + + log.writeLog("--------密码模式获取token-----"); + + return doPost(url, paramMap, mediaType, null, ""); + } + + /** + * @param token token + * @param requestBody 请求参数 + * @return + * @throws Exception + */ + public static String sendApi(String token, String requestBody, String apiUrl) throws Exception { + // token转对象,获取api访问所用token和secret + ResultMessageUtil returnData = new Gson().fromJson(token, (Type) ResultMessageUtil.class); + Map data = (Map) returnData.getData(); + String access_token = data.get("access_token"); + String security_key = data.get("security_key"); + String refresh_token = data.get("refresh_token"); + System.out.println("【ACCESS_TOKEN】:" + access_token); + + // 请求路径 + String url = baseUrl + apiUrl; + // header 参数 + Map headermap = new HashMap(); + headermap.put("access_token", access_token); + headermap.put("client_id", client_id); + + StringBuffer sb = new StringBuffer(); + sb.append(client_id); + if (StringUtils.isNotBlank(requestBody)) { + sb.append(requestBody); + } + sb.append(pubKey); + String sign = SHA256Util.getSHA256(sb.toString()); + headermap.put("signature", sign); + + if (StringUtils.isNotBlank(busi_id)) { + headermap.put("busi_id", busi_id); + } + if (StringUtils.isNotBlank(repeat_check)) { + headermap.put("repeat_check", repeat_check); + } + headermap.put("ucg_flag", "y"); + + String mediaType = "application/json;charset=utf-8"; + + // 表体数据json + // 根据安全级别选择加密或压缩请求表体参数 + String json = dealRequestBody(requestBody, security_key, secret_level); + + log.writeLog("--------token---请求参数--"); + + return doPost(url, null, mediaType, headermap, json); + } + + /** + * 返回值进行过加密和压缩,对返回值进行解压和解密 + * + * @param source + * @param security_key + * @param level + * @return + * @throws Exception + */ + private static String dealResponseBody(String source, String security_key, String level) throws Exception { + String result = null; + + if (StringUtils.isEmpty(level) || "L0".equals(level)) { + result = source; + } else if ("L1".equals(level)) { + result = Decryption.symDecrypt(security_key, source); + } else if ("L2".equals(level)) { + result = CompressUtil.gzipDecompress(source); + } else if ("L3".equals(level)) { + result = CompressUtil.gzipDecompress(Decryption.symDecrypt(security_key, source)); + } else if ("L4".equals(level)) { + result = Decryption.symDecrypt(security_key, CompressUtil.gzipDecompress(source)); + } else { + throw new Exception("无效的安全等级"); + } + return result; + } + + // 根据安全级别设置,表体是否加密或压缩 + private static String dealRequestBody(String source, String security_key, String level) throws Exception { + String result = null; + if (StringUtils.isEmpty(level) || "L0".equals(level)) { + result = source; + } else if ("L1".equals(level)) { + result = Encryption.symEncrypt(security_key, source); + } else if ("L2".equals(level)) { + result = CompressUtil.gzipCompress(source); + } else if ("L3".equals(level)) { + result = Encryption.symEncrypt(security_key, CompressUtil.gzipCompress(source)); + } else if ("L4".equals(level)) { + result = CompressUtil.gzipCompress(Encryption.symEncrypt(security_key, source)); + } else { + throw new Exception("无效的安全等级"); + } + + log.writeLog("-----根据安全级别设置,表体是否加密或压缩--"); + + return result; + } + + /** + * 发送post请求 + * + * @param baseUrl + * @param paramMap + * @param mediaType + * @param headers + * @param json + * @return + */ + private static String doPost(String baseUrl, Map paramMap, String mediaType, Map headers, String json) { + + HttpURLConnection urlConnection = null; + InputStream in = null; + OutputStream out = null; + BufferedReader bufferedReader = null; + String result = null; + try { + StringBuffer sb = new StringBuffer(); + sb.append(baseUrl); + if (paramMap != null) { + sb.append("?"); + for (Map.Entry entry : paramMap.entrySet()) { + String key = entry.getKey(); + String value = entry.getValue(); + sb.append(key + "=" + value).append("&"); + } + baseUrl = sb.toString().substring(0, sb.toString().length() - 1); + } + + URL urlObj = new URL(baseUrl); + urlConnection = (HttpURLConnection) urlObj.openConnection(); + urlConnection.setConnectTimeout(50000); + urlConnection.setRequestMethod("POST"); + urlConnection.setDoOutput(true); + urlConnection.setDoInput(true); + urlConnection.setUseCaches(false); + urlConnection.addRequestProperty("content-type", mediaType); + if (headers != null) { + for (String key : headers.keySet()) { + urlConnection.addRequestProperty(key, headers.get(key)); + } + } + out = urlConnection.getOutputStream(); + out.write(json.getBytes("utf-8")); + out.flush(); + int resCode = urlConnection.getResponseCode(); + if (resCode == HttpURLConnection.HTTP_OK || resCode == HttpURLConnection.HTTP_CREATED || resCode == HttpURLConnection.HTTP_ACCEPTED) { + in = urlConnection.getInputStream(); + } else { + in = urlConnection.getErrorStream(); + } + bufferedReader = new BufferedReader(new InputStreamReader(in, "utf-8")); + StringBuffer temp = new StringBuffer(); + String line = bufferedReader.readLine(); + while (line != null) { + temp.append(line).append("\r\n"); + line = bufferedReader.readLine(); + } + String ecod = urlConnection.getContentEncoding(); + if (ecod == null) { + ecod = Charset.forName("utf-8").name(); + } + result = new String(temp.toString().getBytes("utf-8"), ecod); + } catch (Exception e) { + System.out.println(e); + } finally { + if (null != bufferedReader) { + try { + bufferedReader.close(); + } catch (IOException e) { + e.printStackTrace(); + } + } + if (null != out) { + try { + out.close(); + } catch (IOException e) { + e.printStackTrace(); + } + } + if (null != in) { + try { + in.close(); + } catch (IOException e) { + e.printStackTrace(); + } + } + urlConnection.disconnect(); + } + + log.writeLog("-----发送post请求---"); + + return result; + } + + class SecretConst { + /** + * LEVEL0 不压缩、不加密 + */ + public static final String LEVEL0 = "L0"; + /** + * LEVEL1 只加密、不压缩 + */ + public static final String LEVEL1 = "L1"; + /** + * LEVEL2 只压缩、不加密 + */ + public static final String LEVEL2 = "L2"; + /** + * LEVEL3 先压缩、后加密 + */ + public static final String LEVEL3 = "L3"; + /** + * LEVEL4 先加密、后压缩 + */ + public static final String LEVEL4 = "L4"; + } +} diff --git a/src/main/youhong_ai_jitu_src/jntchina/test/LJL_test.java b/src/main/youhong_ai_jitu_src/jntchina/test/LJL_test.java new file mode 100644 index 0000000..8556873 --- /dev/null +++ b/src/main/youhong_ai_jitu_src/jntchina/test/LJL_test.java @@ -0,0 +1,69 @@ +package jntchina.test; + + +import com.alibaba.fastjson.JSONArray; +import com.alibaba.fastjson.JSONObject; +import com.weaver.integration.datesource.SAPInterationOutUtilTest; +import org.apache.commons.httpclient.HttpClient; +import org.apache.http.HttpEntity; +import org.apache.http.client.methods.CloseableHttpResponse; +import org.apache.http.client.methods.HttpGet; +import org.apache.http.impl.client.CloseableHttpClient; +import org.apache.http.impl.client.HttpClients; +import org.apache.http.util.EntityUtils; +import selfdev.util.log.LogTool; + + +import java.io.IOException; + +/** + * @title: LJL_test + * @Author LJL + * @Date: 2021/10/18 15:24 + * @Version 1.0 + */ +public class LJL_test { + public static void main(String[] args) { + JSONObject jsonObject = new JSONObject(); + jsonObject.put("12","12"); + jsonObject.put("112","12"); + jsonObject.put("123","12"); + jsonObject.put("124","12"); + jsonObject.clear(); + System.out.println(jsonObject); + + +// HttpGet get = new HttpGet("http://192.168.200.231:9905/sunq/provision/v1/get/leave/type"); +// CloseableHttpClient aDefault = HttpClients.createDefault(); +// try { +// CloseableHttpResponse execute = aDefault.execute(get); +// HttpEntity entity = execute.getEntity(); +// JSONObject jsonObject = JSONObject.parseObject(EntityUtils.toString(entity)); +// +// JSONArray data = jsonObject.getJSONArray("data"); +// for (int i = 0; i < data.size(); i++) { +// String o = (String)data.get(i); +// System.out.println(o); +// } +// +// +// } catch (IOException e) { +// e.printStackTrace(); +// } + +// +// Object o = "123"; +// +// String oo = (String)o; +// +// String s = "123"; +// System.out.println(oo.equals(s)); +// System.out.println(s.equals(oo)); + + } + + + + + +} diff --git a/src/main/youhong_ai_jitu_src/jntchina/test/Test_20210407.java b/src/main/youhong_ai_jitu_src/jntchina/test/Test_20210407.java new file mode 100644 index 0000000..17cfe81 --- /dev/null +++ b/src/main/youhong_ai_jitu_src/jntchina/test/Test_20210407.java @@ -0,0 +1,31 @@ +package jntchina.test; + + +import com.alibaba.fastjson.JSONArray; +import com.alibaba.fastjson.JSONObject; +import weaver.general.Util; + +public class Test_20210407 { + + + public static void main(String[] args) { + String s="{\"code\":1,\"msg\":\"请求成功\",\"data\":{\"maxPoint\":null,\"size\":0,\"hasNextPage\":false,\"records\":null},\"succ\":true,\"fail\":false}"; + JSONObject jsonObject = JSONObject.parseObject(s); + + String code= Util.null2String(jsonObject.getString("code")); + if ("1".equals(code)) { + JSONObject result = jsonObject.getJSONObject("data"); + //是否有下一页 + boolean sfyxyy = result.getBoolean("hasNextPage");//是否有下一页 + + String maxPoint = Util.null2o(result.getString("maxPoint"));//下一页开始 + JSONArray records = result.getJSONArray("records"); + if(records!=null){ + System.out.println("1111--->"+records.isEmpty()); + System.out.println("1111"); + } + + + } + } +} diff --git a/src/main/youhong_ai_jitu_src/jntchina/test/Test_20210517.java b/src/main/youhong_ai_jitu_src/jntchina/test/Test_20210517.java new file mode 100644 index 0000000..f68a52b --- /dev/null +++ b/src/main/youhong_ai_jitu_src/jntchina/test/Test_20210517.java @@ -0,0 +1,23 @@ +package jntchina.test; + + +import com.alibaba.fastjson.JSONObject; +import jntchina.util.HttpClientToDC; +import weaver.general.Util; +import weaver.interfaces.workflow.action.Action; + +public class Test_20210517 { + + + public static void main(String[] args) { + //调用NCC接口,将数据传给NCC + String returndata = "{\"code\":1,\"data\":true,\"fail\":false,\"msg\":\"请求成功\",\"succ\":true}"; + if (!"".equals(returndata) && returndata != null) { + JSONObject jsonObject = JSONObject.parseObject(returndata); + String succ = Util.null2String(jsonObject.get("succ")); + System.out.println("-------->"+succ); + } + + + } +} diff --git a/src/main/youhong_ai_jitu_src/jntchina/test/tTest.java b/src/main/youhong_ai_jitu_src/jntchina/test/tTest.java new file mode 100644 index 0000000..bfa9dbf --- /dev/null +++ b/src/main/youhong_ai_jitu_src/jntchina/test/tTest.java @@ -0,0 +1,113 @@ +package jntchina.test; + + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.JSONArray; +import com.alibaba.fastjson.JSONObject; +import jntchina.util.HttpClientToDC; +import jntchina.util.NCCUtils; +import weaver.file.Prop; +import weaver.general.Util; + + +import java.io.*; +import java.sql.Timestamp; +import java.time.LocalDate; +import java.time.LocalDateTime; +import java.time.LocalTime; +import java.util.*; + + + +public class tTest { + + + public static void main(String[] args) throws FileNotFoundException { + + String a = ""; + String zyx9=a.length()>140?a.substring(0,140):a;//标题 + + + System.out.println(zyx9); + + } + + public static String json(){ + + return "{\"gxry\":[{\"subcompanyid1span\":\"J&T集团>J&T中国\",\"subcompanyid\":\"1021\",\"pinyinlastname\":\"张华光\",\"departmentidspan\":\"法律合规部\",\"departmentid\":\"1526\",\"icon\":\"/messager/usericon/af61358e8d9e478590d8970e2a682bb7.jpg\",\"requestParams\":\"{\\\"headformat\\\":\\\"2\\\",\\\"isDefault\\\":true,\\\"gender\\\":\\\"0\\\",\\\"background\\\":\\\"#55B1F9\\\",\\\"messagerurl\\\":\\\"/messager/usericon/af61358e8d9e478590d8970e2a682bb7.jpg\\\",\\\"fontcolor\\\":\\\"#FFFFFF\\\",\\\"defaultmessagerurl\\\":\\\"\\\",\\\"shortname\\\":\\\"华光\\\",\\\"lastname\\\":\\\"张华光\\\"}\",\"subcompanyname\":\"J&T中国\",\"type\":\"resource\",\"supsubcompanyname\":\"J&T集团\",\"lastname\":\"张华光\",\"jobtitlename\":\"合规顾问\",\"departmentname\":\"法律合规部\",\"lastnamespan\":\"张华光\",\"id\":\"1754\",\"displayKeys\":[\"lastnamespan\",\"subcompanyid1span\",\"departmentidspan\"],\"nodeid\":\"resource_1754x\",\"supsubcompanyid\":\"521\",\"email\":\"\",\"name\":\"张华光\"},{\"subcompanyid1span\":\"J&T集团>J&T中国\",\"img\":\"/messager/usericon/e6a341e5-9f10-4d1a-8dc1-ef15d67628ec.jpg\",\"subcompanyid\":\"1021\",\"pinyinlastname\":\"\",\"workcode\":\"00166012\",\"departmentidspan\":\"财务部\",\"departmentid\":\"1525\",\"messagerurl\":\"/messager/usericon/e6a341e5-9f10-4d1a-8dc1-ef15d67628ec.jpg\",\"mobile\":\"18321533556\",\"icon\":\"/messager/usericon/e6a341e5-9f10-4d1a-8dc1-ef15d67628ec.jpg\",\"requestParams\":\"{\\\"headformat\\\":\\\"2\\\",\\\"isDefault\\\":true,\\\"gender\\\":\\\"0\\\",\\\"background\\\":\\\"#55B1F9\\\",\\\"messagerurl\\\":\\\"/messager/usericon/e6a341e5-9f10-4d1a-8dc1-ef15d67628ec.jpg\\\",\\\"fontcolor\\\":\\\"#FFFFFF\\\",\\\"defaultmessagerurl\\\":\\\"\\\",\\\"shortname\\\":\\\"刘庞\\\",\\\"lastname\\\":\\\"刘庞\\\"}\",\"subcompanyid1\":\"1021\",\"subcompanyname\":\"J&T中国\",\"supsubcompanyname\":\"J&T集团\",\"lastname\":\"刘庞\",\"jobtitlename\":\"账务会计\",\"departmentname\":\"财务部\",\"lastnamespan\":\"刘庞\",\"id\":\"44747\",\"supsubcompanyid\":\"521\",\"email\":\"\",\"nodeid\":\"resource_44747x\",\"type\":\"resource\",\"crmNames\":\"财务部/J&T集团/J&T中国\",\"name\":\"刘庞\"}],\"id\":\"12615\"}\n"; + } + + private static void readFile(InputStream input) + + throws IOException { + + InputStreamReader isr = + + new InputStreamReader(input); + + BufferedReader reader = new BufferedReader(isr); + + String line; + + while ((line = reader.readLine()) != null) { + + System.out.println(line); + + } + + reader.close(); + + } + + + + + public static String getCurDateTime() { + Date newdate = new Date(); + long datetime = newdate.getTime(); + Timestamp timestamp = new Timestamp(datetime); + return (timestamp.toString().replace(".","").replace("-", "").replace(":", "").replace(" ", "")); + } + + + //BASE64解码成File文件 + public void base64ToFile(String destPath,String base64, String fileName) { + File file = null; + //创建文件目录 + String filePath=destPath; + File dir=new File(filePath); + if (!dir.exists() && !dir.isDirectory()) { + dir.mkdirs(); + } + BufferedOutputStream bos = null; + java.io.FileOutputStream fos = null; + try { + byte[] bytes = Base64.getDecoder().decode(base64); + file=new File(filePath+"/"+fileName); + fos = new java.io.FileOutputStream(file); + bos = new BufferedOutputStream(fos); + bos.write(bytes); + } catch (Exception e) { + e.printStackTrace(); + } finally { + if (bos != null) { + try { + bos.close(); + } catch (IOException e) { + e.printStackTrace(); + } + } + if (fos != null) { + try { + fos.close(); + } catch (IOException e) { + e.printStackTrace(); + } + } + } + } + + + + +} \ No newline at end of file diff --git a/src/main/youhong_ai_jitu_src/jntchina/test/test4.java b/src/main/youhong_ai_jitu_src/jntchina/test/test4.java new file mode 100644 index 0000000..78246ef --- /dev/null +++ b/src/main/youhong_ai_jitu_src/jntchina/test/test4.java @@ -0,0 +1,40 @@ +package jntchina.test; + + +import jntchina.util.HttpClientUtil; +import jntchina.util.URLConfigEnum; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + + +public class test4 { + public static void main(String[] args) throws Exception { + String a = "abcd"; + String b = "abcd"; + System.out.println(a.getBytes()); + System.out.println(b.getBytes()); + System.out.println(a.equals(b)); + System.out.println(a == b); + } + + /** + * 台账记账Bills + */ + public static List accountBills() { + List datas = new ArrayList(); + Map data = new HashMap(); + //发票代码 + data.put("invoiceCode", "036002000104"); + //发票号码 + data.put("invoiceNum", "25696630"); + data.put("billType", "taxi"); + data.put("accountUser", "系统管理员"); + data.put("accountNote", "别问,问就是测试"); + datas.add(data); + return datas; + } + +} diff --git a/src/main/youhong_ai_jitu_src/jntchina/util/Base64Util.java b/src/main/youhong_ai_jitu_src/jntchina/util/Base64Util.java new file mode 100644 index 0000000..5cb399f --- /dev/null +++ b/src/main/youhong_ai_jitu_src/jntchina/util/Base64Util.java @@ -0,0 +1,88 @@ +package jntchina.util; + +import sun.misc.BASE64Decoder; +import sun.misc.BASE64Encoder; + +import java.io.ByteArrayOutputStream; +import java.io.FileInputStream; +import java.io.IOException; +import java.io.InputStream; +import java.net.HttpURLConnection; +import java.net.URL; +import java.util.Base64; + +/** + * Base64������ + * + * @author liyang + * + */ +public class Base64Util { + + /** + * Base64���� + */ + public static String encryptBASE64(byte[] key) { + return (new BASE64Encoder()).encodeBuffer(key); + } + + /** + * Base64���� + * @throws IOException + */ + public static byte[] decryptBASE64(String key) throws IOException { + return (new BASE64Decoder()).decodeBuffer(key); + } + + public static Object NetImageToBase64(String netImagePath) { + final ByteArrayOutputStream data = new ByteArrayOutputStream(); + try { + // 创建URL + URL url = new URL(netImagePath); + final byte[] by = new byte[1024]; + // 创建链接 + final HttpURLConnection conn = (HttpURLConnection) url.openConnection(); + conn.setRequestMethod("GET"); + conn.setConnectTimeout(5000); + InputStream is = conn.getInputStream(); + // 将内容读取内存中 + int len = -1; + while ((len = is.read(by)) != -1) { + data.write(by, 0, len); + } + // 对字节数组Base64编码 + BASE64Encoder encoder = new BASE64Encoder(); + // 关闭流 + is.close(); + return Base64.getEncoder().encodeToString(data.toByteArray()); + //return encoder.encode(data.toByteArray()).replaceAll("\n", "").replaceAll("\r", ""); + } catch (IOException e) { + e.printStackTrace(); + } + return null; + } + /** + * @description: 本地图片转Base64 + * @author: kw + * @date: 2020/5/22 + * @param: [imgPath] + * @return: java.lang.String + */ + public static String imageToBase64(String imgPath) { + // 将图片文件转化为字节数组字符串,并对其进行Base64编码处理 + InputStream in = null; + byte[] data = null; + // 读取图片字节数组 + try { + in = new FileInputStream(imgPath); + data = new byte[in.available()]; + in.read(data); + in.close(); + } catch (IOException e) { + e.printStackTrace(); + } + // 返回Base64编码过的字节数组字符串 + //return new BASE64Encoder().encode(data).replaceAll("\n", "").replaceAll("\r", ""); + return Base64.getEncoder().encodeToString(data); + } +} diff --git a/src/main/youhong_ai_jitu_src/jntchina/util/CipherConstant.java b/src/main/youhong_ai_jitu_src/jntchina/util/CipherConstant.java new file mode 100644 index 0000000..d592314 --- /dev/null +++ b/src/main/youhong_ai_jitu_src/jntchina/util/CipherConstant.java @@ -0,0 +1,8 @@ +package jntchina.util; + +public class CipherConstant { + // �����㷨����AES�ԳƼ��� + public static final String ALGORITHM_AES = "AES"; + // �����㷨����RSA�ǶԳƼ��� + public static final String ALGORITHM_RSA = "RSA"; +} diff --git a/src/main/youhong_ai_jitu_src/jntchina/util/CompressUtil.java b/src/main/youhong_ai_jitu_src/jntchina/util/CompressUtil.java new file mode 100644 index 0000000..b67e1cf --- /dev/null +++ b/src/main/youhong_ai_jitu_src/jntchina/util/CompressUtil.java @@ -0,0 +1,169 @@ +package jntchina.util; + +import java.io.ByteArrayInputStream; +import java.io.ByteArrayOutputStream; +import java.io.IOException; +import java.nio.charset.StandardCharsets; +import java.util.zip.*; + +/** + * ѹ�������� + * + * @author liyang + * + */ +public class CompressUtil { + + private static int buffSize = 1024; + + /** + * deflaterCompress Ĭ��ѹ�� + * + * @param source + * ԭ�� + * @return + * @throws IOException + * @throws BizException + * @throws Exception + */ + public static String deflaterCompress(String source) throws Exception { + String value = null; + + ByteArrayOutputStream bos = new ByteArrayOutputStream(); + Deflater compressor = new Deflater(); + + try { + + byte[] input = source.getBytes(StandardCharsets.UTF_8); + // ����ѹ���Ǽ� + compressor.setLevel(Deflater.DEFAULT_COMPRESSION); + compressor.setInput(input); + compressor.finish(); + final byte[] buf = new byte[buffSize]; + + while (!compressor.finished()) { + int count = compressor.deflate(buf); + bos.write(buf, 0, count); + } + value = Base64Util.encryptBASE64(bos.toByteArray()); + + } finally { + bos.close(); + compressor.end(); + } + + return value; + } + + /** + * deflaterDecompress Ĭ�Ͻ�ѹ + * + * @param source + * ѹ�����ı� + * @return + * @throws IOException + * @throws @throws + * Exception + */ + public static String deflaterDecompress(String source) throws Exception { + String value = null; + + ByteArrayOutputStream bos = new ByteArrayOutputStream(); + Inflater decompressor = new Inflater(); + + try { + byte[] input = Base64Util.decryptBASE64(source); + + decompressor.setInput(input); + final byte[] buf = new byte[buffSize]; + + while (!decompressor.finished()) { + int count = decompressor.inflate(buf); + bos.write(buf, 0, count); + } + + value = new String(bos.toByteArray(), StandardCharsets.UTF_8); + } catch (IOException | DataFormatException e) { + throw new Exception("��ѹ�쳣 " + e.getMessage()); + } finally { + bos.close(); + decompressor.end(); + } + return value; + } + + /** + * gzipCompress ����gzipѹ�� + * + * @param source + * ԭ�� + * @return + * @throws IOException + * @throws BizException + * @throws Exception + */ + public static String gzipCompress(String source) throws Exception { + String value = null; + + ByteArrayOutputStream out = null; + + try { + out = new ByteArrayOutputStream(); + GZIPOutputStream gzip = new GZIPOutputStream(out); + byte[] input = source.getBytes(StandardCharsets.UTF_8); + gzip.write(input); + gzip.close(); + value = Base64Util.encryptBASE64(out.toByteArray()); + } catch (IOException e) { + throw new Exception("ѹ���쳣 " + e.getMessage()); + }finally { + if(out != null){ + out.close(); + } + } + + return value; + } + + /** + * gzipDecompress gzip��ѹ + * + * @param source + * ѹ�����ı� + * @return + * @throws BizException + * @throws Exception + */ + public static String gzipDecompress(String source) throws Exception { + String value = null; + + ByteArrayOutputStream out = null; + ByteArrayInputStream in = null; + + try { + byte[] input = Base64Util.decryptBASE64(source); + out = new ByteArrayOutputStream(); + in = new ByteArrayInputStream(input); + GZIPInputStream ungzip = new GZIPInputStream(in); + + byte[] buffer = new byte[buffSize]; + int n; + while ((n = ungzip.read(buffer)) >= 0) { + out.write(buffer, 0, n); + } + ungzip.close(); + value = new String(out.toByteArray(), StandardCharsets.UTF_8); + } catch (IOException e) { + throw new Exception("ѹ���쳣 " + e.getMessage()); + } finally { + if (in != null) { + in.close(); + } + if (out != null) { + out.close(); + } + + } + return value; + } +} diff --git a/src/main/youhong_ai_jitu_src/jntchina/util/DataBaseUtils.java b/src/main/youhong_ai_jitu_src/jntchina/util/DataBaseUtils.java new file mode 100644 index 0000000..00464e0 --- /dev/null +++ b/src/main/youhong_ai_jitu_src/jntchina/util/DataBaseUtils.java @@ -0,0 +1,288 @@ +package jntchina.util; + +import selfdev.util.log.LogTool; +import weaver.conn.RecordSet; +import weaver.soa.workflow.request.RequestInfo; + +import java.io.ByteArrayOutputStream; +import java.io.PrintStream; +import java.io.PrintWriter; +import java.io.StringWriter; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.Locale; +import java.util.Map; + +/** + * @title: 工具类 + * @Author ycf + * @Date: 2022/1/7 17:13 + * @Version 1.0 + */ +public class DataBaseUtils { + private final static LogTool log = new LogTool("/log/utils/DataBase/", false); + + + /** + * 通过获取单条数据 + * @param sql 执行的SQL + * @return map + */ + public static Map getDataMap(String sql) { + RecordSet recordSet = new RecordSet(); + sql = strNull(sql); + log.writeLog("获取单行数据SQL:"+sql); + recordSet.execute(sql); + recordSet.next(); + HashMap map = new HashMap<>(); + for (String s : recordSet.getColumnName()) { + map.put(s.toUpperCase(), strNull(recordSet.getString(s))); + } + return map; + } + + + /** + * 通过SQL获取数据集 + * @param sql SQL命令 + * @return map->list + */ + public static ArrayList> getDataList(String sql) { + RecordSet recordSet = new RecordSet(); + sql = strNull(sql); + log.writeLog("通过SQL获取数据集:"+sql); + ArrayList> maps = new ArrayList<>(); + + recordSet.execute(sql); + while (recordSet.next()) { + HashMap map = new HashMap<>(); + for (String s : recordSet.getColumnName()) { + map.put(s.toUpperCase(), strNull(recordSet.getString(s))); + } + maps.add(map); + } + return maps; + } + + + + public static ArrayList getList(String sql) { + RecordSet recordSet = new RecordSet(); + sql = strNull(sql); + log.writeLog("通过SQL获取list:"+sql); + ArrayList list = new ArrayList<>(); + + recordSet.execute(sql); + while (recordSet.next()) { + + list.add(recordSet.getString(recordSet.getColumnName()[0])); + } + return list; + } + + /** + * 获取查询结果中的第一个值 + * @param sql sql + * @return value + */ + public static String getFirstValue(String sql) { + RecordSet recordSet = new RecordSet(); + sql = strNull(sql); + log.writeLog("获取查询结果中的第一个值:"+sql); + + recordSet.execute(sql); + recordSet.next(); + return strNull(recordSet.getString(recordSet.getColumnName()[0])); + } + + + /** + * 获取流程主表的数据 + * @param requestInfo + * @return + */ + public static Map getProcessData(RequestInfo requestInfo) { + String tableName = requestInfo.getRequestManager().getBillTableName(); + String requestid = requestInfo.getRequestid(); + String sql = "select * from " + tableName + " where requestid = " + requestid; + log.writeLog("获取流程主表数据:"+sql); + + return DataBaseUtils.getDataMap(sql); + + } + + /** + * 获取流程主表的数据 + * @param requestInfo req + * @param detailId 明细表索引 明细表1-》1 ,明细表2 -》2 + * @return data + */ + public static ArrayList> getProcessData(RequestInfo requestInfo,int detailId) { + String tableName = requestInfo.getRequestManager().getBillTableName(); + String requestid = requestInfo.getRequestid(); + + + String sql = "select * from " + tableName + "_dt" + detailId + " where mainid = (select id from "+tableName+" where requestid = '"+requestid+"' )"; + log.writeLog("获取流程明细表["+detailId+"]数据:"+sql); + + + return DataBaseUtils.getDataList(sql); + + } + + + + + public static boolean dataIsExists(String sql) { + String firstValue = getFirstValue(strNull(sql)); + log.writeLog("取得结果:" + firstValue); + return !"".equals(firstValue); + + } + + + /** + * 通过表单名称获取建模ID + * @param tableName 表名称 + * @return 建模ID + */ + public static String getModelIdByName(String tableName) { + String sql = "select id from modeinfo where formid = (select id from workflow_bill where tablename = '"+strNull(tableName)+"')"; + log.writeLog("通过表单名称获取建模ID:"+sql); + + return getFirstValue(sql); + } + + /** + * 通过表名获取表单ID + * @param tableName 表名 + * @return 表单ID + */ + public static String getTableIdByName(String tableName) { + String sql = "select id from workflow_bill where tablename = '"+strNull(tableName)+"'"; + log.writeLog("通过表名获取表单ID:"+sql); + return getFirstValue(sql); + } + + /** + * 获取流程中下拉框的字段名 + * @param value 值0,1~ + * @param workFlowId requestInfo.getWorkflowid() + * @param fieldName 字段名 + * @return 选择的值 + */ + public static String getSelectValueOfAction(String value, String workFlowId, String fieldName) { + + String sql = "select SELECTNAME " + + "from WORKFLOW_SELECTITEM " + + "where SELECTVALUE = "+strNull(value)+" " + + " and fieldid in (select id " + + " from workflow_billfield " + + " where billid in " + + " (select formid from workflow_base where id = "+strNull(workFlowId)+") " + + " and FIELDNAME = '"+strNull(fieldName)+"' " + + " and VIEWTYPE = 0)"; + log.writeLog("获取流程中选择的字段名:"+sql); + + return getFirstValue(sql); + } + + + /** + * 获取建模下拉框的字段名 + * @param value 值0,1~ + * @param tableName 建模的表名 + * @param fieldName 字段名 + * @return 选择的值 + */ + public static String getSelectValueOfModel(String value, String tableName, String fieldName) { + + + String sql = "select SELECTNAME" + + " from WORKFLOW_SELECTITEM" + + " where SELECTVALUE = "+strNull(value)+"" + + " and fieldid in (select id" + + " from workflow_billfield" + + " where billid =(select id from workflow_bill where tablename = '"+strNull(tableName)+"')" + + " and FIELDNAME = '"+strNull(fieldName)+"'" + + " and VIEWTYPE = 0)"; + log.writeLog("获取流程中选择的值:"+sql); + + return getFirstValue(sql); + } + + + + /** + * 获取异常详细信息,知道出了什么错,错在哪个类的第几行 . + * + * @param ex + * @return + */ + public static String getExceptionDetail(Exception ex) { + String ret = null; + try { + ByteArrayOutputStream out = new ByteArrayOutputStream(); + PrintStream pout = new PrintStream(out); + ex.printStackTrace(pout); + ret = new String(out.toByteArray()); + pout.close(); + out.close(); + } catch (Exception e) { + } + return ret; + } + + /** + * 获取异常详细信息,知道出了什么错,错在哪个类的第几行 . + * + * @param ex + * @return + */ + public static String getExceptionDetail(Error ex) { + String ret = null; + try { + ByteArrayOutputStream out = new ByteArrayOutputStream(); + PrintStream pout = new PrintStream(out); + ex.printStackTrace(pout); + ret = new String(out.toByteArray()); + pout.close(); + out.close(); + } catch (Exception e) { + } + return ret; + } + + /** + * 获取异常详细信息,知道出了什么错,错在哪个类的第几行 . + * + * @param + * @return + */ + public static String getThrowableDetail(Throwable ex) { + StringWriter sw = new StringWriter(); + try { + PrintWriter pw = new PrintWriter(sw, true); + ex.printStackTrace(pw); + pw.flush(); + sw.flush(); + } catch (Exception e) { + + } + return sw.toString(); + } + + + + /** + * string判空 + * @param str value + * @return "" or value + */ + public static String strNull(String str) { + return (null == str) ? "" : str; + } + + + +} \ No newline at end of file diff --git a/src/main/youhong_ai_jitu_src/jntchina/util/Decryption.java b/src/main/youhong_ai_jitu_src/jntchina/util/Decryption.java new file mode 100644 index 0000000..cb5659b --- /dev/null +++ b/src/main/youhong_ai_jitu_src/jntchina/util/Decryption.java @@ -0,0 +1,104 @@ +package jntchina.util; + +import javax.crypto.BadPaddingException; +import javax.crypto.Cipher; +import javax.crypto.IllegalBlockSizeException; +import javax.crypto.NoSuchPaddingException; +import java.io.ByteArrayOutputStream; +import java.io.IOException; +import java.security.InvalidKeyException; +import java.security.Key; +import java.security.NoSuchAlgorithmException; + +/** + * ������ + * + * @author liyang + * + */ +public class Decryption { + + // RSA���������Ĵ�С + private static final int MAX_DECRYPT_BLOCK = 128; + + /** + * symDecrypt �Գƽ��� + * + * @param strkey �Գ���Կ + * @param src ���� + * @return ԭ�� + * @throws IOException + * @throws Exception + */ + public static String symDecrypt(String strkey, String src) throws Exception { + + String target = null; + + try { + Key key = KeysFactory.getSymKey(strkey); + // ���� + Cipher cipher = Cipher.getInstance(CipherConstant.ALGORITHM_AES); + cipher.init(Cipher.DECRYPT_MODE, key); + byte[] decodeResult = cipher.doFinal(Base64Util.decryptBASE64(src)); + target = new String(decodeResult); + + } catch (NoSuchAlgorithmException | NoSuchPaddingException | IllegalBlockSizeException | BadPaddingException | InvalidKeyException e) { + e.printStackTrace(); + throw new Exception("����ʧ��" + e.getMessage()); + } + + return target; + } + + /** + * priDecrypt ˽Կ���� + * + * @param priKey ˽Կ + * @param src ���� + * @return ԭ�� + * @throws IOException + * @throws Exception + */ + public static String priDecrypt(String priKey, String src) throws Exception { + + String target = null; + ByteArrayOutputStream out = null; + try { + Key key = KeysFactory.getPrivateKey(priKey); + + // ���� + Cipher cipher = Cipher.getInstance(CipherConstant.ALGORITHM_RSA); + cipher.init(Cipher.DECRYPT_MODE, key); + // byte[] decodeResult = cipher.doFinal(src.getBytes(CHARSET)); + // target = new String(decodeResult); + + byte[] data = Base64Util.decryptBASE64(src); + int inputLen = data.length; + out = new ByteArrayOutputStream(); + int offSet = 0; + byte[] cache; + int i = 0; + // �����ݷֶν��� + while (inputLen - offSet > 0) { + if (inputLen - offSet > MAX_DECRYPT_BLOCK) { + cache = cipher.doFinal(data, offSet, MAX_DECRYPT_BLOCK); + } else { + cache = cipher.doFinal(data, offSet, inputLen - offSet); + } + out.write(cache, 0, cache.length); + i++; + offSet = i * MAX_DECRYPT_BLOCK; + } + target = new String(out.toByteArray()); + + } catch (NoSuchAlgorithmException | NoSuchPaddingException | InvalidKeyException | IllegalBlockSizeException | BadPaddingException e) { + e.printStackTrace(); + throw new Exception("����ʧ��" + e.getMessage()); + }finally{ + if(out != null){ + out.close(); + } + } + return target; + } +} diff --git a/src/main/youhong_ai_jitu_src/jntchina/util/Encryption.java b/src/main/youhong_ai_jitu_src/jntchina/util/Encryption.java new file mode 100644 index 0000000..08b0fa6 --- /dev/null +++ b/src/main/youhong_ai_jitu_src/jntchina/util/Encryption.java @@ -0,0 +1,106 @@ +package jntchina.util; + +import javax.crypto.BadPaddingException; +import javax.crypto.Cipher; +import javax.crypto.IllegalBlockSizeException; +import javax.crypto.NoSuchPaddingException; +import java.io.ByteArrayOutputStream; +import java.io.IOException; +import java.io.UnsupportedEncodingException; +import java.nio.charset.StandardCharsets; +import java.security.InvalidKeyException; +import java.security.Key; +import java.security.NoSuchAlgorithmException; +import java.security.Provider; + +/** + * ������ + * + * @author liyang + * + */ +public class Encryption { + + private static Provider DEFAULT_Provider =new com.sun.crypto.provider.SunJCE(); + // RSA���������Ĵ�С + private static final int MAX_ENCRYPT_BLOCK = 117; + + /** + * symEncrypt �ԳƼ��� + * + * @param strkey + * �Գ���Կ + * @param src + * ԭ�� + * @return ���� + * @throws BizException + */ + public static String symEncrypt(String strkey, String src) throws Exception { + String target = null; + try { + Key key = KeysFactory.getSymKey(strkey); + // ���� + Cipher cipher = Cipher.getInstance(CipherConstant.ALGORITHM_AES); + cipher.init(Cipher.ENCRYPT_MODE, key); + byte[] encodeResult = cipher.doFinal(src.getBytes(StandardCharsets.UTF_8)); + target = Base64Util.encryptBASE64(encodeResult); + } catch (NoSuchAlgorithmException | NoSuchPaddingException | UnsupportedEncodingException | InvalidKeyException | IllegalBlockSizeException + | BadPaddingException e) { + e.printStackTrace(); + throw new Exception("����ʧ��" + e.getMessage()); + } + return target; + } + + /** + * pubEncrypt ��Կ���� + * + * @param pubKey + * ��Կ + * @param src + * ԭ�� + * @return ���� + * @throws IOException + * @throws Exception + */ + public static String pubEncrypt(String pubKey, String src) throws Exception { + String target = null; + ByteArrayOutputStream out = null; + try { + Key key = KeysFactory.getPublicKey(pubKey); + + Cipher cipher = Cipher.getInstance(CipherConstant.ALGORITHM_RSA); +// Cipher cipher = Cipher.getInstance(CipherConstant.ALGORITHM_RSA,DEFAULT_Provider); + cipher.init(Cipher.ENCRYPT_MODE, key); + System.out.println(cipher.getProvider().getClass().getName()); + // encodeResult = cipher.doFinal(src.getBytes()); + byte[] data = src.getBytes(); + int inputLen = data.length; + out = new ByteArrayOutputStream(); + int offSet = 0; + byte[] cache; + int i = 0; + // �����ݷֶμ��� + while (inputLen - offSet > 0) { + if (inputLen - offSet > MAX_ENCRYPT_BLOCK) { + cache = cipher.doFinal(data, offSet, MAX_ENCRYPT_BLOCK); + } else { + cache = cipher.doFinal(data, offSet, inputLen - offSet); + } + out.write(cache, 0, cache.length); + i++; + offSet = i * MAX_ENCRYPT_BLOCK; + } + + target = Base64Util.encryptBASE64(out.toByteArray()); + } catch (NoSuchAlgorithmException | NoSuchPaddingException | InvalidKeyException | IllegalBlockSizeException | BadPaddingException e) { + e.printStackTrace(); + throw new Exception("����ʧ��" + e.getMessage()); + }finally{ + if(out != null){ + out.close(); + } + } + return target; + } +} diff --git a/src/main/youhong_ai_jitu_src/jntchina/util/HttpClientConfig.java b/src/main/youhong_ai_jitu_src/jntchina/util/HttpClientConfig.java new file mode 100644 index 0000000..3797093 --- /dev/null +++ b/src/main/youhong_ai_jitu_src/jntchina/util/HttpClientConfig.java @@ -0,0 +1,59 @@ +package jntchina.util; + +/** + * HttpClientConfig http请求配置 + */ +public class HttpClientConfig { + + /** + * 连接时间 ms + */ + protected int CONNECT_TIMING_OUT = 30000; + /** + * 请求响应时间 ms + */ + protected int RESPONSE_TIMING_OUT = 30000; + + /** + * 发起请求时间 ms + */ + protected int REQUEST_TIMING_OUT = 30000; + + public HttpClientConfig(int CONNECT_TIMING_OUT, int RESPONSE_TIMING_OUT, int REQUEST_TIMING_OUT) { + this.CONNECT_TIMING_OUT = CONNECT_TIMING_OUT; + this.RESPONSE_TIMING_OUT = RESPONSE_TIMING_OUT; + this.REQUEST_TIMING_OUT = REQUEST_TIMING_OUT; + } + + public HttpClientConfig(){ + + } + + public static HttpClientConfig defaultConfig(){ + return new HttpClientConfig(); + } + + public int getCONNECT_TIMING_OUT() { + return CONNECT_TIMING_OUT; + } + + public void setCONNECT_TIMING_OUT(int CONNECT_TIMING_OUT) { + this.CONNECT_TIMING_OUT = CONNECT_TIMING_OUT; + } + + public int getRESPONSE_TIMING_OUT() { + return RESPONSE_TIMING_OUT; + } + + public void setRESPONSE_TIMING_OUT(int RESPONSE_TIMING_OUT) { + this.RESPONSE_TIMING_OUT = RESPONSE_TIMING_OUT; + } + + public int getREQUEST_TIMING_OUT() { + return REQUEST_TIMING_OUT; + } + + public void setREQUEST_TIMING_OUT(int REQUEST_TIMING_OUT) { + this.REQUEST_TIMING_OUT = REQUEST_TIMING_OUT; + } +} diff --git a/src/main/youhong_ai_jitu_src/jntchina/util/HttpClientToDC.java b/src/main/youhong_ai_jitu_src/jntchina/util/HttpClientToDC.java new file mode 100644 index 0000000..7c0a2e2 --- /dev/null +++ b/src/main/youhong_ai_jitu_src/jntchina/util/HttpClientToDC.java @@ -0,0 +1,145 @@ +package jntchina.util; + +import selfdev.util.base.TimeCommonUtil; +import selfdev.util.log.LogTool; +import weaver.file.Prop; +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.JSONObject; +import com.weaver.general.Util; +import org.apache.http.HttpEntity; +import org.apache.http.client.methods.CloseableHttpResponse; +import org.apache.http.client.methods.HttpPost; +import org.apache.http.entity.ContentType; +import org.apache.http.entity.StringEntity; +import org.apache.http.impl.client.CloseableHttpClient; +import org.apache.http.impl.client.HttpClients; +import org.apache.http.util.EntityUtils; + +/** + * 数据中台HTTP接口 + * KangMD + * 2021-05-06 + */ +public class HttpClientToDC { + + //获取配置文件中的参数 + public static final String mode = Prop.getPropValue("DevToDC_jntchina","mode"); + // 服务器ip:port + public static final String baseUrl = Prop.getPropValue("DevToDC_jntchina", mode+"_baseUrl"); + // 用户名 + public static final String userName = Prop.getPropValue("DevToDC_jntchina", mode+"_userName"); + // 密码 + public static final String password = Prop.getPropValue("DevToDC_jntchina", mode+"_password"); + // 系统标识 + public static final String systemCode = Prop.getPropValue("DevToDC_jntchina", mode+"_systemCode"); + // 秘钥 + public static final String secretkey = Prop.getPropValue("DevToDC_jntchina", mode+"_secretkey"); + + public static LogTool log = new LogTool("/log/selfdev/util", false); + + /** + * 获取token + * @return + * @throws Exception + */ + public static String getToken() { + String token = null; + try { + //获取当前系统日期 + String today=TimeCommonUtil.obtainDate(0).substring(0,10).replace("-", ""); + //加密串 + String encryptionKey= MD5Utils.encrypt(userName+":"+password+":"+today+":"+secretkey); + CloseableHttpClient client = HttpClients.createDefault(); + HttpPost post = new HttpPost(baseUrl+"/dcoauthedi/oauth/getToken"); + JSONObject param=new JSONObject(); + param.put("userName",userName);//用户名 + param.put("password",password);//密码 + param.put("systemCode",systemCode);//系统标识 + param.put("encryptionKey",encryptionKey);//授权类型 + log.writeLog("调用AccessToken接口传入参数----->"+param.toString()); + StringEntity requestentity=new StringEntity(param.toString(),"utf-8"); + requestentity.setContentType(ContentType.APPLICATION_JSON.toString()); + post.setEntity(requestentity); + + String responseContent = null; // 响应内容 + CloseableHttpResponse response = client.execute(post); + if (response.getStatusLine().getStatusCode() == 200) { + HttpEntity entity = response.getEntity(); + responseContent = EntityUtils.toString(entity, "UTF-8"); + } + log.writeLog("调用getToken接口返回结果----->"+responseContent); + if(!"".equals(responseContent)){ + JSONObject object_return=JSON.parseObject(responseContent); + //接口返回状态 + String succ=Util.null2String(object_return.getString("succ")); + if("true".equals(succ)){ + token= Util.null2String(object_return.getString("data")); + } + } + }catch (Exception e) { + e.printStackTrace(); + } + + return token; + } + + /** + * 发送POST请求 + * @param url + * @param token + * @param parm + * @return + */ + public static String sendPostApi(String url,String token,String param) { + String resulet=""; + try { + CloseableHttpClient client = HttpClients.createDefault(); + HttpPost post = new HttpPost(url); + post.addHeader("token", token); + log.writeLog("调用【"+url+"】接口传入参数----->"+param.toString()); + StringEntity requestentity=new StringEntity(param.toString(),"utf-8"); + requestentity.setContentType(ContentType.APPLICATION_JSON.toString()); + post.setEntity(requestentity); + CloseableHttpResponse response = client.execute(post); + if (response.getStatusLine().getStatusCode() == 200) { + HttpEntity entity = response.getEntity(); + resulet = EntityUtils.toString(entity, "UTF-8"); + } + log.writeLog("调用【"+url+"】接口返回结果----->"+resulet); + }catch (Exception e) { + e.printStackTrace(); + log.writeLog("调用【"+url+"】接口异常,错误信息----->"+resulet); + } + + return resulet; + } + + /** + * 发送POST请求(无Token) + * @param url + * @param parm + * @return + */ + public static String sendPostApiNoToken(String url,String param) { + String resulet=""; + try { + CloseableHttpClient client = HttpClients.createDefault(); + HttpPost post = new HttpPost(url); + log.writeLog("调用【"+url+"】接口传入参数----->"+param.toString()); + StringEntity requestentity=new StringEntity(param.toString(),"utf-8"); + requestentity.setContentType(ContentType.APPLICATION_JSON.toString()); + post.setEntity(requestentity); + CloseableHttpResponse response = client.execute(post); + if (response.getStatusLine().getStatusCode() == 200) { + HttpEntity entity = response.getEntity(); + resulet = EntityUtils.toString(entity, "UTF-8"); + } + log.writeLog("调用【"+url+"】接口返回结果----->"+resulet); + }catch (Exception e) { + e.printStackTrace(); + log.writeLog("调用【"+url+"】接口异常,错误信息----->"+resulet); + } + + return resulet; + } +} diff --git a/src/main/youhong_ai_jitu_src/jntchina/util/HttpClientToJT.java b/src/main/youhong_ai_jitu_src/jntchina/util/HttpClientToJT.java new file mode 100644 index 0000000..6c64edf --- /dev/null +++ b/src/main/youhong_ai_jitu_src/jntchina/util/HttpClientToJT.java @@ -0,0 +1,178 @@ +package jntchina.util; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.JSONObject; +import com.weaver.general.Util; +import org.apache.http.HttpEntity; +import org.apache.http.NameValuePair; +import org.apache.http.client.entity.UrlEncodedFormEntity; +import org.apache.http.client.methods.CloseableHttpResponse; +import org.apache.http.client.methods.HttpGet; +import org.apache.http.client.methods.HttpPost; +import org.apache.http.entity.ContentType; +import org.apache.http.entity.StringEntity; +import org.apache.http.impl.client.CloseableHttpClient; +import org.apache.http.impl.client.HttpClients; +import org.apache.http.message.BasicNameValuePair; +import org.apache.http.util.EntityUtils; +import selfdev.util.base.TimeCommonUtil; +import weaver.file.Prop; + +import java.util.ArrayList; +import java.util.List; +import java.util.Map; + +/** + * 数据中台HTTP接口(极兔) + * CYQ + * 2021-06-15 + */ +public class HttpClientToJT { + +// //获取配置文件中的参数 + public static final String mode = Prop.getPropValue("DevToDC_jntchina","mode"); + // 服务器ip:port + public static final String baseUrl = "https://jtdcapi.jtexpress.com.cn";//Prop.getPropValue("DevToDC_jntchina", mode+"_baseUrl"); +// // 用户名 +// public static final String userName = Prop.getPropValue("DevToDC_jntchina", mode+"_userName"); +// // 密码 +// public static final String password = Prop.getPropValue("DevToDC_jntchina", mode+"_password"); +// // 系统标识 +// public static final String systemCode = Prop.getPropValue("DevToDC_jntchina", mode+"_systemCode"); +// // 秘钥 +// public static final String secretkey = Prop.getPropValue("DevToDC_jntchina", mode+"_secretkey"); + + + + // 服务器ip:port +// public static final String baseUrl = "https://uat-jtdcapi.jtexpress.com.cn"; +// public static final String baseUrl = "https://jtdcapi.jtexpress.com.cn"; + // 用户名 + public static final String userName = "oa001"; + // 密码 + public static final String password = "123456"; + // 系统标识 + public static final String systemCode = "oa"; + // 秘钥 + public static final String secretkey = "5362448sd132d241e5ae27e318qws11d"; + +// public static LogTool log = new LogTool("/log/selfdev/util", false); + + /** + * 获取token + * @return + * @throws Exception + */ + public static String getToken() { + String token = null; + try { + //获取当前系统日期 + String today= TimeCommonUtil.obtainDate(0).substring(0,10).replace("-", ""); + //加密串 + String encryptionKey= MD5Utils.encrypt(userName+":"+password+":"+today+":"+secretkey); +// System.out.println(encryptionKey); + CloseableHttpClient client = HttpClients.createDefault(); + System.out.println("baseUrl:" + baseUrl); + HttpPost post = new HttpPost(baseUrl+"/dcoauthedi/oauth/getToken"); + JSONObject param=new JSONObject(); + param.put("userName",userName);//用户名 + param.put("password",password);//密码 + param.put("systemCode",systemCode);//系统标识 + param.put("encryptionKey",encryptionKey);//授权类型 +// log.writeLog("调用AccessToken接口传入参数----->"+param.toString()); + StringEntity requestentity=new StringEntity(param.toString(),"utf-8"); + requestentity.setContentType(ContentType.APPLICATION_JSON.toString()); + post.setEntity(requestentity); + String responseContent = null; // 响应内容 + CloseableHttpResponse response = client.execute(post); + if (response.getStatusLine().getStatusCode() == 200) { + HttpEntity entity = response.getEntity(); + responseContent = EntityUtils.toString(entity, "UTF-8"); + } +// log.writeLog("调用getToken接口返回结果----->"+responseContent); + if(!"".equals(responseContent)){ + JSONObject object_return= JSON.parseObject(responseContent); + //接口返回状态 + String succ= Util.null2String(object_return.getString("succ")); + if("true".equals(succ)){ + token= Util.null2String(object_return.getString("data")); + } + } + }catch (Exception e) { + e.printStackTrace(); + } + System.out.println(token); + return token; + } + + + + /** + * 发送POST请求 + * + * @param url + * @param token + * @param params + * @return + */ + public static String sendGet(String url, String token, Map params) { + String resulet = ""; + try { + CloseableHttpClient client = HttpClients.createDefault(); + if (params != null && !params.isEmpty()) { + + List pairs = new ArrayList(params.size()); + + for (String key : params.keySet()) { + pairs.add(new BasicNameValuePair(key, params.get(key).toString())); + } + url += "?" + EntityUtils.toString(new UrlEncodedFormEntity(pairs)); + } + HttpGet httpGet = new HttpGet(url); + httpGet.addHeader("token", token); + CloseableHttpResponse response = client.execute(httpGet); + if (response.getStatusLine().getStatusCode() == 200) { + HttpEntity entity = response.getEntity(); + resulet = EntityUtils.toString(entity, "UTF-8"); + } +// log.writeLog("调用【"+url+"】接口返回结果----->"+resulet); + } catch (Exception e) { + e.printStackTrace(); +// log.writeLog("调用【"+url+"】接口异常,错误信息----->"+resulet); + } + + return resulet; + } + + /** + * 发送POST请求 + * + * @param url + * @param token + * @param param + * @return + */ + public static String sendPost(String url, String token, String param) { + String resulet = ""; + try { + CloseableHttpClient client = HttpClients.createDefault(); + HttpPost post = new HttpPost(url); + post.addHeader("token", token); +// log.writeLog("调用【"+url+"】接口传入参数----->"+param.toString()); + StringEntity requestentity = new StringEntity(param.toString(), "utf-8"); + requestentity.setContentType(ContentType.APPLICATION_JSON.toString()); + post.setEntity(requestentity); + CloseableHttpResponse response = client.execute(post); + if (response.getStatusLine().getStatusCode() == 200) { + HttpEntity entity = response.getEntity(); + resulet = EntityUtils.toString(entity, "UTF-8"); + } +// log.writeLog("调用【"+url+"】接口返回结果----->"+resulet); + } catch (Exception e) { + e.printStackTrace(); +// log.writeLog("调用【"+url+"】接口异常,错误信息----->"+resulet); + } + + return resulet; + } +} diff --git a/src/main/youhong_ai_jitu_src/jntchina/util/HttpClientToNCC.java b/src/main/youhong_ai_jitu_src/jntchina/util/HttpClientToNCC.java new file mode 100644 index 0000000..7d40383 --- /dev/null +++ b/src/main/youhong_ai_jitu_src/jntchina/util/HttpClientToNCC.java @@ -0,0 +1,359 @@ +package jntchina.util; + +import com.google.gson.Gson; +import org.apache.commons.lang3.StringUtils; +import selfdev.util.log.LogTool; +import weaver.file.Prop; + +import java.io.*; +import java.lang.reflect.Type; +import java.net.HttpURLConnection; +import java.net.URL; +import java.net.URLEncoder; +import java.nio.charset.Charset; +import java.util.HashMap; +import java.util.Map; + +/** + * @Author Administrator + * @Description + * @Date 2021/2/19 11:21 + */ +public class HttpClientToNCC { + + //获取配置文件中的参数 + public static final String mode = Prop.getPropValue("DevToNCC_jntchina","mode"); + // app_secret + public static final String client_secret = Prop.getPropValue("DevToNCC_jntchina", mode+"_client_secret"); + // 公钥 + public static final String pubKey = Prop.getPropValue("DevToNCC_jntchina", mode+"_pubKey"); + // app_id + public static final String client_id = Prop.getPropValue("DevToNCC_jntchina", mode+"_client_id"); + // ncc用户名 + public static final String username = null; + // ncc用户名密码 + public static final String pwd = null; + // ncc账套 + public static final String busi_center = Prop.getPropValue("DevToNCC_jntchina", mode+"_busi_center"); + // 获取token方式:client_credentials、password + public static final String grant_type = Prop.getPropValue("DevToNCC_jntchina", mode+"_grant_type"); + // 服务器ip:port + public static final String baseUrl = Prop.getPropValue("DevToNCC_jntchina", mode+"_baseUrl"); + // 返回值压缩加密级别 + public static final String secret_level = "L0"; + // openapi请求路径 +// public static String apiUrl = "/nccloud/api/jitu/erm/bxbill/insert"; + // 访问api获取到的access_token + public static String token = null; + // 重复调用检查 + public static String repeat_check = null; + // 接口调用业务标识 + public static String busi_id = null; + + public static LogTool log = new LogTool("/log/selfdev/action", false); + + public static void main(String[] args) { + try { + System.out.println(getToken()); + } catch (Exception e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + } + + /** + * 获取access_token + * + * @return + * @throws Exception + */ + public static String getToken() throws Exception { + String token = null; + if ("password".equals(grant_type)) { + // 密码模式 + token = getTokenByPWD(); + log.writeLog("--------密码模式----获取access_token"); + } else if ("client_credentials".equals(grant_type)) { + // 客户端模式 + token = getTokenByClient(); + log.writeLog("--------客户端模式----获取access_token"); + } + return token; + } + + /** + * 客户端模式获取token + * + * @return + * @throws Exception + */ + public static String getTokenByClient() throws Exception { + Map paramMap = new HashMap(); + // 密码模式认证 + paramMap.put("grant_type", "client_credentials"); + // 第三方应用id + paramMap.put("client_id", client_id); + // 第三方应用secret 公钥加密 + paramMap.put("client_secret", URLEncoder.encode(Encryption.pubEncrypt(pubKey, client_secret), "utf-8")); + // 账套编码 + paramMap.put("biz_center", busi_center); + // 传递数据源和ncc登录用户 + // paramMap.put("dsname", "TM_0614"); + // paramMap.put("usercode", "1"); + + // 签名 + String sign = SHA256Util.getSHA256(client_id + client_secret + pubKey); + paramMap.put("signature", sign); + + String url = baseUrl + "/nccloud/opm/accesstoken"; + String mediaType = "application/x-www-form-urlencoded"; + + log.writeLog("--------客户端模式获取token-----"); + + return doPost(url, paramMap, mediaType, null, ""); + } + + /** + * 密码模式获取token + * + * @return + * @throws Exception + */ + public static String getTokenByPWD() throws Exception { + Map paramMap = new HashMap(); + // 密码模式认证 + paramMap.put("grant_type", "password"); + // 第三方应用id + paramMap.put("client_id", client_id); + // 第三方应用secret 公钥加密 + paramMap.put("client_secret", URLEncoder.encode(Encryption.pubEncrypt(pubKey, client_secret), "utf-8")); + // ncc用户名 + paramMap.put("username", username); + // 密码 公钥加密 + paramMap.put("password", URLEncoder.encode(Encryption.pubEncrypt(pubKey, pwd), "utf-8")); + // 账套编码 + paramMap.put("biz_center", busi_center); + // 签名 + String sign = SHA256Util.getSHA256(client_id + client_secret + username + pwd + pubKey); + paramMap.put("signature", sign); + + String url = baseUrl + "/nccloud/opm/accesstoken"; + String mediaType = "application/x-www-form-urlencoded"; + return doPost(url, paramMap, mediaType, null, ""); + } + + /** + * @param token token + * @param requestBody 请求参数 + * @return + * @throws Exception + */ + public static String sendApi(String token, String requestBody, String apiUrl) throws Exception { + // token转对象,获取api访问所用token和secret + ResultMessageUtil returnData = new Gson().fromJson(token, (Type) ResultMessageUtil.class); + Map data = (Map) returnData.getData(); + String access_token = data.get("access_token"); + String security_key = data.get("security_key"); + //String refresh_token = data.get("refresh_token"); + log.writeLog("【ACCESS_TOKEN】:" + access_token); + + // 请求路径 + String url = baseUrl + apiUrl; + // header 参数 + Map headermap = new HashMap(); + headermap.put("access_token", access_token); + headermap.put("client_id", client_id); + + StringBuffer sb = new StringBuffer(); + sb.append(client_id); + if (StringUtils.isNotBlank(requestBody)) { + sb.append(requestBody); + } + sb.append(pubKey); + String sign = SHA256Util.getSHA256(sb.toString()); + headermap.put("signature", sign); + + if (StringUtils.isNotBlank(busi_id)) { + headermap.put("busi_id", busi_id); + } + if (StringUtils.isNotBlank(repeat_check)) { + headermap.put("repeat_check", repeat_check); + } + headermap.put("ucg_flag", "y"); + + String mediaType = "application/json;charset=utf-8"; + + // 表体数据json + // 根据安全级别选择加密或压缩请求表体参数 + String json = dealRequestBody(requestBody, security_key, secret_level); + + log.writeLog("json------->"+json); + + return doPost(url, null, mediaType, headermap, json); + } + + /** + * 返回值进行过加密和压缩,对返回值进行解压和解密 + * + * @param source + * @param security_key + * @param level + * @return + * @throws Exception + */ + public static String dealResponseBody(String source, String security_key, String level) throws Exception { + String result = null; + + if (StringUtils.isEmpty(level) || Test.SecretConst.LEVEL0.equals(level)) { + result = source; + } else if (Test.SecretConst.LEVEL1.equals(level)) { + result = Decryption.symDecrypt(security_key, source); + } else if (Test.SecretConst.LEVEL2.equals(level)) { + result = CompressUtil.gzipDecompress(source); + } else if (Test.SecretConst.LEVEL3.equals(level)) { + result = CompressUtil.gzipDecompress(Decryption.symDecrypt(security_key, source)); + } else if (Test.SecretConst.LEVEL4.equals(level)) { + result = Decryption.symDecrypt(security_key, CompressUtil.gzipDecompress(source)); + } else { + throw new Exception("无效的安全等级"); + } + return result; + } + + // 根据安全级别设置,表体是否加密或压缩 + public static String dealRequestBody(String source, String security_key, String level) throws Exception { + String result = null; + if (StringUtils.isEmpty(level) || Test.SecretConst.LEVEL0.equals(level)) { + result = source; + } else if (Test.SecretConst.LEVEL1.equals(level)) { + result = Encryption.symEncrypt(security_key, source); + } else if (Test.SecretConst.LEVEL2.equals(level)) { + result = CompressUtil.gzipCompress(source); + } else if (Test.SecretConst.LEVEL3.equals(level)) { + result = Encryption.symEncrypt(security_key, CompressUtil.gzipCompress(source)); + } else if (Test.SecretConst.LEVEL4.equals(level)) { + result = CompressUtil.gzipCompress(Encryption.symEncrypt(security_key, source)); + } else { + throw new Exception("无效的安全等级"); + } + + return result; + } + + /** + * 发送post请求 + * + * @param baseUrl + * @param paramMap + * @param mediaType + * @param headers + * @param json + * @return + */ + public static String doPost(String baseUrl, Map paramMap, String mediaType, Map headers, String json) { + + HttpURLConnection urlConnection = null; + InputStream in = null; + OutputStream out = null; + BufferedReader bufferedReader = null; + String result = null; + try { + StringBuffer sb = new StringBuffer(); + sb.append(baseUrl); + if (paramMap != null) { + sb.append("?"); + for (Map.Entry entry : paramMap.entrySet()) { + String key = entry.getKey(); + String value = entry.getValue(); + sb.append(key + "=" + value).append("&"); + } + baseUrl = sb.toString().substring(0, sb.toString().length() - 1); + } + + URL urlObj = new URL(baseUrl); + urlConnection = (HttpURLConnection) urlObj.openConnection(); + urlConnection.setConnectTimeout(50000); + urlConnection.setRequestMethod("POST"); + urlConnection.setDoOutput(true); + urlConnection.setDoInput(true); + urlConnection.setUseCaches(false); + urlConnection.addRequestProperty("content-type", mediaType); + if (headers != null) { + for (String key : headers.keySet()) { + urlConnection.addRequestProperty(key, headers.get(key)); + } + } + out = urlConnection.getOutputStream(); + out.write(json.getBytes("utf-8")); + out.flush(); + int resCode = urlConnection.getResponseCode(); + if (resCode == HttpURLConnection.HTTP_OK || resCode == HttpURLConnection.HTTP_CREATED || resCode == HttpURLConnection.HTTP_ACCEPTED) { + in = urlConnection.getInputStream(); + } else { + in = urlConnection.getErrorStream(); + } + bufferedReader = new BufferedReader(new InputStreamReader(in, "utf-8")); + StringBuffer temp = new StringBuffer(); + String line = bufferedReader.readLine(); + while (line != null) { + temp.append(line).append("\r\n"); + line = bufferedReader.readLine(); + } + String ecod = urlConnection.getContentEncoding(); + if (ecod == null) { + ecod = Charset.forName("utf-8").name(); + } + result = new String(temp.toString().getBytes("utf-8"), ecod); + } catch (Exception e) { + System.out.println(e); + } finally { + if (null != bufferedReader) { + try { + bufferedReader.close(); + } catch (IOException e) { + e.printStackTrace(); + } + } + if (null != out) { + try { + out.close(); + } catch (IOException e) { + e.printStackTrace(); + } + } + if (null != in) { + try { + in.close(); + } catch (IOException e) { + e.printStackTrace(); + } + } + urlConnection.disconnect(); + } + + return result; + } + + class SecretConst { + /** + * LEVEL0 不压缩、不加密 + */ + public static final String LEVEL0 = "L0"; + /** + * LEVEL1 只加密、不压缩 + */ + public static final String LEVEL1 = "L1"; + /** + * LEVEL2 只压缩、不加密 + */ + public static final String LEVEL2 = "L2"; + /** + * LEVEL3 先压缩、后加密 + */ + public static final String LEVEL3 = "L3"; + /** + * LEVEL4 先加密、后压缩 + */ + public static final String LEVEL4 = "L4"; + } +} diff --git a/src/main/youhong_ai_jitu_src/jntchina/util/HttpClientUtil.java b/src/main/youhong_ai_jitu_src/jntchina/util/HttpClientUtil.java new file mode 100644 index 0000000..a198408 --- /dev/null +++ b/src/main/youhong_ai_jitu_src/jntchina/util/HttpClientUtil.java @@ -0,0 +1,497 @@ +package jntchina.util; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.serializer.SerializerFeature; +import jntchina.action.SignHelper; +import org.apache.http.HttpEntity; +import org.apache.http.HttpResponse; +import org.apache.http.NameValuePair; +import org.apache.http.client.config.RequestConfig; +import org.apache.http.client.entity.UrlEncodedFormEntity; +import org.apache.http.client.methods.CloseableHttpResponse; +import org.apache.http.client.methods.HttpGet; +import org.apache.http.client.methods.HttpPost; +import org.apache.http.client.methods.HttpPut; +import org.apache.http.conn.ssl.SSLConnectionSocketFactory; +import org.apache.http.conn.ssl.TrustStrategy; +import org.apache.http.entity.ContentType; +import org.apache.http.entity.StringEntity; +import org.apache.http.impl.client.CloseableHttpClient; +import org.apache.http.impl.client.HttpClientBuilder; +import org.apache.http.message.BasicNameValuePair; +import org.apache.http.ssl.SSLContextBuilder; +import org.apache.http.util.EntityUtils; +//import org.slf4j.Logger; +//import org.slf4j.LoggerFactory; +import org.springframework.util.CollectionUtils; +import org.springframework.util.ObjectUtils; +import selfdev.util.log.LogTool; + +import javax.net.ssl.*; +import java.io.ByteArrayOutputStream; +import java.io.IOException; +import java.net.HttpURLConnection; +import java.net.URL; +import java.security.KeyManagementException; +import java.security.NoSuchAlgorithmException; +import java.security.cert.CertificateException; +import java.security.cert.X509Certificate; +import java.util.ArrayList; +import java.util.List; +import java.util.Map; +import java.util.Map.Entry; +import java.util.zip.GZIPInputStream; +import java.util.zip.GZIPOutputStream; + +/** + * @description: http请求的工具类 + * @author: kw + * @date: 2020/5/21 + * @param: + * @return: + */ +public class HttpClientUtil { + // private static Logger LOGGER = LoggerFactory.getLogger(HttpClientUtil.class); + private static final LogTool log = new LogTool("/log/selfdev/util", false); + private static final String DEFAULT_CHARSET_UTF8 = "UTF-8"; + private static final String DEFAULT_CONTENT_TYPE_JSON = "application/json"; + + /** + * @param url 请求路径 + * @param params 请求参数 + * @return + * @throws Exception + */ + public static String get(String url, Map params, HttpClientConfig... configList) throws Exception { + CloseableHttpClient httpClient = null; + try { + httpClient = createClient(url, getHttpConfig(configList)); + if (params != null) { + StringBuilder sb = new StringBuilder(); + for (Entry entry : params.entrySet()) { + sb.append("&").append(entry.getKey()).append("=").append(entry.getValue()); + } + if (sb.length() > 0) { + if (url.indexOf("?") > -1) { + url = url + sb.toString(); + } else { + sb.delete(0, 1); + url = url + "?" + sb.toString(); + } + } + } + HttpGet httpGet = new HttpGet(url); + HttpResponse httpResponse = httpClient.execute(httpGet); + HttpEntity httpEntity = httpResponse.getEntity(); + return EntityUtils.toString(httpEntity, "UTF-8"); + } catch (Exception e) { + throw new Exception(e.getMessage(), e); + } finally { + if (httpClient != null) { + try { + httpClient.close(); + } catch (IOException e) { + throw new Exception(e.getMessage(), e); + } + } + } + } + + + /** + * @param url 请求路径 + * @param params 请求参数 + * @return + */ + public static String post(String url, Map params, HttpClientConfig... configList) throws Exception { + CloseableHttpClient httpClient = null; + try { + httpClient = createClient(url, getHttpConfig(configList)); + HttpPost httpPost = new HttpPost(url); +// LOGGER.info("请求地址:"+url); +// LOGGER.info("请求参数:"+JSON.toJSONString(params).replace("\\","")); + httpPost.addHeader("sign", SignHelper.sign((Map)params)); + if (params != null && params.size() > 0) { + List pairs = new ArrayList<>(); + for (Entry entry : params.entrySet()) { + NameValuePair pair = new BasicNameValuePair(entry.getKey(), String.valueOf(entry.getValue())); + pairs.add(pair); + } + HttpEntity httpEntity = new UrlEncodedFormEntity(pairs, "UTF-8"); + httpPost.setEntity(httpEntity); + } + HttpResponse httpResponse = httpClient.execute(httpPost); + if (httpResponse.getStatusLine().getStatusCode() < 400) { + HttpEntity httpEntity = httpResponse.getEntity(); + String result = EntityUtils.toString(httpEntity, "UTF-8"); +// LOGGER.info("返回结果:"+result.replace("\\","")); + return result; + } else { + throw new Exception("http请求错误:" + httpResponse.getStatusLine().getStatusCode() + "," + httpResponse.getEntity().toString()); + } + } catch (Exception e) { + throw e; + } finally { + if (httpClient != null) { + try { + httpClient.close(); + } catch (IOException e) { + throw new Exception(e.getMessage(), e); + } + } + } + } + + /** + * 参数JSON格式 Post + * + * @param url 请求路径 + * @return + */ + public static String jsonPost(String url, Object paramVO, HttpClientConfig... configList) throws Exception { + CloseableHttpClient httpClient = null; + String result = null; + try { + httpClient = createClient(url, getHttpConfig(configList)); + HttpPost httpPost = new HttpPost(url); + log.writeLog("httppost:"+httpPost); + log.writeLog("请求地址:"+url); + log.writeLog("请求参数:"+JSON.toJSONString(paramVO, SerializerFeature.DisableCircularReferenceDetect).replace("\\","")); + if (paramVO instanceof Map) { + httpPost.addHeader("sign", SignHelper.sign((Map)paramVO)); + } + StringEntity requestEntity = new StringEntity(JSON.toJSONString(paramVO, SerializerFeature.DisableCircularReferenceDetect), "UTF-8"); + log.writeLog("requestEntity:"+requestEntity); + requestEntity.setContentType("application/json"); + httpPost.setEntity(requestEntity); + + CloseableHttpResponse httpResponse = httpClient.execute(httpPost); + log.writeLog("httpResponse:"+httpResponse); + HttpEntity httpEntity = httpResponse.getEntity(); + log.writeLog("httpEntity:"+httpEntity); + result = EntityUtils.toString(httpEntity, "UTF-8"); + log.writeLog("result"+result); + EntityUtils.consume(httpEntity); + log.writeLog("result:"+result); + + if (httpResponse.getStatusLine().getStatusCode() < 400) { + log.writeLog("返回结果:"+result.replace("\\","")); +// LOGGER.info("返回结果:"+result.replace("\\","")); + return result; + } else { + throw new Exception("http请求错误:" + httpResponse.getStatusLine().getStatusCode() + "," + result); + } + } catch (Exception e) { + throw new Exception(e.getMessage(), e); + } finally { + if (httpClient != null) { + try { + httpClient.close(); + } catch (IOException e) { + throw new Exception(e.getMessage(), e); + } + } + } + } + + /** + * @param url 请求路径 + * @param params 请求参数 + * @return + */ + public static String put(String url, Map params, HttpClientConfig... configList) throws Exception { + CloseableHttpClient httpClient = null; + try { + httpClient = createClient(url, getHttpConfig(configList)); + HttpPut httpPut = new HttpPut(url); + if (params != null && params.size() > 0) { + List pairs = new ArrayList<>(); + for (Entry entry : params.entrySet()) { + NameValuePair pair = new BasicNameValuePair(entry.getKey(), String.valueOf(entry.getValue())); + pairs.add(pair); + } + HttpEntity httpEntity = new UrlEncodedFormEntity(pairs, "UTF-8"); + httpPut.setEntity(httpEntity); + } + HttpResponse httpResponse = httpClient.execute(httpPut); + if (httpResponse.getStatusLine().getStatusCode() < 400) { + HttpEntity httpEntity = httpResponse.getEntity(); + return EntityUtils.toString(httpEntity, "UTF-8"); + } else { + throw new Exception("http请求错误:" + httpResponse.getStatusLine().getStatusCode()); + } + } catch (Exception e) { + throw new Exception(e.getMessage(), e); + } finally { + if (httpClient != null) { + try { + httpClient.close(); + } catch (IOException e) { + throw new Exception(e.getMessage(), e); + } + } + } + } + + + /** + * 发送带head的请求 + * + * @param url + * @param headerParam + * @param bodyParam + * @param contentType + * @param charSet + * @return + * @throws Exception + */ + public static String post(String url, Map headerParam, Map bodyParam, String contentType, String charSet, HttpClientConfig... configList) throws Exception { + String content_type = contentType; + if (content_type == null || "".equals(content_type)) content_type = DEFAULT_CONTENT_TYPE_JSON; + + String char_set = charSet; + if (char_set == null || "".equals(char_set)) char_set = DEFAULT_CHARSET_UTF8; + + HttpPost httpPost = new HttpPost(url); + + //header参数 + if (headerParam != null && headerParam.size() > 0) { +// LOGGER.info("Post请求Header:" + JSON.toJSONString(headerParam)); + for (String key : headerParam.keySet()) { + httpPost.addHeader(key, headerParam.get(key)); + } + } + + //entity数据 + if (bodyParam != null) { + //x-www-form-urlencoded类型 + if (ContentType.APPLICATION_FORM_URLENCODED.getMimeType().equals(contentType)) { + if (bodyParam instanceof Map) { + + @SuppressWarnings("unchecked") + Map params = bodyParam; + if (!CollectionUtils.isEmpty(params)) { + List pairs = new ArrayList<>(); + for (Entry entry : params.entrySet()) { + NameValuePair pair = new BasicNameValuePair(String.valueOf(entry.getKey()), String.valueOf(entry.getValue())); + pairs.add(pair); + } + HttpEntity httpEntity = new UrlEncodedFormEntity(pairs, "UTF-8"); + httpPost.setEntity(httpEntity); +// LOGGER.info("post请求body:" + httpEntity.toString()); + } + } + } else {//json或其他类型 +// LOGGER.info("Post请求Body:" + JSON.toJSONString(bodyParam)); + StringEntity entity = new StringEntity(JSON.toJSONString(bodyParam, SerializerFeature.DisableCircularReferenceDetect), char_set); + entity.setContentEncoding(char_set); + entity.setContentType(content_type); + + httpPost.setEntity(entity); + } + } + + String resultStr = ""; + CloseableHttpResponse response = null; + try { + response = createClient(url, getHttpConfig(configList)).execute(httpPost); + resultStr = EntityUtils.toString(response.getEntity(), char_set); + } catch (IOException e) { + e.printStackTrace(); + } finally { + try { + response.close(); + httpPost.releaseConnection(); + } catch (IOException e) { + e.printStackTrace(); + } + } + +// LOGGER.info("Post请求返回:" + resultStr); + return resultStr; + } + + /** + * 发送Gzip压缩请求 + * + * @param sendurl + * @param bytes + * @param headMap + * @return + * @throws Exception + */ + public static byte[] postGzip(String sendurl, byte[] bytes, Map headMap, HttpClientConfig... configList) throws Exception { + HttpClientConfig httpClientConfig = getHttpConfig(configList); + HttpURLConnection con = null; + ByteArrayOutputStream baos = null; + GZIPInputStream reader = null; + GZIPOutputStream zip = null; + try { + con = getConnection(sendurl); + if (headMap != null) { + for (Entry en : headMap.entrySet()) { + con.setRequestProperty(en.getKey(), en.getValue()); + } + } + con.setConnectTimeout(httpClientConfig.CONNECT_TIMING_OUT); + con.setReadTimeout(httpClientConfig.RESPONSE_TIMING_OUT); + con.setDoInput(true); + con.setDoOutput(true); + con.setAllowUserInteraction(true); + con.setUseCaches(false); + con.setRequestMethod("POST"); + con.setRequestProperty("Content-type", "application/gzip"); + zip = new GZIPOutputStream(con.getOutputStream()); + zip.write(bytes); + zip.flush(); + zip.close(); + reader = new GZIPInputStream(con.getInputStream()); + baos = new ByteArrayOutputStream(); + byte[] buffer = new byte[4096]; + int len = -1; + while ((len = reader.read(buffer)) != -1) { + baos.write(buffer, 0, len); + } + con.disconnect(); + baos.close(); + return baos.toByteArray(); + } catch (Exception e) { +// LOGGER.error("GzipPost:{}, 出现异常,error: {}", sendurl, e.getMessage()); + throw new RuntimeException("请求异常:" + e.getMessage()); + } finally { + if (reader != null) { + reader.close(); + } + if (zip != null) { + zip.close(); + } + if (baos != null) { + baos.close(); + } + if (con != null) { + con.disconnect(); + } + } + } + + private static CloseableHttpClient createHttpsClient(HttpClientConfig config) throws Exception { + X509TrustManager xtm = new X509TrustManager() { + @Override + public X509Certificate[] getAcceptedIssuers() { + return new X509Certificate[]{}; + } + + @Override + public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException { + + } + + @Override + public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException { + } + + }; + //SSLContext ctx = SSLContext.getInstance("SSL"); + SSLContext ctx = new SSLContextBuilder().loadTrustMaterial(null, new TrustStrategy() { + //信任所有 + @Override + public boolean isTrusted(X509Certificate[] chain, String authType) throws CertificateException { + return true; + } + }).build(); + //ctx.init(null, new TrustManager[]{xtm}, null); + SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(ctx, new HostnameVerifier() { + + @Override + public boolean verify(String hostname, SSLSession session) { + return true; + } + }); + log.writeLog("GGGGGGGGGG:"); + RequestConfig requestConfig = RequestConfig.custom() + .setConnectTimeout(config.CONNECT_TIMING_OUT) + .setConnectionRequestTimeout(config.REQUEST_TIMING_OUT) + .setSocketTimeout(config.RESPONSE_TIMING_OUT).build(); + CloseableHttpClient httpClient = HttpClientBuilder.create().setDefaultRequestConfig(requestConfig).setSSLSocketFactory(sslsf).build(); + log.writeLog("FFFFFFFFFFFFFFF:"); + log.writeLog("httpClient:"+httpClient); + return httpClient; + + } + + private static CloseableHttpClient createHttpClient(HttpClientConfig config) { + RequestConfig requestConfig = RequestConfig.custom() + .setConnectTimeout(config.CONNECT_TIMING_OUT) + .setConnectionRequestTimeout(config.REQUEST_TIMING_OUT) + .setSocketTimeout(config.RESPONSE_TIMING_OUT).build(); + + CloseableHttpClient httpClient = HttpClientBuilder.create().setDefaultRequestConfig(requestConfig).build(); + return httpClient; + } + + private static CloseableHttpClient createClient(String url, HttpClientConfig config) throws Exception { + log.writeLog("555:"); + if (url.startsWith("https")) { //https请求 + log.writeLog("666666:"); + return createHttpsClient(config); + } else { //http请求 + return createHttpClient(config); + } + } + + + private static HttpURLConnection getConnection(String reqUrl) throws Exception { + if (reqUrl.startsWith("https")) { + + log.writeLog("77777777:"+getHttpsConnection(reqUrl)); + return getHttpsConnection(reqUrl); + } else { + return getHttpConnection(reqUrl); + } + } + + private static HttpURLConnection getHttpsConnection(String reqUrl) throws IOException, KeyManagementException, NoSuchAlgorithmException { + SSLContext sc = SSLContext.getInstance("SSL"); + sc.init(null, new TrustManager[]{new TrustAnyTrustManager()}, new java.security.SecureRandom()); + + log.writeLog("888888:"+sc); + URL url = new URL(reqUrl); + HttpsURLConnection conn = (HttpsURLConnection) url.openConnection(); + conn.setSSLSocketFactory(sc.getSocketFactory()); + conn.setHostnameVerifier(new TrustAnyHostnameVerifier()); + log.writeLog("conn:"+conn); + return conn; + } + + private static HttpURLConnection getHttpConnection(String reqUrl) throws IOException { + URL url = new URL(reqUrl); + HttpURLConnection conn = (HttpURLConnection) url.openConnection(); + return conn; + } + + private static class TrustAnyTrustManager implements X509TrustManager { + + public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException { + } + + public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException { + } + + public X509Certificate[] getAcceptedIssuers() { + return new X509Certificate[]{}; + } + } + + private static class TrustAnyHostnameVerifier implements HostnameVerifier { + public boolean verify(String hostname, SSLSession session) { + return true; + } + } + + private static HttpClientConfig getHttpConfig(HttpClientConfig[] configList) { + if (ObjectUtils.isEmpty(configList)) { + return HttpClientConfig.defaultConfig(); + } + return configList[0]; + } +} \ No newline at end of file diff --git a/src/main/youhong_ai_jitu_src/jntchina/util/HttpClientUtils.java b/src/main/youhong_ai_jitu_src/jntchina/util/HttpClientUtils.java new file mode 100644 index 0000000..9f5bb18 --- /dev/null +++ b/src/main/youhong_ai_jitu_src/jntchina/util/HttpClientUtils.java @@ -0,0 +1,247 @@ +package jntchina.util; + +import org.apache.commons.io.IOUtils; +import org.apache.commons.lang3.StringUtils; +import org.apache.http.Consts; +import org.apache.http.HttpEntity; +import org.apache.http.HttpResponse; +import org.apache.http.NameValuePair; +import org.apache.http.client.HttpClient; +import org.apache.http.client.config.RequestConfig; +import org.apache.http.client.config.RequestConfig.Builder; +import org.apache.http.client.entity.UrlEncodedFormEntity; +import org.apache.http.client.methods.HttpGet; +import org.apache.http.client.methods.HttpPost; +import org.apache.http.conn.ConnectTimeoutException; +import org.apache.http.conn.ssl.SSLConnectionSocketFactory; +import org.apache.http.conn.ssl.SSLContextBuilder; +import org.apache.http.entity.ContentType; +import org.apache.http.entity.StringEntity; +import org.apache.http.impl.client.CloseableHttpClient; +import org.apache.http.impl.client.HttpClients; +import org.apache.http.impl.conn.PoolingHttpClientConnectionManager; +import org.apache.http.message.BasicNameValuePair; + +import javax.net.ssl.SSLContext; +import java.net.SocketTimeoutException; +import java.security.GeneralSecurityException; +import java.security.KeyManagementException; +import java.security.KeyStoreException; +import java.security.NoSuchAlgorithmException; +import java.util.ArrayList; +import java.util.List; +import java.util.Map; +import java.util.Map.Entry; +import java.util.Set; + +/** + * @author Administrator + */ +public class HttpClientUtils { + + private static final HttpClient client; + + static { + PoolingHttpClientConnectionManager cm = new PoolingHttpClientConnectionManager(); + cm.setMaxTotal(128); + cm.setDefaultMaxPerRoute(128); + client = HttpClients.custom().setConnectionManager(cm).build(); + } + + /** + * 发送一个 Post 请求, 使用指定的字符集编码. + * + * @param url url + * @param body RequestBody + * @param mimeType 例如 application/xml "application/x-www-form-urlencoded" a=1&b=2&c=3 + * @param CHARSET 编码 + * @param CONN_TIMEOUT 建立链接超时时间,毫秒. + * @param READ_TIMEOUT 响应超时时间,毫秒. + * @return ResponseBody, 使用指定的字符集编码. + * @throws ConnectTimeoutException 建立链接超时异常 + * @throws SocketTimeoutException 响应超时 + * @throws Exception 抛出异常 + */ + public static String postStringBody(String url, String body, String mimeType, String CHARSET, Integer CONN_TIMEOUT, Integer READ_TIMEOUT) throws ConnectTimeoutException, SocketTimeoutException, Exception { + HttpClient client = null; + HttpPost post = new HttpPost(url); + String result; + try { + if (StringUtils.isNotBlank(body)) { + HttpEntity entity = new StringEntity(body, ContentType.create(mimeType, CHARSET)); + post.setEntity(entity); + } + // 设置参数 + Builder customReqConf = getBuilder(CONN_TIMEOUT, READ_TIMEOUT); + post.setConfig(customReqConf.build()); + + HttpResponse res; + if (url.startsWith("https")) { + // 执行 Https 请求. + client = createSSLInsecureClient(); + } else { + // 执行 Http 请求. + client = HttpClientUtils.client; + } + res = client.execute(post); + result = IOUtils.toString(res.getEntity().getContent(), CHARSET); + } finally { + post.releaseConnection(); + if (url.startsWith("https") && client instanceof CloseableHttpClient) { + ((CloseableHttpClient) client).close(); + } + } + return result; + } + + /** + * 提交form表单 + * + * @param url url + * @param params 表体 + * @param headers 表头 + * @param CONN_TIMEOUT 建立链接超时时间,毫秒. + * @param READ_TIMEOUT 响应超时时间,毫秒. + * @return 返回值 + * @throws ConnectTimeoutException 连接超时异常 + * @throws SocketTimeoutException 异常 + * @throws Exception 异常 + */ + public static String postForm(String url, Map params, Map headers, Integer CONN_TIMEOUT, Integer READ_TIMEOUT) throws ConnectTimeoutException, + SocketTimeoutException, Exception { + + HttpClient client = null; + HttpPost post = new HttpPost(url); + try { + if (params != null && !params.isEmpty()) { + List formParams = new ArrayList<>(); + Set> entrySet = params.entrySet(); + for (Entry entry : entrySet) { + formParams.add(new BasicNameValuePair(entry.getKey(), entry.getValue())); + } + UrlEncodedFormEntity entity = new UrlEncodedFormEntity(formParams, String.valueOf(Consts.UTF_8)); + post.setEntity(entity); + } + + if (headers != null && !headers.isEmpty()) { + for (Entry entry : headers.entrySet()) { + post.addHeader(entry.getKey(), entry.getValue()); + } + } + + Builder customReqConf = getBuilder(CONN_TIMEOUT, READ_TIMEOUT); + post.setConfig(customReqConf.build()); + + HttpResponse res; + if (url.startsWith("https")) { + // 执行 Https 请求. + client = createSSLInsecureClient(); + } else { + // 执行 Http 请求. + client = HttpClientUtils.client; + } + res = client.execute(post); + return IOUtils.toString(res.getEntity().getContent(), "UTF-8"); + } finally { + post.releaseConnection(); + if (url.startsWith("https") && client instanceof CloseableHttpClient) { + ((CloseableHttpClient) client).close(); + } + } + } + + /** + * 发送一个 GET 请求 + * + * @param url url + * @param CHARSET 字符集 + * @param CONN_TIMEOUT 建立链接超时时间,毫秒. + * @param READ_TIMEOUT 响应超时时间,毫秒. + * @return 返回值 + * @throws ConnectTimeoutException 建立链接超时 + * @throws SocketTimeoutException 响应超时 + * @throws Exception 抛出异常 + */ + public static String get(String url, String CHARSET, Integer CONN_TIMEOUT, Integer READ_TIMEOUT) + throws ConnectTimeoutException, SocketTimeoutException, Exception { + + HttpClient client = null; + HttpGet get = new HttpGet(url); + String result; + try { + Builder customReqConf = getBuilder(CONN_TIMEOUT, READ_TIMEOUT); // 设置参数 + get.setConfig(customReqConf.build()); + HttpResponse res; + if (url.startsWith("https")) { + // 执行 Https 请求. + client = createSSLInsecureClient(); + } else { + // 执行 Http 请求. + client = HttpClientUtils.client; + } + res = client.execute(get); + result = IOUtils.toString(res.getEntity().getContent(), CHARSET); + } finally { + get.releaseConnection(); + if (url.startsWith("https") && client instanceof CloseableHttpClient) { + ((CloseableHttpClient) client).close(); + } + } + return result; + } + + /** + * 获取Builder + * + * @param CONN_TIMEOUT 建立链接超时时间,毫秒. + * @param READ_TIMEOUT 响应超时时间,毫秒. + * @return 返回获取Builder + */ + private static Builder getBuilder(Integer CONN_TIMEOUT, Integer READ_TIMEOUT) { + // 设置参数 + Builder customReqConf = RequestConfig.custom(); + if (CONN_TIMEOUT != null) { + customReqConf.setConnectTimeout(CONN_TIMEOUT); + } + if (READ_TIMEOUT != null) { + customReqConf.setSocketTimeout(READ_TIMEOUT); + } + return customReqConf; + } + + /** + * 从 response 里获取 CHARSET + * + * @param ressponse 返回结果 + * @return 返回值 + */ + @SuppressWarnings("unused") + private static String getCHARSETFromResponse(HttpResponse ressponse) { + // Content-Type:text/html; CHARSET=GBK + if (ressponse.getEntity() != null && ressponse.getEntity().getContentType() != null && ressponse.getEntity().getContentType().getValue() != null) { + String contentType = ressponse.getEntity().getContentType().getValue(); + if (contentType.contains("CHARSET=")) { + return contentType.substring(contentType.indexOf("CHARSET=") + 8); + } + } + return null; + } + + + /** + * 创建 SSL连接 + * + * @return 返回 + */ + private static CloseableHttpClient createSSLInsecureClient() throws GeneralSecurityException { + SSLContext sslContext; + try { + sslContext = new SSLContextBuilder().loadTrustMaterial(null, (chain, authType) -> true).build(); + SSLConnectionSocketFactory sslCsf = new SSLConnectionSocketFactory(sslContext, (arg0, arg1) -> true); + return HttpClients.custom().setSSLSocketFactory(sslCsf).build(); + } catch (NoSuchAlgorithmException | KeyManagementException | KeyStoreException e) { + e.printStackTrace(); + throw e; + } + } +} \ No newline at end of file diff --git a/src/main/youhong_ai_jitu_src/jntchina/util/JTHrmApiUtil.java b/src/main/youhong_ai_jitu_src/jntchina/util/JTHrmApiUtil.java new file mode 100644 index 0000000..fa91722 --- /dev/null +++ b/src/main/youhong_ai_jitu_src/jntchina/util/JTHrmApiUtil.java @@ -0,0 +1,155 @@ +package jntchina.util; + + +import com.alibaba.fastjson.JSONArray; +import com.alibaba.fastjson.JSONObject; + +/** + * @date 2021年7月16日 01:56:10 + * @author QGX + */ +public class JTHrmApiUtil { + + /** 公司新增*/ + public final static String companyAddUrl = "/dcoaapi/hr/companyAdd"; + /** 部门新增、修改*/ + public final static String deptAddOrEditUrl = "/dcoaapi/hr/deptAdd"; + /** 部门失效*/ + public final static String deptInvalidUrl = "/dcoaapi/hr/deptInvalid"; + /** 岗位新增*/ + public final static String postApplicationUrl = "/dcoaapi/hr/postApplication"; + /** 标准岗位新增*/ + public final static String stdPostApplyUrl = "/dcoaapi/hr/stdPostApply"; + /** 转正申请*/ + public final static String becomeRegularUrl = "/dcoaapi/hr/becomeRegular"; + /** 调动单申请 */ + public final static String callApplicationUrl = "/dcoaapi/hr/callApplication"; + /** 离职申请 */ + public final static String resignationUrl = "/dcoaapi/hr/resignation"; + /** 合同续签 */ + public final static String contractRenewalUrl = "/dcoaapi/hr/contractRenewal"; + /** 用工模式变更 */ + public final static String factoryChangeUrl = "/dcoaapi/hr/factoryChange"; + /** 转换值接口 */ + public final static String translateValueUrl = "/dcoaapi/hr/translateValue"; + + /** 公司查询 */ + public final static String companyQueryUrl = "/dcoaapi/hr/companyQuery"; + /** 一次性薪酬发放 */ + public final static String oneTimeSalaryPayUrl = "/dcoaapi/hr/lumpSumSalary"; + + /** + * 添加公司 + * + * @return + */ + public static JSONObject addCompany(String token, String paramJsonStr) { + String url = HttpClientToJT.baseUrl + companyAddUrl; + String resultStr = HttpClientToJT.sendPost(url, token, paramJsonStr); + JSONObject jsonObject = JSONObject.parseObject(resultStr); +// if (jsonObject.getInteger("code").equals(1)) { +// JSONObject result = jsonObject.getJSONObject("data"); +// String company = result.getString("COMPANY"); +// return company; +// } + return jsonObject; + } + + + /** + * 部门新增、修改 + * @return + */ + public static JSONObject deptAddOrEdit(String token, String paramJsonStr) { + String url = HttpClientToJT.baseUrl + deptAddOrEditUrl; + String resultStr = HttpClientToJT.sendPost(url, token, paramJsonStr); + JSONObject jsonObject = JSONObject.parseObject(resultStr); + return jsonObject; +// JSONObject jsonObject = JSONObject.parseObject(resultStr); +// if (jsonObject.getInteger("code").equals(1)) { +// JSONObject result = jsonObject.getJSONObject("data"); +// String deptid = jsonObject.getString("DEPTID"); +// return resultStr; +// } +// return resultStr; + } + + + /** + * 部门失效 + * @return + */ + public static JSONObject deptInvalid(String token, String paramJsonStr) { + String url = HttpClientToJT.baseUrl + deptInvalidUrl; + String resultStr = HttpClientToJT.sendPost(url, token, paramJsonStr); + JSONObject jsonObject = JSONObject.parseObject(resultStr); +// if (jsonObject.getInteger("code").equals(1)) { +// JSONObject result = jsonObject.getJSONObject("data"); +// return true; +// } + return jsonObject; + } + + /** + * 标准岗位新增 + * @return + */ + public static JSONObject stdPostApply(String token, String paramJsonStr) { + String url = HttpClientToJT.baseUrl + stdPostApplyUrl; + String resultStr = HttpClientToJT.sendPost(url, token, paramJsonStr); + JSONObject jsonObject = JSONObject.parseObject(resultStr); +// if (jsonObject.getInteger("code").equals(1)) { +// JSONObject result = jsonObject.getJSONObject("data"); +// return resultStr; +// } + return jsonObject; + } + + /** + * 岗位新增 + * @return + */ + public static JSONObject postApplication(String token, String paramJsonStr) { + String url = HttpClientToJT.baseUrl + postApplicationUrl; + String resultStr = HttpClientToJT.sendPost(url, token, paramJsonStr); + JSONObject jsonObject = JSONObject.parseObject(resultStr); + return jsonObject; + } + /** + * 转换值 + * @return + */ + public static JSONArray translateValue(String token, String paramJsonStr) { + String url = HttpClientToJT.baseUrl + translateValueUrl; + String resultStr = HttpClientToJT.sendPost(url, token, paramJsonStr); + JSONObject jsonObject = JSONObject.parseObject(resultStr); + if (jsonObject.getInteger("code").equals(1)) { + JSONArray result = jsonObject.getJSONArray("data"); + return result; + } + return null; + } + /** + * 合同 + * @return + */ + public static JSONObject contracRenewt(String token, String paramJsonStr) { + String url = HttpClientToJT.baseUrl + contractRenewalUrl; + String resultStr = HttpClientToJT.sendPost(url, token, paramJsonStr); + JSONObject jsonObject = JSONObject.parseObject(resultStr); + return jsonObject; + } + + /** + * 合同 + * @return + */ + public static JSONObject companyQuery(String token, String paramJsonStr) { + String url = HttpClientToJT.baseUrl + companyQueryUrl; + String resultStr = HttpClientToJT.sendPost(url, token, paramJsonStr); + JSONObject jsonObject = JSONObject.parseObject(resultStr); + return jsonObject; + } + + +} diff --git a/src/main/youhong_ai_jitu_src/jntchina/util/KeyPairs.java b/src/main/youhong_ai_jitu_src/jntchina/util/KeyPairs.java new file mode 100644 index 0000000..cb03f2f --- /dev/null +++ b/src/main/youhong_ai_jitu_src/jntchina/util/KeyPairs.java @@ -0,0 +1,27 @@ +package jntchina.util; + +import java.security.KeyPair; + +/** + * KeyPairs ������ + * + * @author liyang + * @date: 2019-5-20����4:34:51 + * + */ +public class KeyPairs { + + private KeyPair keyPair; + + public KeyPairs(KeyPair keyPair){ + this.keyPair = keyPair; + } + + public String getPublicKey(){ + return Base64Util.encryptBASE64(keyPair.getPublic().getEncoded()); + } + + public String getPrivateKey(){ + return Base64Util.encryptBASE64(keyPair.getPrivate().getEncoded()); + } +} diff --git a/src/main/youhong_ai_jitu_src/jntchina/util/KeysFactory.java b/src/main/youhong_ai_jitu_src/jntchina/util/KeysFactory.java new file mode 100644 index 0000000..4069fac --- /dev/null +++ b/src/main/youhong_ai_jitu_src/jntchina/util/KeysFactory.java @@ -0,0 +1,101 @@ +package jntchina.util; + +import javax.crypto.KeyGenerator; +import javax.crypto.SecretKey; +import javax.crypto.spec.SecretKeySpec; +import java.security.*; +import java.security.spec.PKCS8EncodedKeySpec; +import java.security.spec.X509EncodedKeySpec; + +/** + * Key������ + * + * @author liyang + * + */ +public class KeysFactory { + + /** + * buildAsymKey ����һ��ǶԳ���Կ + * + * @return KeyPair key��PublicKey��PrivateKey + * @throws NoSuchAlgorithmException + */ + public static KeyPairs buildAsymKey() throws Exception { + + /* ��ʼ����Կ������ */ + KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance(CipherConstant.ALGORITHM_RSA); + keyPairGenerator.initialize(1024, new SecureRandom()); + + /* ������Կ */ + return new KeyPairs(keyPairGenerator.generateKeyPair()); + } + + /** + * buildAsymKey ����һ���Գ���Կ + * + * @return �Գ���Կ + * @throws NoSuchAlgorithmException + * @throws Exception + */ + public static String buildSymKey() throws Exception{ + // ����Key + KeyGenerator keyGenerator = KeyGenerator.getInstance(CipherConstant.ALGORITHM_AES); + + keyGenerator.init(256, new SecureRandom()); + // ʹ���������ֳ�ʼ�����������ض�������������Կ���������ܺ��������Ψһ�̶��ġ� + SecretKey secretKey = keyGenerator.generateKey(); + + return Base64Util.encryptBASE64(secretKey.getEncoded()); + + } + + public static Key getPublicKey(String pubKey) throws Exception { + Key key = null; + + try { + byte[] keyBytes = Base64Util.decryptBASE64(pubKey); + KeyFactory keyFactory = KeyFactory.getInstance(CipherConstant.ALGORITHM_RSA); + + X509EncodedKeySpec x509KeySpec = new X509EncodedKeySpec(keyBytes); + key = keyFactory.generatePublic(x509KeySpec); + + } catch (Exception e) { + throw new Exception("��Ч����Կ " + e.getMessage()); + } + + return key; + } + + public static Key getPrivateKey(String priKey) throws Exception { + Key key = null; + + try { + byte[] keyBytes = Base64Util.decryptBASE64(priKey); + + KeyFactory keyFactory = KeyFactory.getInstance(CipherConstant.ALGORITHM_RSA); + + PKCS8EncodedKeySpec pkcs8KeySpec = new PKCS8EncodedKeySpec(keyBytes); + key = keyFactory.generatePrivate(pkcs8KeySpec); + + } catch (Exception e) { + throw new Exception("��Ч��Կ " + e.getMessage()); + } + + return key; + } + + public static Key getSymKey(String symKey) throws Exception { + Key key = null; + + try { + byte[] keyBytes = Base64Util.decryptBASE64(symKey); + // Keyת�� + key = new SecretKeySpec(keyBytes, CipherConstant.ALGORITHM_AES); + } catch (Exception e) { + throw new Exception("��Ч��Կ " + e.getMessage()); + } + + return key; + } +} diff --git a/src/main/youhong_ai_jitu_src/jntchina/util/MD5Utils.java b/src/main/youhong_ai_jitu_src/jntchina/util/MD5Utils.java new file mode 100644 index 0000000..ada6efc --- /dev/null +++ b/src/main/youhong_ai_jitu_src/jntchina/util/MD5Utils.java @@ -0,0 +1,33 @@ +package jntchina.util; + +import java.nio.charset.StandardCharsets; +import java.security.MessageDigest; +import java.security.NoSuchAlgorithmException; + +public class MD5Utils { + + public static String encrypt(String s) { + try { + MessageDigest md5 = MessageDigest.getInstance("MD5"); + md5.update(s.getBytes(StandardCharsets.UTF_8)); + byte[] digest = md5.digest(); + StringBuilder build = new StringBuilder(); + + for (int i = 0; i < digest.length; ++i) { + //以16进制形式输出,高位不足补0 + build.append(String.format("%02X", digest[i])); + } + + return build.toString(); + } catch (NoSuchAlgorithmException var5) { + var5.printStackTrace(); + throw new RuntimeException(var5); + } + } + + + public static void main(String[] args) { + String encryptionKey= encrypt("oa001"+":"+"123456"+":"+"20230119"+":"+"5362448sd132d241e5ae27e318qws11d"); + System.out.println(encryptionKey); + } +} diff --git a/src/main/youhong_ai_jitu_src/jntchina/util/NCCUtils.java b/src/main/youhong_ai_jitu_src/jntchina/util/NCCUtils.java new file mode 100644 index 0000000..af8d266 --- /dev/null +++ b/src/main/youhong_ai_jitu_src/jntchina/util/NCCUtils.java @@ -0,0 +1,351 @@ +package jntchina.util; + +import com.google.gson.Gson; +import org.apache.commons.lang3.StringUtils; +import selfdev.util.log.LogTool; + +import java.io.*; +import java.lang.reflect.Type; +import java.net.HttpURLConnection; +import java.net.URL; +import java.net.URLEncoder; +import java.nio.charset.StandardCharsets; +import java.util.HashMap; +import java.util.Map; + + +public class NCCUtils { + private static final LogTool log = new LogTool("/log/action/NCC", false); + + // app_secret + private static String client_secret = null; + // 公钥 + private static String pubKey = null; + // app_id + private static String client_id = null; + // ncc用户名 + private static String username = null; + // ncc用户名密码 + private static String pwd = null; + // ncc账套 + private static String busi_center = null; + // 获取token方式:client_credentials、password + private static String grant_type = null; + // 服务器ip:port + private static String baseUrl = null; + // 请求参数 + private static String requestBody = null; + // 访问api获取到的access_token + public static String token = null; + // 重复调用检查 + public static String repeat_check = null; + // 接口调用业务标识 + public static String busi_id = null; + + + + /** + * 获取access_token + * + * @return + * @throws Exception + */ + public static String getToken() { + String token = null; + if ("password".equals(grant_type)) { + // 密码模式 + try { + token = getTokenByPWD(); + } catch (Exception e) { + e.printStackTrace(); + } + } else if ("client_credentials".equals(grant_type)) { + // 客户端模式 + try { + token = getTokenByClient(); + } catch (Exception e) { + e.printStackTrace(); + } + } + return token; + } + + /** + * 客户端模式获取token + * + * @return + * @throws Exception + */ + private static String getTokenByClient() throws Exception { + Map paramMap = new HashMap(); + // 密码模式认证 + paramMap.put("grant_type", "client_credentials"); + // 第三方应用id + paramMap.put("client_id", client_id); + // 第三方应用secret 公钥加密 + paramMap.put("client_secret", URLEncoder.encode(Encryption.pubEncrypt(pubKey, client_secret), "utf-8")); + // 账套编码 + paramMap.put("biz_center", busi_center); + + // 签名 + String sign = SHA256Util.getSHA256(client_id + client_secret + pubKey); + paramMap.put("signature", sign); + + String url = baseUrl + "/nccloud/opm/accesstoken"; + String mediaType = "application/x-www-form-urlencoded"; + String token = doPost(url, paramMap, mediaType, null, ""); + return token; + } + + /** + * 密码模式获取token + * + * @return + * @throws Exception + */ + @SuppressWarnings("unused") + private static String getTokenByPWD() throws Exception { + Map paramMap = new HashMap(); + // 密码模式认证 + paramMap.put("grant_type", "password"); + // 第三方应用id + paramMap.put("client_id", client_id); + // 第三方应用secret 公钥加密 + paramMap.put("client_secret", URLEncoder.encode(Encryption.pubEncrypt(pubKey, client_secret), "utf-8")); + // ncc用户名 + paramMap.put("username", username); + // 密码 公钥加密 + paramMap.put("password", URLEncoder.encode(Encryption.pubEncrypt(pubKey, pwd), "utf-8")); + // 账套编码 + paramMap.put("biz_center", busi_center); + // 签名 + String sign = SHA256Util.getSHA256(client_id + client_secret + username + pwd + pubKey); + paramMap.put("signature", sign); + + String url = baseUrl + "/nccloud/opm/accesstoken"; + String mediaType = "application/x-www-form-urlencoded"; + String token = doPost(url, paramMap, mediaType, null, ""); + return token; + } + + /** + * 请求openapi + * 请求body参数加密压缩用的key + * @throws Exception + */ + public static String sendApi(String url,String paramJson) { + init(); + String token = getToken(); + // token转对象,获取api访问所用token和secret + ResultMessageUtil returnData = new Gson().fromJson(token, (Type) ResultMessageUtil.class); + Map data = (Map) returnData.getData(); + String access_token = data.get("access_token"); +// System.err.println("【ACCESS_TOKEN】:" + access_token); +// log.writeLog("【ACCESS_TOKEN】::"+access_token); + + +// System.err.println("【PARAM_JSON】:"+paramJson); +// log.writeLog("【PARAM_JSON】::"+paramJson); + + // header 参数 + Map headermap = new HashMap<>(); + headermap.put("access_token", access_token); + headermap.put("client_id", client_id); + + StringBuilder sb = new StringBuilder(); + sb.append(client_id); + if (StringUtils.isNotBlank(requestBody)) { + sb.append(requestBody); + } + sb.append(pubKey); + String sign = SHA256Util.getSHA256(sb.toString()); + headermap.put("signature", sign); + + if (StringUtils.isNotBlank(busi_id)) { + headermap.put("busi_id", busi_id); + } + if (StringUtils.isNotBlank(repeat_check)) { + headermap.put("repeat_check", repeat_check); + } + headermap.put("ucg_flag", "y"); + + String mediaType = "application/json;charset=utf-8"; + + + // 返回值 + return doPost(url, null, mediaType, headermap, paramJson); + } + + /** + * 返回值进行过加密和压缩,对返回值进行解压和解密 + * + * @param source + * @param security_key + * @param level + * @return + * @throws Exception + */ + private static String dealResponseBody(String source, String security_key, String level) throws Exception { + String result = null; + + if (StringUtils.isEmpty(level) || SecretConst.LEVEL0.equals(level)) { + result = source; + } else if (SecretConst.LEVEL1.equals(level)) { + result = Decryption.symDecrypt(security_key, source); + } else if (SecretConst.LEVEL2.equals(level)) { + result = CompressUtil.gzipDecompress(source); + } else if (SecretConst.LEVEL3.equals(level)) { + result = CompressUtil.gzipDecompress(Decryption.symDecrypt(security_key, source)); + } else if (SecretConst.LEVEL4.equals(level)) { + result = Decryption.symDecrypt(security_key, CompressUtil.gzipDecompress(source)); + } else { + throw new Exception("无效的安全等级"); + } + + return result; + } + + /** + * 初始化参数 + */ + private static void init() { + + try { + client_secret = "431355f00fdd4e2bbaf9"; + client_id = "jms"; + pubKey = "MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQDJsSkNagOJi62zfeXVIEegzdFKTQWkd16BD1b4" + +"qwwJf8GKtos06e2a3ncM86pNLfQGhDQsBXTF2oemDjBI9xGN55FM0eh5eWRCAGDEp4L4zRrUoZ65" + +"Z9b5kSwQmUsgJmXW1ynIc420cd8PiYPf0/tXSg8aB6mR9oYrvUBWHuIlBQIDAQAB"; + username = "y09"; + pwd = "1234qwer"; + busi_center = "jtsd"; + baseUrl = "http://180.169.229.37:8080"; + requestBody = "{\"pk_org\":\"0001V1100000000001L6\",\"pk_supplier\":\"1001V1100000000088M1\",\"begindate\":\"2021-04-22\",\"enddate\":\"2021-04-25\"}"; + grant_type = "client_credentials"; + repeat_check = ""; + busi_id = ""; + + } catch (Exception e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + } + + + + /** + * 发送post请求 + * + * @param baseUrl url + * @param paramMap map + * @param mediaType type + * @param headers + * @param json + * @return + */ + private static String doPost(String baseUrl, Map paramMap, String mediaType, Map headers, String json) { + + HttpURLConnection urlConnection = null; + InputStream in = null; + OutputStream out = null; + BufferedReader bufferedReader = null; + String result = null; + try { + StringBuilder sb = new StringBuilder(); + sb.append(baseUrl); + if (paramMap != null) { + sb.append("?"); + for (Map.Entry entry : paramMap.entrySet()) { + String key = entry.getKey(); + String value = entry.getValue(); + sb.append(key).append("=").append(value).append("&"); + } + baseUrl = sb.substring(0, sb.toString().length() - 1); + } + + URL urlObj = new URL(baseUrl); + urlConnection = (HttpURLConnection) urlObj.openConnection(); + urlConnection.setConnectTimeout(50000); + urlConnection.setRequestMethod("POST"); + urlConnection.setDoOutput(true); + urlConnection.setDoInput(true); + urlConnection.setUseCaches(false); + urlConnection.addRequestProperty("content-type", mediaType); + if (headers != null) { + for (String key : headers.keySet()) { + urlConnection.addRequestProperty(key, headers.get(key)); + } + } + out = urlConnection.getOutputStream(); + out.write(json.getBytes(StandardCharsets.UTF_8)); + out.flush(); + int resCode = urlConnection.getResponseCode(); + if (resCode == HttpURLConnection.HTTP_OK || resCode == HttpURLConnection.HTTP_CREATED || resCode == HttpURLConnection.HTTP_ACCEPTED) { + in = urlConnection.getInputStream(); + } else { + in = urlConnection.getErrorStream(); + } + bufferedReader = new BufferedReader(new InputStreamReader(in, StandardCharsets.UTF_8)); + StringBuilder temp = new StringBuilder(); + String line = bufferedReader.readLine(); + while (line != null) { + temp.append(line).append("\r\n"); + line = bufferedReader.readLine(); + } + String ecod = urlConnection.getContentEncoding(); + if (ecod == null) { + ecod = StandardCharsets.UTF_8.name(); + } + result = new String(temp.toString().getBytes(StandardCharsets.UTF_8), ecod); + } catch (Exception ignored) { + } finally { + if (null != bufferedReader) { + try { + bufferedReader.close(); + } catch (IOException e) { + e.printStackTrace(); + } + } + if (null != out) { + try { + out.close(); + } catch (IOException e) { + e.printStackTrace(); + } + } + if (null != in) { + try { + in.close(); + } catch (IOException e) { + e.printStackTrace(); + } + } + assert urlConnection != null; + urlConnection.disconnect(); + } + return result; + } + + static class SecretConst { + /** + * LEVEL0 不压缩、不加密 + */ + public static final String LEVEL0 = "L0"; + /** + * LEVEL1 只加密、不压缩 + */ + public static final String LEVEL1 = "L1"; + /** + * LEVEL2 只压缩、不加密 + */ + public static final String LEVEL2 = "L2"; + /** + * LEVEL3 先压缩、后加密 + */ + public static final String LEVEL3 = "L3"; + /** + * LEVEL4 先加密、后压缩 + */ + public static final String LEVEL4 = "L4"; + } +} diff --git a/src/main/youhong_ai_jitu_src/jntchina/util/ResultMessageUtil.java b/src/main/youhong_ai_jitu_src/jntchina/util/ResultMessageUtil.java new file mode 100644 index 0000000..9dcfe65 --- /dev/null +++ b/src/main/youhong_ai_jitu_src/jntchina/util/ResultMessageUtil.java @@ -0,0 +1,45 @@ +package jntchina.util; + +public class ResultMessageUtil { + + private boolean success; + + private Object data; + + private String code; + + private String errorMessage; + + public boolean isSuccess() { + return success; + } + + public void setSuccess(boolean success) { + this.success = success; + } + + public Object getData() { + return data; + } + + public void setData(Object data) { + this.data = data; + } + + public String getCode() { + return code; + } + + public void setCode(String code) { + this.code = code; + } + + public String getErrorMessage() { + return errorMessage; + } + + public void setErrorMessage(String errorMessage) { + this.errorMessage = errorMessage; + } + +} diff --git a/src/main/youhong_ai_jitu_src/jntchina/util/SHA256Util.java b/src/main/youhong_ai_jitu_src/jntchina/util/SHA256Util.java new file mode 100644 index 0000000..ab57ae3 --- /dev/null +++ b/src/main/youhong_ai_jitu_src/jntchina/util/SHA256Util.java @@ -0,0 +1,36 @@ +package jntchina.util; + +import java.nio.charset.StandardCharsets; +import java.security.MessageDigest; +import java.security.NoSuchAlgorithmException; + +public class SHA256Util { + + public static String getSHA256(String str) { + MessageDigest messageDigest; + String encodestr = ""; + try { + messageDigest = MessageDigest.getInstance("SHA-256"); + messageDigest.update(str.getBytes(StandardCharsets.UTF_8)); + encodestr = byte2Hex(messageDigest.digest()); + } catch (NoSuchAlgorithmException e) { + e.printStackTrace(); + } + return encodestr; + } + + private static String byte2Hex(byte[] bytes) { + StringBuffer stringBuffer = new StringBuffer(); + String temp = null; + for (int i = 0; i < bytes.length; i++) { + temp = Integer.toHexString(bytes[i] & 0xFF); + if (temp.length() == 1) { + // 1瀵版鍩屾稉?缍呴惃鍕箻鐞涘矁藟0閹垮秳缍�? + stringBuffer.append("0"); + } + stringBuffer.append(temp); + } + return stringBuffer.toString(); + } + +} diff --git a/src/main/youhong_ai_jitu_src/jntchina/util/Test.java b/src/main/youhong_ai_jitu_src/jntchina/util/Test.java new file mode 100644 index 0000000..ea19ee1 --- /dev/null +++ b/src/main/youhong_ai_jitu_src/jntchina/util/Test.java @@ -0,0 +1,406 @@ +package jntchina.util; + +import com.google.gson.Gson; +import org.apache.commons.lang3.StringUtils; + +import java.io.*; +import java.lang.reflect.Type; +import java.net.HttpURLConnection; +import java.net.URL; +import java.net.URLEncoder; +import java.nio.charset.Charset; +import java.util.HashMap; +import java.util.Map; +import java.util.Properties; + +/** + * 1.从resources/config.properties中读取测试api相关的数据 2.运行程序,测试查看测试结果 + * + * @author lizhmf + * @date 2019年6月20日上午10:53:11 + */ +public class Test { + + // app_secret + private static String client_secret = "7f4960d6de4a42bebfc4"; + // 公钥 + private static String pubKey = "MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCbAEDvatjhVymfI2gubZ72iYaOtbcmLZljJOEfKtl0v3rkwoify8o1qBjqOYkvAh8a7iER/lWzMZgg5iHpbUqS1Plejx4fvUvslQt59B+1gzruLbW+4jDEY9Cl2f7vj7J1HYp9K7OBY0oM2GvzFJzLWnpDnJVjgNNyuEqlqYY5kQIDAQAB"; + // app_id + private static String client_id = "oa"; + // ncc用户名 + private static String username = null; + // ncc用户名密码 + private static String pwd = null; + // ncc账套 + private static String busi_center = "JT"; + // 获取token方式:client_credentials、password + private static String grant_type = "client_credentials"; + // 服务器ip:port + private static String baseUrl = "http://180.169.229.37:8080"; + // 返回值压缩加密级别 + private static String secret_level = "L0"; + // 请求参数 +// private static String requestBody = "{\"pk_org\": \"JTSDCN0001\",\"total\": \"103.00\",\"deptid\": \"SD3300101\",\"djlxbm\": \"264X-Cxx-DGBXD\",\"djrq\": \"2021-02-05 08:17:10\",\"payflag\": \"1\",\"paytarget\": \"0\",\"receiver\": \"yonyou88\",\"jkbxr\": \"yonyou88\",\"operator\": \"yonyou88\",\"jsfs\": \"3\",\"fkyhzh\": \"\",\"jobid\": \"\",\"zy\": \"报销测试\",\"kjqj\": \"02\",\"kjnd\": \"2021\",\"fjzs\":\"0\",\"zyx1\": \"CSBX20210303\",\"zyx2\": \"\",\"zyx3\": \"\",\"zyx5\": \"CSBX20210303\",\"er_busitem\": [{\"jobid\": \"\",\"deptid\": \"SD3300101\",\"amount\": \"103.00\",\"tax_rate\": \"3.00\",\"tax_amount\": \"3.00\",\"tni_amount\": \"100.00\",\"tablecode\": \"arap_bxbusitem\",\"rowno\": \"10\",\"szxmid\": \"\",\"defitem46\":\"\",\"defitem45\": \"\",\"defitem44\": \"\",\"defitem43\": \"\",\"defitem42\": \"\",\"defitem7\": \"SD3300301\"}]}"; + private static String requestBody = "{pk_org='JTSDCN0001', total='44', deptid='', djlxbm='264X-Cxx-DSBXD', djrq='2021-03-04', payflag='', paytarget='0', receiver='yonyou88', jkbxr='yonyou88', operator='yonyou88', jsfs='3', fkyhzh='', jobid='', zy='这是一天测试费用报销申请单的摘要', kjqj='', kjnd='', fjzs='0', zyx1='CSBX20210313414', zyx2='1', zyx3='', zyx5='728728', er_busitem=[ReimbursementOrderBody{jobid='', deptid='522', amount='44', tax_rate='0.02', tax_amount='2.2', tni_amount='41.8', tablecode='arap_bxbusitem', rowno='10', szxmid='', defitem46='', defitem45='', defitem44='', defitem43='', defitem42='', defitem7='522'}]}"; + // openapi请求路径 + private static String apiUrl = "/nccloud/api/jitu/erm/bxbill/insert"; + + // 访问api获取到的access_token + public static String token = null; + // 重复调用检查 + public static String repeat_check = null; + // 接口调用业务标识 + public static String busi_id = null; + + /** + * 启动入口 + * + * @param args + */ + public static void main(String[] args) { + try { + // 初始化数据 +// init(); + + // 请求token + token = getToken(); + System.out.println("getTokenData:" + token); + if (token != null) { + // 测试openapi + testApi(token); + } + } catch (Exception e) { + e.printStackTrace(); + } + } + + /** + * 获取access_token + * + * @return + * @throws Exception + */ + private static String getToken() throws Exception { + String token = null; + if ("password".equals(grant_type)) { + // 密码模式 + token = getTokenByPWD(); + } else if ("client_credentials".equals(grant_type)) { + // 客户端模式 + token = getTokenByClient(); + } + return token; + } + + /** + * 客户端模式获取token + * + * @return + * @throws Exception + */ + private static String getTokenByClient() throws Exception { + Map paramMap = new HashMap(); + // 密码模式认证 + paramMap.put("grant_type", "client_credentials"); + // 第三方应用id + paramMap.put("client_id", client_id); + // 第三方应用secret 公钥加密 + paramMap.put("client_secret", URLEncoder.encode(Encryption.pubEncrypt(pubKey, client_secret), "utf-8")); + // 账套编码 + paramMap.put("biz_center", busi_center); + // // TODO 传递数据源和ncc登录用户 + // paramMap.put("dsname", "TM_0614"); + // paramMap.put("usercode", "1"); + + // 签名 + String sign = SHA256Util.getSHA256(client_id + client_secret + pubKey); + paramMap.put("signature", sign); + + String url = baseUrl + "/nccloud/opm/accesstoken"; + String mediaType = "application/x-www-form-urlencoded"; + String token = doPost(url, paramMap, mediaType, null, ""); + return token; + } + + /** + * 密码模式获取token + * + * @return + * @throws Exception + */ + @SuppressWarnings("unused") + private static String getTokenByPWD() throws Exception { + Map paramMap = new HashMap(); + // 密码模式认证 + paramMap.put("grant_type", "password"); + // 第三方应用id + paramMap.put("client_id", client_id); + // 第三方应用secret 公钥加密 + paramMap.put("client_secret", URLEncoder.encode(Encryption.pubEncrypt(pubKey, client_secret), "utf-8")); + // ncc用户名 + paramMap.put("username", username); + // 密码 公钥加密 + paramMap.put("password", URLEncoder.encode(Encryption.pubEncrypt(pubKey, pwd), "utf-8")); + // 账套编码 + paramMap.put("biz_center", busi_center); + // 签名 + String sign = SHA256Util.getSHA256(client_id + client_secret + username + pwd + pubKey); + paramMap.put("signature", sign); + + String url = baseUrl + "/nccloud/opm/accesstoken"; + String mediaType = "application/x-www-form-urlencoded"; + String token = doPost(url, paramMap, mediaType, null, ""); + return token; + } + + /** + * 请求openapi + * + * @param token 请求body参数加密压缩用的key + * @throws Exception + */ + private static void testApi(String token) throws Exception { + // token转对象,获取api访问所用token和secret + ResultMessageUtil returnData = new Gson().fromJson(token, (Type) ResultMessageUtil.class); + Map data = (Map) returnData.getData(); + String access_token = data.get("access_token"); + String security_key = data.get("security_key"); + String refresh_token = data.get("refresh_token"); + System.out.println("【ACCESS_TOKEN】:" + access_token); + + // 请求路径 + String url = baseUrl + apiUrl; + // header 参数 + Map headermap = new HashMap<>(); + headermap.put("access_token", access_token); + headermap.put("client_id", client_id); + + StringBuffer sb = new StringBuffer(); + sb.append(client_id); + if (StringUtils.isNotBlank(requestBody)) { + // sb.append(requestBody.replaceAll("\\s*|\t|\r|\n", "").trim()); + sb.append(requestBody); + } + sb.append(pubKey); + String sign = SHA256Util.getSHA256(sb.toString()); + headermap.put("signature", sign); + + if (StringUtils.isNotBlank(busi_id)) { + headermap.put("busi_id", busi_id); + } + if (StringUtils.isNotBlank(repeat_check)) { + headermap.put("repeat_check", repeat_check); + } + headermap.put("ucg_flag", "y"); + + String mediaType = "application/json;charset=utf-8"; + + // 表体数据json + // 根据安全级别选择加密或压缩请求表体参数 + String json = dealRequestBody(requestBody, security_key, secret_level); + + String result = doPost(url, null, mediaType, headermap, json); + + String result2DecryptAndDecompress = dealResponseBody(result, security_key, secret_level); + System.out.println("【RESULT】:" + result); + // System.out.println("result解密:" + result2); + } + + /** + * 返回值进行过加密和压缩,对返回值进行解压和解密 + * + * @param source + * @param security_key + * @param level + * @return + * @throws Exception + */ + private static String dealResponseBody(String source, String security_key, String level) throws Exception { + String result = null; + + if (StringUtils.isEmpty(level) || SecretConst.LEVEL0.equals(level)) { + result = source; + } else if (SecretConst.LEVEL1.equals(level)) { + result = Decryption.symDecrypt(security_key, source); + } else if (SecretConst.LEVEL2.equals(level)) { + result = CompressUtil.gzipDecompress(source); + } else if (SecretConst.LEVEL3.equals(level)) { + result = CompressUtil.gzipDecompress(Decryption.symDecrypt(security_key, source)); + } else if (SecretConst.LEVEL4.equals(level)) { + result = Decryption.symDecrypt(security_key, CompressUtil.gzipDecompress(source)); + } else { + throw new Exception("无效的安全等级"); + } + + return result; + } + + /** + * 初始化参数 + */ + private static void init() { + // TODO Auto-generated method stub + Properties properties = new Properties(); + + String filepath = "config_info.properties"; + ClassLoader classloader = Thread.currentThread().getContextClassLoader(); + InputStream inputStream = classloader.getResourceAsStream(filepath); + try { + InputStreamReader reader = new InputStreamReader(inputStream, "UTF-8"); + properties.load(reader); + + client_secret = new String(properties.getProperty("client_secret").getBytes("utf-8"), "utf-8"); + client_id = properties.getProperty("client_id"); + pubKey = properties.getProperty("pubKey"); + username = properties.getProperty("username"); + pwd = properties.getProperty("pwd"); + busi_center = properties.getProperty("busi_center"); + baseUrl = properties.getProperty("baseUrl"); + requestBody = new String(properties.getProperty("requestBody").getBytes("utf-8"), "utf-8"); + apiUrl = properties.getProperty("apiUrl"); + grant_type = properties.getProperty("grant_type"); + secret_level = properties.getProperty("secret_level"); + repeat_check = properties.getProperty("repeat_check"); + busi_id = properties.getProperty("busi_id"); + } catch (IOException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + } + + // 根据安全级别设置,表体是否加密或压缩 + private static String dealRequestBody(String source, String security_key, String level) throws Exception { + String result = null; + if (StringUtils.isEmpty(level) || SecretConst.LEVEL0.equals(level)) { + result = source; + } else if (SecretConst.LEVEL1.equals(level)) { + result = Encryption.symEncrypt(security_key, source); + } else if (SecretConst.LEVEL2.equals(level)) { + result = CompressUtil.gzipCompress(source); + } else if (SecretConst.LEVEL3.equals(level)) { + result = Encryption.symEncrypt(security_key, CompressUtil.gzipCompress(source)); + } else if (SecretConst.LEVEL4.equals(level)) { + result = CompressUtil.gzipCompress(Encryption.symEncrypt(security_key, source)); + } else { + throw new Exception("无效的安全等级"); + } + + return result; + } + + /** + * 发送post请求 + * + * @param baseUrl + * @param paramMap + * @param mediaType + * @param headers + * @param json + * @return + */ + private static String doPost(String baseUrl, Map paramMap, String mediaType, Map headers, String json) { + + HttpURLConnection urlConnection = null; + InputStream in = null; + OutputStream out = null; + BufferedReader bufferedReader = null; + String result = null; + try { + StringBuffer sb = new StringBuffer(); + sb.append(baseUrl); + if (paramMap != null) { + sb.append("?"); + for (Map.Entry entry : paramMap.entrySet()) { + String key = entry.getKey(); + String value = entry.getValue(); + sb.append(key + "=" + value).append("&"); + } + baseUrl = sb.toString().substring(0, sb.toString().length() - 1); + } + + URL urlObj = new URL(baseUrl); + urlConnection = (HttpURLConnection) urlObj.openConnection(); + urlConnection.setConnectTimeout(50000); + urlConnection.setRequestMethod("POST"); + urlConnection.setDoOutput(true); + urlConnection.setDoInput(true); + urlConnection.setUseCaches(false); + urlConnection.addRequestProperty("content-type", mediaType); + if (headers != null) { + for (String key : headers.keySet()) { + urlConnection.addRequestProperty(key, headers.get(key)); + } + } + out = urlConnection.getOutputStream(); + out.write(json.getBytes("utf-8")); + out.flush(); + int resCode = urlConnection.getResponseCode(); + if (resCode == HttpURLConnection.HTTP_OK || resCode == HttpURLConnection.HTTP_CREATED || resCode == HttpURLConnection.HTTP_ACCEPTED) { + in = urlConnection.getInputStream(); + } else { + in = urlConnection.getErrorStream(); + } + bufferedReader = new BufferedReader(new InputStreamReader(in, "utf-8")); + StringBuffer temp = new StringBuffer(); + String line = bufferedReader.readLine(); + while (line != null) { + temp.append(line).append("\r\n"); + line = bufferedReader.readLine(); + } + String ecod = urlConnection.getContentEncoding(); + if (ecod == null) { + ecod = Charset.forName("utf-8").name(); + } + result = new String(temp.toString().getBytes("utf-8"), ecod); + } catch (Exception e) { + System.out.println(e); + } finally { + if (null != bufferedReader) { + try { + bufferedReader.close(); + } catch (IOException e) { + e.printStackTrace(); + } + } + if (null != out) { + try { + out.close(); + } catch (IOException e) { + e.printStackTrace(); + } + } + if (null != in) { + try { + in.close(); + } catch (IOException e) { + e.printStackTrace(); + } + } + urlConnection.disconnect(); + } + return result; + } + + class SecretConst { + /** + * LEVEL0 不压缩、不加密 + */ + public static final String LEVEL0 = "L0"; + /** + * LEVEL1 只加密、不压缩 + */ + public static final String LEVEL1 = "L1"; + /** + * LEVEL2 只压缩、不加密 + */ + public static final String LEVEL2 = "L2"; + /** + * LEVEL3 先压缩、后加密 + */ + public static final String LEVEL3 = "L3"; + /** + * LEVEL4 先加密、后压缩 + */ + public static final String LEVEL4 = "L4"; + } +} diff --git a/src/main/youhong_ai_jitu_src/jntchina/util/URLConfigEnum.java b/src/main/youhong_ai_jitu_src/jntchina/util/URLConfigEnum.java new file mode 100644 index 0000000..1aca2ae --- /dev/null +++ b/src/main/youhong_ai_jitu_src/jntchina/util/URLConfigEnum.java @@ -0,0 +1,104 @@ +package jntchina.util; + +import weaver.file.Prop; + +/** + * @description: url的配置类 + * @author: kw + * @date: 2020/5/21 + * @param: + * @return: + */ +public enum URLConfigEnum { + + //如果需要测试其他接口 直接在这里添加枚举即可 + + //发票打印 + TAX_PRINT("/output-tax/api/invoice-his/print?appid="), + //开票申请删除 + INVOICE_APPLY_DEL_URL("/invoiceclient-web/api/invoiceApply/del?appid="), + //开票蓝票请求服务 + INSERT_WITH_ARRAY_URL("/invoiceclient-web/api/invoiceApply/insertWithArray?appid="), + //OCR识别接口 + RECOGNISE("/input-tax/api/ocr/v2/recognise?appid="), + //开票状态查询服务 + QUERY_INBOICE_STATUS("/invoiceclient-web/api/invoiceApply/queryInvoiceStatus?appid="), + //开票申请审核通过 + ISSUE("/invoiceclient-web/api/invoiceApply/issue?appid="), + //发票红冲请求服务 + RED("/invoiceclient-web/api/invoiceApply/red?appid="), + //电子发票部分红冲 + PART_RED("/invoiceclient-web/api/invoiceApply/part-red?appid="), + //开票蓝票请求服务--发票拆分 + INSERT_WITH_SPLIT ("/invoiceclient-web/api/invoiceApply/insertWithSplit?appid="), + //识别结果保存台帐 + OCR_SAVE("/input-tax/api/bill-collections/ocr-save?appid="), + //台账报销 + REIMBURSED("/input-tax/api/bill-collections/reimbursed?appid="), + //台账取消报销 + CANCEL_REIMBURSED("/input-tax/api/bill-collections/cancel-reimbursed?appid="), + //台账记账 + ACCOUNT("/input-tax/api/bill-collections/account?appid="), + //台账记账 + CANCEL_ACCOUNT("/input-tax/api/bill-collections/cancel-account?appid="), + //报销台账删除 + DELETE("/input-tax/api/bill-collections/delete?appid="), + //飞机票台账查询 + AIR("/input-tax/api/bill-collections/air?pagenum=1&pagesize=15&appid="), + //火车票台账查询 + TRAIN("/input-tax/api/bill-collections/train?pagenum=1&pagesize=15&appid="), + //出租车台账查询 + TAXI("/input-tax/api/bill-collections/taxi?pagenum=1&pagesize=15&appid="), + //个人票夹提交发票到报销台账_全票种 + COMMIT("/piaoeda-web/api/bill/v2/commit?appid="), + //发票上传 + UPLOADPDF("/invoiceclient-web/api/reimburseCollection/uploadpdf?appid="), + //发票取消上传 + COLLECTION_DELETE("/invoiceclient-web/api/reimburseCollection/delete?appid="), + //发票已报销 + COLLECTION_REIMBURSED ("/invoiceclient-web/api/reimburseCollection/reimbursed?appid="), + //发票取消报销 + COLLECTION_UNREIMBURSED("/invoiceclient-web/api/reimburseCollection/unreimbursed?appid="), + //报销台账查询接口(新) + QUERY("/invoiceclient-web/api/reimburseCollection/query?appid="), + //入账 + ACCOUNT_STATUS("/invoiceclient-web/api/reimburseCollection/accountStatus?appid="), + //取消入账 + COLLECTION_CANCEL_ACCOUNT("/invoiceclient-web/api/reimburseCollection/cancelAccount?appid="), + //发票上传V2 + V2_UPLOADPDF("/input-tax/api/reimburseCollection/v2/uploadpdf?appid="); + //pro22.pfx为测试环境通讯证书,正式环境需要替换成正式的 + //KEY_PATH("/usr/weaver/ecology/classbean/jntchina/certificate/pro22.pfx"), + //证书密码 + //PASSWORD("password"); + + //获取配置文件中的参数 + String mode = Prop.getPropValue("DevToTaxCould_jntchina","mode"); + // 服务器ip:port + String baseUrl1 = Prop.getPropValue("DevToTaxCould_jntchina", mode+"_baseURL"); + String appid1 = Prop.getPropValue("DevToTaxCould_jntchina",mode+"_appid"); + //证书路径 + String certpath = Prop.getPropValue("DevToTaxCould_jntchina",mode+"_certpath"); + //pro22.pfx为测试环境通讯证书,正式环境需要替换成正式的 + + //测试环境有测试appid和证书,正式环境有正式appid和证书,请务必对应使用 + //测试环境appid就用这个,正式环境需要替换成正式的 + // private static String APPID = ""; + private static String APPID = REIMBURSED.appid1; + + //这个是测试环境的域名,正式环境为https://fapiao.yonyoucloud.com + //测试https://yesfp.yonyoucloud.com + // private static String DOMAIN = "https://fapiao.yonyoucloud.com"; + private static String DOMAIN = REIMBURSED.baseUrl1; + + private String value; + URLConfigEnum(String value) { + this.value = value; + } + + public String getValue() {return value;} + public String getUrl() { + + return DOMAIN + value + APPID; + } +} diff --git a/src/main/youhong_ai_jitu_src/selfdev/util/base/BaseUtil.java b/src/main/youhong_ai_jitu_src/selfdev/util/base/BaseUtil.java new file mode 100644 index 0000000..38c6a9b --- /dev/null +++ b/src/main/youhong_ai_jitu_src/selfdev/util/base/BaseUtil.java @@ -0,0 +1,249 @@ +package selfdev.util.base; + + +import java.io.IOException; +import java.io.UnsupportedEncodingException; +import java.security.MessageDigest; +import java.security.NoSuchAlgorithmException; +import java.util.HashMap; +import java.util.Map; + +import sun.misc.BASE64Decoder; +import sun.misc.BASE64Encoder; +import weaver.conn.RecordSet; +import weaver.conn.RecordSetDataSource; +import weaver.general.Util; + +public class BaseUtil { + + /** + * 根据字段获取相关信息 + * @param fieldName 需要获取的字段 + * @param tableName 从哪个表中读取 + * @param whereField 根据哪个字段来查询,即where后的字段 + * @param whereValue 根据的字段什么值来查询 + * @param whereOther 其他查询条件 + * @return + */ + public static String getBaseInfoByParm(String fieldName,String tableName,String whereField,String whereValue,String whereOther){ + String res = ""; + RecordSet rs = new RecordSet(); + try{ + if(rs.execute("select * from "+tableName+" where "+whereField+"='" + whereValue + "' "+whereOther)){ + if(rs.next()){ + res = Util.null2String( rs.getString(fieldName) ); + } + } + } catch(Exception e){ + e.printStackTrace(); + } + return res; + } + + /** + * 根据字段获取Map + * @param tableName 从哪个表中读取 + * @param whereStr where条件 + * @param keyFiled Map中的key字段名 + * @param valueFiled Map中的value字段名 + * @return + */ + public static Map getMapKeyValueInfoByParm(String tableName,String whereStr,String keyFiled,String valueFiled){ + Map map=new HashMap(); + RecordSet rs = new RecordSet(); + try{ + String sql="select * from "+tableName; + if(!"".equals(whereStr)){ + sql=sql+" "+whereStr; + } + rs.execute(sql); + while(rs.next()){ + map.put(Util.null2String(rs.getString(keyFiled)), Util.null2String(rs.getString(valueFiled))); + } + } catch(Exception e){ + e.printStackTrace(); + } + return map; + } + + /** + * 根据字段获取相关信息 + * @param datasourceName 数据源名称 + * @param fieldName 需要获取的字段 + * @param tableName 从哪个表中读取 + * @param whereField 根据哪个字段来查询,即where后的字段 + * @param whereValue 根据的字段什么值来查询 + * @param whereOther 其他查询条件 + * @return + */ + public static String getBaseInfoByParm_DataSource(String datasourceName,String fieldName,String tableName,String whereField,String whereValue,String whereOther){ + String res = ""; + RecordSetDataSource rsds = new RecordSetDataSource(datasourceName); + try{ + if(rsds.execute("select * from "+tableName+" where "+whereField+"='" + whereValue + "' "+whereOther)){ + if(rsds.next()){ + res = Util.null2String( rsds.getString(fieldName) ); + } + } + } catch(Exception e){ + e.printStackTrace(); + } + return res; + } + + /** + * 根据字段获取Map + * @param datasourceName 数据源名称 + * @param tableName 从哪个表中读取 + * @param whereStr where条件 + * @param keyFiled Map中的key字段名 + * @param valueFiled Map中的value字段名 + * @return + */ + public static Map getMapKeyValueInfoByParm_DataSource(String datasourceName,String tableName,String whereStr,String keyFiled,String valueFiled){ + Map map=new HashMap(); + RecordSetDataSource rsds = new RecordSetDataSource(datasourceName); + try{ + String sql="select * from "+tableName; + if(!"".equals(whereStr)){ + sql=sql+" "+whereStr; + } + rsds.execute(sql); + while(rsds.next()){ + map.put(Util.null2String(rsds.getString(keyFiled)), Util.null2String(rsds.getString(valueFiled))); + } + } catch(Exception e){ + e.printStackTrace(); + } + return map; + } + + /** + * XML字符串转译(5个) + * < < + * > > + * & & + * " " + * ' ' + * @return + */ + public static String XMLConvert(String xml){ + String str=""; + str=xml.replaceAll("<", "<").replaceAll(">", ">").replaceAll("&", "&").replaceAll("\"", """).replaceAll("'", "'"); + return str; + } + /** + * 判断字符串是否为数字 + * @param str + * @return + */ + public static boolean isNumeric(String str){ + for (int i = str.length();--i>=0;){ + if (!Character.isDigit(str.charAt(i))){ + return false; + } + } + return true; + } + + /** + * base64解码 + * @param str + * @return + */ + public static String base64Decoder(String str){ + BASE64Decoder decode=new BASE64Decoder(); + String result=""; + byte[] b; + try { + b = decode.decodeBuffer(str); + result=new String(b,"UTF-8");//UTF-8编码格式 + } catch (IOException e) { + e.printStackTrace(); + } + return result; + } + /** + * base64编码 + * @param str + * @return + */ + public static String base64Eecoder(String str){ + BASE64Encoder encode=new BASE64Encoder(); + String result=""; + try { + result = encode.encode(str.getBytes("UTF-8")); + } catch (IOException e) { + e.printStackTrace(); + } + return result; + } + /** + * MD5加密 + * @param s + * @return + */ + public final static String MD5(String s) { + char hexDigits[]={'0','1','2','3','4','5','6','7','8','9','A','B','C','D','E','F'}; + try { + byte[] btInput = s.getBytes(); + // 获得MD5摘要算法的 MessageDigest 对象 + MessageDigest mdInst = MessageDigest.getInstance("MD5"); + // 使用指定的字节更新摘要 + mdInst.update(btInput); + // 获得密文 + byte[] md = mdInst.digest(); + // 把密文转换成十六进制的字符串形式 + int j = md.length; + char str[] = new char[j * 2]; + int k = 0; + for (int i = 0; i < j; i++) { + byte byte0 = md[i]; + str[k++] = hexDigits[byte0 >>> 4 & 0xf]; + str[k++] = hexDigits[byte0 & 0xf]; + } + return new String(str); + } catch (Exception e) { + e.printStackTrace(); + return null; + } + } + /** + * SHA256加密 + * @param str 加密后的报文 + * @return + */ + public static String getSHA256(String str) { + MessageDigest messageDigest; + String encodestr = ""; + try { + messageDigest = MessageDigest.getInstance("SHA-256"); + messageDigest.update(str.getBytes("UTF-8")); + encodestr = byte2Hex(messageDigest.digest()); + } catch (NoSuchAlgorithmException e) { + e.printStackTrace(); + } catch (UnsupportedEncodingException e) { + e.printStackTrace(); + } + return encodestr; + } + + /** + * 将byte转为16进制 + * @param bytes + * @return + */ + private static String byte2Hex(byte[] bytes) { + StringBuffer stringBuffer = new StringBuffer(); + String temp = null; + for (int i = 0; i < bytes.length; i++) { + temp = Integer.toHexString(bytes[i] & 0xFF); + if (temp.length() == 1) { + // 1得到一位的进行补0操作 + stringBuffer.append("0"); + } + stringBuffer.append(temp); + } + return stringBuffer.toString(); + } +} diff --git a/src/main/youhong_ai_jitu_src/selfdev/util/base/TimeCommonUtil.java b/src/main/youhong_ai_jitu_src/selfdev/util/base/TimeCommonUtil.java new file mode 100644 index 0000000..7be7ff5 --- /dev/null +++ b/src/main/youhong_ai_jitu_src/selfdev/util/base/TimeCommonUtil.java @@ -0,0 +1,181 @@ +package selfdev.util.base; + +import java.text.ParseException; +import java.text.SimpleDateFormat; +import java.util.Arrays; +import java.util.Calendar; +import java.util.Date; + +/** + * 时间公共类 + * @author KangMD + * + */ +public class TimeCommonUtil { + + /** + * 获取当前几天前/几天后的日期 + * @param days 负数表示获取多少天前,正数表示获取多少天后 + * @return yyyy-MM-dd HH:mm:ss格式 + */ + public static String obtainDate(int days){ + String dt=""; + //获得入参的日期 + Calendar calendar = Calendar.getInstance(); + calendar.setTime(new Date()); + //获取下个月第一天: + calendar.add(Calendar.DAY_OF_MONTH, days); + SimpleDateFormat sdf =new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); + dt=sdf.format(calendar.getTime()); + return dt; + } + + /** + * 计算2个日期相差多少天 + * @param smdate 开始日期(yyyy-MM-dd格式) + * @param bdate 结束日期(yyyy-MM-dd格式) + * @return 相差天数 + * @throws ParseException + */ + public static int daysBetween(String smdate,String bdate){ + SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd"); + Calendar cal = Calendar.getInstance(); + long between_days=0; + try { + cal.setTime(sdf.parse(smdate)); + long time1 = cal.getTimeInMillis(); + cal.setTime(sdf.parse(bdate)); + long time2 = cal.getTimeInMillis(); + between_days=(time2-time1)/(1000*3600*24); + } catch (ParseException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + return Integer.parseInt(String.valueOf(between_days)); + } + /** + * 计算2个日期相差多少个月 + * @param smdate 开始日期(yyyy-MM-dd格式) + * @param bdate 结束日期(yyyy-MM-dd格式) + * @return 相差天数 + * @throws ParseException + */ + public static int monthsBetween(String smdate,String bdate){ + SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd"); + long between_months=0; + try { + Calendar startCalendar = Calendar.getInstance(); + startCalendar.setTime(sdf.parse(smdate)); + Calendar endCalendar = Calendar.getInstance(); + endCalendar.setTime(sdf.parse(bdate)); + Calendar temp = Calendar.getInstance(); + temp.setTime(sdf.parse(bdate)); + temp.add(Calendar.DATE, 1); + int year = endCalendar.get(Calendar.YEAR) - startCalendar.get(Calendar.YEAR); + int month = endCalendar.get(Calendar.MONTH) - startCalendar.get(Calendar.MONTH); + if ((startCalendar.get(Calendar.DATE) == 1)&& (temp.get(Calendar.DATE) == 1)) { + between_months= year * 12 + month + 1; + } else if ((startCalendar.get(Calendar.DATE) != 1) && (temp.get(Calendar.DATE) == 1)) { + between_months= year * 12 + month; + } else if ((startCalendar.get(Calendar.DATE) == 1) && (temp.get(Calendar.DATE) != 1)) { + between_months= year * 12 + month; + } else { + between_months= (year * 12 + month - 1) < 0 ? 0 : (year * 12 + month); + } + } catch (ParseException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + return Integer.parseInt(String.valueOf(between_months)); + } + /** + * 获取某月的最后一天 + * @Title:getLastDayOfMonth + * @Description: + * @param:@param year + * @param:@param month + * @param:@return + * @return:String + * @throws + */ + public static String getLastDayOfMonth(int year,int month){ + Calendar cal = Calendar.getInstance(); + //设置年份 + cal.set(Calendar.YEAR,year); + //设置月份 + cal.set(Calendar.MONTH, month); + // + cal.set(Calendar.DAY_OF_MONTH, 0); + //获取某月最大天数 + //int lastDay = cal.getActualMaximum(Calendar.DAY_OF_MONTH); + //设置日历中月份的最大天数 + //cal.set(Calendar.DAY_OF_MONTH, lastDay); + //格式化日期 + SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd"); + String lastDayOfMonth = sdf.format(cal.getTime()); + return lastDayOfMonth; + } + + /** + * 根据传入的年月获取上个月的年月(若传入为空则获取当前系统上个月的年月) + * @param ny 年月(yyyy-MM格式) + * @return 上个月的年月(yyyy-MM格式) + * @throws ParseException + */ + public static String loadLastMonth(String ny){ + SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd"); + String ny_last=""; + try { + Calendar cal = Calendar.getInstance(); + //若传入为空则获取当前系统上个月的年月 + if(!"".equals(ny)){ + //设置年份 + cal.setTime(sdf.parse(ny+"-01")); + } + //月份-1 + cal.add(Calendar.MONTH, -1); + cal.set(Calendar.DAY_OF_MONTH,1); + //获取前一个月第一天 + String firstDay = sdf.format(cal.getTime()).substring(0,7); + ny_last = firstDay.substring(0,7); + } catch (Exception e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + return ny_last; + } + /** + * 获取某个月下所有的日期所对应的是星期几 + * @param ny 年月(yyyy-MM格式) + * @return 数组格式 + * @throws Exception + */ + public static String[] loadWeekByYearMonth(String ny){ + SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd"); + String week[]=new String[0]; + try { + Calendar cal = Calendar.getInstance(); + //若传入为空则获取当前系统上个月的年月 + if(!"".equals(ny)){ + //设置年份 + cal.setTime(sdf.parse(ny+"-01")); + } + String[] weekDays = {"日", "一", "二", "三", "四", "五", "六"}; + //获取该月第一天是星期几 + int w = cal.get(Calendar.DAY_OF_WEEK) - 1; + //获取该月有多少天 + int days=cal.getActualMaximum(Calendar.DAY_OF_MONTH); + for(int t=0;t paramMap = weaAfterReplaceParam.getParamMap(); + String loginId = Util.null2String(paramMap.get("loginid")); + String lastName = Util.null2String(paramMap.get("lastname")); + ToolUtil toolUtil = new ToolUtil(); + toolUtil.writeErrorLog(weaAfterReplaceParam.getParamMap().toString()); + toolUtil.writeErrorLog(loginId); + toolUtil.writeErrorLog(lastName); + if (StringUtils.isNullOrEmpty(loginId)) { +// 没有登录id + if (!StringUtils.isNullOrEmpty(lastName)) { +// 查询该名称的最后一名 + String query = "select id from hrmresource where lastname = ? ORDER BY id desc limit 1"; + RecordSet rs = new RecordSet(); + rs.executeQuery(query, lastName); + if (rs.next()) { + toolUtil.writeErrorLog(rs.getString(1)); + ChangeStatusUtil.changeStatus(rs.getString(1), 1); + } + } + } else { + String query = "select id from hrmresource where loginid = ? "; + RecordSet rs = new RecordSet(); + rs.executeQuery(query, loginId); + if (rs.next()) { + toolUtil.writeErrorLog(rs.getString(1)); + ChangeStatusUtil.changeStatus(rs.getString(1), 1); + } + } + return weaAfterReplaceParam.getData(); + } + + + /* + +++++++++++++++++++++++++++++++++++++++++++添加人员数据END+++++++++++++++++++++++++++++ + */ + + + /* + +++++++++++++++++++++++++++++++++++++++++++离职人员数据Start+++++++++++++++++++++++++++++ + */ + +/* @WeaReplaceBefore(value = "/api/hrm/statechange/saveHrmDismiss", order = 1, description = "人员离职") + public void saveHrmDismissBefore(WeaBeforeReplaceParam weaBeforeReplaceParam) { + ChangeStatusUtil.changeHrmResourceStatus(weaBeforeReplaceParam, "tempresourceid", 3); + }*/ + + @WeaReplaceAfter(value = "/api/hrm/statechange/saveHrmDismiss", order = 1, description = "人员离职") + public String saveHrmDismissAfter(WeaAfterReplaceParam weaAfterReplaceParam) { + try { + ChangeStatusUtil.changeHrmResourceStatusAfter(weaAfterReplaceParam, "tempresourceid", 3); + + } catch (Exception e) { + e.printStackTrace(); + } + return weaAfterReplaceParam.getData(); + } + + + +/* @WeaReplaceBefore(value = "/api/hrm/statechange/saveHrmFire", order = 1, description = "人员解聘") + public void saveHrmFireBefore(WeaBeforeReplaceParam weaBeforeReplaceParam) { + ChangeStatusUtil.changeHrmResourceStatus(weaBeforeReplaceParam, "tempresourceid", 3); + }*/ + + @WeaReplaceAfter(value = "/api/hrm/statechange/saveHrmFire", order = 1, description = "人员解聘") + public String saveHrmFireAfter(WeaAfterReplaceParam weaAfterReplaceParam) { + try { + ChangeStatusUtil.changeHrmResourceStatusAfter(weaAfterReplaceParam, "tempresourceid", 3); + + } catch (Exception e) { + e.printStackTrace(); + } + return weaAfterReplaceParam.getData(); + } + + +/* + @WeaReplaceBefore(value = "/api/hrm/statechange/saveHrmRetire", order = 1, description = "人员退修") + public void saveHrmRetireBefore(WeaBeforeReplaceParam weaBeforeReplaceParam) { + ChangeStatusUtil.changeHrmResourceStatus(weaBeforeReplaceParam, "tempresourceid", 3); + }*/ + + /* + +++++++++++++++++++++++++++++++++++++++++++离职员数据END+++++++++++++++++++++++++++++ + */ + +} diff --git a/src/main/youhong_ai_old_src/com/api/aiy_changeStatus/Impl/Util/ChangeStatusUtil.java b/src/main/youhong_ai_old_src/com/api/aiy_changeStatus/Impl/Util/ChangeStatusUtil.java new file mode 100644 index 0000000..92997de --- /dev/null +++ b/src/main/youhong_ai_old_src/com/api/aiy_changeStatus/Impl/Util/ChangeStatusUtil.java @@ -0,0 +1,128 @@ +package com.api.aiy_changeStatus.Impl.Util; + +import aiyh.utils.Util; +import aiyh.utils.zwl.common.ToolUtil; +import com.alibaba.fastjson.JSON; +import com.weaverboot.frame.ioc.handler.replace.weaReplaceParam.impl.WeaAfterReplaceParam; +import com.weaverboot.frame.ioc.handler.replace.weaReplaceParam.impl.WeaBeforeReplaceParam; +import org.h2.util.StringUtils; +import weaver.conn.RecordSet; + +import java.util.ArrayList; +import java.util.List; +import java.util.Map; + +/** + * @author EBU7-dev1-ayh + * @create 2021/11/27 0027 13:28 + * util + */ + +// TODO 去除日志文件打印相关 +public class ChangeStatusUtil { + private final static ToolUtil TOOL_UTIL = new ToolUtil(); + + private final static RecordSet rs = new RecordSet(); + + + public static void changeHrmResourceStatus(WeaBeforeReplaceParam weaBeforeReplaceParam, String key, int status) { + String apiUrl = weaBeforeReplaceParam.getApiUrl(); + Map paramMap = weaBeforeReplaceParam.getParamMap(); + String id = Util.null2String(paramMap.get(key)); + if (!StringUtils.isNullOrEmpty(id)) { + ChangeStatusUtil.changeStatus(id, status); + } + TOOL_UTIL.writeDebuggerLog(String.format("进入拦截请求方法,获取到的api{%s},请求参数{%s}", apiUrl, JSON.toJSONString(paramMap))); + } + + public static void changeHrmResourceStatusByIds(WeaBeforeReplaceParam weaBeforeReplaceParam, String key, int status) { + String apiUrl = weaBeforeReplaceParam.getApiUrl(); + Map paramMap = weaBeforeReplaceParam.getParamMap(); + String id = Util.null2String(paramMap.get(key)); + if (!StringUtils.isNullOrEmpty(id)) { + ChangeStatusUtil.changeStatusByIds(id, status); + } + TOOL_UTIL.writeDebuggerLog(String.format("进入拦截请求方法,获取到的api{%s},请求参数{%s}", apiUrl, JSON.toJSONString(paramMap))); + } + + public static void batchChangeHrmResourceStatus(WeaBeforeReplaceParam weaBeforeReplaceParam, String key, int status) { + String apiUrl = weaBeforeReplaceParam.getApiUrl(); + Map paramMap = weaBeforeReplaceParam.getParamMap(); + List> datas = (List>) paramMap.get("datas"); + if (datas == null || datas.isEmpty()) { + return; + } + List ids = new ArrayList<>(); + for (Map data : datas) { + String id = Util.null2String(data.get(key)); + if (!StringUtils.isNullOrEmpty(id)) { + ids.add(id); + } + } + if (!ids.isEmpty()) { + ChangeStatusUtil.changeStatus(ids, status); + } + TOOL_UTIL.writeDebuggerLog(String.format("进入拦截请求方法,获取到的api{%s},请求参数{%s}", apiUrl, JSON.toJSONString(paramMap))); + } + + + public static boolean changeStatus(List ids, int status) { + String sql = "update hrmresource set changestatus = ? where id in ( " + String.join(",", ids) + ")"; + TOOL_UTIL.writeDebuggerLog(sql + " ---------------> " + status); + return rs.executeUpdate(sql, status); + } + + public static boolean changeStatusByIds(String ids, int status) { + String sql = "update hrmresource set changestatus = ? where id in ( " + ids + ")"; + TOOL_UTIL.writeDebuggerLog(sql + " ---------------> " + status); + return rs.executeUpdate(sql, status); + } + + + public static boolean changeStatus(String id, int status) { + String sql = "update hrmresource set changestatus = ? where id = ?"; + TOOL_UTIL.writeDebuggerLog(sql + " ---------------> " + id + "," + status); + return rs.executeUpdate(sql, status, id); + } + + + public static void changeHrmResourceStatusAfter(WeaAfterReplaceParam weaAfterReplaceParam, String key, int status) { + String apiUrl = weaAfterReplaceParam.getApiUrl(); + Map paramMap = weaAfterReplaceParam.getParamMap(); + String id = Util.null2String(paramMap.get(key)); + if (!StringUtils.isNullOrEmpty(id)) { + ChangeStatusUtil.changeStatus(id, status); + } + TOOL_UTIL.writeDebuggerLog(String.format("进入拦截请求方法,获取到的api{%s},请求参数{%s}", apiUrl, JSON.toJSONString(paramMap))); + } + + public static void batchChangeHrmResourceStatusAfter(WeaAfterReplaceParam weaAfterReplaceParam, String key, int status) { + String apiUrl = weaAfterReplaceParam.getApiUrl(); + Map paramMap = weaAfterReplaceParam.getParamMap(); + List> datas = (List>) paramMap.get("datas"); + if (datas == null || datas.isEmpty()) { + return; + } + List ids = new ArrayList<>(); + for (Map data : datas) { + String id = Util.null2String(data.get(key)); + if (!StringUtils.isNullOrEmpty(id)) { + ids.add(id); + } + } + if (!ids.isEmpty()) { + ChangeStatusUtil.changeStatus(ids, status); + } + TOOL_UTIL.writeDebuggerLog(String.format("进入拦截请求方法,获取到的api{%s},请求参数{%s}", apiUrl, JSON.toJSONString(paramMap))); + } + + public static void changeHrmResourceStatusByIdsAfter(WeaAfterReplaceParam weaAfterReplaceParam, String key, int status) { + String apiUrl = weaAfterReplaceParam.getApiUrl(); + Map paramMap = weaAfterReplaceParam.getParamMap(); + String id = Util.null2String(paramMap.get(key)); + if (!StringUtils.isNullOrEmpty(id)) { + ChangeStatusUtil.changeStatusByIds(id, status); + } + TOOL_UTIL.writeDebuggerLog(String.format("进入拦截请求方法,获取到的api{%s},请求参数{%s}", apiUrl, JSON.toJSONString(paramMap))); + } +} diff --git a/src/main/youhong_ai_old_src/com/api/aiyh_IHG/mobil_ui/controller/CalendarWorkController.java b/src/main/youhong_ai_old_src/com/api/aiyh_IHG/mobil_ui/controller/CalendarWorkController.java new file mode 100644 index 0000000..c480d79 --- /dev/null +++ b/src/main/youhong_ai_old_src/com/api/aiyh_IHG/mobil_ui/controller/CalendarWorkController.java @@ -0,0 +1,106 @@ +package com.api.aiyh_IHG.mobil_ui.controller; + +import aiyh.utils.ApiResult; +import aiyh.utils.Util; +import aiyh.utils.excention.CustomerException; +import com.api.aiyh_IHG.mobil_ui.service.CalendarWorkService; +import com.api.aiyh_IHG.mobil_ui.vo.UserInfoVo; +import weaver.hrm.HrmUserVarify; +import weaver.hrm.User; + +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; +import javax.ws.rs.Consumes; +import javax.ws.rs.GET; +import javax.ws.rs.Path; +import javax.ws.rs.Produces; +import javax.ws.rs.core.Context; +import javax.ws.rs.core.MediaType; +import java.util.List; +import java.util.Map; + +/** + *

+ *

create 2022/6/10 18:08

+ * + * @author ayh + */ +@Path("/aiyh-calendar") +public class CalendarWorkController { + private CalendarWorkService service = new CalendarWorkService(); + + @Path("/work-mark") + @GET + @Produces(MediaType.APPLICATION_JSON) + public String getWorkMarkList(@Context HttpServletRequest request, @Context HttpServletResponse response){ + try { + User user = HrmUserVarify.getUser(request, response); + String startDate = request.getParameter("startDate"); + String endDate = request.getParameter("endDate"); + List result = service.getWorkMarkList(user,startDate,endDate); + return ApiResult.success(result); + }catch (Exception e){ + Util.getLogger().info("查询日期标记失败!" + Util.getErrString(e)); + return ApiResult.error("查询日期标记失败!"); + } + } + + + @Path("/user-info") + @GET + @Produces(MediaType.APPLICATION_JSON) + public String getUserInfo(@Context HttpServletRequest request, @Context HttpServletResponse response){ + try { + String rolesId = request.getParameter("rolesId"); + User user = HrmUserVarify.getUser(request, response); + UserInfoVo userInfoVo = service.getUserInfo(user,rolesId); + return ApiResult.success(userInfoVo); + }catch (Exception e){ + Util.getLogger().info("查询用户信息失败!" + Util.getErrString(e)); + return ApiResult.error("查询用户信息失败!"); + } + } + + @Path("/calendar-works") + @GET + @Consumes(MediaType.APPLICATION_JSON) + @Produces(MediaType.APPLICATION_JSON) + public String getWorkInfo(@Context HttpServletRequest request, @Context HttpServletResponse response){ + String date = request.getParameter("date"); + User user = HrmUserVarify.getUser(request, response); + try { + Map result = service.getWorkInfo(date,user.getUID()); + return ApiResult.success(result); + }catch (Exception e){ + Util.getLogger().info("查询日程信息失败!" + Util.getErrString(e)); + return ApiResult.error("查询异常!"); + } + } + + @Path("/every-work") + @GET + @Consumes(MediaType.APPLICATION_JSON) + @Produces(MediaType.APPLICATION_JSON) + public String getEveryDayWork(@Context HttpServletRequest request, @Context HttpServletResponse response){ + String zq = request.getParameter("zq"); + String page = request.getParameter("page"); + String pageSize = request.getParameter("pageSize"); + String rolesId = request.getParameter("rolesId"); + User user = HrmUserVarify.getUser(request, response); + try { + Map result = service.getEveryDayWork(page,pageSize,zq,user.getUID(),rolesId); + return ApiResult.success(result); + }catch (CustomerException e){ + Integer code = e.getCode(); + if(code == 403){ + return ApiResult.success(new String[]{},403,"无权限查看!"); + } + Util.getLogger().info("查询每日任务失败!" + Util.getErrString(e)); + return ApiResult.error("查询每日任务失败!"); + } catch (Exception e){ + Util.getLogger().info("查询每日任务失败!" + Util.getErrString(e)); + return ApiResult.error("查询每日任务失败!"); + } + } + +} diff --git a/src/main/youhong_ai_old_src/com/api/aiyh_IHG/mobil_ui/mapper/CalendarWorkMapper.java b/src/main/youhong_ai_old_src/com/api/aiyh_IHG/mobil_ui/mapper/CalendarWorkMapper.java new file mode 100644 index 0000000..2e1a845 --- /dev/null +++ b/src/main/youhong_ai_old_src/com/api/aiyh_IHG/mobil_ui/mapper/CalendarWorkMapper.java @@ -0,0 +1,121 @@ +package com.api.aiyh_IHG.mobil_ui.mapper; + +import aiyh.utils.annotation.recordset.ParamMapper; +import aiyh.utils.annotation.recordset.Select; +import aiyh.utils.annotation.recordset.SqlMapper; +import com.api.aiyh_IHG.mobil_ui.vo.EveryWorkVo; +import com.api.aiyh_IHG.mobil_ui.vo.WorkInfoVo; + +import java.util.List; +import java.util.Map; + +/** + *

+ *

create 2022/6/10 18:08

+ * + * @author ayh + */ + +@SqlMapper +public interface CalendarWorkMapper { + + /** + * 根据状态和日期查询工作日程 + * @param date 日期 + * @param i 状态 + * @param userId 用户ID + * @return 工作日程列表 + */ + @Select("select id,requestid, begindate, begintime,enddate,endtime,createrid,deptid,subcompanyid,`name`,`status`,( " + + "case when type_n = 15 then -1 else type_n end " + + ") type_n_order,type_n from workplan " + + "where requestid is not null and `status` = #{status} and (#{date} BETWEEN begindate and enddate) " + + "and (deleted = 0 or deleted is null) and (CONCAT(',',resourceid,',') like '%,$t{userId},%' or createrid = #{userId}) order by type_n_order") + List selectWorkInfo(@ParamMapper("date") String date, @ParamMapper("status") int i,@ParamMapper("userId") Integer userId); + + /** + * 根据日期查询提醒任务日程 + * @param date 日期 + * @param userId 用户ID + * @return 提醒任务 + */ + @Select("select id,requestid, begindate, begintime,enddate,endtime,createrid,deptid,subcompanyid,`name`,`status`,( " + + "case when type_n = 15 then -1 else type_n end " + + ") type_n_order,type_n from workplan " + + "where requestid is null and (#{date} BETWEEN begindate and enddate) " + + "and (deleted = 0 or deleted is null) and (CONCAT(',',resourceid,',') like '%,$t{userId},%' or createrid = #{userId}) order by type_n") + List selectReminderWorkInfo(@ParamMapper("date") String date,@ParamMapper("userId") Integer userId); + + /** + * 查询任务清单 + * @param start 开始数量 + * @param pageSize 结束数量 + * @param zq 周期 + * @return 任务清单 + */ +// @Select("select * from uf_rwqd where zq = #{zq} order by id desc limit #{start},#{pageSize}") + @Select("select * from uf_rwqd where zq = #{zq} and id in ($t{workPackageIdListStr}) order by lb limit #{start},#{pageSize}") + List selectEveryDayWork(@ParamMapper("start") Integer start, + @ParamMapper("pageSize") Integer pageSize, + @ParamMapper("zq") String zq, + @ParamMapper("workPackageIdListStr") String workPackageIdListStr); + + /** + * 查询任务清单总数 + * @param zq 周期 + * @return 任务清单 + */ + @Select("select count(*) from uf_rwqd where zq = #{zq}") + Integer selectTotalCount(@ParamMapper("zq") String zq); + + /** + * 查询日程标识 + * @param uid 用户ID + * @param startDate 开始时间 + * @param endDate 结束时间 + * @return 日程标识 + */ + @Select("select distinct begindate from workplan where begindate between #{startDate} and #{endDate} " + + "and (deleted = 0 or deleted is null) " + + "and (CONCAT(',',resourceid,',') like '%,$t{userId},%' or createrid = #{userId}) " + + "union all " + + "select distinct enddate from workplan where enddate between #{startDate} and #{endDate} " + + "and (deleted = 0 or deleted is null) " + + "and (CONCAT(',',resourceid,',') like '%,$t{userId},%' or createrid = #{userId}) and begindate <> enddate") + List selectWorkMarkList(@ParamMapper("userId") int uid, + @ParamMapper("startDate") String startDate, + @ParamMapper("endDate") String endDate); + + /** + *

通过用户ID查询用户对应的酒店ID

+ * @param userId 用户ID + * @return 酒店ID + */ + @Select("select textfield1 from hrmresource where id = #{userId}") + String selectHotelId(@ParamMapper("userId") Integer userId); + + /** + *

通过酒店ID查询任务包类型

+ * @param hotelId 酒店ID + * @return 任务包类型 + */ + @Select("select rwblx from uf_hotelinfo where holidex = #{hotelId}") + String selectWorkPackage(@ParamMapper("hotelId") String hotelId); + + /** + *

通过任务包id查询任务包配置表中对应的任务列表

+ * @param workPackageId 任务包ID + * @return 任务列表ids字符串 + */ + @Select("select rwlb from uf_rwbpzb where id = #{workPackageId}") + String selectWorkPackageList(@ParamMapper("workPackageId") String workPackageId); + + /** + *

查询查看每日任务的角色权限

+ * @param rolesId 角色ID + * @return 插叙结果 + */ + @Select("select hl.id,hl.rolesname,hl.subcompanyid,hlb.resourcetype,hlb.resourceid,GROUP_CONCAT(hlb.resourceid) resourceids from hrmroles hl\n" + + "left join hrmrolemembers hlb on hl.id = hlb.ROLEID where hl.id = #{rolesId} GROUP BY hl.id") + Map selectRoles(@ParamMapper("rolesId") String rolesId); +} diff --git a/src/main/youhong_ai_old_src/com/api/aiyh_IHG/mobil_ui/service/CalendarWorkService.java b/src/main/youhong_ai_old_src/com/api/aiyh_IHG/mobil_ui/service/CalendarWorkService.java new file mode 100644 index 0000000..da1fb06 --- /dev/null +++ b/src/main/youhong_ai_old_src/com/api/aiyh_IHG/mobil_ui/service/CalendarWorkService.java @@ -0,0 +1,170 @@ +package com.api.aiyh_IHG.mobil_ui.service; + +import aiyh.utils.Util; +import aiyh.utils.excention.CustomerException; +import com.api.aiyh_IHG.mobil_ui.mapper.CalendarWorkMapper; +import com.api.aiyh_IHG.mobil_ui.vo.EveryWorkVo; +import com.api.aiyh_IHG.mobil_ui.vo.UserInfoVo; +import com.api.aiyh_IHG.mobil_ui.vo.WorkInfoVo; +import weaver.hrm.User; +import weaver.hrm.company.DepartmentComInfo; +import weaver.hrm.company.SubCompanyComInfo; +import weaver.hrm.job.JobTitlesComInfo; + +import java.util.*; + +/** + *

+ *

create 2022/6/10 18:08

+ * + * @author ayh + */ + +public class CalendarWorkService { + private final SubCompanyComInfo subCompanyComInfo = new SubCompanyComInfo(); + private final DepartmentComInfo departmentComInfo = new DepartmentComInfo(); + private final JobTitlesComInfo jobTitlesComInfo = new JobTitlesComInfo(); + private final CalendarWorkMapper mapper = Util.getMapper(CalendarWorkMapper.class); + + /** + *

获取工作任务信息

+ * @param date 时间 + * @param userId 用户ID + * @return 工作任务信息 + */ + public Map getWorkInfo(String date,Integer userId) { + + Map result = new HashMap<>(8); + List doneWorkInfoVoList = mapper.selectWorkInfo(date,1,userId); + if(doneWorkInfoVoList == null){ + doneWorkInfoVoList = new ArrayList<>(); + } + result.put("done",doneWorkInfoVoList); + List unfinishedWorkInfoVoList = mapper.selectWorkInfo(date, 0,userId); + if(unfinishedWorkInfoVoList == null){ + unfinishedWorkInfoVoList = new ArrayList<>(); + } + result.put("unfinished",unfinishedWorkInfoVoList); + List reminderWorkInfoList = mapper.selectReminderWorkInfo(date,userId); + if(reminderWorkInfoList == null){ + reminderWorkInfoList = new ArrayList<>(); + } + result.put("reminder",reminderWorkInfoList); + return result; + } + + /** + *

查询用户基本信息

+ * @param user 用户 + * @param rolesId 角色ID + * @return 用户基本信息 + */ + public UserInfoVo getUserInfo(User user,String rolesId) { + UserInfoVo userInfoVo = new UserInfoVo(); + userInfoVo.setId(user.getUID()); + userInfoVo.setUserName(user.getUsername()); + userInfoVo.setDepartName(departmentComInfo.getDepartmentname(String.valueOf(user.getUserDepartment()))); + userInfoVo.setSubCompanyName(subCompanyComInfo.getSubCompanyname(String.valueOf(user.getUserSubCompany1()))); + userInfoVo.setJobTitle(jobTitlesComInfo.getJobTitlesname(user.getJobtitle())); + userInfoVo.setJobIds(user.getJobtitle()); + userInfoVo.setHasViewAuthority(true); + try { + if(!Util.isNullOrEmpty(rolesId)){ + userInfoVo.setHasViewAuthority(this.verifyAuthority(rolesId,String.valueOf(user.getUID()))); + } + }catch (CustomerException e){ + e.printStackTrace(); + if(e.getCode() == 403){ + userInfoVo.setHasViewAuthority(false); + } + } + return userInfoVo; + } + + + /** + *

获取每日工作计划信息

+ * @param page 当前页码 + * @param pageSize 每页数据量大小 + * @param zq 周期ID + * @param userId 用户ID + * @param rolesId 角色ID + * @return 每日工作计划信息 + */ + public Map getEveryDayWork(String page, String pageSize, String zq,Integer userId,String rolesId) { + if(!Util.isNullOrEmpty(rolesId)){ + this.verifyAuthority(rolesId, String.valueOf(userId)); + } + Map result = new HashMap<>(16); + int pageNum = Integer.parseInt(page); + if(pageNum <= 1){ + pageNum = 1; + } + int start = 0; + String hotelId = mapper.selectHotelId(userId); + if(null == hotelId || "".equals(hotelId)){ + throw new CustomerException("无法查询酒店ID,人员ID:" + userId); + } + String workPackageId = mapper.selectWorkPackage(hotelId); + if(null == workPackageId || "".equals(workPackageId)){ + throw new CustomerException("无法查询任务包类型,酒店ID:" + workPackageId); + } +// TODO 查询任务列表 + String workPackageListStr = mapper.selectWorkPackageList(workPackageId); + if(null == workPackageListStr){ + throw new CustomerException("没有查询到任务包配置中的任务列表数据!"); + } + start = (pageNum - 1) * Integer.parseInt(pageSize); + List list = mapper.selectEveryDayWork(start,Integer.parseInt(pageSize),zq,workPackageListStr); + if(list == null){ + throw new CustomerException("查询每日工作失败!"); + } + for (EveryWorkVo everyWorkVo : list) { + String lb = everyWorkVo.getLb(); + String selectFiledValueByValue = Util.getSelectFiledValueByValue("uf_rwqd", "lb", lb); + everyWorkVo.setLb(selectFiledValueByValue); + String zq1 = everyWorkVo.getZq(); + String selectFiledValueByValue1 = Util.getSelectFiledValueByValue("uf_rwqd", "lb", zq1); + everyWorkVo.setZq(selectFiledValueByValue1); + } + Integer total = mapper.selectTotalCount(zq); + result.put("list",list); + result.put("totalSize",total); + result.put("page",page); + result.put("pageSize",pageSize); + return result; + } + + public List getWorkMarkList(User user, String startDate, String endDate) { + return mapper.selectWorkMarkList(user.getUID(),startDate,endDate); + } + + /** + *

检查是否有权限查看每日任务

+ * @param rolesId 权限ID + * @param userId 人员ID + * @return 是否有权限查看 + */ + private boolean verifyAuthority(String rolesId,String userId){ + Map map = mapper.selectRoles(rolesId); + if(null == map || map.size() == 0){ + throw new CustomerException("无权限查看!查询每日任务角色权限为空",403); + } + String resourceids = String.valueOf(map.get("resourceids")); + if(Util.isNullOrEmpty(resourceids)){ + throw new CustomerException("无权限查看!查询每日任务角色权限中resourcesids为空",403); + } + String resourcetype = String.valueOf(map.get("resourcetype")); + if("1".equals(resourcetype)){ +// 人力资源 + String resourceId = Arrays.stream(resourceids.split(",")) + .filter(v -> v.equals(userId)) + .findFirst() + .orElseThrow(() -> new CustomerException("无权限查看!没查找到对应人员的权限", 403)); + if(Util.isNullOrEmpty(resourceId)){ + throw new CustomerException("无权限查看!没查找到对应的人员权限在权限角色中",403); + } + } + return true; + } +} diff --git a/src/main/youhong_ai_old_src/com/api/aiyh_IHG/mobil_ui/vo/EveryWorkVo.java b/src/main/youhong_ai_old_src/com/api/aiyh_IHG/mobil_ui/vo/EveryWorkVo.java new file mode 100644 index 0000000..62e977a --- /dev/null +++ b/src/main/youhong_ai_old_src/com/api/aiyh_IHG/mobil_ui/vo/EveryWorkVo.java @@ -0,0 +1,27 @@ +package com.api.aiyh_IHG.mobil_ui.vo; + +import lombok.Data; + +/** + *

+ *

create 2022/6/10 20:14

+ * + * @author ayh + */ + +@Data +public class EveryWorkVo { + private Integer id; + private String lb; + private String zq; + private String rwbt; + private String rwnr; + private String sfxyfanku; + private String ksrq; + private String kssj; + private String jsrq; + private String jssj; + private String cjr; + private String jsr; + private String jjcd; +} diff --git a/src/main/youhong_ai_old_src/com/api/aiyh_IHG/mobil_ui/vo/UserInfoVo.java b/src/main/youhong_ai_old_src/com/api/aiyh_IHG/mobil_ui/vo/UserInfoVo.java new file mode 100644 index 0000000..fb2a71d --- /dev/null +++ b/src/main/youhong_ai_old_src/com/api/aiyh_IHG/mobil_ui/vo/UserInfoVo.java @@ -0,0 +1,22 @@ +package com.api.aiyh_IHG.mobil_ui.vo; + +import lombok.Data; + +/** + *

+ *

create 2022/6/10 18:46

+ * + * @author ayh + */ + +@Data +public class UserInfoVo { + private Integer id; + private String name; + private String subCompanyName; + private String departName; + private String jobTitle; + private String userName; + private String jobIds; + private boolean hasViewAuthority; +} diff --git a/src/main/youhong_ai_old_src/com/api/aiyh_IHG/mobil_ui/vo/WorkInfoVo.java b/src/main/youhong_ai_old_src/com/api/aiyh_IHG/mobil_ui/vo/WorkInfoVo.java new file mode 100644 index 0000000..d2a981e --- /dev/null +++ b/src/main/youhong_ai_old_src/com/api/aiyh_IHG/mobil_ui/vo/WorkInfoVo.java @@ -0,0 +1,25 @@ +package com.api.aiyh_IHG.mobil_ui.vo; + +import lombok.Data; + +/** + *

+ *

create 2022/6/10 18:18

+ * + * @author ayh + */ + +@Data +public class WorkInfoVo { + private Integer id; + private String requestid; + private String begindate; + private String begintime; + private String enddate; + private String endtime; + private String createrid; +/* private String deptid; + private String subcompanyid;*/ + private String name; + private String status; +} diff --git a/src/main/youhong_ai_old_src/com/api/aiyh_common/multiple_language/MultipleLanguageController.java b/src/main/youhong_ai_old_src/com/api/aiyh_common/multiple_language/MultipleLanguageController.java new file mode 100644 index 0000000..f64aa3d --- /dev/null +++ b/src/main/youhong_ai_old_src/com/api/aiyh_common/multiple_language/MultipleLanguageController.java @@ -0,0 +1,52 @@ +package com.api.aiyh_common.multiple_language; + +import aiyh.utils.ApiResult; +import aiyh.utils.Util; +import weaver.hrm.HrmUserVarify; +import weaver.hrm.User; + +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; +import javax.ws.rs.GET; +import javax.ws.rs.Path; +import javax.ws.rs.PathParam; +import javax.ws.rs.Produces; +import javax.ws.rs.core.Context; +import javax.ws.rs.core.MediaType; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +/** + *

多语言自定义标签接口

+ *

create 2022/2/10 0010 10:09

+ * + * @author EBU7-dev1-ayh + */ + +@Path("/languageLabel") +public class MultipleLanguageController { + + MultipleLanguageMapper multipleLanguageMapper = Util.getMapper(MultipleLanguageMapper.class); + + @GET + @Path("/getMultipleLanguage/{descLike}") + @Produces(MediaType.APPLICATION_JSON) + public String getMultipleLanguage(@Context HttpServletRequest request, + @Context HttpServletResponse response, + @PathParam("descLike") String descLike) { + + User user = HrmUserVarify.getUser(request, response); + List> labelList = + multipleLanguageMapper.selectCustomerLabel(descLike+"%", user.getLanguage()); + if (labelList == null) { + return ApiResult.success(new HashMap<>(2)); + } + Map result = new HashMap<>(16); + for (Map map : labelList) { + result.put(String.valueOf(map.get("id")), map.get("labelname")); + } + return ApiResult.success(result); + } + +} diff --git a/src/main/youhong_ai_old_src/com/api/aiyh_common/multiple_language/MultipleLanguageMapper.java b/src/main/youhong_ai_old_src/com/api/aiyh_common/multiple_language/MultipleLanguageMapper.java new file mode 100644 index 0000000..a3318f9 --- /dev/null +++ b/src/main/youhong_ai_old_src/com/api/aiyh_common/multiple_language/MultipleLanguageMapper.java @@ -0,0 +1,31 @@ +package com.api.aiyh_common.multiple_language; + +import aiyh.utils.annotation.recordset.ParamMapper; +import aiyh.utils.annotation.recordset.Select; +import aiyh.utils.annotation.recordset.SqlMapper; + +import java.util.List; +import java.util.Map; + +/** + *

+ *

create 2022/2/10 0010 10:13

+ * + * @author EBU7-dev1-ayh + */ + + +@SqlMapper +public interface MultipleLanguageMapper { + + /** + * 查询自定义的标签信息 + * @param descLike 描述 + * @param languageId 语言id + * @return 查询到的标签信息 + */ + @Select("select hi.id,hf.labelname from htmllabelindex hi " + + "left join htmllabelinfo hf on hf.indexid = hi.id " + + "where id < 0 and indexdesc like ${descLike} and languageid = #{languageId}") + public List> selectCustomerLabel(@ParamMapper("descLike") String descLike, @ParamMapper("languageId") int languageId); +} diff --git a/src/main/youhong_ai_old_src/com/api/aiyh_ftpfiel/ReadFTPFielController.java b/src/main/youhong_ai_old_src/com/api/aiyh_ftpfiel/ReadFTPFielController.java new file mode 100644 index 0000000..a02f02f --- /dev/null +++ b/src/main/youhong_ai_old_src/com/api/aiyh_ftpfiel/ReadFTPFielController.java @@ -0,0 +1,78 @@ +package com.api.aiyh_ftpfiel; + +import weaver.hrm.HrmUserVarify; +import weaver.hrm.User; +import weaver.interfaces.workflow.action.DlWfOutPutFileAction; +import weaver.interfaces.workflow.action.dloutputfile.util.FTPUtil; +import weaver.soa.workflow.request.RequestInfo; +import weaver.workflow.request.RequestManager; + +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; +import javax.ws.rs.*; +import javax.ws.rs.core.Context; +import javax.ws.rs.core.MediaType; +import java.io.IOException; +import java.io.PrintWriter; +import java.io.StringWriter; + +/** + *

ftp 下载文件类

+ *

create 2022/2/28 0028 18:39

+ * + * @author EBU7-dev1-ayh + */ + +@Path("/ftp") +public class ReadFTPFielController { + + @GET + @Path("/down-file/{requestId}/{workflowId}") + @Produces(MediaType.APPLICATION_JSON) + @Consumes(MediaType.APPLICATION_JSON) + public String downFtpFile(@Context HttpServletRequest request, @Context HttpServletResponse response, + @PathParam("requestId") String requestId, @PathParam("workflowId") String workflowId) { + FTPUtil.logger.info("进入请求方法!" + String.format("requestId : {%s}, workflowId: {%s}.", request, workflowId)); + try { + + User user = HrmUserVarify.getUser(request, response); + DlWfOutPutFileAction dlWfOutPutFileAction = new DlWfOutPutFileAction(); + FTPUtil.logger.info("创建action对象"); + RequestInfo requestInfo = new RequestInfo(); + FTPUtil.logger.info("创建RequestInfo对象"); + RequestManager requestManager = new RequestManager(); + FTPUtil.logger.info("创建RequestManager对象"); + requestManager.setUser(user); + requestManager.setWorkflowid(Integer.parseInt(workflowId)); + requestManager.setRequestid(Integer.parseInt(requestId)); + requestInfo.setRequestid(requestId); + requestInfo.setWorkflowid(workflowId); + requestInfo.setRequestManager(requestManager); + FTPUtil.logger.info("设置requestInfo信息"); + dlWfOutPutFileAction.execute(requestInfo); + FTPUtil.logger.info("执行execute方法!"); + }catch (Exception e){ + FTPUtil.logger.error("执行失败: " + getErrString(e)); + return "{\"msg\": \"访问成功,执行失败!\",\"code\": 200}\n"; + } + return "{\"msg\": \"访问成功!\",\"code\": 200}\n"; + } + + /** + * 获取完整的错误信息 + * + * @param throwable 异常 + * @return 完整堆栈信息 + */ + public String getErrString(Throwable throwable) { + StringWriter stringWriter = new StringWriter(); + throwable.printStackTrace(new PrintWriter(stringWriter, true)); + String errStr = stringWriter.getBuffer().toString(); + try { + stringWriter.close(); + } catch (IOException e) { + e.printStackTrace(); + } + return errStr; + } +} diff --git a/src/main/youhong_ai_old_src/com/api/aiyh_fute/sign_in/controller/SignFTController.java b/src/main/youhong_ai_old_src/com/api/aiyh_fute/sign_in/controller/SignFTController.java new file mode 100644 index 0000000..7736ed9 --- /dev/null +++ b/src/main/youhong_ai_old_src/com/api/aiyh_fute/sign_in/controller/SignFTController.java @@ -0,0 +1,120 @@ +package com.api.aiyh_fute.sign_in.controller; + + +import aiyh.utils.ApiResult; +import aiyh.utils.Util; +import aiyh.utils.excention.CustomerException; +import com.alibaba.fastjson.JSON; +import com.api.aiyh_fute.sign_in.service.SignFtService; +import io.swagger.v3.oas.annotations.parameters.RequestBody; +import org.apache.log4j.Logger; + +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; +import javax.ws.rs.*; +import javax.ws.rs.core.Context; +import javax.ws.rs.core.MediaType; +import javax.ws.rs.core.Response; +import java.net.URI; +import java.util.HashMap; +import java.util.Map; + +/** + * 登录福特系统接口 + * + * @author aoey.oct.22 + */ + +@Path("/sign-in/") +public class SignFTController { + + /** + * service 逻辑处理 + */ + private final SignFtService signFtService = new SignFtService(); + /** + * 日志 + */ + private final Logger logger = Util.getLogger(); + + + /** + * 跳转到福特链接 + * + * @param request 请求体 + * @param response 响应体 + * @return 响应对象 + */ + @Path("/to-fute") + @Produces(MediaType.APPLICATION_JSON) + @GET + public Response toFtRedirect(@Context HttpServletRequest request, @Context HttpServletResponse response) { + try { + URI uri = signFtService.createJumpUri(request, response); + return Response.temporaryRedirect(uri).build(); + } catch (Exception e) { + e.printStackTrace(); + return Response.ok(ApiResult.error(e.getMessage())).build(); + } + } + + + /** + * 通过secret和ID获取token + * + * @param params 传递的参数信息 + * @return token数据 + */ + @Path("/get-token") + @Produces(MediaType.APPLICATION_JSON) + @Consumes(MediaType.APPLICATION_JSON) + @POST + public String getToken(@RequestBody Map params) { + try { + Map success = signFtService.getToken(params); + return JSON.toJSONString(success); + } catch (Exception e) { + e.printStackTrace(); + Map err = new HashMap<>(2); + err.put("error", "500 There is an internal error in the server. Please contact the administrator or operation and maintenance staff of the other party. "); + return JSON.toJSONString(err); + } + } + + + /** + * 获取用户信息 + * @param request 请求题 + * @param response 响应体 + * @param params 请求参数 + * @param authorization 请求头中的验证信息 + * @return 用户数据 + */ + @Path("/user") + @Produces(MediaType.APPLICATION_JSON) + @Consumes(MediaType.APPLICATION_JSON) + @POST + public String getUserInfo(@Context HttpServletRequest request, @Context HttpServletResponse response, + @RequestBody Map params,@HeaderParam("Authorization") String authorization) { + + Map result = new HashMap<>(8); + try { + Map userInfo = signFtService.getUserInfo(authorization,params); + return JSON.toJSONString(userInfo ); + } catch (CustomerException e){ + e.printStackTrace(); + result.put("result_message", e.getMessage()); + result.put("result_code", "1001"); + result.put("result", null); + result.put("success", false); + return JSON.toJSONString(result); + }catch (Exception e) { + logger.error(Util.getErrString(e)); + result.put("result_message", "500 There is an internal error in the server. Please contact the administrator or operation and maintenance staff of the other party. "); + result.put("result_code", "500"); + result.put("result", null); + result.put("success", false); + return JSON.toJSONString(result); + } + } +} diff --git a/src/main/youhong_ai_old_src/com/api/aiyh_fute/sign_in/mapper/SignFtMapper.java b/src/main/youhong_ai_old_src/com/api/aiyh_fute/sign_in/mapper/SignFtMapper.java new file mode 100644 index 0000000..6c9b382 --- /dev/null +++ b/src/main/youhong_ai_old_src/com/api/aiyh_fute/sign_in/mapper/SignFtMapper.java @@ -0,0 +1,56 @@ +package com.api.aiyh_fute.sign_in.mapper; + +import aiyh.utils.annotation.recordset.*; + +import java.util.Map; + +/** + *

查询数据库

+ *

create 2022/3/9 10:57 AM

+ * + * @author ayh + */ + +@SqlMapper +public interface SignFtMapper { + + /** + * 更新数据信息 + * @param dataId 数据ID + * @param jumpCode 跳转码 + * @param jumpCodeTime 跳转码过期时间 + * @param uid 用户ID + */ + @Update("update uf_jump_code set user_id = #{uid}, jump_code = #{jumpCode}, effective_time = #{effectiveTime}" + + " where id = #{dataId}") + public void updateFtJumpCode(@ParamMapper("dataId") int dataId, + @ParamMapper("jumpCode") String jumpCode, + @ParamMapper("effectiveTime") Long jumpCodeTime, + @ParamMapper("uid") int uid); + + + /** + * 查询是否拥有处于有效期内的用户跳转码 + * @param jumpCode 用户跳转码 + * @param jumpCodeTime 跳转码过期时间 + * @return 用户id + */ + @Select("select user_id from uf_jump_code where jump_code = #{jumpCode} and effective_time >= #{effectiveTime}") + int selectFtJumpCodeExist(@ParamMapper("jumpCode") String jumpCode, @ParamMapper("effectiveTime") Long jumpCodeTime); + + /** + * 查询是否存在记录 + * @param uid 用户ID + * @return 数据id + */ + @Select("select id from uf_jump_code where user_id = #{uid}") + int selectFtJumpCodeId(@ParamMapper("uid") int uid); + + /** + * 查询人员数据 + * @param userId 用户ID + * @return 用户信息 + */ + @Select("select * from hrmresource where id = #{userId}") + Map selectUser(@ParamMapper("userId") int userId); +} diff --git a/src/main/youhong_ai_old_src/com/api/aiyh_fute/sign_in/service/SignFtService.java b/src/main/youhong_ai_old_src/com/api/aiyh_fute/sign_in/service/SignFtService.java new file mode 100644 index 0000000..6ebd83a --- /dev/null +++ b/src/main/youhong_ai_old_src/com/api/aiyh_fute/sign_in/service/SignFtService.java @@ -0,0 +1,260 @@ +package com.api.aiyh_fute.sign_in.service; + +import aiyh.utils.Util; +import aiyh.utils.excention.CustomerException; +import cn.hutool.core.lang.UUID; +import com.alibaba.fastjson.JSON; +import com.api.aiyh_fute.sign_in.mapper.SignFtMapper; +import com.api.aiyh_fute.sign_in.util.TokenUtils; +import com.auth0.jwt.algorithms.Algorithm; +import com.weaver.general.TimeUtil; +import org.apache.log4j.Logger; +import org.h2.util.StringUtils; +import weaver.formmode.data.ModeDataIdUpdate; +import weaver.hrm.HrmUserVarify; +import weaver.hrm.User; + +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; +import java.io.UnsupportedEncodingException; +import java.net.URI; +import java.net.URISyntaxException; +import java.util.Date; +import java.util.HashMap; +import java.util.Map; +import java.util.Objects; +import java.util.regex.Matcher; +import java.util.regex.Pattern; + +/** + *

+ *

create 2022/3/9 10:50 AM

+ * + * @author ayh + */ + +public class SignFtService { + + private final SignFtMapper signFtMapper = Util.getMapper(SignFtMapper.class); + private final String ftConfigTable = "uf_jump_code"; + private final Logger logger = Util.getLogger(); + private final Map secretMap = new HashMap<>(); + private final TokenUtils tokenUtils = new TokenUtils(); + + + /** + * 生成跳转码 + * + * @param user 用户信息 + * @return 跳转码 + */ + public String createJumpCode(User user) { + String jumpCode = UUID.randomUUID().toString(); + String jumpCodeTimeConfig = Util.getCusConfigValueNullOrEmpty("FT_JUMP_CODE_TIME", "0"); + int jumpCodeTimeConfigNum = Integer.parseInt(jumpCodeTimeConfig); + if (jumpCodeTimeConfigNum <= 1000) { + jumpCodeTimeConfigNum = 1000 * 60; + } + int dataId = signFtMapper.selectFtJumpCodeId(user.getUID()); + if (dataId <= 0) { +// 生成新的数据id + ModeDataIdUpdate mdu = ModeDataIdUpdate.getInstance(); + String formModeId = Util.getCusConfigValueNullOrEmpty("FT_FORM_MODE_ID", "9"); + dataId = mdu.getModeDataNewId(ftConfigTable, Util.getIntValue(formModeId, -1), 1, 0, TimeUtil.getCurrentDateString(), TimeUtil.getOnlyCurrentTimeString()); + } + long currentTime = System.currentTimeMillis(); + Long jumpCodeTime = currentTime + jumpCodeTimeConfigNum; +// 存在就跟新 + signFtMapper.updateFtJumpCode(dataId, jumpCode, jumpCodeTime, user.getUID()); + return jumpCode; + } + + /** + * 创建链接对象URI + * + * @param request 用户请求 + * @param response 响应体 + * @return URI对象 + */ + public URI createJumpUri(HttpServletRequest request, HttpServletResponse response) { + User user = HrmUserVarify.getUser(request, response); + String jumpCode = createJumpCode(user); + URI uri = null; + String ftUri = Util.getCusConfigValueNullOrEmpty("FU_TE_URI", ""); + String newFtUri = ftUri.replaceAll("#\\{\\s*jumpCode\\s*}", jumpCode); + try { + uri = new URI(newFtUri); + } catch (URISyntaxException e) { + throw new CustomerException("福特跳转链接失败!链接:" + newFtUri, e); + } + return uri; + } + + /** + * 获取token + * + * @param params 请求参数 + * @return 响应参数 + */ + public Map getToken(Map params) { + verifySecret(); + String clientId = String.valueOf(params.get("clientid")); + String clientSecret = String.valueOf(params.get("clientsecret")); + if (!clientId.equals(secretMap.get("clientId"))) { + logger.error("clientId 错误:" + JSON.toJSONString(params)); + return new HashMap(2) {{ + put("error", "clientId it doesn't exist."); + }}; + } + if (!clientSecret.equals(secretMap.get("clientSecret"))) { + logger.error("clientSecret 错误:" + JSON.toJSONString(params)); + return new HashMap(2) {{ + put("error", "clientSecret error."); + }}; + } + Map claims = new HashMap<>(4); + claims.put("clientId", clientId); + claims.put("clientSecret", clientSecret); + Map result = new HashMap<>(16); + try { + tokenUtils.setAlgorithm(Algorithm.HMAC256(clientSecret)); + } catch (UnsupportedEncodingException e) { + throw new RuntimeException(e); + } + String tokenExpires = Util.getCusConfigValueNullOrEmpty("TOKEN_EXPIRES", "3600"); + int expiresTime = Integer.parseInt(tokenExpires); + tokenUtils.setExpiresAt(new Date(System.currentTimeMillis() + 1000L * expiresTime)); + tokenUtils.setIssuer("FU_TE"); + tokenUtils.setSecret(clientSecret); + tokenUtils.setClaims(claims); + String token = tokenUtils.getToken(); + result.put("access_token", token); + result.put("expires_in", String.valueOf(expiresTime)); + result.put("token_type", "Bearer"); + result.put("scope", ""); + return result; + } + + /** + * 通过token获取用户信息 + * + * @param authorization token字符串 + * @param params 请求参数,跳转码 + * @return 请求响应消息 + */ + public Map getUserInfo(String authorization, Map params) { + String token = authorization == null ? "" : authorization.replace("Bearer", "").trim(); + Map result = new HashMap<>(16); + if (StringUtils.isNullOrEmpty(token)) { + result.put("result_message", "token不存在,请生成token后重新调用!"); + result.put("result_code", "401"); + result.put("result", null); + result.put("success", false); + return result; + } + if (tokenUtils.verifyTokenValid(token)) { + result.put("result_message", "token已过期,请重新生成token!"); + result.put("result_code", "403"); + result.put("result", null); + result.put("success", false); + return result; + } + verifySecret(); + Map claims = new HashMap<>(4); + claims.put("clientId", secretMap.get("lientId")); + claims.put("clientSecret", secretMap.get("clientSecret")); + try { + try { + tokenUtils.setAlgorithm(Algorithm.HMAC256(secretMap.get("clientSecret"))); + } catch (UnsupportedEncodingException e) { + throw new RuntimeException(e); + } + tokenUtils.setExpiresAt(new Date()); + tokenUtils.setIssuer("FU_TE"); + tokenUtils.setSecret(secretMap.get("clientSecret")); + tokenUtils.setClaims(claims); + if (tokenUtils.verifyToken(token)) { + result.put("result_message", "success"); + result.put("result_code", "code_cracked"); + result.put("result", getUserInfoByJumpCode(params.get("code"))); + result.put("success", true); + return result; + } + throw new CustomerException("token验证失败!"); + } catch (CustomerException e) { + e.printStackTrace(); + result.clear(); + if (e.getCode() == 404) { + result.put("result_message", "跳转码失效或不存在,请重新生成跳转码!"); + result.put("result_code", "404"); + } else if (e.getCode() == 500) { + result.put("result_message", "内部服务出错,请联系系统管理员或运维人员!"); + result.put("result_code", "500"); + } else { + result.put("result_message", "token不存在,请重新生成token后调用!"); + result.put("result_code", "401"); + } + result.put("result", null); + result.put("success", false); + return result; + } + } + + /** + * 获取secret信息 + */ + private void verifySecret() { + try { + if (secretMap.isEmpty()) { + Map proper = Util.readProperties2Map("ftClientSecret", "aiyh.client"); + for (Map.Entry entry : proper.entrySet()) { + secretMap.put(entry.getKey(), String.valueOf(entry.getValue())); + } + } + } catch (Exception e) { + throw new CustomerException("未读取到配置文件WEB-INF/pro/prop2map/ftClientSecret.properties;", e); + } + } + + + /** + * 查询用户信息 + * + * @param jumpCode 跳转码 + * @return 用户信息 + */ + private Map getUserInfoByJumpCode(String jumpCode) { + int userId = signFtMapper.selectFtJumpCodeExist(jumpCode, System.currentTimeMillis()); + if (userId <= 0) { + throw new CustomerException("跳转码实效或不存在,请重新生成跳转码!", 404); + } + Map user = signFtMapper.selectUser(userId); + if (Objects.isNull(user)) { + throw new CustomerException("未查询到用户,请检查用户是否为系统管理员, 用户ID: " + userId, 500); + } + Map sqlMapper; + Map result = new HashMap<>(8); + try { + sqlMapper = Util.readProperties2Map("ftClientSecret", "aiyh.sqlMapper"); + for (Map.Entry entry : sqlMapper.entrySet()) { + String pattern = "#\\{\\s*(?\\S+)\\s*}"; + Pattern compile = Pattern.compile(pattern); + Matcher matcher = compile.matcher(String.valueOf(entry.getValue())); + if (matcher.find()) { + String field = matcher.group("field"); + if (user.containsKey(field)) { + result.put(entry.getKey(), user.get(field)); + } else { + result.put(entry.getKey(), user.get(field.toUpperCase())); + } + continue; + } + result.put(entry.getKey(), entry.getValue()); + } + result.put("ee_no", String.valueOf(result.get("org_code")) + result.get("ee_no")); + return result; + } catch (Exception e) { + throw new CustomerException("未读取到配置文件WEB-INF/pro/prop2map/ftClientSecret.properties;", e); + } + } +} diff --git a/src/main/youhong_ai_old_src/com/api/aiyh_fute/sign_in/util/TokenUtils.java b/src/main/youhong_ai_old_src/com/api/aiyh_fute/sign_in/util/TokenUtils.java new file mode 100644 index 0000000..13769fd --- /dev/null +++ b/src/main/youhong_ai_old_src/com/api/aiyh_fute/sign_in/util/TokenUtils.java @@ -0,0 +1,114 @@ +package com.api.aiyh_fute.sign_in.util; + +import aiyh.utils.excention.CustomerException; +import com.auth0.jwt.JWT; +import com.auth0.jwt.JWTCreator; +import com.auth0.jwt.JWTVerifier; +import com.auth0.jwt.algorithms.Algorithm; +import com.auth0.jwt.interfaces.DecodedJWT; +import com.auth0.jwt.interfaces.Verification; +import lombok.AllArgsConstructor; +import lombok.Getter; +import lombok.NoArgsConstructor; +import lombok.Setter; + +import java.io.UnsupportedEncodingException; +import java.util.Date; +import java.util.Map; + +/** + *

token 工具类

+ *

create 2022/3/9 5:32 PM

+ * + * @author ayh + */ + +@Setter +@Getter +@AllArgsConstructor +@NoArgsConstructor +public class TokenUtils { + + private String secret; + private Algorithm algorithm; + private Map claims; + private String issuer; + private Date expiresAt; + + + /** + * 获取根据设置的属性获取token + * + * @return token字符串 + */ + public String getToken() { + try { + JWTCreator.Builder builder = JWT.create() + .withExpiresAt(expiresAt) + .withIssuer(issuer); + for (Map.Entry claim : claims.entrySet()) { + builder.withClaim(claim.getKey(), claim.getValue()); + } + return builder.sign(algorithm); + } catch (NullPointerException e) { + throw new CustomerException("缺少生成token的必要参数!"); + } + } + + /** + * 根据自定义数据生成token + * + * @param secret 验签字符串 + * @param claims 索赔 + * @param expiresAt 过期时间 + * @param issuer 创建者信息 + * @return token字符串 + */ + public String getToken(String secret, Map claims, Date expiresAt, String issuer) { + this.secret = secret; + try { + this.algorithm = Algorithm.HMAC256(secret); + } catch (UnsupportedEncodingException e) { + throw new RuntimeException(e); + } + this.claims = claims; + this.expiresAt = expiresAt; + this.issuer = issuer; + return this.getToken(); + } + + + /** + * 验证token的有效性 + * + * @param token token + * @return 是否有效 + */ + public boolean verifyTokenValid(String token) { + DecodedJWT jwt = JWT.decode(token); + Date expiresAt = jwt.getExpiresAt(); + Date currentTime = new Date(); + return !currentTime.before(expiresAt); + } + + /** + * 验证token的有效性 + * + * @param token token字符串 + * @return 是否有效 + */ + public boolean verifyToken(String token) { + try { + Verification verification = JWT.require(this.algorithm) + .withIssuer(this.issuer); + for (Map.Entry claim : this.claims.entrySet()) { + verification.withClaim(claim.getKey(), claim.getValue()); + } + JWTVerifier jwtVerifier = verification.build(); + jwtVerifier.verify(token); + } catch (Exception e) { + return false; + } + return true; + } +} diff --git a/src/main/youhong_ai_old_src/com/api/aiyh_guijiu/dao/ConflictWorkflowDao.java b/src/main/youhong_ai_old_src/com/api/aiyh_guijiu/dao/ConflictWorkflowDao.java new file mode 100644 index 0000000..7edfa63 --- /dev/null +++ b/src/main/youhong_ai_old_src/com/api/aiyh_guijiu/dao/ConflictWorkflowDao.java @@ -0,0 +1,212 @@ +package com.api.aiyh_guijiu.dao; + +import aiyh.utils.Util; +import aiyh.utils.zwl.common.ToolUtil; +import com.api.aiyh_guijiu.pojo.UfWorkflowConflicDt1DTO; +import com.api.aiyh_guijiu.pojo.WorkflowBaseInfoDTO; +import com.api.aiyh_guijiu.pojo.WorkflowConfigDTO; +import com.api.aiyh_guijiu.vo.ConfigInfoVo; +import org.h2.util.StringUtils; +import weaver.conn.RecordSet; +import weaver.workflow.workflow.WorkflowVersion; + +import java.util.ArrayList; +import java.util.List; + +/** + * @author EBU7-dev1-ayh + * @create 2021/9/10 0010 11:27 + * 查询配置信息 + */ + + +public class ConflictWorkflowDao { + + RecordSet rs = new RecordSet(); + ToolUtil toolUtil = new ToolUtil(); + + public List queryConfig(String workflowId) { + + String query = "select * from uf_workflow_conflic_dt1 " + + "where workflow_type in (select id from workflow_base " + + "where activeVersionID in (select activeVersionID " + + "from workflow_base where id = ?) or id = ?)"; + rs.executeQuery(query, workflowId, workflowId); + UfWorkflowConflicDt1DTO ufWorkflowConflicDt1DTO = Util.recordeSet2Entity(rs, UfWorkflowConflicDt1DTO.class, true); + if (ufWorkflowConflicDt1DTO == null) { + return null; + } +// String ids = WorkflowVersion.getVersionStringByWfid(workflowId); + query = "select dt.id,dt.workflow_type,main.enable,wf.tablename,wf.fieldname start_date_field, " + + "wf1.fieldname start_time_field,wf2.fieldname end_date_field,wf4.fieldname hrm_field, " + + "wf3.fieldname end_time_field from uf_workflow_conflic main " + + "left join uf_workflow_conflic_dt1 dt on dt.mainid = main.id " + + "left join workflow_field_table_view wf on wf.id = dt.start_date_field " + + "left join workflow_field_table_view wf1 on wf1.id = dt.start_time_field " + + "left join workflow_field_table_view wf2 on wf2.id = dt.end_date_field " + + "left join workflow_field_table_view wf3 on wf3.id = dt.end_time_field " + + "left join workflow_field_table_view wf4 on wf4.id = dt.hrm_field " + + "where main.id = ? and main.enable = 0"; +// and dt.workflow_type not in (" + ids + ") + rs.executeQuery(query, ufWorkflowConflicDt1DTO.getMainid()); + return Util.recordeSet2Array(rs, WorkflowConfigDTO.class, true); + } + + public List queryConflict(WorkflowConfigDTO workflowConfigDTO, String startTime + , String startDate, String endTime, String endDate, String hrmId, String requestId) { +// (a,b)(c,d) == > (2021-09-10 12:00:23 , 2021-09-10 20:00:23) (2021-09-10 15:00:23 , 2021-09-10 19:00:23) +// select * from table where (hrm = ? or hrm like "%?%") and a <= d and b >= c and requestid != requestId; + String query = "select id from " + workflowConfigDTO.getTablename() + + " where (',' || " + workflowConfigDTO.getHrmField() +" || ',') like ('%,' || '" + hrmId + "' || ',%') " + + " and requestid != " + requestId + " and " + workflowConfigDTO.getStartDateField() + " is not null " + + " and " + workflowConfigDTO.getEndDateField() + " is not null" + + (StringUtils.isNullOrEmpty(workflowConfigDTO.getStartTimeField()) ? "" : " and " + workflowConfigDTO.getStartTimeField() + " is not null") + + (StringUtils.isNullOrEmpty(workflowConfigDTO.getEndTimeField()) ? "" : " and " + workflowConfigDTO.getEndTimeField() + " is not null"); + rs.executeQuery(query); + List integers = Util.recordeSet2Array(rs, String.class); + String ids = String.join(",", integers); + if(StringUtils.isNullOrEmpty(ids)){ + ids = "-1"; + } + query = "select * from " + + workflowConfigDTO.getTablename() + + " where to_date(concat(" + + workflowConfigDTO.getStartDateField() + + " || ' ' ," + + (StringUtils.isNullOrEmpty(workflowConfigDTO.getStartTimeField()) ? "'00:00:00'" : workflowConfigDTO.getStartTimeField()) + + "), 'yyyy-mm-dd hh24:mi:ss') <= to_date('" + + endDate + + " " + + (StringUtils.isNullOrEmpty(endTime) ? "23:59:59" : endTime) + + "', 'yyyy-mm-dd hh24:mi:ss')" + + " and to_date(concat(" + + workflowConfigDTO.getEndDateField() + + " || ' ' ," + + (StringUtils.isNullOrEmpty(workflowConfigDTO.getEndTimeField()) ? "'23:59:59'" : workflowConfigDTO.getEndTimeField()) + + "), 'yyyy-mm-dd hh24:mi:ss') >= to_date('" + + startDate + + " " + + (StringUtils.isNullOrEmpty(startTime) ? "00:00:00" : startTime) + + "', 'yyyy-mm-dd hh24:mi:ss') " + + " and id in (" + ids + ")"; + /*query = "select * from " + + workflowConfigDTO.getTablename() + + " where to_date(concat(" + + workflowConfigDTO.getStartDateField() + + " || ' ' ," + + (StringUtils.isNullOrEmpty(workflowConfigDTO.getStartTimeField()) ? "'00:00:00'" : workflowConfigDTO.getStartTimeField()) + + "), 'yyyy-mm-dd hh24:mi:ss') <= to_date('" + + endDate + + " " + + (StringUtils.isNullOrEmpty(endTime) ? "23:59:59" : endTime) + + "', 'yyyy-mm-dd hh24:mi:ss')" + + " and to_date(concat(" + + workflowConfigDTO.getEndDateField() + + " || ' ' ," + + (StringUtils.isNullOrEmpty(workflowConfigDTO.getEndTimeField()) ? "'23:59:59'" : workflowConfigDTO.getEndTimeField()) + + "), 'yyyy-mm-dd hh24:mi:ss') >= to_date('" + + startDate + + " " + + (StringUtils.isNullOrEmpty(startTime) ? "00:00:00" : startTime) + + "', 'yyyy-mm-dd hh24:mi:ss') " + + " and " + " (',' || " + workflowConfigDTO.getHrmField() + " || ',') like " + " ('%,' || '" + hrmId + "' || ',%') " + + " and requestid != " + requestId;*/ + /*hrmId + + " in (select regexp_substr(hrm_str, '[^,]+', 1, level) " + + "from dual connect by regexp_substr(hrm_str, '[^,]+', 1, level) is not null)" + + " and requestid != " + requestId;*/ +// toolUtil.writeErrorLog(query); + +// System.out.println(query); + /*query = "select * from " + workflowConfigDTO.getTablename() + " where to_date(concat(" + + workflowConfigDTO.getStartDateField() + " || ' ' ," + workflowConfigDTO.getStartTimeField() + + "), 'yyyy-mm-dd hh24:mi:ss') <= to_date(concat(" + + endDate + " " + endTime + "), 'yyyy-mm-dd hh24:mi:ss')" + + " and " + workflowConfigDTO.getEndDateField() + " || ' ' ," + workflowConfigDTO.getEndTimeField() + + "), 'yyyy-mm-dd hh24:mi:ss') >= to_date(concat(" + + startDate + " " + startTime + "), 'yyyy-mm-dd hh24:mi:ss') " + hrmId + + " and in (select regexp_substr(hrm_str, '[^,]+', 1, level) " + + "from dual connect by regexp_substr(hrm_str, '[^,]+', 1, level) is not null)";*/ + try { + rs.executeQuery(query); + }catch (Exception e){ + toolUtil.writeErrorLog("查询重复的流程错误,错误信息:" + e); + } + List list = new ArrayList<>(); + while(rs.next()){ +// 存在时间段冲突的数据,查询冲突数据的流程信息 + RecordSet rsT = new RecordSet(); + requestId = Util.null2String(rs.getString("requestid")); + query = "select distinct wrb.requestid,wrb.workflowid,wrb.requestnamenew,wb.workflowname, " + + "(case when hr.lastname is null and wrb.creater != 1 then '未知' " + + "when wrb.creater = 1 then '系统管理员' else hr.lastname end) creater, " + + "wrb.createdate,wrb.createtime from workflow_requestbase wrb " + + "left join HrmResource hr on wrb.creater = hr.id " + + "left join workflow_base wb on wb.id = wrb.workflowid " + + "where wrb.requestid = ?"; + rsT.executeQuery(query, requestId); + WorkflowBaseInfoDTO workflowBaseInfoDTO = Util.recordeSet2Entity(rsT, WorkflowBaseInfoDTO.class, true); + list.add(workflowBaseInfoDTO); + } +// if (rs.next()) { +// toolUtil.writeDebuggerLog("into next;"); +//// 存在时间段冲突的数据,查询冲突数据的流程信息 +// requestId = Util.null2String(rs.getString("requestid")); +// query = "select wrb.workflowid,wrb.requestid,wrb.requestnamenew,wb.workflowname, " + +// "(case when hr.lastname is null and wrb.creater != 1 then '未知' " + +// "when wrb.creater = 1 then '系统管理员' else hr.lastname end) creater, " + +// "wrb.createdate,wrb.createtime from workflow_requestbase wrb " + +// "left join HrmResource hr on wrb.creater = hr.id " + +// "left join workflow_base wb on wb.id = wrb.workflowid " + +// "where wrb.requestid = ?"; +// rs.executeQuery(query, requestId); +// return Util.recordeSet2Entity(rs, WorkflowBaseInfoDTO.class, true); +// } + if(list.size() == 0){ + return null; + } + return list; + } + + public List getWatermarkConfig(String workflowId) { + String query = "select id from workflow_base " + + "where activeVersionID in (select activeVersionID " + + "from workflow_base where id = ?) or id = ?"; + rs.executeQuery(query, workflowId, workflowId); + return Util.recordeSet2Array(rs, Integer.class); + } + + public WorkflowConfigDTO getWorkflowConfig(String workflowId){ + String query = "select * from uf_workflow_conflic_dt1 " + + "where workflow_type in (select id from workflow_base " + + "where activeVersionID in (select activeVersionID " + + "from workflow_base where id = ?) or id = ?)"; + rs.executeQuery(query, workflowId, workflowId); + UfWorkflowConflicDt1DTO ufWorkflowConflicDt1DTO = Util.recordeSet2Entity(rs, UfWorkflowConflicDt1DTO.class, true); + if (ufWorkflowConflicDt1DTO == null) { + return null; + } + String ids = WorkflowVersion.getVersionStringByWfid(workflowId); + query = "select dt.id,main.enable,wf.tablename,wf.fieldname start_date_field, " + + "wf1.fieldname start_time_field,wf2.fieldname end_date_field,wf4.fieldname hrm_field, " + + "wf3.fieldname end_time_field from uf_workflow_conflic main " + + "left join uf_workflow_conflic_dt1 dt on dt.mainid = main.id " + + "left join workflow_field_table_view wf on wf.id = dt.start_date_field " + + "left join workflow_field_table_view wf1 on wf1.id = dt.start_time_field " + + "left join workflow_field_table_view wf2 on wf2.id = dt.end_date_field " + + "left join workflow_field_table_view wf3 on wf3.id = dt.end_time_field " + + "left join workflow_field_table_view wf4 on wf4.id = dt.hrm_field " + + "where main.id = ? and main.enable = 0 and dt.workflow_type in (" + ids + ")"; + rs.executeQuery(query, ufWorkflowConflicDt1DTO.getMainid()); + return Util.recordeSet2Entity(rs,WorkflowConfigDTO.class,true); + } + + + public ConfigInfoVo getConfigInfo(String tableName,String workflowId){ + String query = "select cf.workflow_type ,cf.workflow_node ,cf.enable ,wf.fieldname workflow_field from " + tableName + + " cf left join workflow_field_table_view wf on wf.id = cf.workflow_field " + + " where cf.workflow_type = ?"; + rs.executeQuery(query,workflowId); + return Util.recordeSet2Entity(rs, ConfigInfoVo.class, true); + } +} diff --git a/src/main/youhong_ai_old_src/com/api/aiyh_guijiu/pojo/UfWorkflowConflicDt1DTO.java b/src/main/youhong_ai_old_src/com/api/aiyh_guijiu/pojo/UfWorkflowConflicDt1DTO.java new file mode 100644 index 0000000..926fac0 --- /dev/null +++ b/src/main/youhong_ai_old_src/com/api/aiyh_guijiu/pojo/UfWorkflowConflicDt1DTO.java @@ -0,0 +1,83 @@ + +package com.api.aiyh_guijiu.pojo; + + +public class UfWorkflowConflicDt1DTO { + + private int id; + private int mainid; + private int workflowType; + private String startDateField; + private String startTimeField; + private String endDateField; + private String endTimeField; + + public void setId(int id){ + this.id = id; + } + + public void setMainid(int mainid){ + this.mainid = mainid; + } + + public void setWorkflowType(int workflowType){ + this.workflowType = workflowType; + } + + public void setStartDateField(String startDateField){ + this.startDateField = startDateField; + } + + public void setStartTimeField(String startTimeField){ + this.startTimeField = startTimeField; + } + + public void setEndDateField(String endDateField){ + this.endDateField = endDateField; + } + + public void setEndTimeField(String endTimeField){ + this.endTimeField = endTimeField; + } + + public int getId(){ + return this.id; + } + + public int getMainid(){ + return this.mainid; + } + + public int getWorkflowType(){ + return this.workflowType; + } + + public String getStartDateField(){ + return this.startDateField; + } + + public String getStartTimeField(){ + return this.startTimeField; + } + + public String getEndDateField(){ + return this.endDateField; + } + + public String getEndTimeField(){ + return this.endTimeField; + } + + @Override + public String toString() { + return "UfWorkflowConflicDt1DTO{" + + "id='" + id + '\'' + + ", mainid='" + mainid + '\'' + + ", workflowType='" + workflowType + '\'' + + ", startDateField='" + startDateField + '\'' + + ", startTimeField='" + startTimeField + '\'' + + ", endDateField='" + endDateField + '\'' + + ", endTimeField='" + endTimeField + '\'' + + '}'; + } +} \ No newline at end of file diff --git a/src/main/youhong_ai_old_src/com/api/aiyh_guijiu/pojo/WorkflowBaseInfoDTO.java b/src/main/youhong_ai_old_src/com/api/aiyh_guijiu/pojo/WorkflowBaseInfoDTO.java new file mode 100644 index 0000000..9f38ea5 --- /dev/null +++ b/src/main/youhong_ai_old_src/com/api/aiyh_guijiu/pojo/WorkflowBaseInfoDTO.java @@ -0,0 +1,83 @@ + +package com.api.aiyh_guijiu.pojo; + + +public class WorkflowBaseInfoDTO { + + private int workflowid; + private int requestid; + private String requestnamenew; + private String workflowname; + private String creater; + private String createdate; + private String createtime; + + public void setWorkflowid(int workflowid){ + this.workflowid = workflowid; + } + + public void setRequestid(int requestid){ + this.requestid = requestid; + } + + public void setRequestnamenew(String requestnamenew){ + this.requestnamenew = requestnamenew; + } + + public void setWorkflowname(String workflowname){ + this.workflowname = workflowname; + } + + public void setCreater(String creater){ + this.creater = creater; + } + + public void setCreatedate(String createdate){ + this.createdate = createdate; + } + + public void setCreatetime(String createtime){ + this.createtime = createtime; + } + + public int getWorkflowid(){ + return this.workflowid; + } + + public int getRequestid(){ + return this.requestid; + } + + public String getRequestnamenew(){ + return this.requestnamenew; + } + + public String getWorkflowname(){ + return this.workflowname; + } + + public String getCreater(){ + return this.creater; + } + + public String getCreatedate(){ + return this.createdate; + } + + public String getCreatetime(){ + return this.createtime; + } + + @Override + public String toString() { + return "WorkflowBaseInfoDTO{" + + "workflowid='" + workflowid + '\'' + + ", requestid='" + requestid + '\'' + + ", requestnamenew='" + requestnamenew + '\'' + + ", workflowname='" + workflowname + '\'' + + ", creater='" + creater + '\'' + + ", createdate='" + createdate + '\'' + + ", createtime='" + createtime + '\'' + + '}'; + } +} \ No newline at end of file diff --git a/src/main/youhong_ai_old_src/com/api/aiyh_guijiu/pojo/WorkflowConfigDTO.java b/src/main/youhong_ai_old_src/com/api/aiyh_guijiu/pojo/WorkflowConfigDTO.java new file mode 100644 index 0000000..c27e94c --- /dev/null +++ b/src/main/youhong_ai_old_src/com/api/aiyh_guijiu/pojo/WorkflowConfigDTO.java @@ -0,0 +1,103 @@ + +package com.api.aiyh_guijiu.pojo; + + +public class WorkflowConfigDTO { + + private int id; + private int enable; + private int workflowType; + private String tablename; + private String startDateField; + private String startTimeField; + private String endDateField; + private String endTimeField; + private String hrmField; + + public int getWorkflowType() { + return workflowType; + } + + public void setWorkflowType(int workflowType) { + this.workflowType = workflowType; + } + + public String getHrmField() { + return hrmField; + } + + public void setHrmField(String hrmField) { + this.hrmField = hrmField; + } + + public void setId(int id){ + this.id = id; + } + + public void setEnable(int enable){ + this.enable = enable; + } + + public void setTablename(String tablename){ + this.tablename = tablename; + } + + public void setStartDateField(String startDateField){ + this.startDateField = startDateField; + } + + public void setStartTimeField(String startTimeField){ + this.startTimeField = startTimeField; + } + + public void setEndDateField(String endDateField){ + this.endDateField = endDateField; + } + + public void setEndTimeField(String endTimeField){ + this.endTimeField = endTimeField; + } + + public int getId(){ + return this.id; + } + + public int getEnable(){ + return this.enable; + } + + public String getTablename(){ + return this.tablename; + } + + public String getStartDateField(){ + return this.startDateField; + } + + public String getStartTimeField(){ + return this.startTimeField; + } + + public String getEndDateField(){ + return this.endDateField; + } + + public String getEndTimeField(){ + return this.endTimeField; + } + + @Override + public String toString() { + return "WorkflowConfigDTO{" + + "id=" + id + + ", enable=" + enable + + ", workflowType=" + workflowType + + ", tablename='" + tablename + '\'' + + ", startDateField='" + startDateField + '\'' + + ", startTimeField='" + startTimeField + '\'' + + ", endDateField='" + endDateField + '\'' + + ", endTimeField='" + endTimeField + '\'' + + ", hrmField='" + hrmField + '\'' + + '}'; + } +} \ No newline at end of file diff --git a/src/main/youhong_ai_old_src/com/api/aiyh_guijiu/service/WorkflowQueueService.java b/src/main/youhong_ai_old_src/com/api/aiyh_guijiu/service/WorkflowQueueService.java new file mode 100644 index 0000000..6fec1b8 --- /dev/null +++ b/src/main/youhong_ai_old_src/com/api/aiyh_guijiu/service/WorkflowQueueService.java @@ -0,0 +1,488 @@ +package com.api.aiyh_guijiu.service; + +import aiyh.utils.ApiResult; +import aiyh.utils.Util; +import aiyh.utils.fileUtil.WatermarkPoint; +import aiyh.utils.fileUtil.WatermarkPointEnum; +import aiyh.utils.fileUtil.WritWatermark; +import aiyh.utils.mapUtil.ParaMap; +import aiyh.utils.sqlUtil.sqlResult.impl.PrepSqlResultImpl; +import aiyh.utils.zwl.common.ToolUtil; +import com.api.aiyh_guijiu.dao.ConflictWorkflowDao; +import com.api.aiyh_guijiu.pojo.WorkflowBaseInfoDTO; +import com.api.aiyh_guijiu.pojo.WorkflowConfigDTO; +import com.api.aiyh_guijiu.vo.ConfigInfoVo; +import com.api.aiyh_guijiu.vo.PicPsVO; +import com.api.workflow.constant.RequestAuthenticationConstant; +import com.drew.imaging.ImageMetadataReader; +import com.drew.imaging.ImageProcessingException; +import com.drew.metadata.Directory; +import com.drew.metadata.Metadata; +import com.drew.metadata.Tag; +import com.engine.workflow.biz.requestForm.FileBiz; +import com.fasterxml.jackson.databind.JavaType; +import com.fasterxml.jackson.databind.ObjectMapper; +import org.apache.log4j.Logger; +import org.h2.util.StringUtils; +import weaver.conn.RecordSet; +import weaver.docs.docs.DocManager; +import weaver.file.ImageFileManager; +import weaver.hrm.User; + +import java.awt.*; +import java.io.IOException; +import java.io.InputStream; +import java.util.List; +import java.util.*; +import java.util.concurrent.atomic.AtomicBoolean; +import java.util.stream.Collectors; + +/** + * @author EBU7-dev1-ayh + * @create 2021/9/7 0007 12:43 + * workflow queue + */ + + +public class WorkflowQueueService { + ToolUtil toolUtil = new ToolUtil(); + ObjectMapper mapper = new ObjectMapper(); + ConflictWorkflowDao conflictWorkflowDao = new ConflictWorkflowDao(); + private Logger log = Util.getLogger(); + + /** + * 查询ps配置参数 + * + * @return 配置信息 + */ + public String getPicIsPsConfig(String workflowId) { + ConfigInfoVo ufPsNodeConfig = conflictWorkflowDao.getConfigInfo("uf_ps__node_config", workflowId); + if (ufPsNodeConfig == null) { + return ApiResult.successNoData(); + } + return ApiResult.success(ufPsNodeConfig); +// String picPsWorkflowId = toolUtil.getSystemParamValue("PIC_PS_WORKFLOW_ID"); +// if (StringUtils.isNullOrEmpty(picPsWorkflowId)) { +// return ApiResult.successNoData(); +// } +// String nodeId = toolUtil.getSystemParamValue("PIC_PS_NODE_ID"); +// String fieldName = toolUtil.getSystemParamValue("PIC_PS_FIELD_NAME"); +// List watermarkConfig = conflictWorkflowDao.getWatermarkConfig(picPsWorkflowId); +// Map map = new HashMap<>(); +// map.put("workflowIds", watermarkConfig); +// map.put("nodeId", nodeId); +// map.put("fieldName", fieldName); +// return ApiResult.success(map); + } + + /** + * 查询图片是否经过ps + * + * @param imgIds 需要查询的图片的id + * @return 是否进行ps的分析结果 + */ + public String getPicIsPs(String imgIds) { +// 通过docId查询到物理文件的id + String query = "select imagefileid,imagefilename,docid from docimagefile where docid in ( " + imgIds + ")"; + RecordSet rs = new RecordSet(); + rs.executeQuery(query); + List list = new ArrayList<>(); + while (rs.next()) { + int id = rs.getInt(1); + String name = rs.getString(2); + int docId = rs.getInt(3); + PicPsVO picPsVO = PicPsVO.PicPsVOBuilder.aPicPsVO() + .docId(docId) + .fileId(id) + .fileName(name) + .build(); +// 通过物理文件的id进行获取对应的输入流信息。 +// ImageFileManager imageFileManager = new ImageFileManager(); + // 通过文件id获取输入流 + InputStream inputStreamById = ImageFileManager.getInputStreamById(id); + try { +// 获取媒体数据 + Metadata metadata = ImageMetadataReader.readMetadata(inputStreamById); +// 遍历Directory对象,每个对象里面包含标签 + for (Directory directory : metadata.getDirectories()) { + String directoryName = directory.getName(); + log.info(directory); + if ("Photoshop".equalsIgnoreCase(directoryName) || "Adobe JPEG".equalsIgnoreCase(directoryName) + || directoryName.contains("Adobe")) { + if (picPsVO.getScore() > 90) { + continue; + } + picPsVO.setDescribe("图片经过Adobe Photoshop软件,注意审核!"); + picPsVO.setScore(90); + } + String model = ""; + for (Tag tag : directory.getTags()) { + log.info(tag); + if (tag.getDescription() != null && tag.getDescription().toLowerCase().contains("Adobe".toLowerCase())) { + picPsVO.setDescribe("图片经过Adobe Photoshop软件,注意审核!"); + picPsVO.setScore(70); + if (picPsVO.getScore() > 70) { + continue; + } + } + if ("Software".equalsIgnoreCase(tag.getTagName())) { + if (tag.getDescription().toLowerCase().contains("Adobe".toLowerCase()) + || tag.getDescription().toLowerCase().contains("Photoshop".toLowerCase())) { + picPsVO.setDescribe("图片经过Adobe Photoshop软件,注意审核!"); + picPsVO.setScore(100); + } else { + if (picPsVO.getScore() > 70) { + continue; + } + picPsVO.setDescribe("图片经过" + tag.getDescription() + "软件,注意审核!"); + picPsVO.setScore(70); + } + if (!StringUtils.isNullOrEmpty(model) && picPsVO.getDescribe().contains(model)) { + picPsVO.setDescribe(""); + picPsVO.setScore(-1); + } + } + if ("Model".equalsIgnoreCase(tag.getTagName())) { + model = tag.getDescription(); + if (!StringUtils.isNullOrEmpty(picPsVO.getDescribe())) { + if (picPsVO.getDescribe().contains(tag.getDescription())) { + picPsVO.setDescribe(""); + picPsVO.setScore(-1); + } + } + } + if ("User Comment".equalsIgnoreCase(tag.getTagName())) { + try { + if (picPsVO.getScore() > 80) { + continue; + } + com.alibaba.fastjson.JSONObject.parseObject(tag.getDescription()); + picPsVO.setDescribe("图片经过手机端图片处理软件,软件未知!请注意审核!"); + picPsVO.setScore(80); + } catch (Exception e) { + if (picPsVO.getScore() > 40) { + continue; + } + picPsVO.setDescribe("图片可能经过未知软件!请注意审核!"); + picPsVO.setScore(40); + } + } + } + } + } catch (ImageProcessingException | IOException e) { + e.printStackTrace(); + toolUtil.writeErrorLog("图片识别异常!"); + } + if (picPsVO.getScore() > 0){ + list.add(picPsVO); + } + } + List collect = list.stream().filter(item -> item.getScore() > 0).collect(Collectors.toList()); +// log.info("最终识别后的数组:" + collect); + return ApiResult.success(collect); + } + + public String getWorkflowQueue(Map param) { + String workflowId = param.get("workflowId"); + String requestId = param.get("requestId"); + List watermarkConfig = conflictWorkflowDao.getWatermarkConfig(workflowId); + List workflowConfigDTOS = conflictWorkflowDao.queryConfig(workflowId); + if (workflowConfigDTOS == null || workflowConfigDTOS.size() == 0) { + return ApiResult.successNoData(); + } + WorkflowConfigDTO nowConfig = workflowConfigDTOS.stream().filter(item -> { + AtomicBoolean flag = new AtomicBoolean(false); + watermarkConfig.forEach(id -> { + if (id == item.getWorkflowType()) { + flag.set(true); + } + }); + return flag.get(); + }).collect(Collectors.toList()).get(0); + +// 获取当前流程填写的时间信息 + String startTime = param.get("startTime"); + String startDate = param.get("startDate"); + String endTime = param.get("endTime"); + String endDate = param.get("endDate"); + String hrmStr = param.get("hrmStr"); +// 如果当前的requestid不是创建节点,则查询数据库信息作为对比条件 + if (!"-1".equals(requestId)) { + String hrmField = Util.null2String(nowConfig.getHrmField()); + String query = "select * from " + nowConfig.getTablename() + " where requestid = ?"; + RecordSet rs = new RecordSet(); + rs.executeQuery(query, requestId); + rs.next(); + hrmStr = rs.getString(hrmField); + startDate = rs.getString(nowConfig.getStartDateField()); + startTime = rs.getString(nowConfig.getStartTimeField()); + endTime = rs.getString(nowConfig.getEndTimeField()); + endDate = rs.getString(nowConfig.getEndDateField()); + } + + List list = new ArrayList<>(); +// 循环查询流程中时间是否存在冲突 + for (WorkflowConfigDTO workflowConfigDTO : workflowConfigDTOS) { +// 查询冲突的流程数据 流程相关人 查询数据库 + toolUtil.writeErrorLog(hrmStr); + toolUtil.writeErrorLog(workflowConfigDTO.toString() + "\n"); + for (String hrmId : hrmStr.split(",")) { + List workflowBaseInfoDTOList = conflictWorkflowDao.queryConflict(workflowConfigDTO, startTime, + startDate, endTime, endDate, hrmId, requestId); + toolUtil.writeErrorLog(workflowBaseInfoDTOList + "\n"); + if (workflowBaseInfoDTOList != null) { +// toolUtil.writeErrorLog(workflowBaseInfoDTOList.toString()); + list.addAll(workflowBaseInfoDTOList); + } + } + } + if (list.size() == 0) { + return ApiResult.successNoData(); + } + ArrayList collect = list.stream().collect( + Collectors.collectingAndThen( + Collectors.toCollection(() -> new TreeSet<>(Comparator.comparing(WorkflowBaseInfoDTO::getRequestid))), ArrayList::new) + ); +// 将查询到的信息进行返回给前端 + return ApiResult.success(collect); + } + + + /** + * 给图片添加水印信息 + * + * @param user user对象 + * @param param 请求参数 + * @return 添加水印后的文档信息 + */ + public String addWaterMark(User user, Map param) { + String fileIds = param.get("fileIds"); + String location = param.get("location"); + String time = param.get("time"); + if (StringUtils.isNullOrEmpty(time)) { + time = Util.getTime("yyyy-MM-dd HH:mm:ss"); + } + String pressText = "地点:" + location + "\n" + "时间:" + time; + String watermarkColor = toolUtil.getSystemParamValue("WATERMARK_COLOR"); + if (StringUtils.isNullOrEmpty(watermarkColor)) { + watermarkColor = "0,0,0"; + } + // 处理文字水印的RGB颜色 + String[] RGBStr = watermarkColor.replace(",", ",").split(","); + int[] RGB = Arrays.stream(RGBStr).mapToInt(Integer::parseInt).toArray(); + if (RGB.length < 3) { + RGB = new int[]{0, 0, 0}; + } + int R = RGB[0]; + int G = RGB[1]; + int B = RGB[2]; + if (R < 0) { + R = 0; + } + if (R > 255) { + R = 255; + } + if (G < 0) { + G = 0; + } + if (G > 255) { + G = 255; + } + if (B < 0) { + B = 0; + } + if (B > 255) { + B = 255; + } + Color color = new Color(R, G, B); + String fontName = toolUtil.getSystemParamValue("FONT_NAME"); + if (StringUtils.isNullOrEmpty(fontName)) { + fontName = "Microsoft YaHei"; + } + int fontSize = Util.getIntValue(toolUtil.getSystemParamValue("FONT_SIZE"), 10); + StringBuilder newIds = new StringBuilder(); + int index = 0; + //根据fileId 查询物理文件 + String query = "select imagefileid from docimagefile where docid in ( " + fileIds + ")"; + RecordSet rs = new RecordSet(); + rs.executeQuery(query); + + while (rs.next()) { + int id = rs.getInt(1); + int newId; + try { + toolUtil.writeDebuggerLog("开始添加水印,传递字体大小!"); + newId = WritWatermark.addTextWatermarkById(id, pressText, color, fontName, Font.PLAIN, fontSize + , new WatermarkPoint(WatermarkPointEnum.RIGHT_BOTTOM), 0, 1, 1.3); + } catch (IOException e) { + return ApiResult.error("图片水印添加失败!"); + } + if (index == 0) { + newIds.append(newId); + } else { + newIds.append(",").append(newId); + } + index++; + } + //复制原图的权限信息等 + //复制原来的文件信息,并将现有的信息进行绑定 + DocManager docManager = new DocManager(); + String[] picIdStrArr = fileIds.split(","); + String[] newImgArr = newIds.toString().split(","); + int[] picIdArr = Arrays.stream(picIdStrArr).mapToInt(Integer::parseInt).toArray(); + StringBuilder newDocIds = new StringBuilder(); + for (int i = 0; i < picIdArr.length; i++) { + docManager.setId(picIdArr[i]); +// 复制文件 + int newId = 0; + try { + newId = docManager.copyDoc(false); + } catch (Exception e) { + e.printStackTrace(); + toolUtil.writeErrorLog("file copy fail!"); + } + if (i == 0) { + newDocIds.append(newId); + } else { + newDocIds.append(",").append(newId); + } +// 替换复制出来的数据的物理文件关联关系 + PrepSqlResultImpl prepSqlResult = aiyh.utils.Util.createSqlBuilder().updateSql("docimagefile" + , ParaMap.create().put("imagefileid", newImgArr[i]) + , aiyh.utils.Util.createPrepWhereImpl().whereAnd("docid").whereEqual(newId)); + rs.executeUpdate(prepSqlResult.getSqlStr(), prepSqlResult.getArgs()); + } + + // 替换原来图片的字段 + String isSaveResource = toolUtil.getSystemParamValue("SAVE_RESOURCE"); + String sourceField = toolUtil.getSystemParamValue("RESOURCE_FIELD"); + if (StringUtils.isNullOrEmpty(isSaveResource)) { + isSaveResource = "0"; + } + String fieldName = param.get("fieldName"); + String tableName = param.get("tableName"); + String isWrite = param.get("isWrite"); + String isAppend = param.get("isAppend"); +// String sourceField = param.get("sourceField"); + String requestId = param.get("requestId"); + String oldFileIds = param.get("oldFileIds"); + if ("true".equals(isWrite)) { + if ("true".equals(isAppend)) { +// // 查询原字段是否存在图片 +// String queryStr = ""; +// try { +// queryStr = "select " + fieldName + " from " + tableName + " where requestid = ?"; +// rs.executeQuery(queryStr, requestId); +// rs.next(); +// String oldImg = Util.null2String(rs.getString(1)); +// if (!StringUtils.isNullOrEmpty(oldImg)) { + newDocIds.append(",").append(oldFileIds); +// } +// }catch (Exception e){ +// toolUtil.writeErrorLog("查询错误:" + queryStr); +// } + } + if ("0".equals(isSaveResource)) { + // 不保存原来的图片 + String update = "update " + + tableName + + " set " + + fieldName + + " = '" + + newDocIds + + "' where " + + " requestid = ?"; + rs.executeUpdate(update, requestId); + } else { + String update = "update " + + tableName + + " set " + + fieldName + + " = '" + + newDocIds + + "' , " + + sourceField + + " = '" + + fileIds + + "' where " + + " requestid = ?"; + rs.executeUpdate(update, requestId); + } + } + + // 查询新文件信息 + String listType = Util.null2String(String.valueOf(param.get("listType")), "list"); + int requestid = Util.getIntValue(Util.null2String(String.valueOf(param.get("requestid"))), -1); + int desrequestid = Util.getIntValue(Util.null2String(String.valueOf(param.get("desrequestid"))), -1); + int isprint = Util.getIntValue(Util.null2String(String.valueOf(param.get("isprint"))), 0); + int workflowid = Util.getIntValue(Util.null2String(String.valueOf(param.get("workflowid"))), 0); + String f_weaver_belongto_userid = Util.null2String(String.valueOf(param.get("f_weaver_belongto_userid"))); + String f_weaver_belongto_usertype = Util.null2String(String.valueOf(param.get("f_weaver_belongto_usertype"))); + String authStr = Util.null2String(String.valueOf(param.get(RequestAuthenticationConstant.AUTHORITY_STRING))); + String authSignatureStr = Util.null2String(String.valueOf(param.get(RequestAuthenticationConstant.AUTHORITY_SIGNATURESTRING))); + Map paramsMap = new HashMap<>(); + paramsMap.put("user", user); + Map retobj; + try { + retobj = FileBiz.getFileDatas(Util.null2String(newDocIds.toString()), listType, requestid, desrequestid, + isprint, f_weaver_belongto_userid, f_weaver_belongto_usertype, true, false, authStr, authSignatureStr, paramsMap); + } catch (Exception e) { + e.printStackTrace(); + return ApiResult.error("查询附件信息失败:" + e); + } + Map result = new HashMap<>(); + result.put("fileData", retobj); + result.put("fileIds", newDocIds.toString()); + return ApiResult.success(result); + } + + + /** + * 获取某个流程需要添加水印的字段和全版本的流程id + * + * @return 配置信息 + */ + public String getWatermarkConfig(String workflowId) { + ConfigInfoVo configInfo = conflictWorkflowDao.getConfigInfo("uf_watermark_cofig", workflowId); + if (configInfo == null) { + return ApiResult.successNoData(); + } + return ApiResult.success(configInfo); +// Map map = new HashMap<>(); +// String workflowId = toolUtil.getSystemParamValue("PIC_WATERMARK_WORKFLOW_ID"); +// List list = conflictWorkflowDao.getWatermarkConfig(workflowId); +// String picWatermarkField = toolUtil.getSystemParamValue("PIC_WATERMARK_FIELD_NAME"); +// String nodeId = toolUtil.getSystemParamValue("PIC_WATERMARK_NODE_ID"); +// map.put("fieldName", picWatermarkField); +// map.put("workflowIds", list); +// map.put("nodeId", nodeId); +// return ApiResult.success(map); + } + + /** + * 获取泛型的Collection Type + * + * @param collectionClass 泛型的Collection + * @param elementClasses 元素类 + * @return JavaType Java类型 + */ + public JavaType getCollectionType(Class collectionClass, Class... elementClasses) { + return mapper.getTypeFactory().constructParametricType(collectionClass, elementClasses); + } + + + /** + * 查询需要排查流程时间片段冲突的配置信息 + * + * @param workflowId 流程id + * @return 配置信息 + */ + public String getWorkflowConflictConfig(String workflowId) { + Map map = new HashMap<>(); + List watermarkConfig = conflictWorkflowDao.getWatermarkConfig(workflowId); + WorkflowConfigDTO workflowConfig = conflictWorkflowDao.getWorkflowConfig(workflowId); + map.put("workflowIds", watermarkConfig); + map.put("workflowConfig", workflowConfig); + return ApiResult.success(map); + } +} diff --git a/src/main/youhong_ai_old_src/com/api/aiyh_guijiu/vo/ConfigInfoVo.java b/src/main/youhong_ai_old_src/com/api/aiyh_guijiu/vo/ConfigInfoVo.java new file mode 100644 index 0000000..b7c56cf --- /dev/null +++ b/src/main/youhong_ai_old_src/com/api/aiyh_guijiu/vo/ConfigInfoVo.java @@ -0,0 +1,67 @@ +package com.api.aiyh_guijiu.vo; + +/** + * @author EBU7-dev1-ayh + * @create 2021/9/14 0014 21:28 + * peizhi xinxi Vo + */ + + +public class ConfigInfoVo { + int workflowType; + String workflowField; + String workflowNode; + int enable; + + public ConfigInfoVo() { + } + + public ConfigInfoVo(int workflowType, String workflowField, String workflowNode, int enable) { + this.workflowType = workflowType; + this.workflowField = workflowField; + this.workflowNode = workflowNode; + this.enable = enable; + } + + public int getWorkflowType() { + return workflowType; + } + + public void setWorkflowType(int workflowType) { + this.workflowType = workflowType; + } + + public String getWorkflowField() { + return workflowField; + } + + public void setWorkflowField(String workflowField) { + this.workflowField = workflowField; + } + + public String getWorkflowNode() { + return workflowNode; + } + + public void setWorkflowNode(String workflowNode) { + this.workflowNode = workflowNode; + } + + public int getEnable() { + return enable; + } + + public void setEnable(int enable) { + this.enable = enable; + } + + @Override + public String toString() { + return "ConfigInfoVo{" + + "workflowType=" + workflowType + + ", workflowField='" + workflowField + '\'' + + ", workflowNode='" + workflowNode + '\'' + + ", enable=" + enable + + '}'; + } +} diff --git a/src/main/youhong_ai_old_src/com/api/aiyh_guijiu/vo/PicPsVO.java b/src/main/youhong_ai_old_src/com/api/aiyh_guijiu/vo/PicPsVO.java new file mode 100644 index 0000000..e1b8c9c --- /dev/null +++ b/src/main/youhong_ai_old_src/com/api/aiyh_guijiu/vo/PicPsVO.java @@ -0,0 +1,120 @@ +package com.api.aiyh_guijiu.vo; + +/** + * @author EBU7-dev1-ayh + * @create 2021/9/10 0010 16:50 + * pic ps vo + */ + + +public class PicPsVO { + private int docId; + private int fileId; + private String fileName; + private int score; + private String describe; + + public PicPsVO(int docId, int fileId, String fileName, int score, String describe) { + this.docId = docId; + this.fileId = fileId; + this.fileName = fileName; + this.score = score; + this.describe = describe; + } + + public int getDocId() { + return docId; + } + + public void setDocId(int docId) { + this.docId = docId; + } + + public int getFileId() { + return fileId; + } + + public void setFileId(int fileId) { + this.fileId = fileId; + } + + public String getFileName() { + return fileName; + } + + public void setFileName(String fileName) { + this.fileName = fileName; + } + + public int getScore() { + return score; + } + + public void setScore(int score) { + this.score = score; + } + + public String getDescribe() { + return describe; + } + + public void setDescribe(String describe) { + this.describe = describe; + } + + + public static final class PicPsVOBuilder { + private int docId; + private int fileId; + private String fileName; + private int score; + private String describe; + + private PicPsVOBuilder() { + } + + public static PicPsVOBuilder aPicPsVO() { + return new PicPsVOBuilder(); + } + + public PicPsVOBuilder docId(int docId) { + this.docId = docId; + return this; + } + + public PicPsVOBuilder fileId(int fileId) { + this.fileId = fileId; + return this; + } + + public PicPsVOBuilder fileName(String fileName) { + this.fileName = fileName; + return this; + } + + public PicPsVOBuilder score(int score) { + this.score = score; + return this; + } + + public PicPsVOBuilder describe(String describe) { + this.describe = describe; + return this; + } + + public PicPsVO build() { + return new PicPsVO(docId, fileId, fileName, score, describe); + } + } + + @Override + public String toString() { + return "PicPsVO{" + + "docId=" + docId + + ", fileId=" + fileId + + ", fileName='" + fileName + '\'' + + ", score=" + score + + ", describe='" + describe + '\'' + + '}'; + } +} diff --git a/src/main/youhong_ai_old_src/com/api/aiyh_guijiu/web/ConflictWorkflowController.java b/src/main/youhong_ai_old_src/com/api/aiyh_guijiu/web/ConflictWorkflowController.java new file mode 100644 index 0000000..35f3546 --- /dev/null +++ b/src/main/youhong_ai_old_src/com/api/aiyh_guijiu/web/ConflictWorkflowController.java @@ -0,0 +1,157 @@ +package com.api.aiyh_guijiu.web; + +import aiyh.utils.ApiResult; +import aiyh.utils.zwl.common.ToolUtil; +import com.api.aiyh_guijiu.service.WorkflowQueueService; +import io.swagger.v3.oas.annotations.parameters.RequestBody; +import weaver.hrm.HrmUserVarify; +import weaver.hrm.User; + +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; +import javax.ws.rs.*; +import javax.ws.rs.core.Context; +import javax.ws.rs.core.MediaType; +import java.util.Map; + +/** + * @author EBU7-dev1-ayh + * @create 2021/9/3 0003 12:08 + * 查询同一时段内的指定流程 + */ + + +@Path("/change2Workflow") +public class ConflictWorkflowController { + + private final WorkflowQueueService workflowQueueService = new WorkflowQueueService(); + private final ToolUtil toolUtil = new ToolUtil(); + private final String className = "QueryWorkflow"; + + /** + * 查询需要前端判断添加水印的流程和流程字段 + * + * @return 前端必要的配置参数 + */ + @Path("/queryWatermark/{workflowId}") + @GET + @Consumes(MediaType.APPLICATION_JSON) + @Produces(MediaType.APPLICATION_JSON) + public String queryWatermark(@PathParam("workflowId") String workflowId) { + try { + return workflowQueueService.getWatermarkConfig(workflowId); + }catch (Exception e){ + toolUtil.writeErrorLog(className + "======> queryWatermark",e.toString()); + return ApiResult.error(e.toString()); + } + } + + + /** + * 图片添加水印请求 + * + * @param request 请求体 + * @param response 响应对象 + * @param param 请求参数 + * @return 添加水印后的图片信息 + */ + @Path("/addWatermark") + @POST + @Consumes(MediaType.APPLICATION_JSON) + @Produces(MediaType.APPLICATION_JSON) + public String addWatermark(@Context HttpServletRequest request, @Context HttpServletResponse response, + @RequestBody Map param) { + + User user = HrmUserVarify.getUser(request, response); + try { + return workflowQueueService.addWaterMark(user, param); + }catch (Exception e){ + toolUtil.writeErrorLog(className + "======> addWatermark",e.toString()); + return ApiResult.error(e.toString()); + } + } + + + /** + * 查询流程冲突前端需要拦截和必要的字段 + * + * @param workflowId 流程id + * @return 配置信息 + */ + @Path("/queryWorkflow/config/{workflowId}") + @GET + @Consumes(MediaType.APPLICATION_JSON) + @Produces(MediaType.APPLICATION_JSON) + public String queryWorkflowConfig(@PathParam("workflowId") String workflowId) { + + try { + return workflowQueueService.getWorkflowConflictConfig(workflowId); + }catch (Exception e){ + toolUtil.writeErrorLog(className + "======> queryWorkflowConfig",e.toString()); + return ApiResult.error(e.toString()); + } + } + + /** + * 查询冲突流程 + * + * @param param 请求参数 + * @return 冲突流程的基本数据 + */ + @Path("/queryConflict") + @POST + @Consumes(MediaType.APPLICATION_JSON) + @Produces(MediaType.APPLICATION_JSON) + public String queryWorkflowQueue(@RequestBody Map param) { + + try { + return workflowQueueService.getWorkflowQueue(param); + }catch (Exception e){ + toolUtil.writeErrorLog(className + "======> queryWorkflowQueue",e.toString()); + e.printStackTrace(); + return ApiResult.error(e.toString()); + } + } + + /** + * 判断图片是否经过ps + * + * @param imgIds 需要判断的图片 + * @return 查询ps的结果 + */ + @Path("/picIsPs/{imgIds}") + @GET + @Consumes(MediaType.APPLICATION_JSON) + @Produces(MediaType.APPLICATION_JSON) + public String queryPicIsPs(@PathParam("imgIds") String imgIds) { + try { + return workflowQueueService.getPicIsPs(imgIds); + }catch (Exception e){ + toolUtil.writeErrorLog(className + "======> queryPicIsPs",e.toString()); + return ApiResult.error(e.toString()); + } + } + + + + + /** + * 查询需要校验ps的节点等信息 + * + * @return 配置信息 + */ + @Path("/queryPicPsConfig/{workflowId}") + @GET + @Consumes(MediaType.APPLICATION_JSON) + @Produces(MediaType.APPLICATION_JSON) + public String queryPicPsConfig(@PathParam("workflowId") String workflowId) { + try { + return workflowQueueService.getPicIsPsConfig(workflowId); + }catch (Exception e){ + toolUtil.writeErrorLog(className + "======> queryPicPsConfig",e.toString()); + return ApiResult.error(e.toString()); + } + + } + +} diff --git a/src/main/youhong_ai_old_src/com/api/aiyh_jifen/controller/MaintenanceWorkOrderController.java b/src/main/youhong_ai_old_src/com/api/aiyh_jifen/controller/MaintenanceWorkOrderController.java new file mode 100644 index 0000000..2fdd848 --- /dev/null +++ b/src/main/youhong_ai_old_src/com/api/aiyh_jifen/controller/MaintenanceWorkOrderController.java @@ -0,0 +1,13 @@ +package com.api.aiyh_jifen.controller; + + +/** + *

${description}

+ * + * @author EBU7-dev-1 aiyh + *

create: ${YEAR}-${MONTH}-${DAY} ${HOUR}:${MINUTE}

+ */ +public class MaintenanceWorkOrderController { + + +} diff --git a/src/main/youhong_ai_old_src/com/api/aiyh_jitu/fadada/controller/CallbackController.java b/src/main/youhong_ai_old_src/com/api/aiyh_jitu/fadada/controller/CallbackController.java new file mode 100644 index 0000000..024cb98 --- /dev/null +++ b/src/main/youhong_ai_old_src/com/api/aiyh_jitu/fadada/controller/CallbackController.java @@ -0,0 +1,90 @@ +package com.api.aiyh_jitu.fadada.controller; + +import aiyh.utils.Util; +import aiyh.utils.excention.CustomerException; +import com.alibaba.fastjson.JSON; +import com.api.aiyh_jitu.fadada.service.CallbackService; +import io.swagger.v3.oas.annotations.parameters.RequestBody; +import org.apache.log4j.Logger; + +import javax.ws.rs.Consumes; +import javax.ws.rs.POST; +import javax.ws.rs.Path; +import javax.ws.rs.Produces; +import javax.ws.rs.core.MediaType; +import java.util.HashMap; +import java.util.Map; + +/** + *

法大大实名认证回调

+ * + *

create: 2022-08-14 15:24

+ * + * @author aiyh EBU7-dev-1 + */ + +@Path("/aiyh/fadada/callback") +public class CallbackController { + + private final CallbackService service = new CallbackService(); + private final Logger log = Util.getLogger(); + + /** + *

实名认证回调地址

+ * + * @param params 回调参数 + * @return 回调接口响应消息 + */ + @Path("/real-name-authentication") + @POST + public String realNameAuthenticationCallback(@RequestBody Map params) { + Map result = new HashMap<>(8); + try { + service.realNameAuthenticationCallback(params); + result.put("code", 0); + result.put("msg", "success"); + } catch (CustomerException e) { + result.put("code", 5); + result.put("msg", e.getMessage()); + } catch (IllegalArgumentException e) { + result.put("code", 4); + result.put("msg", e.getMessage()); + } catch (Exception e) { + result.put("code", 4); + result.put("msg", e.getMessage()); + log.error("call back error ! error msg :" + e.getMessage() + "\n" + Util.getErrString(e)); + } + return JSON.toJSONString(result); + } + + + /** + *

手动签署回调

+ * + * @param params 回调参数 + * @return 回调接口响应消息 + */ + @Path("/manual-sign/callback") + @POST + @Produces(MediaType.APPLICATION_JSON) + @Consumes(MediaType.APPLICATION_JSON) + public String manualSignCallback(@RequestBody Map params) { + Map result = new HashMap<>(8); + try { + service.manualSignCallback(params); + result.put("code", 0); + result.put("msg", "success"); + } catch (CustomerException e) { + result.put("code", 5); + result.put("msg", e.getMessage()); + } catch (IllegalArgumentException e) { + result.put("code", 4); + result.put("msg", e.getMessage()); + } catch (Exception e) { + result.put("code", 4); + result.put("msg", e.getMessage()); + log.error("call back error ! error msg :" + e.getMessage() + "\n" + Util.getErrString(e)); + } + return JSON.toJSONString(result); + } +} diff --git a/src/main/youhong_ai_old_src/com/api/aiyh_jitu/fadada/controller/WidgetsController.java b/src/main/youhong_ai_old_src/com/api/aiyh_jitu/fadada/controller/WidgetsController.java new file mode 100644 index 0000000..3ad8ba8 --- /dev/null +++ b/src/main/youhong_ai_old_src/com/api/aiyh_jitu/fadada/controller/WidgetsController.java @@ -0,0 +1,45 @@ +package com.api.aiyh_jitu.fadada.controller; + +import aiyh.utils.ApiResult; +import aiyh.utils.Util; +import com.api.aiyh_jitu.fadada.service.WidgetsService; + +import javax.ws.rs.GET; +import javax.ws.rs.Path; +import javax.ws.rs.PathParam; +import javax.ws.rs.Produces; +import javax.ws.rs.core.MediaType; +import java.util.List; + +/** + *

获取控件列表

+ * + *

create: 2022-08-17 15:12

+ * + * @author aiyh EBU7-dev-1 + */ + +@Path("/aiyh/fadada/widgets") +public class WidgetsController { + + private final WidgetsService service = new WidgetsService(); + + /** + *

查询控件列表

+ * + * @param contractId 合同模板ID + * @return 控件列表 + */ + @Path("/get/{id}") + @GET + @Produces(MediaType.APPLICATION_JSON) + public String getWidgets(@PathParam("id") String contractId) { + try { + List widgets = service.getWidgets(contractId); + return ApiResult.success(widgets); + } catch (Exception e) { + Util.getLogger().error("fetch widgetList error, error msg is " + e.getMessage() + "\n" + Util.getErrString(e)); + return ApiResult.error(e.getMessage()); + } + } +} diff --git a/src/main/youhong_ai_old_src/com/api/aiyh_jitu/fadada/mapper/CallbackMapper.java b/src/main/youhong_ai_old_src/com/api/aiyh_jitu/fadada/mapper/CallbackMapper.java new file mode 100644 index 0000000..eb83a62 --- /dev/null +++ b/src/main/youhong_ai_old_src/com/api/aiyh_jitu/fadada/mapper/CallbackMapper.java @@ -0,0 +1,75 @@ +package com.api.aiyh_jitu.fadada.mapper; + +import aiyh.utils.annotation.recordset.*; + +import java.util.List; +import java.util.Map; + +/** + *

+ * + *

create: 2022-08-14 18:32

+ * + * @author aiyh EBU7-dev-1 + */ + +@SqlMapper +public interface CallbackMapper { + /** + *

插入回调日志

+ * + * @param sqlString 更新SQL语句 + * @param insertParams 插入的参数 + * @return 是否插入成功 + */ + @Select(custom = true) + boolean updateCallbackLog(@SqlString String sqlString, Map insertParams); + + /** + *

删除插入失败的数据

+ * + * @param dataId 数据ID + */ + @Delete("delete from uf_fdd_callback_log where id = #{id}") + void deleteLogId(@ParamMapper("id") int dataId); + + /** + *

更新实名认证状态

+ * + * @param customerIdOaField customerID字段 + * @param customerId customerId + * @param registerStatusOaField 注册状态字段 + * @param registerStatus 实名认证状态 + * @return 是否更新成功! + */ + @Update("update cus_fielddata set $t{registerStatusOaField} = #{registerStatus} where $t{customerIdOaField} = #{customerId}") + boolean updateCusFieldDataRegisterStatus(@ParamMapper("customerIdOaField") String customerIdOaField, @ParamMapper("customerId") String customerId, + @ParamMapper("registerStatusOaField") String registerStatusOaField, @ParamMapper("registerStatus") Integer registerStatus); + + /** + *

查询配置信息

+ * + * @param workflowIds 全流程版本 + * @return 配置明细表信息 + */ + @Select("select * from uf_manual_sign_conf main " + + "inner join uf_manual_sign_conf_dt1 dt on dt.mainid = main.id " + + "where workflow_type in (${workflowIds})") + List> queryWritBackWorkflowConfig( + @ParamMapper("workflowIds") String[] workflowIds); + + /** + *

查询合同信息中间表获取流程信息

+ * + * @param contractNo 合同编号 + * @return 流程信息 + */ + @Select("select id, request_id, contract_no, workflow_table, workflow_field " + + "from uf_jt_contract_info where contract_no = #{contractNo}") + Map queryWorkflowInfo( + @ParamMapper("contractNo") String contractNo); + + @Update(custom = true) + boolean updateCallbackParams( + @SqlString String sqlString, Map params); +} diff --git a/src/main/youhong_ai_old_src/com/api/aiyh_jitu/fadada/service/CallbackService.java b/src/main/youhong_ai_old_src/com/api/aiyh_jitu/fadada/service/CallbackService.java new file mode 100644 index 0000000..e8204cb --- /dev/null +++ b/src/main/youhong_ai_old_src/com/api/aiyh_jitu/fadada/service/CallbackService.java @@ -0,0 +1,136 @@ +package com.api.aiyh_jitu.fadada.service; + +import aiyh.utils.Util; +import aiyh.utils.excention.CustomerException; +import cn.hutool.core.lang.Assert; +import com.alibaba.fastjson.JSONObject; +import com.alibaba.fastjson.serializer.SerializerFeature; +import com.api.aiyh_jitu.fadada.mapper.CallbackMapper; +import org.apache.log4j.Logger; +import weaver.aiyh_jitu.schedule.registerfadada.constants.FaDaDaConstants; +import weaver.workflow.workflow.WorkflowVersion; + +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +/** + *

回调业务处理

+ * + *

create: 2022-08-14 16:00

+ * + * @author aiyh EBU7-dev-1 + */ + +public class CallbackService { + + private final CallbackMapper mapper = Util.getMapper(CallbackMapper.class); + + + private final Logger log = Util.getLogger(); + + /** + *

实名认证回调地址

+ * + * @param params 回调参数 + */ + public void realNameAuthenticationCallback(Map params) { + String customerIdOaField = Util.getCusConfigValue(FaDaDaConstants.CUSTOMER_ID_OA_FIELD); + String registerStatusOaField = Util.getCusConfigValue(FaDaDaConstants.REGISTER_STATUS_OA_FIELD); + String customerId = Util.null2String(params.get("customerId")); + Assert.notEmpty(customerId, "customerId is empty!"); + String status = Util.null2String(params.get("status")); + Assert.notEmpty(status, "status is empty!"); + Integer registerStatus = Integer.parseInt(status) + 2; + writeLog(0, params); + int n = 0; + // 将认证回调状态写入到自定义人员卡片中 + while (mapper.updateCusFieldDataRegisterStatus(customerIdOaField, customerId, registerStatusOaField, registerStatus)) { + n++; + if (n > 5) { + return; + } + } + throw new CustomerException("business failure! code : 001"); + } + + + /** + *

将回调数据写入日志表中

+ * + * @param type 回调类型 + * @param params 回调参数 + */ + private void writeLog(Integer type, Map params) { + Map insertParams = new HashMap<>(16); + insertParams.put("callback_time", Util.getTime("yyyy-MM-dd HH:mm:ss")); + insertParams.put("callback_params", JSONObject.toJSONString(params, SerializerFeature.PrettyFormat, SerializerFeature.WriteDateUseDateFormat)); + insertParams.put("callback_type", type); + if (type == 0) { + String customerId = Util.null2String(params.get("customerId")); + insertParams.put("customer_id", customerId); + } + String modelId = Util.getModeIdByTableName("uf_fdd_callback_log"); + int dataId = Util.getModeDataId("uf_fdd_callback_log", Integer.parseInt(modelId), 1); + StringBuilder sb = new StringBuilder(); + sb.append("update uf_fdd_callback_log set "); + for (Map.Entry entry : insertParams.entrySet()) { + sb.append(entry.getKey()) + .append(" = #{") + .append(entry.getKey()) + .append("}, "); + } + StringBuilder replace = sb.replace(sb.lastIndexOf(","), sb.length() - 1, ""); + replace.append(" where id = #{id}"); + insertParams.put("id", dataId); + boolean success = mapper.updateCallbackLog(replace.toString(), insertParams); + if (!success) { + mapper.deleteLogId(dataId); + return; + } + Util.rebuildModeDataShare(1, Integer.valueOf(modelId), dataId); + } + + /** + *

签署合同回调

+ * + * @param params 回调请求参数 + */ + public void manualSignCallback(Map params) { + String contractNo = Util.null2String(params.get("docNo")); + Assert.notEmpty(contractNo, "docNo not be null!"); + writeLog(1, params); + // TODO 建模表让客户定义回调结果参数映射到那个流程字段中 + Map workflowInfo = mapper.queryWorkflowInfo(contractNo); + Assert.notEmpty(workflowInfo, "can not find uf_jt_contract_info for " + contractNo); + String workflowType = Util.null2String(workflowInfo.get("workflowType")); + String workflowTable = Util.null2String(workflowInfo.get("workflowTable")); + String requestId = Util.null2String(workflowInfo.get("requestId")); + String workflowVersionIds = Util.null2String(WorkflowVersion.getVersionStringByWfid(workflowType)); + List> configList = mapper.queryWritBackWorkflowConfig(workflowVersionIds.split(",")); + Assert.notEmpty(configList, "not query config data,uf_manual_sign_conf config data can not to be empty!"); + StringBuilder sb = new StringBuilder(); + sb.append("update ") + .append(workflowTable) + .append(" set "); + for (Map rowConfig : configList) { + String workflowFieldName = Util.null2String(rowConfig.get("workflowFieldName")); + String resultField = Util.null2String(rowConfig.get("callbackField")); + sb.append(workflowFieldName) + .append(" = #{") + .append(resultField) + .append("},"); + } + StringBuilder replace = sb.replace(sb.lastIndexOf(","), sb.length() - 1, ""); + replace.append(" where requestid = ") + .append(requestId); + int n = 0; + while (mapper.updateCallbackParams(replace.toString(), params)) { + n++; + if (n > 5) { + log.error("回写签署回调信息失败!" + replace); + return; + } + } + } +} diff --git a/src/main/youhong_ai_old_src/com/api/aiyh_jitu/fadada/service/WidgetsService.java b/src/main/youhong_ai_old_src/com/api/aiyh_jitu/fadada/service/WidgetsService.java new file mode 100644 index 0000000..35a47b9 --- /dev/null +++ b/src/main/youhong_ai_old_src/com/api/aiyh_jitu/fadada/service/WidgetsService.java @@ -0,0 +1,40 @@ +package com.api.aiyh_jitu.fadada.service; + +import aiyh.utils.Util; +import cn.hutool.core.lang.Assert; +import weaver.aiyh_jitu.schedule.registerfadada.constants.FaDaDaConstants; +import weaver.aiyh_jitu.schedule.registerfadada.util.JiTuFaDaDaUtil; + +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +/** + *

+ * + *

create: 2022-08-17 15:17

+ * + * @author aiyh EBU7-dev-1 + */ + +public class WidgetsService { + + + /** + *

获取控件列表

+ * + * @param contractId 合同模板ID + * @return 控件列表 + */ + public List getWidgets(String contractId) { + Map configMap = Util.readProperties2Map(FaDaDaConstants.FDD_CONFIG_FILE_NAME, FaDaDaConstants.FDD_CONFIG_FIEL_PREFIX); + Assert.notEmpty(configMap, "can not read config file [{}], check you config file!", FaDaDaConstants.FDD_CONFIG_FILE_NAME); + String url = configMap.get(FaDaDaConstants.FDD_BASE_URL_KEY) + "/online-template/widget/list"; + Map params = new HashMap<>(8); + params.put("id", contractId); + Map result = JiTuFaDaDaUtil.fetchOnlineWidgetDetailList(url, params); + Assert.notEmpty(result, "can not fetch onlineWidgetDetailList!"); + List data = (List) result.get("data"); + return data; + } +} diff --git a/src/main/youhong_ai_old_src/com/api/aiyh_jitu/pushdata/controller/ClearPushDataActionTokenCache.java b/src/main/youhong_ai_old_src/com/api/aiyh_jitu/pushdata/controller/ClearPushDataActionTokenCache.java new file mode 100644 index 0000000..3370680 --- /dev/null +++ b/src/main/youhong_ai_old_src/com/api/aiyh_jitu/pushdata/controller/ClearPushDataActionTokenCache.java @@ -0,0 +1,26 @@ +package com.api.aiyh_jitu.pushdata.controller; + +import aiyh.utils.ApiResult; +import weaver.aiyh_jitu.pushdata.util.JiTuTokenUtil; + +import javax.ws.rs.GET; +import javax.ws.rs.Path; + +/** + *

清除token缓存

+ * + *

create: 2022-08-15 14:41

+ * + * @author aiyh EBU7-dev-1 + */ + +@Path("/aiyh/token-cache") +public class ClearPushDataActionTokenCache { + + @Path("/clear") + @GET + public String clearToken() { + JiTuTokenUtil.clearToken(); + return ApiResult.successNoData(); + } +} diff --git a/src/main/youhong_ai_old_src/com/api/aiyh_kafang/dao/InvoiceMapping.java b/src/main/youhong_ai_old_src/com/api/aiyh_kafang/dao/InvoiceMapping.java new file mode 100644 index 0000000..050dbba --- /dev/null +++ b/src/main/youhong_ai_old_src/com/api/aiyh_kafang/dao/InvoiceMapping.java @@ -0,0 +1,103 @@ +package com.api.aiyh_kafang.dao; + +import aiyh.utils.Util; +import aiyh.utils.sqlUtil.sqlResult.impl.PrepSqlResultImpl; +import aiyh.utils.sqlUtil.whereUtil.Where; +import aiyh.utils.zwl.common.ToolUtil; +import com.api.aiyh_kafang.entity.UfInvoiceConfigDTO; +import weaver.conn.RecordSet; +import weaver.workflow.workflow.WorkflowVersion; + +import java.util.List; +import java.util.Map; + +/** + * @author EBU7-dev1-ayh + * @create 2021/11/9 0009 14:38 + */ + + +public class InvoiceMapping { + private RecordSet rs = new RecordSet(); + private ToolUtil toolUtil = new ToolUtil(); + private final String ModeTable = "uf_fpyzjb"; + private final String ModeDetailTable = "uf_fpyzjb_dt1"; + + public UfInvoiceConfigDTO getConfigInfo(String workflowId) { + String versionStringByWfid = WorkflowVersion.getVersionStringByWfid(workflowId); + String query = "select ic.id,ic.invoice_browse,ic.workflow_nodes,ic.workflow_type, " + + "dtv.tablename invoice_detail_table,ftv.fieldname invoice_field,ftv1.fieldname invoice_price " + + "from uf_invoice_config ic " + + "left join workflow_detail_table_view dtv on ic.invoice_detail_table = dtv.id " + + "left join workflow_field_table_view ftv on ic.invoice_field = ftv.id " + + "left join workflow_field_table_view ftv1 on ic.invoice_price = ftv1.id " + + " where workflow_type in (" + workflowId + " )"; + rs.executeQuery(query); + UfInvoiceConfigDTO ufInvoiceConfigDTO = Util.recordeSet2Entity(rs, UfInvoiceConfigDTO.class, true); + if (ufInvoiceConfigDTO != null) { + ufInvoiceConfigDTO.setWorkflowType(versionStringByWfid); + } + return ufInvoiceConfigDTO; + } + + public void saveInvoiceInfo(int dataId, String tableName, String requestId) { +// 主表数据 + Map update = Util.createUtilHashMap() + .uPut("lc", requestId) + .uPut("sm", "发票扫描自动添加实体发票信息!"); + Where where = Util.createPrepWhereImpl().whereAnd("id").whereEqual(dataId); + PrepSqlResultImpl sqlResult = Util.createSqlBuilder().updateSql(tableName, update, where); + toolUtil.writeErrorLog("SQL:" + sqlResult.getSqlStr() + " ---->参数:" + sqlResult.getArgs()); + rs.executeUpdate(sqlResult.getSqlStr(), sqlResult.getArgs()); + } + + public void saveInvoiceDetail(Map insert, String modeTable) { + PrepSqlResultImpl sqlResult = Util.createSqlBuilder().insertSql(modeTable, insert); + toolUtil.writeErrorLog("SQL:" + sqlResult.getSqlStr() + " ---->参数:" + sqlResult.getArgs()); + rs.executeUpdate(sqlResult.getSqlStr(), sqlResult.getArgs()); + } + + public String getMainId(String requestId) { + String query = "select * from uf_fpyzjb where lc = ?"; + rs.executeQuery(query, requestId); + rs.next(); + return rs.getString("id"); + } + + public List> selectModeInfo(String mainId) { + RecordSet rs = new RecordSet(); + String query = "select * from " + ModeDetailTable + " where mainid = ?"; + rs.executeQuery(query, mainId); + return Util.recordSet2MapList(rs); + } + + + public List> selectWorkflowData(String workflowId, String requestId, UfInvoiceConfigDTO configInfo) { +// 根据流程id查询流程主表 + String mainTable = Util.getMainTable(workflowId); + String query = "select * from " + mainTable + " where requestid = ?"; + rs.executeQuery(query, requestId); + rs.next(); + String mainId = rs.getString("id"); +// 查询明细表数据 + RecordSet rs = new RecordSet(); + query = "select * from " + configInfo.getInvoiceDetailTable() + " where mainid = ?"; + rs.executeQuery(query, mainId); + return Util.recordSet2MapList(rs); + } + + public String getWorkflowCode(String workflowCodeId, String invoiceTable) { + String query = "select * from " + invoiceTable + " where id = ?"; + rs.executeQuery(query, workflowCodeId); + if (rs.next()) { + return rs.getString("invoicenumber"); + } else { + throw new RuntimeException("发票不存在!"); + } + } + + public boolean selectExist(String main, String number) { + rs.executeQuery("select * from " + ModeDetailTable + " where mainid = ? and fphm2 = ?",main,number); + return rs.next(); + } +} \ No newline at end of file diff --git a/src/main/youhong_ai_old_src/com/api/aiyh_kafang/entity/UfInvoiceConfigDTO.java b/src/main/youhong_ai_old_src/com/api/aiyh_kafang/entity/UfInvoiceConfigDTO.java new file mode 100644 index 0000000..46fa3d0 --- /dev/null +++ b/src/main/youhong_ai_old_src/com/api/aiyh_kafang/entity/UfInvoiceConfigDTO.java @@ -0,0 +1,93 @@ + +package com.api.aiyh_kafang.entity; + + +public class UfInvoiceConfigDTO { + + private int id; + private int requestId; + private String workflowType; + private String workflowNodes; + private String invoiceField; + private String invoicePrice; + private int invoiceBrowse; + private String invoiceDetailTable; + + public void setId(int id) { + this.id = id; + } + + public void setRequestId(int requestId) { + this.requestId = requestId; + } + + public void setWorkflowType(String workflowType) { + this.workflowType = workflowType; + } + + public void setWorkflowNodes(String workflowNodes) { + this.workflowNodes = workflowNodes; + } + + public void setInvoiceField(String invoiceField) { + this.invoiceField = invoiceField; + } + + public void setInvoicePrice(String invoicePrice) { + this.invoicePrice = invoicePrice; + } + + public void setInvoiceBrowse(int invoiceBrowse) { + this.invoiceBrowse = invoiceBrowse; + } + + public void setInvoiceDetailTable(String invoiceDetailTable) { + this.invoiceDetailTable = invoiceDetailTable; + } + + public int getId() { + return this.id; + } + + public int getRequestId() { + return this.requestId; + } + + public String getWorkflowType() { + return this.workflowType; + } + + public String getWorkflowNodes() { + return this.workflowNodes; + } + + public String getInvoiceField() { + return this.invoiceField; + } + + public String getInvoicePrice() { + return this.invoicePrice; + } + + public int getInvoiceBrowse() { + return this.invoiceBrowse; + } + + public String getInvoiceDetailTable() { + return this.invoiceDetailTable; + } + + @Override + public String toString() { + return "UfInvoiceConfigDTO{" + + "id='" + id + '\'' + + ", requestId='" + requestId + '\'' + + ", workflowType='" + workflowType + '\'' + + ", workflowNodes='" + workflowNodes + '\'' + + ", invoiceField='" + invoiceField + '\'' + + ", invoicePrice='" + invoicePrice + '\'' + + ", invoiceBrowse='" + invoiceBrowse + '\'' + + ", invoiceDetailTable='" + invoiceDetailTable + '\'' + + '}'; + } +} \ No newline at end of file diff --git a/src/main/youhong_ai_old_src/com/api/aiyh_kafang/service/InvoiceService.java b/src/main/youhong_ai_old_src/com/api/aiyh_kafang/service/InvoiceService.java new file mode 100644 index 0000000..6af3aa0 --- /dev/null +++ b/src/main/youhong_ai_old_src/com/api/aiyh_kafang/service/InvoiceService.java @@ -0,0 +1,314 @@ +package com.api.aiyh_kafang.service; + +import aiyh.utils.Util; +import aiyh.utils.sqlUtil.sqlResult.impl.BatchSqlResultImpl; +import aiyh.utils.zwl.common.ToolUtil; +import com.api.aiyh_kafang.dao.InvoiceMapping; +import com.api.aiyh_kafang.entity.UfInvoiceConfigDTO; +import com.sun.image.codec.jpeg.JPEGCodec; +import com.weaver.general.TimeUtil; +import net.sf.json.JSONArray; +import net.sf.json.JSONObject; +import org.h2.util.StringUtils; +import weaver.conn.RecordSet; +import weaver.file.ImageFileManager; +import weaver.fna.invoice.utils.HttpUtil; +import weaver.formmode.data.ModeDataIdUpdate; +import weaver.formmode.setup.ModeRightInfo; +import weaver.hrm.User; + +import javax.imageio.IIOException; +import javax.imageio.ImageIO; +import java.awt.image.BufferedImage; +import java.io.ByteArrayOutputStream; +import java.io.IOException; +import java.io.InputStream; +import java.util.*; + +/** + * @author EBU7-dev1-ayh + * @create 2021/11/2 0002 15:17 + * 检查发票 + */ + + +public class InvoiceService { + + private final InvoiceMapping invoiceMapping = new InvoiceMapping(); + private final ModeDataIdUpdate mdu = ModeDataIdUpdate.getInstance(); + private final RecordSet rs = new RecordSet(); + private final ToolUtil toolUtil = new ToolUtil(); + private final String ModeTable = "uf_fpyzjb"; + private final String ModeDetailTable = "uf_fpyzjb_dt1"; + private final String ModeDetailTableErr = "uf_fpyzjb_dt3"; + private String formModeId = "17"; + private final String invoiceTable = "fnainvoiceledger"; + + public InvoiceService() { + String formModeId = toolUtil.getSystemParamValue("formModeId"); + if (!StringUtils.isNullOrEmpty(formModeId)) { + this.formModeId = formModeId; + } + } + + /** + * 查询发票信息,OCR识别 + * + * @param user + * @param fileId + * @return + * @throws IOException + */ + public JSONObject getInvoiceInfo(User user, int fileId) throws Exception { +// 方法一 +/* InputStream inputStreamById = ImageFileManager.getInputStreamById(fileId); + byte[] bytes; + bytes = IOUtils.toByteArray(inputStreamById); + JSONObject jsonObject = HttpUtil.postImage(bytes, user);*/ + +// 方法二 +/* String fileData = FnaInvoiceUploadUtil.changeFileTobase64(fileId); + byte[] imageBytes = ImageUtil.transformImage(fileData); + JSONObject jsonObject = HttpUtil.postImage(imageBytes, user);*/ + + +// 方法三 + try { + InputStream inputStreamById = ImageFileManager.getInputStreamById(fileId); + BufferedImage imageBuffer = ImageIO.read(inputStreamById); + ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(); + boolean jpeg = ImageIO.write(imageBuffer, "jpeg", byteArrayOutputStream); + if (!jpeg) { + toolUtil.writeErrorLog("图片转化转化失败!"); + } + byte[] bytes = byteArrayOutputStream.toByteArray(); + // toolUtil.writeErrorLog(jsonObject.toString()); + return HttpUtil.postImage(bytes, user); + } catch (IIOException e) { + InputStream inputStreamById = ImageFileManager.getInputStreamById(fileId); + BufferedImage imageBuffer = JPEGCodec.createJPEGDecoder(inputStreamById).decodeAsBufferedImage(); + ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(); + boolean jpeg = ImageIO.write(imageBuffer, "jpeg", byteArrayOutputStream); + if (!jpeg) { + toolUtil.writeErrorLog("图片转化转化失败!"); + } + byte[] bytes = byteArrayOutputStream.toByteArray(); + // toolUtil.writeErrorLog(jsonObject.toString()); + return HttpUtil.postImage(bytes, user); + } + } + + /** + * 对比合同信息 + */ + public Map contrastInvoiceInfo(Map params) { +// 获取到流程表中的明细数据,对比建模表中的发票信息,查验数量是否一致以及发票的钱 +// List fileIdList = (List) params.get("fileIdList"); + String requestId = Util.null2String(params.get("requestId")); + String workflowId = Util.null2String(params.get("workflowId")); +// 查询建模表数据 + String mainId = invoiceMapping.getMainId(requestId); + List> modeData = invoiceMapping.selectModeInfo(mainId); +// 查询配置表信息 + UfInvoiceConfigDTO configInfo = invoiceMapping.getConfigInfo(workflowId); +// 查询流程中的发票数据 + List> workflowData = invoiceMapping.selectWorkflowData(workflowId, requestId, configInfo); +// 对比合同信息,查询出相差的发票 + List> priceNotEqual = new ArrayList<>(); + List> workflowDataRm = new ArrayList<>(); + List> modeDataRm = new ArrayList<>(); + if (configInfo.getInvoiceBrowse() == 1) { +// 属于浏览框 + for (Map workflowDatum : workflowData) { + String workflowCodeId = Util.null2String(workflowDatum.get(configInfo.getInvoiceField())); + String workflowCode = ""; + String workflowInvoicePrice = Util.null2String(workflowDatum.get(configInfo.getInvoicePrice())); + try { + workflowCode = invoiceMapping.getWorkflowCode(workflowCodeId, invoiceTable); + workflowDatum.put(configInfo.getInvoiceField(), workflowCode); + workflowDatum.put("fphm2", workflowCode); + } catch (Exception e) { + e.printStackTrace(); + toolUtil.writeErrorLog("发票不存在:" + e); + } + for (Map modeDatum : modeData) { + String modeCode = Util.null2String(modeDatum.get("fphm2")); + String modePrice = Util.null2String(modeDatum.get("fpje")); + if (workflowCode.equals(modeCode)) { +// 发票号码相等,校验发票金额 + if (!workflowInvoicePrice.equals(modePrice)) { +// 金额不相等 +// 添加校验失败数据到数组中 + priceNotEqual.add(modeDatum); + } +// 求差集 + workflowDataRm.add(workflowDatum); + modeDataRm.add(modeDatum); + break; + } + } + } +// 求差 +// 建模表中多余的发票信息 + modeData.removeAll(modeDataRm); +// 流程中有但是建模表中没有的发票信息 + workflowData.removeAll(workflowDataRm); + + } else { +// 不属于浏览框 + for (Map workflowDatum : workflowData) { + String workflowCode = Util.null2String(workflowDatum.get(configInfo.getInvoiceField())); + String workflowInvoicePrice = Util.null2String(workflowDatum.get(configInfo.getInvoicePrice())); + for (Map modeDatum : modeData) { + String modeCode = Util.null2String(modeDatum.get("fphm2")); + String modePrice = Util.null2String(modeDatum.get("fpje")); + if (workflowCode.equals(modeCode)) { +// 发票号码相等,校验发票金额 + if (!workflowInvoicePrice.equals(modePrice)) { +// 金额不相等 +// 添加校验失败数据到数组中 + priceNotEqual.add(modeDatum); + } +// 求差集 + workflowDataRm.add(workflowDatum); + modeDataRm.add(modeDatum); + break; + } + } + } +// 求差 +// 建模表中多余的发票信息 + modeData.removeAll(modeDataRm); +// 流程中有但是建模表中没有的发票信息 + workflowData.removeAll(workflowDataRm); + } + + List> insertList = new ArrayList<>(); +// 将价格不一样的数据保存到建模表明细3中,并标识错误原因为价格不一致 + for (Map map : priceNotEqual) { + LinkedHashMap data = new LinkedHashMap<>(); + data.put("fphm1", map.get("fphm2")); + data.put("sbyy", "流程发票明细信息表中的发票与扫描识别发票的发票金额不一致!"); + data.put("mainid", mainId); + insertList.add(data); + } +// 将建模表多的发票保存到建模表明细3中,并标识错误原因为流程中不存在改发票信息 + for (Map map : modeData) { + LinkedHashMap data = new LinkedHashMap<>(); + data.put("fphm1", map.get("fphm2")); + data.put("sbyy", "流程中不存在该发票信息,但扫描发票中存在改发票!"); + data.put("mainid", mainId); + insertList.add(data); + } +// 将流程中多的发票保存到建模表明细3中,并标识错误原因为,扫描发票中不存在改发票信息 + for (Map map : workflowData) { + LinkedHashMap data = new LinkedHashMap<>(); + data.put("fphm1", Util.null2String(map.get(configInfo.getInvoiceField()))); + data.put("sbyy", "流程中存在改发票,但是扫描发票中没有发现该发票信息!"); + data.put("mainid", mainId); + insertList.add(data); + } + RecordSet rs = new RecordSet(); + BatchSqlResultImpl batchSqlResult = Util.createSqlBuilder().insertBatchSql(ModeDetailTableErr, insertList); + toolUtil.writeErrorLog("SQL:" + batchSqlResult.getSqlStr() + " ---->参数:" + batchSqlResult.getBatchList()); + System.out.println("SQL:" + batchSqlResult.getSqlStr() + " ---->参数:" + batchSqlResult.getBatchList()); +/* for (List list : batchSqlResult.getBatchList()) { + rs.executeUpdate(batchSqlResult.getSqlStr(),list); + }*/ + try { + rs.executeBatchSql(batchSqlResult.getSqlStr(), batchSqlResult.getBatchList()); + } catch (Exception e) { + e.printStackTrace(); + } + Map result = new HashMap<>(); + result.put("priceNotEqual", priceNotEqual); + result.put("workflowData", workflowData); + result.put("modeData", modeData); + return result; + } + + /** + * 获取配置信息 + * + * @param workflowId + * @return + */ + public UfInvoiceConfigDTO getConfigInfo(String workflowId) { + return invoiceMapping.getConfigInfo(workflowId); + } + + /** + * 保存合同信息 + * + * @param invoiceInfo + * @param requestId + */ + public void saveInvoiceInfo(JSONObject invoiceInfo, String requestId) { +// 查询是否已经存在,不存在则新增,存在则更新 + String query = "select * from " + ModeTable + " where lc = ?"; + rs.executeQuery(query, requestId); + if (rs.next()) { +// 存在,往明细表中添加数据 + saveInvoiceDetail(invoiceInfo, requestId, rs.getString("id")); + return; + } +// 添加主表数据,并且添加明细 + int dataId = mdu.getModeDataNewId(ModeTable, + Util.getIntValue(formModeId, -1), + 1, 0, TimeUtil.getCurrentDateString(), + TimeUtil.getOnlyCurrentTimeString()); +// 插入数据库信息 + invoiceMapping.saveInvoiceInfo(dataId, ModeTable, requestId); + saveInvoiceDetail(invoiceInfo, requestId, String.valueOf(dataId)); + ModeRightInfo mri = new ModeRightInfo(); + mri.rebuildModeDataShareByEdit(1, Util.getIntValue(formModeId, -1), dataId); + } + + /** + * 保存发票信息到建模明细表 + * + * @param invoiceInfo + * @param requestId + * @param mainId + */ + public void saveInvoiceDetail(JSONObject invoiceInfo, String requestId, String mainId) { + String main = mainId; + if (StringUtils.isNullOrEmpty(main)) { +// 查询主表数据 + String query = "select * from " + ModeTable + " where lc = ?"; + rs.executeQuery(query, requestId); + rs.next(); + main = rs.getString("id"); + } +// 保存明细表数据 + JSONObject returnInfo = (JSONObject) invoiceInfo.get("returnInfo"); + toolUtil.writeErrorLog("returnInfo:" + returnInfo); + if (returnInfo == null) { + throw new RuntimeException("发票数据获取失败:" + invoiceInfo); + } + JSONObject response = (JSONObject) returnInfo.get("response"); + JSONObject data = (JSONObject) response.get("data"); + JSONArray identifyResults = (JSONArray) data.get("identify_results"); + for (int i = 0; i < identifyResults.size(); i++) { + JSONObject item = (JSONObject) identifyResults.get(i); + JSONObject details = (JSONObject) item.get("details"); +// 查询是否存在该发票,不存在则添加 + if (invoiceMapping.selectExist(main, Util.null2String(details.get("number")))) { + return; + } + // 明细表数据 + Map insert = Util.createUtilHashMap() +// 发票号码 + .uPut("fphm2", details.get("number")) +// 费用日期 + .uPut("fyrq", details.get("date")) +// 服务内容 + .uPut("fwnr", details.get("item_names")) +// 发票金额 + .uPut("fpje", details.get("total")) + .uPut("mainid", main); + toolUtil.writeErrorLog("insert:" + insert); + invoiceMapping.saveInvoiceDetail(insert, ModeDetailTable); + } + } +} diff --git a/src/main/youhong_ai_old_src/com/api/aiyh_kafang/service/UploadByBase64Service.java b/src/main/youhong_ai_old_src/com/api/aiyh_kafang/service/UploadByBase64Service.java new file mode 100644 index 0000000..746320f --- /dev/null +++ b/src/main/youhong_ai_old_src/com/api/aiyh_kafang/service/UploadByBase64Service.java @@ -0,0 +1,32 @@ +package com.api.aiyh_kafang.service; + + +import aiyh.utils.zwl.common.ToolUtil; +import org.apache.axiom.util.base64.Base64Utils; +import weaver.file.ImageFileManager; + +import java.util.Map; +import java.util.UUID; + +/** + * @author EBU7-dev1-ayh + * @create 2021/10/8 0008 13:36 + * 业务逻辑处理 + */ + + +public class UploadByBase64Service { + public int uploadImage(Map param) { + ToolUtil toolUtil = new ToolUtil(); + String base64 = String.valueOf(param.get("base64")).replaceAll(" ", "+");; + ImageFileManager fileManager = new ImageFileManager(); + byte[] data = null; + data = Base64Utils.decode(base64); + fileManager.setData(data); + String fileName = "" + System.currentTimeMillis() + UUID.randomUUID() + ".jpg"; + fileManager.setImagFileName(fileName); + int i = fileManager.saveImageFile(); + toolUtil.writeErrorLog("生成的图片的id:" + i); + return i; + } +} diff --git a/src/main/youhong_ai_old_src/com/api/aiyh_kafang/web/InvoiceController.java b/src/main/youhong_ai_old_src/com/api/aiyh_kafang/web/InvoiceController.java new file mode 100644 index 0000000..7d1b380 --- /dev/null +++ b/src/main/youhong_ai_old_src/com/api/aiyh_kafang/web/InvoiceController.java @@ -0,0 +1,36 @@ +package com.api.aiyh_kafang.web; + +import aiyh.utils.ApiResult; +import com.api.aiyh_kafang.service.InvoiceService; +import io.swagger.v3.oas.annotations.parameters.RequestBody; + +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; +import javax.ws.rs.Consumes; +import javax.ws.rs.POST; +import javax.ws.rs.Path; +import javax.ws.rs.Produces; +import javax.ws.rs.core.Context; +import javax.ws.rs.core.MediaType; +import java.util.Map; + +/** + * @author EBU7-dev1-ayh + * @create 2021/9/27 0027 10:29 + * 发票相关控制器 + */ + +@Path("/kafang/invoiceCheck") +public class InvoiceController { + private InvoiceService invoiceService = new InvoiceService(); + + @Path("/check/contrast") + @POST + @Consumes(MediaType.APPLICATION_JSON) + @Produces(MediaType.APPLICATION_JSON) + public String check(@Context HttpServletRequest request, @Context HttpServletResponse response, + @RequestBody Map params) { + Map result = invoiceService.contrastInvoiceInfo(params); + return ApiResult.success(result); + } +} diff --git a/src/main/youhong_ai_old_src/com/api/aiyh_kafang/web/UploadByBase64.java b/src/main/youhong_ai_old_src/com/api/aiyh_kafang/web/UploadByBase64.java new file mode 100644 index 0000000..d87977a --- /dev/null +++ b/src/main/youhong_ai_old_src/com/api/aiyh_kafang/web/UploadByBase64.java @@ -0,0 +1,97 @@ +package com.api.aiyh_kafang.web; + +import aiyh.utils.ApiResult; +import aiyh.utils.zwl.common.ToolUtil; +import com.api.aiyh_kafang.entity.UfInvoiceConfigDTO; +import com.api.aiyh_kafang.service.InvoiceService; +import com.api.aiyh_kafang.service.UploadByBase64Service; +import io.swagger.v3.oas.annotations.parameters.RequestBody; +import net.sf.json.JSONObject; +import org.apache.commons.io.IOUtils; +import weaver.file.ImageFileManager; +import weaver.hrm.HrmUserVarify; +import weaver.hrm.User; + +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; +import javax.ws.rs.*; +import javax.ws.rs.core.Context; +import javax.ws.rs.core.MediaType; +import javax.ws.rs.core.Response; +import javax.ws.rs.core.StreamingOutput; +import java.io.InputStream; +import java.util.Map; + +/** + * @author EBU7-dev1-ayh + * @create 2021/9/27 0027 14:13 + * upload invoice by base64 arr + */ + + +@Path("/kafang/upload") +public class UploadByBase64 { + private final ToolUtil toolUtil = new ToolUtil(); + private final UploadByBase64Service uploadByBase64Service = new UploadByBase64Service(); + private final InvoiceService invoiceService = new InvoiceService(); + + @Path("/uploadImage/byBase64") + @POST + @Consumes(MediaType.APPLICATION_JSON) + @Produces(MediaType.APPLICATION_JSON) + public String uploadImage(@Context HttpServletRequest request, @Context HttpServletResponse response, + @RequestBody Map base64Map) { + int i = uploadByBase64Service.uploadImage(base64Map); +// 上传完成过后,调用发票识别接口,将数据保存到建模表中 + User user = HrmUserVarify.getUser(request, response); + JSONObject invoiceInfo = null; + try { + invoiceInfo = invoiceService.getInvoiceInfo(user, i); + if (invoiceInfo == null || "1".equals(String.valueOf(invoiceInfo.get("status")))) { + throw new RuntimeException(invoiceInfo == null ? "识别数据为空!" : invoiceInfo.toString()); + } + } catch (Exception e) { + e.printStackTrace(); + toolUtil.writeErrorLog("发票识别失败!" + e + invoiceInfo); + return ApiResult.error("发票识别失败!"); + } + try { + invoiceService.saveInvoiceInfo(invoiceInfo, base64Map.get("requestId")); + } catch (Exception e) { + e.printStackTrace(); + toolUtil.writeErrorLog("发票保存失败!" + e); + return ApiResult.error("发票保存失败!"); + } + return ApiResult.success(i); + } + + @Path("/getConfigInfo/{workflowId}") + @GET + @Consumes(MediaType.APPLICATION_JSON) + @Produces(MediaType.APPLICATION_JSON) + public String getWorkflowId(@PathParam("workflowId") String workflowId) { + UfInvoiceConfigDTO configInfo = invoiceService.getConfigInfo(workflowId); + return ApiResult.success(configInfo); + } + + + @Path("/download/img/{fileId}") + @GET + @Produces(MediaType.APPLICATION_OCTET_STREAM) + public Response downloadFile(@PathParam("fileId") int fileId){ + try { + InputStream inputStreamById = ImageFileManager.getInputStreamById(fileId); + byte[] bytes = IOUtils.toByteArray(inputStreamById); + StreamingOutput output = outputStream -> { + outputStream.write(bytes); + outputStream.close(); + }; + Response.ResponseBuilder header = Response.ok(output, MediaType.APPLICATION_OCTET_STREAM) + .header("Content-Disposition", + "attachment; filename=image_from_server.jpg"); + return header.build(); + } catch (Exception e) { + return Response.ok(ApiResult.error("异常" + e), MediaType.APPLICATION_JSON).build(); + } + } +} diff --git a/src/main/youhong_ai_old_src/com/api/aiyh_logincheck/controller/DynamicCodeController.java b/src/main/youhong_ai_old_src/com/api/aiyh_logincheck/controller/DynamicCodeController.java new file mode 100644 index 0000000..edcf2cd --- /dev/null +++ b/src/main/youhong_ai_old_src/com/api/aiyh_logincheck/controller/DynamicCodeController.java @@ -0,0 +1,86 @@ +package com.api.aiyh_logincheck.controller; + +import aiyh.utils.ApiResult; +import aiyh.utils.Util; +import aiyh.utils.excention.CustomerException; +import com.api.aiyh_logincheck.service.DynamicCodeService; +import com.engine.common.util.ParamUtil; +import io.swagger.v3.oas.annotations.parameters.RequestBody; + +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; +import javax.ws.rs.*; +import javax.ws.rs.core.Context; +import javax.ws.rs.core.MediaType; +import java.util.Map; + +/** + * create 2022/1/17 0017 16:34 + * + * @author EBU7-dev1-ayh + */ + + +@Path("/dynamicCode") +public class DynamicCodeController { + private final DynamicCodeService dynamicCodeService = new DynamicCodeService(); + + /** + * 生成动态验证码 + * + * @param loginId 登录id + * @return 是否成功 + */ + @Path("/getCode/{loginId}") + @GET + @Produces(MediaType.APPLICATION_JSON) + public String getCode(@PathParam("loginId") String loginId) { + try { + return ApiResult.success(dynamicCodeService.getCode(loginId)); + } catch (Exception e) { + Util.getLogger().error("获取动态验证码失败 !", e); + return ApiResult.error("获取动态验证码失败"); + } + } + + /** + * 验证动态码是否正确 + * + * @param request 请求体 + * @return 验证结果 + */ + @Path("/checkCode") + @POST + @Produces(MediaType.APPLICATION_JSON) + public String checkCode(@Context HttpServletRequest request, @Context HttpServletResponse response) { + @SuppressWarnings("unchecked") + Map params = ParamUtil.request2Map(request); + Util.getLogger().debug(params); + try { + int i = dynamicCodeService.checkDynamicCode(String.valueOf(params.get("loginId")), + String.valueOf(params.get("dynamicCode")), request, response); + return ApiResult.success(i); + } catch (Exception e) { + Util.getLogger().error("检查动态验证码出错 !", e); + } + return ApiResult.error("检查动态验证码出错"); + } + + + @Path("/getUncheck") + @POST + @Produces(MediaType.APPLICATION_JSON) + public String getUncheck(@RequestBody Map userInfo) { + try { + return ApiResult.success(dynamicCodeService.getUncheck(userInfo)); + + } catch (CustomerException e) { + if (e.getCode() == 403) { + return ApiResult.error(403, "用户名或密码错误!"); + } + } catch (Exception e) { + Util.getLogger().error("检查是否开启动态码或获取白名单 !", e); + } + return ApiResult.error("检查动态验证码出错"); + } +} diff --git a/src/main/youhong_ai_old_src/com/api/aiyh_logincheck/enumType/CodeStatus.java b/src/main/youhong_ai_old_src/com/api/aiyh_logincheck/enumType/CodeStatus.java new file mode 100644 index 0000000..baf30b2 --- /dev/null +++ b/src/main/youhong_ai_old_src/com/api/aiyh_logincheck/enumType/CodeStatus.java @@ -0,0 +1,36 @@ +package com.api.aiyh_logincheck.enumType; + +/** + * create 2022/1/17 0017 17:24 + * + * @author EBU7-dev1-ayh + */ + +public enum CodeStatus { + + /** + * 没有动态验证码,验证码过期 + */ + withoutDynamicCode(-1), + /** + * 动态 验证码错误 + */ + dynamicCodeErr(-2), + /** + * 验证通过 + */ + success(0); + + private final int value; + + + + CodeStatus(int value){ + this.value = value; + } + + public int getValue(){ + return this.value; + } + +} \ No newline at end of file diff --git a/src/main/youhong_ai_old_src/com/api/aiyh_logincheck/mapper/DynamicCodeMapper.java b/src/main/youhong_ai_old_src/com/api/aiyh_logincheck/mapper/DynamicCodeMapper.java new file mode 100644 index 0000000..e4291f8 --- /dev/null +++ b/src/main/youhong_ai_old_src/com/api/aiyh_logincheck/mapper/DynamicCodeMapper.java @@ -0,0 +1,29 @@ +package com.api.aiyh_logincheck.mapper; + +import aiyh.utils.annotation.recordset.ParamMapper; +import aiyh.utils.annotation.recordset.Select; +import aiyh.utils.annotation.recordset.SqlMapper; + +/** + * create 2022/1/17 0017 16:57 + * + * @author EBU7-dev1-ayh + */ + +@SqlMapper +public interface DynamicCodeMapper { + + @Select("select email from hrmresource where loginid = #{loginId}") + public String selectEmail(@ParamMapper("loginId") String loginId); + + /** + *

查询用户

+ * + * @param user 用户loginId + * @param mdPassword 用户加密后的密码 + * @return 用户 id + */ + @Select("select id from hrmresource where loginid = #{loginId} and password = #{password}") + Integer selectUser(@ParamMapper("loginId") String user, + @ParamMapper("password") String mdPassword); +} diff --git a/src/main/youhong_ai_old_src/com/api/aiyh_logincheck/service/DynamicCodeService.java b/src/main/youhong_ai_old_src/com/api/aiyh_logincheck/service/DynamicCodeService.java new file mode 100644 index 0000000..9058784 --- /dev/null +++ b/src/main/youhong_ai_old_src/com/api/aiyh_logincheck/service/DynamicCodeService.java @@ -0,0 +1,137 @@ +package com.api.aiyh_logincheck.service; + +import aiyh.utils.Util; +import aiyh.utils.excention.CustomerException; +import aiyh.utils.zwl.common.ToolUtil; +import cn.hutool.core.util.RandomUtil; +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.JSONObject; +import com.api.aiyh_logincheck.enumType.CodeStatus; +import com.api.aiyh_logincheck.mapper.DynamicCodeMapper; +import com.api.login.util.LoginUtil; +import com.cloudstore.dev.api.util.Util_DataCache; +import com.weaver.formmodel.util.EncryptHelper; +import org.apache.commons.lang.StringUtils; +import org.apache.log4j.Logger; +import weaver.email.EmailWorkRunnable; +import weaver.general.BaseBean; +import weaver.sm.SM4Utils; + +import javax.servlet.ServletContext; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; +import java.util.Base64; +import java.util.HashMap; +import java.util.Map; +import java.util.Objects; + +/** + * create 2022/1/17 0017 16:38 + * + * @author EBU7-dev1-ayh + */ + + +public class DynamicCodeService { + private final DynamicCodeMapper dynamicCodeMapper = Util.getMapper(DynamicCodeMapper.class); + private final Logger log = Util.getLogger(); + private final ToolUtil toolUtil = new ToolUtil(); + + /** + * 生成动态 验证码并发送邮箱 + * + * @param loginId 登录id + * @return 验证码 + */ + public boolean getCode(String loginId) { + String code = RandomUtil.randomString(6); + Util_DataCache.setObjVal(loginId, code, 60 * 3); + String emailAddress = dynamicCodeMapper.selectEmail(loginId); + if ("".equals(emailAddress) || emailAddress == null) { + return false; + } + String dynamicCodeTitle = toolUtil.getSystemParamValue("dynamicCodeTitle"); + if (StringUtils.isBlank(dynamicCodeTitle)) { + dynamicCodeTitle = "OA办公系统登录邮箱验证码"; + } + String dynamicCodeContent = toolUtil.getSystemParamValue("dynamicCodeContent"); + if (StringUtils.isBlank(dynamicCodeContent)) { + dynamicCodeContent = "您的登录验证码为:${code}!3分钟内有效!"; + } + String content = dynamicCodeContent.replaceAll("\\$\\{\\s*code\\s*}", code); + content = content.replaceAll("\\$\\{\\s*time\\s*}", Util.getTime("yyyy-MM-dd HH:mm:ss")); +// 发送邮件 + try { + EmailWorkRunnable.threadModeReminder(emailAddress, "", "", + dynamicCodeTitle, + content); + return true; + } catch (Exception e) { + log.error("发送邮件错误!", e); + } + return false; + } + + /** + * 检验动态验证码是否正确 + * + * @param loginId 登录id + * @param code 动态验证码 + * @return 状态代码 + */ + public int checkDynamicCode(String loginId, String code, HttpServletRequest request, HttpServletResponse response) { + Object dynamicCode = Util.null2DefaultStr(Util_DataCache.getObjVal(loginId), ""); + if ("".equals(dynamicCode)) { + ServletContext application = request.getSession().getServletContext(); + new LoginUtil().checkLogout(application, request, response); + return CodeStatus.withoutDynamicCode.getValue(); + } + if (code.equals(dynamicCode)) { + return CodeStatus.success.getValue(); + } + ServletContext application = request.getSession().getServletContext(); + new LoginUtil().checkLogout(application, request, response); + return CodeStatus.dynamicCodeErr.getValue(); + } + + /** + * 不通过二次验证的登录名 + * + * @return 不通过二次 验证的登录名 + */ + public Map getUncheck(Map userInfo) { + if (Objects.isNull(userInfo)) { + throw new CustomerException("userInfo no can be null!"); + } + String userStr = Util.null2String(userInfo.get("userInfo")); + if (userStr.isEmpty()) { + throw new CustomerException("userInfoStr is null!"); + } + userStr = userStr.substring(10); + userStr = userStr.substring(0, 10) + userStr.substring(20); + userStr = new String(Base64.getDecoder().decode(userStr.getBytes())); + JSONObject jsonObject = JSON.parseObject(userStr); + String user = jsonObject.getString("user"); + String password = jsonObject.getString("password"); + if (password.endsWith("_random_")) { + SM4Utils sm4 = new SM4Utils(); + BaseBean bb = new BaseBean(); + String key = weaver.general.Util.null2String(bb.getPropValue("weaver_client_pwd", "key")); + if (!"".equals(key)) { + password = password.substring(0, password.lastIndexOf("_random_")); + password = sm4.decrypt(password, key); + } + } + String mdPassword = EncryptHelper.encodeMd5(password).toUpperCase(); + Integer userId = dynamicCodeMapper.selectUser(user, mdPassword); + if (Objects.isNull(userId) || userId < 0) { + throw new CustomerException("账号或密码错误!", 403); + } + String uncheckList = toolUtil.getSystemParamValue("uncheckList"); + String isEnable = toolUtil.getSystemParamValue("enableDynamicCode"); + Map map = new HashMap<>(4); + map.put("uncheckList", Util.null2DefaultStr(uncheckList, "").split(",")); + map.put("isEnable", Boolean.valueOf(isEnable)); + return map; + } +} diff --git a/src/main/youhong_ai_old_src/com/api/aiyh_pcn/async_organization/ExportExcel.java b/src/main/youhong_ai_old_src/com/api/aiyh_pcn/async_organization/ExportExcel.java new file mode 100644 index 0000000..adc6f1a --- /dev/null +++ b/src/main/youhong_ai_old_src/com/api/aiyh_pcn/async_organization/ExportExcel.java @@ -0,0 +1,159 @@ +package com.api.aiyh_pcn.async_organization; + +import aiyh.utils.zwl.common.ToolUtil; +import km.org.apache.poi.hssf.usermodel.HSSFCellStyle; +import km.org.apache.poi.hssf.util.HSSFColor; +import org.apache.poi.ss.usermodel.*; +import org.apache.poi.ss.util.CellRangeAddress; +import org.apache.poi.xssf.streaming.SXSSFWorkbook; +import weaver.aiyh_pcn.async_organization.model.Department; +import weaver.aiyh_pcn.async_organization.model.Employee; +import weaver.aiyh_pcn.async_organization.model.Position; +import weaver.aiyh_pcn.async_organization.result.GetOrganizationResult; + +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; +import javax.ws.rs.GET; +import javax.ws.rs.Path; +import javax.ws.rs.Produces; +import javax.ws.rs.core.Context; +import javax.ws.rs.core.MediaType; +import javax.ws.rs.core.Response; +import java.io.ByteArrayOutputStream; +import java.io.IOException; +import java.text.SimpleDateFormat; +import java.util.Date; +import java.util.List; + +/** + * @author EBU7-dev1-ayh + * @create 2021/8/8 0008 16:06 + * 导出api请求数据的表格 + */ + +@Path("/asyncOrganization") +public class ExportExcel { + + @GET + @Path("/exportExcel") + @Produces(MediaType.APPLICATION_OCTET_STREAM) + public Response exportExcel(@Context HttpServletRequest request, @Context HttpServletResponse response) { + ToolUtil toolUtil = new ToolUtil(); + GetOrganizationResult getOrganizationResult = new GetOrganizationResult(); + List employeeList = getOrganizationResult.getEmployeeList(); + SXSSFWorkbook sxssfWorkbook = new SXSSFWorkbook(); + CellStyle cellStyle = sxssfWorkbook.createCellStyle(); + // 设置单元格居中对齐 + cellStyle.setAlignment(HorizontalAlignment.forInt(HSSFCellStyle.ALIGN_CENTER)); + Font font = sxssfWorkbook.createFont(); + font.setColor(HSSFColor.RED.index); + cellStyle.setFont(font); + Sheet sheet = sxssfWorkbook.createSheet("人员信息"); + Row desc = sheet.createRow(0); + sheet.addMergedRegion(new CellRangeAddress(0, 0, 0, 13)); + Cell cell2 = desc.createCell(0); + cell2.setCellValue("员工信息表,同步数据时,按照岗位id进行排序同步!"); + cell2.setCellStyle(cellStyle); + Row th = sheet.createRow(1); + th.createCell(0).setCellValue("员工ID"); + th.createCell(1).setCellValue("名(英文)"); + th.createCell(2).setCellValue("姓(英文)"); + th.createCell(3).setCellValue("中文姓名"); + th.createCell(4).setCellValue("英文名"); + th.createCell(5).setCellValue("员工编号"); + th.createCell(6).setCellValue("岗位ID"); + th.createCell(7).setCellValue("部门ID"); + th.createCell(8).setCellValue("部门名称"); + th.createCell(9).setCellValue("成本中心编码"); + th.createCell(10).setCellValue("邮箱"); + th.createCell(11).setCellValue("公司实体"); + th.createCell(12).setCellValue("电话号"); + th.createCell(13).setCellValue("座机号"); + try { + for (int i = 0; i < employeeList.size(); i++) { + Employee e = employeeList.get(i); +// toolUtil.writeErrorLog("item数据库:" + e); + if (e.getJOBCODEID() == null || e.getJOBCODEID() == 0){ +// toolUtil.writeErrorLog("数据出现错误:" + e); + e.setJOBCODEID(-0L); +// continue; + } + Row row = sheet.createRow(i + 2); + row.createCell(0).setCellValue(e.getUserID()); + row.createCell(1).setCellValue(e.getFIRSTNAMEEN()); + row.createCell(2).setCellValue(e.getLASTNAMEEN()); + row.createCell(3).setCellValue(e.getUSERNAMECN()); + row.createCell(4).setCellValue(e.getPreferred_Name()); + row.createCell(5).setCellValue(e.getUSERCODE()); + row.createCell(6).setCellValue(e.getJOBCODEID()); + row.createCell(7).setCellValue(e.getDEPARTMENTID()); + row.createCell(8).setCellValue(e.getDEPARTMENTNAME()); + row.createCell(9).setCellValue(e.getCOSTCENTERCODE()); + row.createCell(10).setCellValue(e.getEMAIL()); + row.createCell(11).setCellValue(e.getORGANIZATION()); + row.createCell(12).setCellValue(e.getMOBILENO()); + row.createCell(13).setCellValue(e.getTEL()); + } + }catch (Exception e){ + toolUtil.writeErrorLog("出现异常:"+e); + } + + List departmentList = getOrganizationResult.getDepartmentList(); + Sheet depSheet = sxssfWorkbook.createSheet("部门信息"); + Row depdesc = depSheet.createRow(0); + depSheet.addMergedRegion(new CellRangeAddress(0, 0, 0, 2)); + Cell cell1 = depdesc.createCell(0); + cell1.setCellValue("部门信息表,同步数据时按照该上级部门id进行排序同步!红色字体为根部门!"); + cell1.setCellStyle(cellStyle); + Row depTh = depSheet.createRow(1); + depTh.createCell(0).setCellValue("部门ID"); + depTh.createCell(1).setCellValue("部门名称"); + depTh.createCell(2).setCellValue("上级部门"); + for (int i = 0; i < departmentList.size(); i++) { + Row row = depSheet.createRow(i + 2); + Department d = departmentList.get(i); + row.createCell(0).setCellValue(d.getDEPARTMENTID()); + row.createCell(1).setCellValue(d.getDEPARTMENTNAME()); + Cell cell = row.createCell(2); + cell.setCellValue(d.getPARENTDEPARTMENDID()); + if (d.getPARENTDEPARTMENDID() == 0) { + cell.setCellStyle(cellStyle); + } + } + + List positionList = getOrganizationResult.getPositionList(); + Sheet posSheet = sxssfWorkbook.createSheet("职位信息"); + Row posdesc = posSheet.createRow(0); + posSheet.addMergedRegion(new CellRangeAddress(0, 0, 0, 3)); + Cell cell3 = posdesc.createCell(0); + cell3.setCellValue("职位信息表,职位同步过程中以上级岗位id升序排序进行同步!"); + cell3.setCellStyle(cellStyle); + Row posTh = posSheet.createRow(1); + posTh.createCell(0).setCellValue("岗位编号"); + posTh.createCell(1).setCellValue("岗位编号"); + posTh.createCell(2).setCellValue("岗位描述"); + posTh.createCell(3).setCellValue("上级岗位ID"); + for (int i = 0; i < positionList.size(); i++) { + Row row = posSheet.createRow(i + 2); + Position p = positionList.get(i); + row.createCell(0).setCellValue(p.getJOBCODEID()); + row.createCell(1).setCellValue(p.getJOBCODE()); + row.createCell(2).setCellValue(p.getJOBFUNCTION()); + row.createCell(3).setCellValue(p.getSUPERIORJOBCODEID()); + } + SimpleDateFormat newsdf = new SimpleDateFormat("yyyy-MM-dd-HHmmss"); + String date = newsdf.format(new Date()); + ByteArrayOutputStream bos = new ByteArrayOutputStream(); + try { + sxssfWorkbook.write(bos); + return Response.ok(bos.toByteArray(), "application/msexcel;charset=UTF-8") + .header("Content-Disposition", "attachment;filename=\"" + + new String(("CMS人员同步接口数据" + date + ".xlsx").getBytes("GBK"), + "ISO8859_1") + "\"") + .build(); + } catch (IOException e) { + e.printStackTrace(); + throw new RuntimeException(e); + } + } +} diff --git a/src/main/youhong_ai_old_src/com/api/aiyh_pcn/common_fadada/contraller/CommonFaCallbackController.java b/src/main/youhong_ai_old_src/com/api/aiyh_pcn/common_fadada/contraller/CommonFaCallbackController.java new file mode 100644 index 0000000..7068961 --- /dev/null +++ b/src/main/youhong_ai_old_src/com/api/aiyh_pcn/common_fadada/contraller/CommonFaCallbackController.java @@ -0,0 +1,34 @@ +package com.api.aiyh_pcn.common_fadada.contraller; + +import com.alibaba.fastjson.JSON; +import io.swagger.v3.oas.annotations.parameters.RequestBody; + +import javax.ws.rs.Consumes; +import javax.ws.rs.POST; +import javax.ws.rs.Path; +import javax.ws.rs.Produces; +import javax.ws.rs.core.MediaType; +import java.util.HashMap; +import java.util.Map; + +/** + *

回调

+ *

create 2022/4/26 11:02 AM

+ * + * @author ayh + */ + +@Path("/common_fadada/callback") +public class CommonFaCallbackController { + + @Path("/dealers/callback") + @POST + @Produces(MediaType.APPLICATION_JSON) + @Consumes(MediaType.APPLICATION_JSON) + public String dealersCallback(@RequestBody Map params) { + Map result = new HashMap<>(); + result.put("code", 200); + result.put("msg", "操作成功!"); + return JSON.toJSONString(result); + } +} diff --git a/src/main/youhong_ai_old_src/com/api/aiyh_pcn/common_fadada/contraller/CommonFaController.java b/src/main/youhong_ai_old_src/com/api/aiyh_pcn/common_fadada/contraller/CommonFaController.java new file mode 100644 index 0000000..0ba3004 --- /dev/null +++ b/src/main/youhong_ai_old_src/com/api/aiyh_pcn/common_fadada/contraller/CommonFaController.java @@ -0,0 +1,108 @@ +package com.api.aiyh_pcn.common_fadada.contraller; + +import aiyh.utils.ApiResult; +import aiyh.utils.Util; +import aiyh.utils.mapUtil.ParaMap; +import com.api.aiyh_pcn.common_fadada.service.CommonFaService; +import io.swagger.v3.oas.annotations.parameters.RequestBody; +import weaver.hrm.HrmUserVarify; +import weaver.hrm.User; + +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; +import javax.ws.rs.*; +import javax.ws.rs.core.Context; +import java.util.Map; + +/** + *

公共发大大请求方法

+ *

create 2022/4/14 10:25 AM

+ * + * @author ayh + */ + + +@Path("/fadada/common") +public class CommonFaController { + + private final CommonFaService service = new CommonFaService(); + + @Path("/create-contract") + @POST + public String createContract(@Context HttpServletRequest request, @Context HttpServletResponse response, + @RequestBody Map params) { + User user = HrmUserVarify.getUser(request, response); + Map result = service.createContract(user, params); + return ApiResult.success(result); + } + + @Path("/sign-contract") + @POST + public String signContract(@Context HttpServletRequest request, @Context HttpServletResponse response, + @RequestBody Map params) { + User user = HrmUserVarify.getUser(request, response); + Map result = service.signContract(user, params); + return ApiResult.success(result); + } + + @POST + @Path("/sign-oneself") + public String signOneself(@Context HttpServletRequest request, @Context HttpServletResponse response, + @RequestBody Map params) { + User user = HrmUserVarify.getUser(request, response); + Map result = service.signOneself(user, params); + return ApiResult.success(result); + } + + @POST + @Path("/download-contract") + public String downloadContract(@Context HttpServletRequest request, @Context HttpServletResponse response, + @RequestBody Map params) { + User user = HrmUserVarify.getUser(request, response); + Map result = service.downloadContract(user, params); + return ApiResult.success(result); + } + + @POST + @Path("/pigeonhole-contract") + public String pigeonholeContract(@Context HttpServletRequest request, @Context HttpServletResponse response, + @RequestBody Map params) { + User user = HrmUserVarify.getUser(request, response); + Map result = service.pigeonholeContract(user, params); + return ApiResult.success(result); + } + + @POST + @Path("/resign-contract") + @Produces("application/json") + @Consumes("application/json") + public String getContract(@Context HttpServletRequest request, @Context HttpServletResponse response, + @RequestBody Map params) { + User user = HrmUserVarify.getUser(request, response); + Map result; + try { + service.resignContract(user, params); + result = ParaMap.create().put("success", true).put("msg", "推送成功"); + } catch (Exception e) { + e.printStackTrace(); + result = ParaMap.create().put("success", false).put("msg", "推送失败"); + } + return ApiResult.success(result); + } + + @GET + @Path("/get-contract-button/{workflowId}/{markOnly}") + @Produces("application/json") + public String getContractStatus(@Context HttpServletRequest request, @Context HttpServletResponse response, + @PathParam("workflowId") String workflowId, + @PathParam("markOnly") String markOnly) { + Map result; + try { + result = service.getContractButton(workflowId,markOnly); + }catch (Exception e){ + Util.getLogger().error("查询流程添加节点配置出错:" + workflowId + " == " + markOnly + "\n" + Util.getErrString(e)); + result = ParaMap.create().put("allVersion",new String[]{}).put("allVersion",new String[]{}); + } + return ApiResult.success(result); + } +} diff --git a/src/main/youhong_ai_old_src/com/api/aiyh_pcn/common_fadada/mapper/ContractMapper.java b/src/main/youhong_ai_old_src/com/api/aiyh_pcn/common_fadada/mapper/ContractMapper.java new file mode 100644 index 0000000..afaf31f --- /dev/null +++ b/src/main/youhong_ai_old_src/com/api/aiyh_pcn/common_fadada/mapper/ContractMapper.java @@ -0,0 +1,49 @@ +package com.api.aiyh_pcn.common_fadada.mapper; + +import aiyh.utils.annotation.recordset.ParamMapper; +import aiyh.utils.annotation.recordset.SqlMapper; +import aiyh.utils.annotation.recordset.Update; + +/** + *

+ *

create 2022/4/14 10:44 PM

+ * + * @author ayh + */ + +@SqlMapper +public interface ContractMapper { + + + /** + * 更新合同号 + * + * @param tableName 表名 + * @param contractField 合同字段 + * @param contractNo 合同号 + * @param requestId 流程类型 + * @return 是否更新成功 + */ + @Update + boolean updateContractInMainTable(@ParamMapper("tableName") String tableName, + @ParamMapper("contractField") String contractField, + @ParamMapper("contractNo") String contractNo, + @ParamMapper("requestId") String requestId); + + + /** + * 更新合同号 + * + * @param tableName 表名 + * @param contractField 合同字段 + * @param contractNo 合同号 + * @param detailId 明细表ID + * @return 是否更新成功 + */ + @Update + boolean updateContractInDetailTable(@ParamMapper("tableName") String tableName, + @ParamMapper("contractField") String contractField, + @ParamMapper("contractNo") String contractNo, + @ParamMapper("detailId") String detailId); + +} diff --git a/src/main/youhong_ai_old_src/com/api/aiyh_pcn/common_fadada/service/CommonFaService.java b/src/main/youhong_ai_old_src/com/api/aiyh_pcn/common_fadada/service/CommonFaService.java new file mode 100644 index 0000000..87c7da8 --- /dev/null +++ b/src/main/youhong_ai_old_src/com/api/aiyh_pcn/common_fadada/service/CommonFaService.java @@ -0,0 +1,249 @@ +package com.api.aiyh_pcn.common_fadada.service; + +import aiyh.utils.Util; +import aiyh.utils.entity.WorkflowNodeConfig; +import aiyh.utils.excention.CustomerException; +import com.fasterxml.jackson.core.JsonProcessingException; +import com.google.common.base.Strings; +import org.jetbrains.annotations.Nullable; +import weaver.aiyh_pcn.common_fadada.action.PushContractInfoAction; +import weaver.aiyh_pcn.common_fadada.entity.FaResultEntity; +import weaver.aiyh_pcn.common_fadada.mapper.ActionMapper; +import weaver.aiyh_pcn.common_fadada.service.*; +import weaver.hrm.User; +import weaver.interfaces.workflow.action.Action; +import weaver.soa.workflow.request.RequestInfo; +import weaver.soa.workflow.request.RequestService; +import weaver.workflow.workflow.WorkflowVersion; + +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +/** + *

+ *

create 2022/4/14 1:55 PM

+ * + * @author ayh + */ + +public class CommonFaService { + private final ActionMapper mapper = Util.getMapper(ActionMapper.class); + + public Map createContract(User user, Map params) { + List resultList = null; + try { + resultList = requestFaDaDa(user, params, new CreateContractService()); + } catch (JsonProcessingException e) { + throw new CustomerException("合同创建失败!"); + } + String requestId = String.valueOf(params.get("requestId")); + String workflowId = String.valueOf(params.get("workflowId")); + String contractNoField = String.valueOf(params.get("contractNoField")); + String billTable = Util.getMainTable(workflowId); + for (FaResultEntity result : resultList) { + writeBackContractNo(result, contractNoField, requestId, billTable); + } + return null; + } + + private void writeBackContractNo(FaResultEntity result, String contractNoField, String requestId, String billTable) { + Map entityMap = null; + try { + entityMap = result.getResponeVo().getEntityMap(); + } catch (JsonProcessingException e) { + throw new CustomerException("获取合同号失败,JSON转换错误"); + } + Map data = (Map) entityMap.get("data"); + String contractNo = String.valueOf(data.get("contractNo")); + if (result.getType() == 1) { +// 回写主表 + boolean flag = mapper.updateContractInMainTable(billTable, contractNoField, contractNo, requestId); + if (!flag) { + throw new CustomerException("回写主表失败,更新语句执行false"); + } + return; + } +// 回写明细表 + mapper.updateContractInDetailTable(result.getDetailTable(), contractNoField, contractNo, String.valueOf(result.getDetailId())); + } + + + public Map pigeonholeContract(User user, Map params) { + List resultList = null; + try { + resultList = requestFaDaDa(user, params, new PigeonholeContractService()); + } catch (JsonProcessingException e) { + e.printStackTrace(); + } + for (FaResultEntity result : resultList) { + Map entityMap = null; + try { + entityMap = result.getResponeVo().getEntityMap(); + } catch (JsonProcessingException e) { + throw new CustomerException("合同归档失败!"); + } + String code = String.valueOf(entityMap.get("code")); + if (!"200".equals(code)) { + throw new CustomerException("合同归档失败!"); + } + } +// String requestId = String.valueOf(params.get("requestId")); +// Util.submitWorkflow(Integer.valueOf(requestId), 1, "流程自动提交!"); + return null; + } + + public Map downloadContract(User user, Map params) { + List resultList = null; + try { + resultList = requestFaDaDa(user, params, new DownloadContractService()); + } catch (JsonProcessingException e) { + e.printStackTrace(); + } + String requestId = String.valueOf(params.get("requestId")); + String workflowId = String.valueOf(params.get("workflowId")); + String contractField = String.valueOf(params.get("contractField")); + int userId = user.getUID(); + for (FaResultEntity result : resultList) { + Map entityMap = null; + try { + entityMap = result.getResponeVo().getEntityMap(); + } catch (JsonProcessingException e) { + throw new CustomerException("合同签署失败!"); + } + String code = String.valueOf(entityMap.get("code")); + if (!"200".equals(code)) { + throw new CustomerException("合同签署失败!"); + } +// 获取result中的responeVo中的imageFileId并命名为imageFileId + int imageFileId = result.getImageFileId(); +// 调用Util中的方法获取目录id + writeBackContractFile(String.valueOf(imageFileId),result,contractField,workflowId,requestId,userId); + } + return null; + } + + private boolean writeBackContractFile(String imgFileId,FaResultEntity result,String contractField ,String workflowId,String requestId,int userId) { + if (result.getType() == 1) { +// 回写到主表 + String docCategorys = Util.getDocCategorysByTable(workflowId, contractField,""); + String[] docCategoryArr = docCategorys.split(","); + int docId = 0; + try { + docId = Util.createDocByImageFileId(Integer.parseInt(docCategoryArr[docCategoryArr.length - 1]), Integer.parseInt(imgFileId),userId); + } catch (Exception e) { + throw new CustomerException("生成文档信息失败"); + } + String billTable = Util.getWorkflowMainTable(workflowId); + return mapper.updateContractInMainTable(billTable, contractField, String.valueOf(docId), requestId); + } + // 回写明细表 + String docCategorys = Util.getDocCategorysByTable(workflowId, contractField, result.getDetailTable()); + String[] docCategoryArr = docCategorys.split(","); + int docId = 0; + try { + docId = Util.createDocByImageFileId(Integer.parseInt(docCategoryArr[docCategoryArr.length - 1]), Integer.parseInt(imgFileId),userId); + } catch (Exception e) { + throw new CustomerException("生成文档信息失败"); + } + return mapper.updateContractInDetailTable(result.getDetailTable(), contractField, String.valueOf(docId), String.valueOf(result.getDetailId())); + } + + public Map signOneself(User user, Map params) { + List resultList = null; + try { + resultList = requestFaDaDa(user, params, new OneselfSignContractService()); + } catch (JsonProcessingException e) { + throw new CustomerException("合同签署失败!"); + } + for (FaResultEntity result : resultList) { + Map entityMap = null; + try { + entityMap = result.getResponeVo().getEntityMap(); + } catch (JsonProcessingException e) { + throw new CustomerException("合同签署失败!"); + } + String code = String.valueOf(entityMap.get("code")); + if (!"200".equals(code)) { + throw new CustomerException("合同签署失败!"); + } + } +// String requestId = String.valueOf(params.get("requestId")); +// Util.submitWorkflow(Integer.valueOf(requestId),1,"流程自动提交!"); + return null; + } + + public Map signContract(User user, Map params) { + List resultList = null; + try { + resultList = requestFaDaDa(user, params, new SignContractService()); + } catch (JsonProcessingException e) { + e.printStackTrace(); + } + for (FaResultEntity result : resultList) { + Map entityMap = null; + try { + entityMap = result.getResponeVo().getEntityMap(); + } catch (JsonProcessingException e) { + throw new CustomerException("合同签署失败!"); + } + String code = String.valueOf(entityMap.get("code")); + if (!"200".equals(code)) { + throw new CustomerException("合同签署失败!"); + } + } + return null; + } + + @Nullable + private List requestFaDaDa(User user, Map params, IFaIntegration utilService) throws JsonProcessingException { + String requestId = String.valueOf(params.get("requestId")); + String workflowId = String.valueOf(params.get("workflowId")); + int userId = user.getUID(); + return utilService.execute(workflowId, requestId, userId); + } + + /** + * 重新推送合同数据到d-flow + * @param user 当前用户 + * @param params 请求参数 + */ + public void resignContract(User user, Map params) { + String requestId = Util.null2DefaultStr(params.get("requestId"), ""); + String dealersConfigMark = Util.null2String(params.get("dealersConfigMark")); + String apiKey = Util.null2String(params.get("apiKey")); + if(Strings.isNullOrEmpty(requestId) || Strings.isNullOrEmpty(dealersConfigMark) || Strings.isNullOrEmpty(apiKey)) { + throw new CustomerException("请求参数不能为空!"); + } + RequestService requestService = new RequestService(); + RequestInfo req = requestService.getRequest(Integer.parseInt(requestId)); + req.getRequestManager().setUser(user); + PushContractInfoAction pushContractInfoAction = new PushContractInfoAction(); + pushContractInfoAction.setApikey(apiKey); + pushContractInfoAction.setDealersConfigMark(dealersConfigMark); + try { + String execute = pushContractInfoAction.execute(req); + if(Action.FAILURE_AND_CONTINUE.equals(execute)) { + throw new CustomerException("重新推送合同数据到d-flow失败!"); + } + }catch (Exception e){ + throw new CustomerException("重新推送合同数据到d-flow失败!",e); + } + } + + public Map getContractButton(String workflowId,String markOnly) { + String allVersion = WorkflowVersion.getVersionStringByWfid(workflowId); + WorkflowNodeConfig workflowNodeConfig = Util.selectNodeConfig(allVersion,markOnly); + Util.getLogger().info("查询到的数据:" + workflowNodeConfig); + if(workflowNodeConfig == null){ + return null; + } + String workflowType = workflowNodeConfig.getWorkflowType(); + allVersion = WorkflowVersion.getVersionStringByWfid(workflowType); + Map map = new HashMap<>(8); + map.put("nodes", workflowNodeConfig.getWorkflowNodes().split(",")); + map.put("allVersion", allVersion.split(",")); + Util.getLogger().info("最终数据:" + map); + return map; + } +} diff --git a/src/main/youhong_ai_old_src/com/api/aiyh_pcn/copy_attachment/dao/ConfigTableData.java b/src/main/youhong_ai_old_src/com/api/aiyh_pcn/copy_attachment/dao/ConfigTableData.java new file mode 100644 index 0000000..efa90a8 --- /dev/null +++ b/src/main/youhong_ai_old_src/com/api/aiyh_pcn/copy_attachment/dao/ConfigTableData.java @@ -0,0 +1,101 @@ +package com.api.aiyh_pcn.copy_attachment.dao; + +import aiyh.utils.zwl.common.ToolUtil; +import com.api.aiyh_pcn.copy_attachment.model.ConfigEmpty; +import weaver.conn.RecordSet; +import weaver.general.Util; + +/** + * @author EBU7-dev1-ayh + * @create 2021/8/26 0026 18:21 + * config + */ + + +public class ConfigTableData { + + public static ConfigEmpty getConfig(String workflowId) { + ToolUtil toolUtil = new ToolUtil(); + RecordSet rs = new RecordSet(); +// 查询配置表,获取配置数据 + String querySql = "select ufta.id,ufta.workflow_type,wftva.fieldname as template_field, " + + "wftvb.fieldname as attachment_field,wftv.fieldname as show_field, wftvb.id as attachment_field_id, " + + "ufta.is_template_show,ufta.model_table_name, ufta.model_field,wsl.selectvalue as show_value, " + + "wftv.tablename as show_table_name,wftva.tablename as template_table_name,wftvb.tablename as attachment_table_name, " + + "wsla.selectvalue as hidden_value from uf_temp_attachment as ufta " + + "left join workflow_selectitem as wsl on wsl.id = ufta.show_value " + + "left join workflow_selectitem as wsla on wsla.id = ufta.hidden_value " + + "left join workflow_field_table_view as wftv on wftv.id = ufta.show_field " + + "left join workflow_field_table_view as wftva on wftva.id = ufta.template_field " + + "left join workflow_field_table_view as wftvb on wftvb.id = ufta.attachment_field " + + "where workflow_type in " + + "(select id from workflow_base where activeVersionID in " + + "(select activeVersionID from workflow_base where id = ?) or id = ?) and attachment_type = ?"; + rs.executeQuery(querySql, workflowId, workflowId,0); + if(rs.next()){ +// id + int id = Util.getIntValue(rs.getString("id")); +// 显示值 + int showValue = Util.getIntValue(rs.getString("show_value")); +// 隐藏值 + int hiddenValue = Util.getIntValue(rs.getString("hidden_value")); +// 流程id + String workflowType = rs.getString("workflow_type"); +// 模板字段 + String templateField = rs.getString("template_field"); +// 附件字段 + String attachmentField = rs.getString("attachment_field"); +// 是否用字段控制模板 + String isTemplateShow = rs.getString("is_template_show"); +// 模板建模表表名 + String modelTableName = rs.getString("model_table_name"); +// 控制模板显示与否的字段 + String showField = rs.getString("show_field"); +// 建模表福建模板字段 + String modelField = rs.getString("model_field"); +// 控制显示所在表 + String showTableName = rs.getString("show_table_name"); +// 模板字段所在表 + String templateTableName = rs.getString("template_table_name"); +// 附件字段所在表 + String attachmentTableName = rs.getString("attachment_table_name"); +// 附件字段id + String attachmentFieldId = rs.getString("attachment_field_id"); + toolUtil.writeDebuggerLog("已经查询到数据!"); + return ConfigEmpty.create() + .id(id) + .showValue(showValue) + .hiddenValue(hiddenValue) + .workflowType(workflowType) + .templateField(templateField) + .attachmentField(attachmentField) + .isTemplateShow(isTemplateShow) + .modelTableName(modelTableName) + .showField(showField) + .modelField(modelField) + .showTableName(showTableName) + .templateTableName(templateTableName) + .attachmentTableName(attachmentTableName) + .attachmentFieldId(attachmentFieldId) + .builder(); + } + return null; + } + + + public static String[] getTemplateData(String tableName, String fieldName, String configId){ + RecordSet rs = new RecordSet(); + String queryBuilder = "select " + fieldName + + " from " + + tableName + + " where id = ?"; + ToolUtil toolUtil = new ToolUtil(); + rs.executeQuery(queryBuilder,configId); + if(rs.next()){ + String docIds = Util.null2String(rs.getString(1)); + return docIds.split(","); + } + return new String[0]; + } + +} diff --git a/src/main/youhong_ai_old_src/com/api/aiyh_pcn/copy_attachment/dao/DocTemplateDao.java b/src/main/youhong_ai_old_src/com/api/aiyh_pcn/copy_attachment/dao/DocTemplateDao.java new file mode 100644 index 0000000..9826126 --- /dev/null +++ b/src/main/youhong_ai_old_src/com/api/aiyh_pcn/copy_attachment/dao/DocTemplateDao.java @@ -0,0 +1,158 @@ +package com.api.aiyh_pcn.copy_attachment.dao; + +import aiyh.utils.Util; +import aiyh.utils.sqlUtil.sqlResult.impl.PrepSqlResultImpl; +import aiyh.utils.sqlUtil.whereUtil.Where; +import aiyh.utils.zwl.common.ToolUtil; +import org.apache.axiom.util.base64.Base64Utils; +import org.apache.commons.io.IOUtils; +import weaver.conn.RecordSet; +import weaver.docs.docs.DocManager; +import weaver.file.ImageFileManager; +import weaver.hrm.User; +import weaver.hrm.resource.ResourceComInfo; +import weaver.soa.workflow.FileProcessor; + +import java.io.IOException; +import java.io.InputStream; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; +import java.util.Map; + +/** + * @author EBU7-dev1-ayh + * @create 2021/8/26 0026 11:14 + * copy mybatisTest.dao + */ + + +public class DocTemplateDao { + ToolUtil toolUtil = new ToolUtil(); + private int userId; + + public int[] copyFile(User user,String tableName, String fieldName, String configId,String workflowId, String fileFieldId){ + this.userId = user.getUID(); + String[] templateData = ConfigTableData.getTemplateData(tableName, fieldName, configId); + String joinId = String.join(",", templateData); +// 查询物理文件id + String query = "select imagefileid,imagefilename from docimagefile where docid in (" + joinId + ")"; + RecordSet rs = new RecordSet(); + rs.executeQuery(query); + FileProcessor fileProcessor = new FileProcessor(); + String docCategorys = Util.getDocCategorys(workflowId, fileFieldId); + List docIds = new ArrayList<>(); + while (rs.next()){ +// 获取物理文件id和物理文件名 + String id = rs.getString("imagefileid"); + String name = rs.getString("imagefilename"); + InputStream inputStreamById = ImageFileManager.getInputStreamById(Integer.parseInt(id)); + byte[] bytes = new byte[0]; + try { + bytes = IOUtils.toByteArray(inputStreamById); + } catch (IOException e) { + e.printStackTrace(); + toolUtil.writeErrorLog("复制文件时,文件转为base64出错,文件转换出错!" + e); + } + String base64 = Base64Utils.encode(bytes); + int docid = fileProcessor.Process("base64:" + base64, docCategorys, user, name); + docIds.add(docid); + } + Integer[] strings = docIds.toArray(new Integer[0]); + return Arrays.stream(strings).mapToInt(Integer::valueOf).toArray(); +// return ; + } + + public int[] copyFile(int userId, String tableName, String fieldName, String configId) { + this.userId = userId; + String[] templateData = ConfigTableData.getTemplateData(tableName, fieldName, configId); + int[] array = Arrays.stream(templateData).mapToInt(Integer::parseInt).toArray(); + return this.copyFile(array); + } + + private int[] copyFile(int... ids) { + RecordSet rs = new RecordSet(); +// 传入需要拷贝的附件的id + DocManager docManager = new DocManager(); + int[] docIds = new int[ids.length]; + try { + for (int i = 0; i < ids.length; i++) { + // 设置需要拷贝的附件的id + docManager.setId(ids[i]); + // 进行附件的拷贝 + docManager.copyDocNew(); + // 获取到新拷贝的附件的id + docIds[i] = docManager.getId(); +// 对新文档进行权限重置 + rs.executeProc("DocSecCategoryShare_SBySecCate", String.valueOf(docManager.getId())); + } + return docIds; + } catch (Exception e) { + this.toolUtil.writeErrorLog("复制错误" + e); + return null; + } + } + + public boolean updateFileInfo(String workflowId, String fileFieldId, int... ids) { + RecordSet rs = new RecordSet(); +// 通过流程查询到该流程对应的目录 + String query = "select catelogType, (case when catelogType = 9 then " + + "(select docCategory from workflow_base where id = ?) else docCategory end )" + + " as docCategory from workflow_fileupload " + + "where workflowid = ? and fieldid = ?"; + + rs.executeQuery(query, workflowId, workflowId, fileFieldId); + String catelogType = ""; + String docCategory = ""; + if (rs.next()) { + catelogType = rs.getString("catelogType"); + docCategory = rs.getString("docCategory"); + } + this.toolUtil.writeDebuggerLog(catelogType + "," + docCategory); + if (!"1".equals(catelogType)) { + List list = new ArrayList<>(); + for (int id : ids) { + list.add(id); + } + ResourceComInfo resourceComInfo = null; + try { + resourceComInfo = new ResourceComInfo(); + } catch (Exception e) { + e.printStackTrace(); + } + String departmentID = resourceComInfo.getDepartmentID(String.valueOf(this.userId)); +// 附件目录不为自己选择,更新文件的目录信息和其他信息 + Map updateMap = Util.createUtilHashMap().uPut("ownerid", this.userId) + .uPut("maincategory", 0) + .uPut("subcategory", 0) + .uPut("docstatus", 0) + .uPut("shareroleid", this.userId) + .uPut("doccreaterid", this.userId) + .uPut("doclastmoduserid", this.userId) + .uPut("docdepartmentid", departmentID) + .uPut("doclastmoddate", Util.getTime("yyyy-MM-dd")) + .uPut("doccreatedate", Util.getTime("yyyy-MM-dd")) + .uPut("doclastmodtime", Util.getTime("HH:mm:ss")) + .uPut("doccreatetime", Util.getTime("HH:mm:ss")) + .uPut("seccategory", docCategory.split(",")[docCategory.split(",").length - 1]); + Where whereIn = Util.createPrepWhereImpl().whereAnd("id").whereInList(list); + PrepSqlResultImpl updateResult = Util.createSqlBuilder().updateSql("docdetail", updateMap, whereIn); + return rs.executeUpdate(updateResult.getSqlStr(), updateResult.getArgs()); + } + return false; + } + + public boolean deleteFile(int... ids) throws Exception { + DocManager docManager = new DocManager(); + for (int id : ids) { + try { + docManager.setId(id); + docManager.DeleteDocInfo(); + } catch (Exception e) { + e.printStackTrace(); + throw e; + } + } + return true; + } +} diff --git a/src/main/youhong_ai_old_src/com/api/aiyh_pcn/copy_attachment/model/ConfigEmpty.java b/src/main/youhong_ai_old_src/com/api/aiyh_pcn/copy_attachment/model/ConfigEmpty.java new file mode 100644 index 0000000..d61f3e4 --- /dev/null +++ b/src/main/youhong_ai_old_src/com/api/aiyh_pcn/copy_attachment/model/ConfigEmpty.java @@ -0,0 +1,257 @@ +package com.api.aiyh_pcn.copy_attachment.model; + +/** + * @author EBU7-dev1-ayh + * @create 2021/8/26 0026 19:48 + */ + + +public class ConfigEmpty { + /** + * id + */ + private int id; + /** + * 流程id + */ + private String workflowType; + /** + * 模板字段 + */ + private String templateField; + /** + * 附件字段 + */ + private String attachmentField; + /** + * 是否控制模板字段 + */ + private String isTemplateShow; + /** + * 控制模板字段字段 + */ + private String showField; + /** + * 显示模板值 + */ + private int showValue; + /** + * 隐藏模板值 + */ + private int hiddenValue; + /** + * 模板表表名 + */ + private String modelTableName; + /** + * 模板表附件字段 + */ + private String modelField; + /** + * 控制模板字段字段所在表 + */ + private String showTableName; + /** + * 模板字段所在表 + */ + private String templateTableName; + /** + * 附件字段所在表 + */ + private String attachmentTableName; + /** + * 附件字段id + */ + private String attachmentFieldId; + + + + public ConfigEmpty(Builder builder) { + this.id = builder.id; + this.workflowType = builder.workflowType; + this.templateField = builder.templateField; + this.attachmentField = builder.attachmentField; + this.isTemplateShow = builder.isTemplateShow; + this.showField = builder.showField; + this.showValue = builder.showValue; + this.hiddenValue = builder.hiddenValue; + this.modelTableName = builder.modelTableName; + this.modelField = builder.modelField; + this.showTableName = builder.showTableName; + this.templateTableName = builder.templateTableName; + this.attachmentTableName = builder.attachmentTableName; + this.attachmentFieldId = builder.attachmentFieldId; + } + + @Override + public String toString() { + return "ConfigEmpty{" + + "id=" + id + + ", workflowType='" + workflowType + '\'' + + ", templetField='" + templateField + '\'' + + ", attachmentField='" + attachmentField + '\'' + + ", isTempletShow='" + isTemplateShow + '\'' + + ", showField='" + showField + '\'' + + ", showValue=" + showValue + + ", hiddenValue=" + hiddenValue + + ", modelTableName='" + modelTableName + '\'' + + ", modelField='" + modelField + '\'' + + ", showTableName='" + showTableName + '\'' + + ", templateTableName='" + templateTableName + '\'' + + ", attachmentTableName='" + attachmentTableName + '\'' + + ", attachmentFieldId='" + attachmentFieldId + '\'' + + '}'; + } + + public String getAttachmentFieldId() { + return attachmentFieldId; + } + + public int getId() { + return id; + } + + public String getWorkflowType() { + return workflowType; + } + + public String getTemplateField() { + return templateField; + } + + public String getAttachmentField() { + return attachmentField; + } + + public String getIsTemplateShow() { + return isTemplateShow; + } + + public String getShowField() { + return showField; + } + + public int getShowValue() { + return showValue; + } + + public int getHiddenValue() { + return hiddenValue; + } + + public String getModelTableName() { + return modelTableName; + } + + public String getModelField() { + return modelField; + } + + public String getShowTableName() { + return showTableName; + } + + public String attachmentFieldId() { + return attachmentFieldId; + } + + public String getTemplateTableName() { + return templateTableName; + } + + public String getAttachmentTableName() { + return attachmentTableName; + } + + public static Builder create(){ + return new Builder(); + } + + public static class Builder{ + private int id; + private String workflowType; + private String templateField; + private String attachmentField; + private String isTemplateShow; + private String showField; + private int showValue; + private int hiddenValue; + private String modelTableName; + private String modelField; + String showTableName; + String templateTableName; + String attachmentTableName; + String attachmentFieldId; + + public ConfigEmpty builder(){ + return new ConfigEmpty(this); + } + + public Builder id(int id) { + this.id = id; + return this; + } + public Builder showTableName(String showTableName) { + this.showTableName = showTableName; + return this; + } + public Builder templateTableName(String templateTableName) { + this.templateTableName = templateTableName; + return this; + } + public Builder attachmentTableName(String attachmentTableName) { + this.attachmentTableName = attachmentTableName; + return this; + } + + public Builder attachmentFieldId(String attachmentFieldId) { + this.attachmentFieldId = attachmentFieldId; + return this; + } + + public Builder workflowType(String workflowType) { + this.workflowType = workflowType; + return this; + } + + public Builder templateField(String templateField) { + this.templateField = templateField; + return this; + } + + public Builder attachmentField(String attachmentField) { + this.attachmentField = attachmentField; + return this; + } + + public Builder isTemplateShow(String isTemplateShow) { + this.isTemplateShow = isTemplateShow; + return this; + } + + public Builder showField(String showField) { + this.showField = showField; + return this; + } + + public Builder showValue(int showValue) { + this.showValue = showValue; + return this; + } + + public Builder hiddenValue(int hiddenValue) { + this.hiddenValue = hiddenValue; + return this; + } + + public Builder modelTableName(String modelTableName) { + this.modelTableName = modelTableName; + return this; + } + + public Builder modelField(String modelField) { + this.modelField = modelField; + return this; + } + } +} diff --git a/src/main/youhong_ai_old_src/com/api/aiyh_pcn/copy_attachment/service/CopyAttachmentService.java b/src/main/youhong_ai_old_src/com/api/aiyh_pcn/copy_attachment/service/CopyAttachmentService.java new file mode 100644 index 0000000..2a42a12 --- /dev/null +++ b/src/main/youhong_ai_old_src/com/api/aiyh_pcn/copy_attachment/service/CopyAttachmentService.java @@ -0,0 +1,99 @@ +package com.api.aiyh_pcn.copy_attachment.service; + +import aiyh.utils.ApiResult; +import aiyh.utils.zwl.common.ToolUtil; +import com.api.aiyh_pcn.copy_attachment.dao.DocTemplateDao; +import com.api.workflow.constant.RequestAuthenticationConstant; +import com.engine.workflow.biz.requestForm.FileBiz; +import weaver.general.Util; +import weaver.hrm.User; + +import java.util.Arrays; +import java.util.HashMap; +import java.util.Map; + +/** + * @author EBU7-dev1-ayh + * @create 2021/8/27 0027 14:52 + * copyservice + */ + + +public class CopyAttachmentService { + public static String copyFile(User user, Map params) { + ToolUtil toolUtil = new ToolUtil(); +// 建模表名称 + String tableName = String.valueOf(params.get("tableName")); +// 建模字段名 + String fieldName = String.valueOf(params.get("fieldName")); +// 附件字段id + String fileFieldId = String.valueOf(params.get("fileFieldId")); +// 配置id + String configId = String.valueOf(params.get("configId")); +// 流程id + String workflowId = String.valueOf(params.get("workflowId")); + DocTemplateDao docTemplateDao = new DocTemplateDao(); + int[] docIds = null; + try { +// docIds = docTemplateDao.copyFile(user.getUID(), tableName, fieldName, configId); + docIds = docTemplateDao.copyFile(user, tableName, fieldName, configId, workflowId, fileFieldId); + } catch (Exception e) { + toolUtil.writeErrorLog("复制文件出错: " + e); + return ApiResult.error("复制文件出错!"); + } + if (docIds == null) { + return ApiResult.error("未查询到附件模板!"); + } + /*try{ + docTemplateDao.updateFileInfo(workflowId,fileFieldId,docIds); + }catch(Exception e){ + toolUtil.writeErrorLog("复制文件更新权限和目录出错: " + e); + return null; + }*/ + toolUtil.writeDebuggerLog("数据更新成功!" + Arrays.toString(docIds)); + return ApiResult.success(docIds); + } + + public static String deleteFile(String docIdStr) { + String[] docIds = docIdStr.split(","); + DocTemplateDao docTemplateDao = new DocTemplateDao(); + int[] array = Arrays.stream(docIds).mapToInt(Integer::parseInt).toArray(); + try { + docTemplateDao.deleteFile(array); + } catch (Exception e) { + e.printStackTrace(); + return ApiResult.error("删除失败!"); + } + return ApiResult.success(array, "删除成功!"); + } + + /** + * 查询文档信息 + * + * @param user user对象 + * @param params 前端参数 + * @return 文档信息 + */ + public static String queryFilesData(User user, Map params) { + String listType = Util.null2String(String.valueOf(params.get("listType")), "list"); + int requestid = Util.getIntValue(Util.null2String(String.valueOf(params.get("requestid"))), -1); + int desrequestid = Util.getIntValue(Util.null2String(String.valueOf(params.get("desrequestid"))), -1); + int isprint = Util.getIntValue(Util.null2String(String.valueOf(params.get("isprint"))), 0); + int workflowid = Util.getIntValue(Util.null2String(String.valueOf(params.get("workflowid"))), 0); + String f_weaver_belongto_userid = Util.null2String(String.valueOf(params.get("f_weaver_belongto_userid"))); + String f_weaver_belongto_usertype = Util.null2String(String.valueOf(params.get("f_weaver_belongto_usertype"))); + String authStr = Util.null2String(String.valueOf(params.get(RequestAuthenticationConstant.AUTHORITY_STRING))); + String authSignatureStr = Util.null2String(String.valueOf(params.get(RequestAuthenticationConstant.AUTHORITY_SIGNATURESTRING))); + Map paramsMap = new HashMap<>(); + paramsMap.put("user", user); + Map retobj; + try { + retobj = FileBiz.getFileDatas(Util.null2String(params.get("docIds")), listType, requestid, desrequestid, + isprint, f_weaver_belongto_userid, f_weaver_belongto_usertype, true, false, authStr, authSignatureStr, paramsMap); + } catch (Exception e) { + e.printStackTrace(); + return ApiResult.error("查询附件信息失败:" + e); + } + return ApiResult.success(retobj); + } +} diff --git a/src/main/youhong_ai_old_src/com/api/aiyh_pcn/copy_attachment/web/CopyAttachment.java b/src/main/youhong_ai_old_src/com/api/aiyh_pcn/copy_attachment/web/CopyAttachment.java new file mode 100644 index 0000000..b0b9040 --- /dev/null +++ b/src/main/youhong_ai_old_src/com/api/aiyh_pcn/copy_attachment/web/CopyAttachment.java @@ -0,0 +1,67 @@ +package com.api.aiyh_pcn.copy_attachment.web; + + +import aiyh.utils.ApiResult; +import aiyh.utils.zwl.common.ToolUtil; +import com.api.aiyh_pcn.copy_attachment.service.CopyAttachmentService; +import com.api.aiyh_pcn.copy_attachment.dao.ConfigTableData; +import io.swagger.v3.oas.annotations.parameters.RequestBody; +import weaver.hrm.HrmUserVarify; +import weaver.hrm.User; + +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; +import javax.ws.rs.*; +import javax.ws.rs.core.Context; +import javax.ws.rs.core.MediaType; +import java.util.Map; + +/** + * @author EBU7-dev1-ayh + * @create 2021/8/26 0026 10:16 + * copy ttachment to workflow + */ + + +@Path("/aiyh/copyAttachment") +public class CopyAttachment { + + ToolUtil toolUtil = new ToolUtil(); + + @POST + @Path("/copy") + @Consumes(MediaType.APPLICATION_JSON) + @Produces(MediaType.APPLICATION_JSON) + public String copyAttachment(@Context HttpServletRequest request, @Context HttpServletResponse response, + @RequestBody Map params) { + User user = HrmUserVarify.getUser(request, response); + return CopyAttachmentService.copyFile(user, params); + } + + @Path("/deleteFile/{docIds}") + @GET + @Consumes(MediaType.APPLICATION_JSON) + @Produces(MediaType.APPLICATION_JSON) + public String deleteFile(@Context HttpServletRequest request, @Context HttpServletResponse response, + @PathParam("docIds") String docIds) { + return CopyAttachmentService.deleteFile(docIds); + } + + @Path("/queryConfig/{workflowId}") + @GET + @Consumes(MediaType.APPLICATION_JSON) + @Produces(MediaType.APPLICATION_JSON) + public String queryConfig(@PathParam("workflowId") String workflowId) { + return ApiResult.success(ConfigTableData.getConfig(workflowId)); + } + + @Path("/queryFilesData") + @POST + @Consumes(MediaType.APPLICATION_JSON) + @Produces(MediaType.APPLICATION_JSON) + public String queryFilesData(@Context HttpServletRequest request, @Context HttpServletResponse response, + @RequestBody Map params) { + User user = HrmUserVarify.getUser(request, response); + return CopyAttachmentService.queryFilesData(user, params); + } +} diff --git a/src/main/youhong_ai_old_src/com/api/aiyh_pcn/copy_multiple_file/dto/CopyFileParam.java b/src/main/youhong_ai_old_src/com/api/aiyh_pcn/copy_multiple_file/dto/CopyFileParam.java new file mode 100644 index 0000000..631bcb8 --- /dev/null +++ b/src/main/youhong_ai_old_src/com/api/aiyh_pcn/copy_multiple_file/dto/CopyFileParam.java @@ -0,0 +1,29 @@ +package com.api.aiyh_pcn.copy_multiple_file.dto; + +import com.api.aiyh_pcn.copy_multiple_file.vo.MultipleCopyConfigDetailVO; +import lombok.Getter; +import lombok.Setter; +import lombok.ToString; + +import java.util.List; +import java.util.Map; + +/** + * create 2021/12/23 0023 11:42 + * 复制附件时,需要专递的参数 + * + * @author EBU7-dev1-ayh + */ + + +@Getter +@Setter +@ToString +public class CopyFileParam { + private int workflowType; + private int requestId; + private int browseValue; + private String modeTable; + private List fileMapperList; + private Map queryFileInfoMap; +} diff --git a/src/main/youhong_ai_old_src/com/api/aiyh_pcn/copy_multiple_file/enumType/EnableType.java b/src/main/youhong_ai_old_src/com/api/aiyh_pcn/copy_multiple_file/enumType/EnableType.java new file mode 100644 index 0000000..9efc99e --- /dev/null +++ b/src/main/youhong_ai_old_src/com/api/aiyh_pcn/copy_multiple_file/enumType/EnableType.java @@ -0,0 +1,9 @@ +package com.api.aiyh_pcn.copy_multiple_file.enumType; + +/** + * @author @author EBU7-dev1-ay + * create 2021/12/22 0022 16:34 + */ + +public enum EnableType { +} diff --git a/src/main/youhong_ai_old_src/com/api/aiyh_pcn/copy_multiple_file/mapper/MultipleCopyMapper.java b/src/main/youhong_ai_old_src/com/api/aiyh_pcn/copy_multiple_file/mapper/MultipleCopyMapper.java new file mode 100644 index 0000000..7450b82 --- /dev/null +++ b/src/main/youhong_ai_old_src/com/api/aiyh_pcn/copy_multiple_file/mapper/MultipleCopyMapper.java @@ -0,0 +1,61 @@ +package com.api.aiyh_pcn.copy_multiple_file.mapper; + +import aiyh.utils.annotation.recordset.*; +import com.api.aiyh_pcn.copy_multiple_file.pojo.CopyMultipleDetail; +import com.api.aiyh_pcn.copy_multiple_file.pojo.CopyMultipleMain; +import com.api.aiyh_pcn.copy_multiple_file.pojo.ImageFileInfo; + +import java.util.List; +import java.util.Map; + +/** + * @author EBU7-dev1-ayh + * create 2021/12/22 0022 16:18 + */ + +@SqlMapper +public interface MultipleCopyMapper { + + /** + * 查询配置表主表数据,通过全版本的workflowId + * @param workflowIds 全版本的workflowid + * @return 查询到的数据 + */ + @Select("select uf.id,uf.workflow_type,bv.tablename mode_table,wv.fieldname browse_box, " + + "uf.is_enable from uf_copy_multiple uf " + + "left join workflow_field_table_view wv on uf.browse_box = wv.id " + + "left join mode_bill_info_view bv on uf.mode_table = bv.id " + + "where workflow_type in (${workflowIds}) and uf.is_enable = 1") + public List selectMainData(@ParamMapper("workflowIds") String[] workflowIds); + + /** + * 查询配置表明细表数据 + * @param mainId 配置表主表id + * @return 明细表数据 + */ + @Select("select wv.fieldname workflow_file,wvm.fieldname mode_file,is_enable " + + "from uf_copy_multiple_dt1 uf " + + "left join workflow_field_table_view wv on wv.id = uf.workflow_file " + + "left join workflow_field_table_view wvm on wvm.id = uf.mode_file " + + "where mainid = #{mainId} and uf.is_enable = 1") + public List selectDetailData(@ParamMapper("mainId") Integer mainId); + + + /** + * 查询建模表中的附件信息 + * @param modeTable 建模表表名 + * @param browseValue 浏览库值 + * @return 建模表数据 + */ + @Select("select * from $t{modeTable} where id = #{browseValue}") + Map selectModelFiles(@ParamMapper("modeTable") String modeTable, + @ParamMapper("browseValue") int browseValue); + + /** + * 查询物理文件的信息 + * @param modeFileVal doc id字符串 + * @return 物理文件的信息 + */ + @Select("select imagefileid id,imagefilename image_file_name from docimagefile where docid in (${modeFileVal})") + List selectImageFileId(String[] modeFileVal); +} diff --git a/src/main/youhong_ai_old_src/com/api/aiyh_pcn/copy_multiple_file/pojo/CopyMultipleDetail.java b/src/main/youhong_ai_old_src/com/api/aiyh_pcn/copy_multiple_file/pojo/CopyMultipleDetail.java new file mode 100644 index 0000000..bcc52c1 --- /dev/null +++ b/src/main/youhong_ai_old_src/com/api/aiyh_pcn/copy_multiple_file/pojo/CopyMultipleDetail.java @@ -0,0 +1,16 @@ +package com.api.aiyh_pcn.copy_multiple_file.pojo; + +import lombok.Data; + +/** + * @author EBU7-dev1-ayh + * create 2021/12/22 0022 16:32 + */ + + +@Data +public class CopyMultipleDetail { + private String workflowFile; + private String modeFile; + private Integer isEnable; +} \ No newline at end of file diff --git a/src/main/youhong_ai_old_src/com/api/aiyh_pcn/copy_multiple_file/pojo/CopyMultipleMain.java b/src/main/youhong_ai_old_src/com/api/aiyh_pcn/copy_multiple_file/pojo/CopyMultipleMain.java new file mode 100644 index 0000000..94be1cc --- /dev/null +++ b/src/main/youhong_ai_old_src/com/api/aiyh_pcn/copy_multiple_file/pojo/CopyMultipleMain.java @@ -0,0 +1,20 @@ +package com.api.aiyh_pcn.copy_multiple_file.pojo; + +import lombok.Data; + +import java.util.List; + +/** + * @author EBU7-dev1-ayh + * create 2021/12/22 0022 16:32 + */ + +@Data +public class CopyMultipleMain { + private Integer id; + private Integer workflowType; + private String modeTable; + private String browseBox; + private Integer isEnable; + private List detailList; +} diff --git a/src/main/youhong_ai_old_src/com/api/aiyh_pcn/copy_multiple_file/pojo/ImageFileInfo.java b/src/main/youhong_ai_old_src/com/api/aiyh_pcn/copy_multiple_file/pojo/ImageFileInfo.java new file mode 100644 index 0000000..57d9cff --- /dev/null +++ b/src/main/youhong_ai_old_src/com/api/aiyh_pcn/copy_multiple_file/pojo/ImageFileInfo.java @@ -0,0 +1,20 @@ +package com.api.aiyh_pcn.copy_multiple_file.pojo; + +import lombok.Getter; +import lombok.Setter; +import lombok.ToString; + +/** + * create 2021/12/23 0023 18:33 + * + * @author EBU7-dev1-ayh + */ + + +@Getter +@Setter +@ToString +public class ImageFileInfo { + private Integer id; + private String imageFileName; +} diff --git a/src/main/youhong_ai_old_src/com/api/aiyh_pcn/copy_multiple_file/services/MultipleCopyService.java b/src/main/youhong_ai_old_src/com/api/aiyh_pcn/copy_multiple_file/services/MultipleCopyService.java new file mode 100644 index 0000000..2c3750a --- /dev/null +++ b/src/main/youhong_ai_old_src/com/api/aiyh_pcn/copy_multiple_file/services/MultipleCopyService.java @@ -0,0 +1,210 @@ +package com.api.aiyh_pcn.copy_multiple_file.services; + +import aiyh.utils.Util; +import aiyh.utils.zwl.common.ToolUtil; +import aiyh.utils.tool.cn.hutool.core.bean.BeanUtil; +import com.alibaba.fastjson.JSON; +import com.api.aiyh_pcn.copy_multiple_file.dto.CopyFileParam; +import com.api.aiyh_pcn.copy_multiple_file.mapper.MultipleCopyMapper; +import com.api.aiyh_pcn.copy_multiple_file.pojo.CopyMultipleDetail; +import com.api.aiyh_pcn.copy_multiple_file.pojo.CopyMultipleMain; +import com.api.aiyh_pcn.copy_multiple_file.pojo.ImageFileInfo; +import com.api.aiyh_pcn.copy_multiple_file.vo.CopyResult; +import com.api.aiyh_pcn.copy_multiple_file.vo.MultipleCopyConfigDetailVO; +import com.api.aiyh_pcn.copy_multiple_file.vo.MultipleCopyConfigVO; +import com.api.workflow.constant.RequestAuthenticationConstant; +import com.engine.workflow.biz.requestForm.FileBiz; +import org.apache.axiom.util.base64.Base64Utils; +import org.apache.commons.io.IOUtils; +import weaver.docs.docs.DocManager; +import weaver.file.ImageFileManager; +import weaver.hrm.User; +import weaver.soa.workflow.FileProcessor; +import weaver.workflow.workflow.WorkflowVersion; + +import java.io.IOException; +import java.io.InputStream; +import java.util.*; + +/** + * @author EBU7-dev1-ayh + * create 2021/12/22 0022 16:17 + */ + + +public class MultipleCopyService { + private final MultipleCopyMapper mapper; + private final ToolUtil toolUtil = new ToolUtil(); + + { + mapper = Util.getMapper(MultipleCopyMapper.class); + } + + /** + * 查询配置表信息 + * + * @param workflowId 当前查询流程的流程id + * @return 配置表信息 + */ + public List getConfigInfo(String workflowId) { + String versionIds = WorkflowVersion.getVersionStringByWfid(workflowId); +// 获取动态代理对象 +// 查询主表配置信息数据 + List copyMultipleMainList = this.mapper.selectMainData(versionIds.split(",")); + if (copyMultipleMainList == null) { + return null; + } +// 查询明细表配置信息数据 + List configResult = new ArrayList<>(); + for (CopyMultipleMain copyMultipleMain : copyMultipleMainList) { + List copyMultipleDetails = this.mapper.selectDetailData(copyMultipleMain.getId()); + copyMultipleMain.setDetailList(copyMultipleDetails); + MultipleCopyConfigVO multipleCopyConfigVO = new MultipleCopyConfigVO(); +// 进行数据拷贝 + BeanUtil.copyProperties(copyMultipleMain, multipleCopyConfigVO); + configResult.add(multipleCopyConfigVO); + } + + return configResult; + } + + + /** + * 复制文件附件文件,同时返回文件信息 + * + * @param user 当前操作用户 + * @param copyFileParam 复制文件所需要的参数信息 + * @return 复制后的新文档的信息 + */ + public List copyMultipleFile(User user, CopyFileParam copyFileParam) { + if (copyFileParam == null || copyFileParam.getFileMapperList().isEmpty() || copyFileParam.getBrowseValue() <= 0) { + return null; + } +// 查询模板文件 + toolUtil.writeDebuggerLog(copyFileParam.toString()); + Map modelFileMap = this.mapper.selectModelFiles(copyFileParam.getModeTable(), copyFileParam.getBrowseValue()); + if (modelFileMap == null) { + toolUtil.writeDebuggerLog("查询到参数为null "); + return null; + } + List fileMapperList = copyFileParam.getFileMapperList(); + List copyResultList = new ArrayList<>(); + for (MultipleCopyConfigDetailVO multipleCopyConfigDetailVO : fileMapperList) { +// 复制新的附件 + List docIdList = copyFileHandler(multipleCopyConfigDetailVO, modelFileMap, copyFileParam.getWorkflowType(), user); + CopyResult copyResult = new CopyResult(); +// TODO 解决bug 使用List 无法进行join + copyResult.setFileId(Util.intJoin(docIdList, ",")); + copyResult.setWorkflowFile(multipleCopyConfigDetailVO.getWorkflowFile()); +// 获取查询附件列表参数 + Map queryFileInfoMap = copyFileParam.getQueryFileInfoMap(); + queryFileInfoMap.put("docIds", copyResult.getFileId()); +// 查询附件列表参数 + Map fileInfoMap = queryFilesData(user, queryFileInfoMap); + if (fileInfoMap == null) { + toolUtil.writeErrorLog("查询文件信息出错,查询数据:" + JSON.toJSONString(queryFileInfoMap)); + throw new RuntimeException("查询文件信息出错!"); + } + copyResult.setFileInfo(fileInfoMap); + copyResultList.add(copyResult); + } + return copyResultList; + } + + + /** + * 复制文件的具体操作,复制出来的文档,权限根据流程字段所属的目录的权限进行初始化 + * + * @param multipleCopyConfigDetailVO 复制文件的明细配置信息 + * @param modelFileMap 复制文件的建模表的的查询数据(浏览框值对应的建模数据) + * @param workflowId 流程id + * @param user 当前用户 + * @return 复制文件后的全新的文档id + */ + public List copyFileHandler(MultipleCopyConfigDetailVO multipleCopyConfigDetailVO, + Map modelFileMap, int workflowId, + User user) { + toolUtil.writeDebuggerLog("配置明细表数据:" + multipleCopyConfigDetailVO); + toolUtil.writeDebuggerLog("查询到的文件模板数据信息:" + modelFileMap); + String modeFile = multipleCopyConfigDetailVO.getModeFile(); + String modeFileVal = Objects.isNull(modelFileMap.get(modeFile)) ? "" : String.valueOf(modelFileMap.get(modeFile)); + List imageFileInfos = mapper.selectImageFileId(modeFileVal.split(",")); + FileProcessor fileProcessor = new FileProcessor(); + String docCategorys = Util.getDocCategorys(workflowId, multipleCopyConfigDetailVO.getWorkflowFile()); + List docIdList = new ArrayList<>(); + for (ImageFileInfo imageFileInfo : imageFileInfos) { + InputStream inputStreamById = ImageFileManager.getInputStreamById(imageFileInfo.getId()); + byte[] bytes = new byte[0]; + try { + bytes = IOUtils.toByteArray(inputStreamById); + } catch (IOException e) { + e.printStackTrace(); + toolUtil.writeErrorLog("复制文件时,文件转为base64出错,文件转换出错!" + e); + } + String base64 = Base64Utils.encode(bytes); + int docId = fileProcessor.Process("base64:" + base64, docCategorys, user, imageFileInfo.getImageFileName()); + if (docId <= 0) { + toolUtil.writeErrorLog("复制文件时,文件Process复制出错!"); + return null; + } + docIdList.add(docId); + } + return docIdList; + } + + + /** + * 查询文件列表信息,用于前端进行附件上传浏览框赋值 + * + * @param user 当前用户 + * @param params 查询文件列表信息的查询参数 + * @return 文件信息对象 + */ + public Map queryFilesData(User user, Map params) { + String listType = Util.null2String(String.valueOf(params.get("listType")), "list"); + int requestId = Util.getIntValue(Util.null2String(String.valueOf(params.get("requestid"))), -1); + int desrequestId = Util.getIntValue(Util.null2String(String.valueOf(params.get("desrequestid"))), -1); + int isprint = Util.getIntValue(Util.null2String(String.valueOf(params.get("isprint"))), 0); + String weaverBelongtoUserid = Util.null2String(String.valueOf(params.get("f_weaver_belongto_userid"))); + String weaverBelongtoUsertype = Util.null2String(String.valueOf(params.get("f_weaver_belongto_usertype"))); + String authStr = Util.null2String(String.valueOf(params.get(RequestAuthenticationConstant.AUTHORITY_STRING))); + String authSignatureStr = Util.null2String(String.valueOf(params.get(RequestAuthenticationConstant.AUTHORITY_SIGNATURESTRING))); + Map paramsMap = new HashMap<>(); + paramsMap.put("user", user); + Map retobj; + try { + retobj = FileBiz.getFileDatas(Util.null2String(params.get("docIds")), listType, requestId, desrequestId, + isprint, weaverBelongtoUserid, weaverBelongtoUsertype, true, false, authStr, authSignatureStr, paramsMap); + } catch (Exception e) { + e.printStackTrace(); + return null; + } + return retobj; + } + + + /** + * 删除文件 + * + * @param docIds 需要删除的文件的docId + * @return 是否删除成功 + */ + public boolean deleteFile(String docIds) { + DocManager docManager = new DocManager(); + if (docIds == null) { + return false; + } + String[] split = docIds.split(","); + int[] array = Arrays.stream(split).mapToInt(Integer::parseInt).toArray(); + for (int id : array) { + try { + docManager.setId(id); + docManager.DeleteDocInfo(); + } catch (Exception e) { + toolUtil.writeErrorLog("文件删除错误:" + id); + return false; + } + } + return true; + } +} diff --git a/src/main/youhong_ai_old_src/com/api/aiyh_pcn/copy_multiple_file/vo/CopyResult.java b/src/main/youhong_ai_old_src/com/api/aiyh_pcn/copy_multiple_file/vo/CopyResult.java new file mode 100644 index 0000000..81c7a9d --- /dev/null +++ b/src/main/youhong_ai_old_src/com/api/aiyh_pcn/copy_multiple_file/vo/CopyResult.java @@ -0,0 +1,23 @@ +package com.api.aiyh_pcn.copy_multiple_file.vo; + +import lombok.Getter; +import lombok.Setter; +import lombok.ToString; + +import java.util.Map; + +/** + * create 2021/12/23 0023 12:11 + * + * @author EBU7-dev1-ayh + */ + + +@Getter +@Setter +@ToString +public class CopyResult { + private String workflowFile; + private String fileId; + private Map fileInfo; +} diff --git a/src/main/youhong_ai_old_src/com/api/aiyh_pcn/copy_multiple_file/vo/MultipleCopyConfigDetailVO.java b/src/main/youhong_ai_old_src/com/api/aiyh_pcn/copy_multiple_file/vo/MultipleCopyConfigDetailVO.java new file mode 100644 index 0000000..478f657 --- /dev/null +++ b/src/main/youhong_ai_old_src/com/api/aiyh_pcn/copy_multiple_file/vo/MultipleCopyConfigDetailVO.java @@ -0,0 +1,14 @@ +package com.api.aiyh_pcn.copy_multiple_file.vo; + +import lombok.Data; + +/** + * @author EBU7-dev1-ayh + * create 2021/12/22 0022 18:08 + */ + +@Data +public class MultipleCopyConfigDetailVO { + private String workflowFile; + private String modeFile; +} diff --git a/src/main/youhong_ai_old_src/com/api/aiyh_pcn/copy_multiple_file/vo/MultipleCopyConfigVO.java b/src/main/youhong_ai_old_src/com/api/aiyh_pcn/copy_multiple_file/vo/MultipleCopyConfigVO.java new file mode 100644 index 0000000..ddaeb33 --- /dev/null +++ b/src/main/youhong_ai_old_src/com/api/aiyh_pcn/copy_multiple_file/vo/MultipleCopyConfigVO.java @@ -0,0 +1,19 @@ +package com.api.aiyh_pcn.copy_multiple_file.vo; + +import lombok.Data; + +import java.util.List; + +/** + * create 2021/12/22 0022 18:06 + * + * @author EBU7-dev1-ayh + */ + +@Data +public class MultipleCopyConfigVO { + private Integer workflowType; + private String modeTable; + private String browseBox; + private List detailList; +} diff --git a/src/main/youhong_ai_old_src/com/api/aiyh_pcn/copy_multiple_file/web/MultipleCopyController.java b/src/main/youhong_ai_old_src/com/api/aiyh_pcn/copy_multiple_file/web/MultipleCopyController.java new file mode 100644 index 0000000..166241c --- /dev/null +++ b/src/main/youhong_ai_old_src/com/api/aiyh_pcn/copy_multiple_file/web/MultipleCopyController.java @@ -0,0 +1,109 @@ +package com.api.aiyh_pcn.copy_multiple_file.web; + +import aiyh.utils.ApiResult; +import aiyh.utils.Util; +import aiyh.utils.zwl.common.ToolUtil; +import com.api.aiyh_pcn.copy_multiple_file.dto.CopyFileParam; +import com.api.aiyh_pcn.copy_multiple_file.services.MultipleCopyService; +import com.api.aiyh_pcn.copy_multiple_file.vo.CopyResult; +import com.api.aiyh_pcn.copy_multiple_file.vo.MultipleCopyConfigVO; +import io.swagger.v3.oas.annotations.parameters.RequestBody; +import weaver.hrm.HrmUserVarify; +import weaver.hrm.User; + +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; + +import javax.ws.rs.*; +import javax.ws.rs.core.Context; +import javax.ws.rs.core.MediaType; +import java.util.List; + +/** + * @author EBU7-dev1-ayh + * create 2021/12/22 0022 11:12 + */ + + +@Path("/aiyh/browseBox/copyMultipleFile") +public class MultipleCopyController { + + private final MultipleCopyService multipleCopyService = new MultipleCopyService(); + private final ToolUtil toolUtil = new ToolUtil(); + + + /** + * 根据workflowId查询配置信息 + * + * @param workflowId 流程id + * @return 配置信息 + */ + @Path("/getConfig/{workflowId}") + @GET + @Consumes(MediaType.APPLICATION_JSON) + @Produces(MediaType.APPLICATION_JSON) + public String getConfigInfo(@PathParam("workflowId") String workflowId) { + try { + List configInfo = multipleCopyService.getConfigInfo(workflowId); + return ApiResult.success(configInfo); + } catch (Exception e) { + toolUtil.writeErrorLog(Util.getErrString(e)); + return ApiResult.error(e.toString()); + } + } + + + /** + * 复制模板文件为新的文件附件 + * + * @param request 请求对象 + * @param response 响应对象 + * @param copyFileParam 复制文件所需要的参数信息 + * @return 复制后的附件的列表信息 + */ + @Path("/copy") + @POST + @Consumes(MediaType.APPLICATION_JSON) + @Produces(MediaType.APPLICATION_JSON) + public String copyMultipleFile(@Context HttpServletRequest request, + @Context HttpServletResponse response, + @RequestBody CopyFileParam copyFileParam) { + User user = HrmUserVarify.getUser(request, response); + try { + List result = multipleCopyService.copyMultipleFile(user, copyFileParam); + return ApiResult.success(result); + } catch (Exception e) { + toolUtil.writeErrorLog(Util.getErrString(e)); + return ApiResult.error(e.toString()); + } + } + + /** + * 删除文件 + * + * @param docIds 需要删除的文件id + * @return 是否删除成功 + */ + @Path("/delete/{docIds}") + @GET + @Consumes(MediaType.APPLICATION_JSON) + @Produces(MediaType.APPLICATION_JSON) + public String deleteMultipleFile(@PathParam("docIds") String docIds) { + try { + boolean b = multipleCopyService.deleteFile(docIds); + return ApiResult.success(b); + } catch (Exception e) { + toolUtil.writeErrorLog("删除文件时出错! " + e); + return ApiResult.error("删除文件出错!"); + } + } + + @GET + @Path("/getTest") + @Produces(MediaType.APPLICATION_JSON) + @Consumes(MediaType.APPLICATION_JSON) + public String testGet() { + return ApiResult.success("能访问到的!"); + } + +} diff --git a/src/main/youhong_ai_old_src/com/api/aiyh_pcn/dealers_contract/DealersContractController.java b/src/main/youhong_ai_old_src/com/api/aiyh_pcn/dealers_contract/DealersContractController.java new file mode 100644 index 0000000..1c6d66a --- /dev/null +++ b/src/main/youhong_ai_old_src/com/api/aiyh_pcn/dealers_contract/DealersContractController.java @@ -0,0 +1,52 @@ +package com.api.aiyh_pcn.dealers_contract; + +import aiyh.utils.Util; +import com.alibaba.fastjson.JSON; +import io.swagger.v3.oas.annotations.parameters.RequestBody; + +import javax.ws.rs.Consumes; +import javax.ws.rs.POST; +import javax.ws.rs.Path; +import javax.ws.rs.Produces; +import javax.ws.rs.core.MediaType; +import java.util.HashMap; +import java.util.Map; + +/** + *

+ *

create 2022/4/19 2:39 PM

+ * + * @author ayh + */ + +@Path("/v3/fadada") +public class DealersContractController { + + private final DealersContractService dealersContractService = new DealersContractService(); + + + @Path("/d-flow/callback-contract") + @POST + @Consumes(MediaType.APPLICATION_JSON) + @Produces(MediaType.APPLICATION_JSON) + public String callback(@RequestBody Map params) { + Map result = new HashMap<>(16); + try { + Util.getLogger().info("callback params:" + JSON.toJSONString(params)); + dealersContractService.callback(params); + Util.getLogger().info("处理回调请求完成!"); + result.put("code", 1); + result.put("errorMessage", "success"); + result.put("callbackStatus", "success"); + Util.getLogger().info("回调处理成功!======================================"); + } catch (Exception e) { + Util.getLogger().error("处理请求失败了,开始准备返回消息!"); + result.put("code", 0); + result.put("errorMessage", e.getMessage()); + result.put("callbackStatus", "fail"); + Util.getLogger().error("回调处理失败==========================================" + Util.getErrString(e)); + } + return JSON.toJSONString(result); + } + +} diff --git a/src/main/youhong_ai_old_src/com/api/aiyh_pcn/dealers_contract/DealersContractMapper.java b/src/main/youhong_ai_old_src/com/api/aiyh_pcn/dealers_contract/DealersContractMapper.java new file mode 100644 index 0000000..99f1c37 --- /dev/null +++ b/src/main/youhong_ai_old_src/com/api/aiyh_pcn/dealers_contract/DealersContractMapper.java @@ -0,0 +1,35 @@ +package com.api.aiyh_pcn.dealers_contract; + +import aiyh.utils.annotation.recordset.*; + +import java.util.Map; + +/** + *

mappr

+ *

create 2022/4/19 3:51 PM

+ * + * @author ayh + */ + +@SqlMapper +public interface DealersContractMapper { + + @Select("select * from uf_contract_log where contract_id = #{contractId}") + @CaseConversion(false) + Map selectContractInfo(@ParamMapper("contractId") String contractId); + + @Update(custom = true) + boolean updateContractSignStatus(@SqlString String sql, Map updateMap); + + @Select("select $t{submitStatusField} from $t{workflowTable} where requestid = #{requestId}") + Integer selectSubmitStatus(@ParamMapper("workflowTable") String workflowTable, + @ParamMapper("submitStatusField") String submitStatusField, + @ParamMapper("requestId") String requestId); + + @Update("update $t{workflowTable} set $t{submitStatusField} = #{status} where requestid = #{requestId}") + boolean updateSubmitStatus(@ParamMapper("workflowTable") String workflowTable, + @ParamMapper("submitStatusField") String submitStatusField, + @ParamMapper("requestId") String requestId, + @ParamMapper("status") int status); +} + diff --git a/src/main/youhong_ai_old_src/com/api/aiyh_pcn/dealers_contract/DealersContractService.java b/src/main/youhong_ai_old_src/com/api/aiyh_pcn/dealers_contract/DealersContractService.java new file mode 100644 index 0000000..d8e59a6 --- /dev/null +++ b/src/main/youhong_ai_old_src/com/api/aiyh_pcn/dealers_contract/DealersContractService.java @@ -0,0 +1,117 @@ +package com.api.aiyh_pcn.dealers_contract; + +import aiyh.utils.Util; +import aiyh.utils.excention.CustomerException; +import com.google.common.base.Strings; + +import java.util.HashMap; +import java.util.Map; + +/** + *

+ *

create 2022/4/19 2:49 PM

+ * + * @author ayh + */ + +public class DealersContractService { + + DealersContractMapper mapper = Util.getMapper(DealersContractMapper.class); + + public void callback(Map params) { +// 合同编号 + String contractNo = Util.null2String(params.get("contractNo")); +// 是否签署 1-签署中 2-拒绝签署 3-已签署 + int isSeal = Integer.parseInt(Util.null2String(params.get("isSeal"))); +// d-flow生成的唯一 使用String.valueOf转换为String + String data = Util.null2String(params.get("data")); + // todo msg的键是多少 + String msg = Util.null2String(params.get("rejectedReason")); + String rejectedEmail = Util.null2String(params.get("rejectedBy")); + Map map = mapper.selectContractInfo(contractNo); + String workflowTable = Util.null2String(map.get("workflow_table")); + if (Strings.isNullOrEmpty(workflowTable)) { + throw new CustomerException("无法获取表明!请检查日志表中是否存在该流程的记录!"); + } + String workflowDetailTable = Util.null2String(map.get("workflow_detail_table")); + String requestId = Util.null2String(map.get("request_id")); + +// 获取回调签署状态 1 主表 0 明细表 + String dealersContractCallbackType = Util.getCusConfigValue(workflowTable + "_dealers_contract_callback_type"); +// 回写签署值 + String dealersSignValue = Util.getCusConfigValue(workflowTable + "_dealers_sign_value"); +// 回写正在签署值 + String dealersSigningValue = Util.getCusConfigValue(workflowTable + "_dealers_signing_value"); +// 回写不签署值 + String dealersNotSignValue = Util.getCusConfigValue(workflowTable + "_dealers_not_sign_value"); +// 签署字段 + String dealersSingStatusField = Util.getCusConfigValue(workflowTable + "_dealers_sing_status_field"); +// 原因字段 + String dealersSingMessageField = Util.getCusConfigValue(workflowTable + "_dealers_sing_message_field"); +// 拒签邮箱 + String dealersSingEmailField = Util.getCusConfigValue(workflowTable + "_dealers_sing_email_field"); +// d-flow-id字段 + String dealersD_FlowIdField = Util.getCusConfigValue(workflowTable + "_dealers_d-flow_id_field"); +// 合同字段 + String contractField = Util.getCusConfigValue(workflowTable + "_dealers_contract_field"); +// 自动提交字段状态标识字段 + String submitStatusField = Util.getCusConfigValue(workflowTable + "_submit_status_field"); + Map updateMap = new HashMap<>(16); + if (1 == isSeal) { + updateMap.put(dealersSingStatusField, dealersSigningValue); + } else if (2 == isSeal) { + updateMap.put(dealersSingStatusField, dealersNotSignValue); + } else if (3 == isSeal) { + updateMap.put(dealersSingStatusField, dealersSignValue); + } + if (!Strings.isNullOrEmpty(dealersD_FlowIdField)) { + updateMap.put(dealersD_FlowIdField, data); + } + if (!Strings.isNullOrEmpty(dealersSingMessageField)) { + updateMap.put(dealersSingMessageField, msg); + } + if (!Strings.isNullOrEmpty(dealersSingEmailField)) { + updateMap.put(dealersSingEmailField, rejectedEmail); + } + if ("1".equals(dealersContractCallbackType.trim())) { + String sql = Util.builderUpdateSql(workflowTable, updateMap); + sql += " where " + contractField + " = #{" + contractField + "}"; + updateMap.put(contractField, contractNo); +// 回写到主表 + Util.getLogger().info("回写到主表sql:" + sql); + if (!mapper.updateContractSignStatus(sql, updateMap)) { + throw new CustomerException("回写到主表失败"); + } + submitWorkflow(workflowTable, requestId, submitStatusField); + } else { + String sql = Util.builderUpdateSql(workflowDetailTable, updateMap); + sql += " where " + contractField + " = #{" + contractField + "}"; + updateMap.put(contractField, contractNo); + Util.getLogger().info("回写到明细表sql:" + sql); +// 回写到明细表 + if (!mapper.updateContractSignStatus(sql, updateMap)) { + throw new CustomerException("回写到明细表失败"); + } + submitWorkflow(workflowTable, requestId, submitStatusField); + } + + } + + private void submitWorkflow(String workflowTable, String requestId, String submitStatusField) { + int n = 0; + Integer status = mapper.selectSubmitStatus(workflowTable, submitStatusField, requestId); + if (status <= 0) { + while (!Util.submitWorkflow(Integer.valueOf(requestId), 1, "流程自动提交")) { + n++; + if (n > 5) { + Util.getLogger().error("流程自动提交失败,回调失败!"); + throw new CustomerException("流程已经提交,请勿重复调用!"); + } + } + // 修改值 + while (!mapper.updateSubmitStatus(workflowTable, submitStatusField, requestId, 1) && n <= 10) { + n++; + } + } + } +} diff --git a/src/main/youhong_ai_old_src/com/api/aiyh_pcn/fadada/dao/FaDDContractMapping.java b/src/main/youhong_ai_old_src/com/api/aiyh_pcn/fadada/dao/FaDDContractMapping.java new file mode 100644 index 0000000..80f4c4f --- /dev/null +++ b/src/main/youhong_ai_old_src/com/api/aiyh_pcn/fadada/dao/FaDDContractMapping.java @@ -0,0 +1,206 @@ +package com.api.aiyh_pcn.fadada.dao; + +import aiyh.utils.Util; +import aiyh.utils.zwl.common.ToolUtil; +import com.api.aiyh_pcn.fadada.entity.FaDaDaConfigDTO; +import com.api.aiyh_pcn.fadada.entity.PushAPushEmailEntity; +import com.api.aiyh_pcn.fadada.entity.UfContractInfoDTO; +import com.api.aiyh_pcn.fadada.typeEnum.DisableEnableType; +import weaver.aiyh_pcn.fadada.entity.FileInfo; +import weaver.conn.RecordSet; +import weaver.workflow.workflow.WorkflowVersion; + +import java.util.List; +import java.util.Map; + +/** + * @author EBU7-dev1-ayh + * @create 2021/11/3 0003 14:56 + */ + + +public class FaDDContractMapping { + private final RecordSet rs = new RecordSet(); + private final ToolUtil toolUtil = new ToolUtil(); + + /** + * 查询合同相关的配置信息 + * + * @param workflowId 流程id + * @param type 配置的类型 + * @return 配置信息 + */ + public FaDaDaConfigDTO queryConfig(String workflowId, int type) { + String versionStringByWfid = WorkflowVersion.getVersionStringByWfid(workflowId); + String query = "select main.id,main.workflow_type,main.api_type, main.params_config," + + "main.signed_type,wf2.fieldname field_control1," + + "wf.fieldname field_control, wf1.fieldname contract_doc, " + + "(select GROUP_CONCAT('',selectvalue,'') selectvalue from workflow_selectitem " + + "where FIND_IN_SET(id,main.only_own)) only_own, " + + "(select GROUP_CONCAT('',selectvalue,'') selectvalue from workflow_selectitem " + + "where FIND_IN_SET(id,main.only_other)) only_other, " + + "(select GROUP_CONCAT('',selectvalue,'') selectvalue from workflow_selectitem " + + "where FIND_IN_SET(id,main.both_all)) both_all, " + + "(select GROUP_CONCAT('',selectvalue,'') selectvalue from workflow_selectitem " + + "where FIND_IN_SET(id,main.check_personal)) check_personal, " + + "(select GROUP_CONCAT('',selectvalue,'') selectvalue from workflow_selectitem " + + "where FIND_IN_SET(id,main.check_enterprise)) check_enterprise," + + "main.check_source_type,wdt.tablename check_source " + + "from uf_contract_config main " + + "left join workflow_field_table_view wf on wf.id = main.field_control " + + "left join workflow_field_table_view wf1 on wf1.id = main.contract_doc " + + "left join workflow_field_table_view wf2 on wf2.id = main.field_control1 " + + "left join workflow_detail_table_view wdt on wdt.id = main.check_source and " + + "wdt.workflow_id = main.workflow_type " + + "where main.workflow_type in ( " + versionStringByWfid + ") and api_type = ?"; + rs.executeQuery(query, type); + return Util.recordeSet2Entity(rs, FaDaDaConfigDTO.class, true); + } + + + /** + * 获取全版本的workflowId + * + * @param versionStringByWfid 全版本的workflowId + * @return + */ + public String getAllVersion(String versionStringByWfid) { + String query = "select distinct workflow_type from uf_contract_config where workflow_type in (" + versionStringByWfid + ")"; + rs.executeQuery(query); + rs.next(); + return rs.getString(1); + } + + /** + * 获取节点信息 + * + * @param versionStringByWfid 全版本的流程 + * @return + */ + public String getNodes(String versionStringByWfid,String markOnly) { + String query = "select workflow_nodes from uf_node_config where workflow_type in (" + versionStringByWfid + ") and enable_nodes = ? and mark_only = ?"; + rs.executeQuery(query, 1,markOnly); + String nodes = ""; + while (rs.next()){ + if("".equals(nodes)){ + nodes += rs.getString(1); + }else{ + String node = Util.null2String(rs.getString(1)); + nodes += "".equals(node) ? "" : "," + node; + } + } + return nodes; + } + + /** + * 获取流程主表 + * + * @param workflowId + * @return + */ + public String getMainTable(String workflowId) { + String versionStringByWfid = WorkflowVersion.getVersionStringByWfid(workflowId); + String query = "select tablename from workflow_bill " + + " where id in (select formid from workflow_base " + + " where id in (" + versionStringByWfid + ") )"; + rs.executeQuery(query); + rs.next(); + String mainTable = rs.getString(1); + toolUtil.writeDebuggerLog("mainTable:" + mainTable); + return mainTable; + } + + /** + * 获取配置的明细表 + * + * @param workflowId + * @param type + * @return + */ + public String getDetailTable(String workflowId, int type) { + FaDaDaConfigDTO faDaDaConfigDTO = this.queryConfig(workflowId, type); + String detailTable = faDaDaConfigDTO.getCheckSource(); + toolUtil.writeDebuggerLog("detailTable:" + detailTable); + return detailTable; + } + + /** + * 根据主表和请求id查询主表数据 + * + * @param requestId 请求id + * @param mainTableName 主表表名 + * @return + */ + public Map queryMainMap(String requestId, String mainTableName) { + String query = "select * from " + mainTableName + " where requestid = ?"; + RecordSet rs = new RecordSet(); + rs.executeQuery(query, requestId); + return Util.recordSet2Map(rs); + } + + /** + * 查询明细数据 + * + * @param mainId 主表id + * @param tableName 明细表表名 + * @return + */ + public List> queryDetailMaps(String mainId, String tableName) { + String query = "select * from " + tableName + " where mainid = ?"; + RecordSet rs = new RecordSet(); + rs.executeQuery(query, mainId); + return Util.recordSet2MapList(rs); + } + + + /** + * 查询合同的配置信息 + * + * @param workflowId + * @return + */ +/* public Map queryContractConfig(String workflowId) { + String versionStringByWfid = WorkflowVersion.getVersionStringByWfid(workflowId); + RecordSet rs = new RecordSet(); + rs.executeQuery("select * from uf_contract_config where workflow_type in ( " + versionStringByWfid + " ) and api_type = ?", 2); + return Util.recordSet2Map(rs); + }*/ + + /** + * 根据文件的id查询物理文件的id + * + * @param fileIds + * @return + */ + public List queryImgFileIdByDocIds(String fileIds) { + String query = "select imagefileid,imagefilename from docimagefile where docid in ( " + fileIds + " )"; + rs.executeQuery(query); + return Util.recordeSet2Array(rs, FileInfo.class); + } + + public UfContractInfoDTO queryContractInfo(String contractNo) { + String query = "select * from uf_contract_info where contract_no = ?"; + RecordSet rs = new RecordSet(); + rs.executeQuery(query, contractNo); + return Util.recordeSet2Entity(rs, UfContractInfoDTO.class, true); + } + + public UfContractInfoDTO queryContractInfoByRequestId(String requestId) { + String query = "select * from uf_contract_info where workflow_request_id = ?"; + RecordSet rs = new RecordSet(); + rs.executeQuery(query, requestId); + return Util.recordeSet2Entity(rs, UfContractInfoDTO.class, true); + } + + public PushAPushEmailEntity queryEmailInfo(int workflowType) { + String query = "select * from uf_push_a_push where workflow_type = ? and disable_enable = ?"; + RecordSet rs = new RecordSet(); + rs.executeQuery(query, workflowType, DisableEnableType.enable.getValue()); + return Util.recordeSet2Entity(rs, PushAPushEmailEntity.class, true); + } + + public boolean updateBackInfo(String workflowMainTable, String workflowRequestId, String backWritField,String fieldValue) { + String update = "update " + workflowMainTable + " set " + backWritField + " = ? where requestid = ?" ; + return rs.executeUpdate(update, fieldValue, workflowRequestId); + } +} diff --git a/src/main/youhong_ai_old_src/com/api/aiyh_pcn/fadada/dao/FaDDServiceMapping.java b/src/main/youhong_ai_old_src/com/api/aiyh_pcn/fadada/dao/FaDDServiceMapping.java new file mode 100644 index 0000000..047955e --- /dev/null +++ b/src/main/youhong_ai_old_src/com/api/aiyh_pcn/fadada/dao/FaDDServiceMapping.java @@ -0,0 +1,173 @@ +package com.api.aiyh_pcn.fadada.dao; + +import aiyh.utils.Util; +import aiyh.utils.sqlUtil.sqlResult.impl.PrepSqlResultImpl; +import aiyh.utils.sqlUtil.whereUtil.Where; +import aiyh.utils.zwl.common.ToolUtil; +import com.api.aiyh_pcn.fadada.entity.FaDaDaConfigDTO; +import weaver.aiyh_pcn.fadada.entity.FileInfo; +import weaver.conn.RecordSet; +import weaver.workflow.workflow.WorkflowVersion; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +/** + * @author EBU7-dev1-ayh + * @create 2021/9/30 0030 11:18 + * 数据 + */ + + +public class FaDDServiceMapping { + private final RecordSet rs = new RecordSet(); + private final ToolUtil toolUtil = new ToolUtil(); + +// private final String MAIN_TABLE = "formtable_main_17"; +// private final String DETAIL_TABLE = "formtable_main_17_dt1"; + + public FaDaDaConfigDTO queryConfig(String workflowId, int type) { + String versionStringByWfid = WorkflowVersion.getVersionStringByWfid(workflowId); + String query = "select main.id,main.workflow_type,main.api_type, main.params_config, " + + "wf.fieldname field_control, " + + "(select GROUP_CONCAT('',selectvalue,'') selectvalue from workflow_selectitem where FIND_IN_SET(id,main.check_personal)) check_personal, " + + "(select GROUP_CONCAT('',selectvalue,'') selectvalue from workflow_selectitem where FIND_IN_SET(id,main.check_enterprise)) check_enterprise, " + + "main.check_source_type,wdt.tablename check_source " + + "from uf_contract_config main " + + "left join workflow_field_table_view wf on wf.id = main.field_control " + + "left join workflow_detail_table_view wdt on wdt.id = main.check_source and wdt.workflow_id = main.workflow_type " + + "where main.workflow_type in ( " + versionStringByWfid + ") and api_type = ?"; + rs.executeQuery(query, type); + return Util.recordeSet2Entity(rs, FaDaDaConfigDTO.class, true); + } + + public List queryImgFileIdByDocIds(String fileIds) { + String query = "select imagefileid,imagefilename from docimagefile where docid in ( " + fileIds + " )"; + rs.executeQuery(query); + return Util.recordeSet2Array(rs, FileInfo.class); + } + + public List> queryDetailInfo(String requestId,String workflowId,int type) { + + String mainTable = this.getMainTable(workflowId); + toolUtil.writeDebuggerLog("进入查询数据库方法"); + String query = "select id from " + mainTable + " where requestid = ?"; + rs.executeQuery(query, requestId); + rs.next(); + String mainId = rs.getString("id"); + String detailTable = this.getDetailTable(workflowId, type); + query = "select * from " + detailTable + " where mainid = ? and ( contract_status in (1,6) or contract_status is null) "; + this.toolUtil.writeDebuggerLog(query); + RecordSet rs = new RecordSet(); + rs.executeQuery(query, mainId); + List> maps = null; + try { + maps = Util.recordSet2MapList(rs); + toolUtil.writeDebuggerLog("查询到状态:" + maps); + } catch (Exception e) { + e.printStackTrace(); + toolUtil.writeErrorLog("工具类出现异常:" + e); + } + return maps == null ? new ArrayList<>() : maps; + } + + public List> queryDetailDownInfo(String requestId,String workflowId,int type) { + + String mainTable = this.getMainTable(workflowId); + toolUtil.writeDebuggerLog("进入查询数据库方法"); + String query = "select id from " + mainTable + " where requestid = ?"; + rs.executeQuery(query, requestId); + rs.next(); + String mainId = rs.getString("id"); + String detailTable = this.getDetailTable(workflowId, type); + query = "select * from " + detailTable + " where mainid = ?"; + this.toolUtil.writeDebuggerLog(query); + RecordSet rs = new RecordSet(); + rs.executeQuery(query, mainId); + List> maps = null; + try { + maps = Util.recordSet2MapList(rs); + toolUtil.writeDebuggerLog("查询到状态:" + maps); + } catch (Exception e) { + e.printStackTrace(); + toolUtil.writeErrorLog("工具类出现异常:" + e); + } + return maps == null ? new ArrayList<>() : maps; + } + + + public List> querySignedInfo(String requestId, String workflowId) { + String mainTable = this.getMainTable(workflowId); + String query = "select id from " + mainTable + " where requestid = ? and signed_oneself = 1"; + rs.executeQuery(query, requestId); + return Util.recordSet2MapList(rs); + } + + public void updateContractStatus(Map map,String workflowId,int type) { + String detailTable = this.getDetailTable(workflowId,type); + Map updateData = new HashMap<>(); + updateData.put("contract_status", map.get("contract_status")); + Where where = Util.createPrepWhereImpl().whereAnd("id").whereEqual(map.get("id")); + PrepSqlResultImpl sqlResult = Util.createSqlBuilder().updateSql(detailTable, updateData, where); + rs.executeUpdate(sqlResult.getSqlStr(), sqlResult.getArgs()); + } + + public String getAllVersion(String versionStringByWfid) { + String query = "select distinct workflow_type from uf_contract_config where workflow_type in (" + versionStringByWfid + ")"; + rs.executeQuery(query); + rs.next(); + return rs.getString(1); + } + + public String getMainTable(String workflowId){ + String versionStringByWfid = WorkflowVersion.getVersionStringByWfid(workflowId); + String query = "select tablename from workflow_bill " + + " where id in (select formid from workflow_base " + + " where id in (" + versionStringByWfid + ") )"; + rs.executeQuery(query); + rs.next(); + String mainTable = rs.getString(1); + toolUtil.writeDebuggerLog("mainTable:" + mainTable); + return mainTable; + } + + public String getDetailTable(String workflowId, int type){ + FaDaDaConfigDTO faDaDaConfigDTO = this.queryConfig(workflowId, type); + String detailTable = faDaDaConfigDTO.getCheckSource(); + toolUtil.writeDebuggerLog("detailTable:" + detailTable); + return detailTable; + } + + public String getNodes(String versionStringByWfid, String markOnly) { + String query = "select workflow_nodes from uf_node_config where workflow_type in (" + versionStringByWfid + ") and mark_only = ?"; + rs.executeQuery(query,markOnly); + rs.next(); + return rs.getString(1); + } + +/* public FaDDConfigMainDTO getConfigParam(String workflowId) { + String versionStringByWfid = WorkflowVersion.getVersionStringByWfid(workflowId); + System.out.println(versionStringByWfid); + String query = "select main.id,main.workflow_type, wf.fieldname field_control, " + + "(select GROUP_CONCAT('',selectvalue,'') selectvalue from workflow_selectitem where FIND_IN_SET(id,main.check_personal)) check_personal, " + + "(select GROUP_CONCAT('',selectvalue,'') selectvalue from workflow_selectitem where FIND_IN_SET(id,main.check_enterprise)) check_enterprise, " + + "main.check_source_type,wdt.tablename check_source " + + "from uf_attestation_conf main " + + "left join workflow_field_table_view wf on wf.id = main.field_control " + + "left join workflow_detail_table_view wdt on wdt.id = main.check_source and wdt.workflow_id = main.workflow_type " + + "where main.workflow_type in ( " + versionStringByWfid + ")"; + rs.executeQuery(query); + FaDDConfigMainDTO faDDConfigMainDTO = Util.recordeSet2Entity(rs, FaDDConfigMainDTO.class, true); + query = "select dt.id,dt.line_num,dt.param_name,dt.param_type,dt.object_child,dt.parent_line,dt.change_rule, " + + "dt.param_value,wf.fieldname workflow_field,wf.tablename tablename,dt.array_sql,dt.api_type " + + "from uf_attestation_conf_dt1 dt " + + "left join workflow_field_table_view wf on wf.id = dt.workflow_field " + + "where dt.mainid = ?"; + rs.executeQuery(query, faDDConfigMainDTO.getId()); + List faDDConfigDetailDTOS = Util.recordeSet2Array(rs, FaDDConfigDetailDTO.class, true); + faDDConfigMainDTO.setList(faDDConfigDetailDTOS); + return faDDConfigMainDTO; + }*/ +} diff --git a/src/main/youhong_ai_old_src/com/api/aiyh_pcn/fadada/entity/FaDaDaConfigDTO.java b/src/main/youhong_ai_old_src/com/api/aiyh_pcn/fadada/entity/FaDaDaConfigDTO.java new file mode 100644 index 0000000..370b673 --- /dev/null +++ b/src/main/youhong_ai_old_src/com/api/aiyh_pcn/fadada/entity/FaDaDaConfigDTO.java @@ -0,0 +1,144 @@ + +package com.api.aiyh_pcn.fadada.entity; + + +public class FaDaDaConfigDTO { + + private int id; + private int workflowType; + private int apiType; + private String paramsConfig; + private String fieldControl; + private int checkSourceType; + private String checkSource; + private String contractDoc; + private int signedType; + private String fieldControl1; + private int onlyOwn; + private int onlyOther; + private int bothAll; + + + public void setId(int id){ + this.id = id; + } + + public void setWorkflowType(int workflowType){ + this.workflowType = workflowType; + } + + public void setApiType(int apiType){ + this.apiType = apiType; + } + + public void setParamsConfig(String paramsConfig){ + this.paramsConfig = paramsConfig; + } + + public void setFieldControl(String fieldControl){ + this.fieldControl = fieldControl; + } + + public void setCheckSourceType(int checkSourceType){ + this.checkSourceType = checkSourceType; + } + + public void setCheckSource(String checkSource){ + this.checkSource = checkSource; + } + + public int getId(){ + return this.id; + } + + public int getWorkflowType(){ + return this.workflowType; + } + + public int getApiType(){ + return this.apiType; + } + + public String getParamsConfig(){ + return this.paramsConfig; + } + + public String getFieldControl(){ + return this.fieldControl; + } + + public int getCheckSourceType(){ + return this.checkSourceType; + } + + public String getCheckSource(){ + return this.checkSource; + } + + public String getContractDoc() { + return contractDoc; + } + + public void setContractDoc(String contractDoc) { + this.contractDoc = contractDoc; + } + + public int getSignedType() { + return signedType; + } + + public void setSignedType(int signedType) { + this.signedType = signedType; + } + + public String getFieldControl1() { + return fieldControl1; + } + + public void setFieldControl1(String fieldControl1) { + this.fieldControl1 = fieldControl1; + } + + public int getOnlyOwn() { + return onlyOwn; + } + + public void setOnlyOwn(int onlyOwn) { + this.onlyOwn = onlyOwn; + } + + public int getOnlyOther() { + return onlyOther; + } + + public void setOnlyOther(int onlyOther) { + this.onlyOther = onlyOther; + } + + public int getBothAll() { + return bothAll; + } + + public void setBothAll(int bothAll) { + this.bothAll = bothAll; + } + + @Override + public String toString() { + return "FaDaDaConfigDTO{" + + "id=" + id + + ", workflowType=" + workflowType + + ", apiType=" + apiType + + ", paramsConfig='" + paramsConfig + '\'' + + ", fieldControl='" + fieldControl + '\'' + + ", checkSourceType=" + checkSourceType + + ", checkSource='" + checkSource + '\'' + + ", contractDoc='" + contractDoc + '\'' + + ", signedType=" + signedType + + ", fieldControl1='" + fieldControl1 + '\'' + + ", onlyOwn=" + onlyOwn + + ", onlyOther=" + onlyOther + + ", bothAll=" + bothAll + + '}'; + } +} \ No newline at end of file diff --git a/src/main/youhong_ai_old_src/com/api/aiyh_pcn/fadada/entity/PushAPushEmailEntity.java b/src/main/youhong_ai_old_src/com/api/aiyh_pcn/fadada/entity/PushAPushEmailEntity.java new file mode 100644 index 0000000..4547567 --- /dev/null +++ b/src/main/youhong_ai_old_src/com/api/aiyh_pcn/fadada/entity/PushAPushEmailEntity.java @@ -0,0 +1,21 @@ +package com.api.aiyh_pcn.fadada.entity; + +import lombok.Getter; +import lombok.Setter; +import lombok.ToString; + +/** + * @author EBU7-dev1-ayh + * create 2021/12/13 0013 14:54 + */ + +@Getter +@Setter +@ToString +public class PushAPushEmailEntity { + private Integer workflowType; + private Integer disableEnable; + private String emailAddress; + private String emailTitle; + private String emailContent; +} diff --git a/src/main/youhong_ai_old_src/com/api/aiyh_pcn/fadada/entity/TreeEntity.java b/src/main/youhong_ai_old_src/com/api/aiyh_pcn/fadada/entity/TreeEntity.java new file mode 100644 index 0000000..ff3e6f2 --- /dev/null +++ b/src/main/youhong_ai_old_src/com/api/aiyh_pcn/fadada/entity/TreeEntity.java @@ -0,0 +1,29 @@ +package com.api.aiyh_pcn.fadada.entity; + +import java.util.List; + +/** + * @author EBU7-dev1-ayh + * @create 2021/10/12 0012 11:16 + * 树形结构 + */ + + +public class TreeEntity { + private List children; + + public List getChildren() { + return children; + } + + public void setChildren(List children) { + this.children = children; + } + + @Override + public String toString() { + return "TreeEntity{" + + "children=" + children + + '}'; + } +} diff --git a/src/main/youhong_ai_old_src/com/api/aiyh_pcn/fadada/entity/UfContractInfoDTO.java b/src/main/youhong_ai_old_src/com/api/aiyh_pcn/fadada/entity/UfContractInfoDTO.java new file mode 100644 index 0000000..e620d60 --- /dev/null +++ b/src/main/youhong_ai_old_src/com/api/aiyh_pcn/fadada/entity/UfContractInfoDTO.java @@ -0,0 +1,222 @@ +package com.api.aiyh_pcn.fadada.entity; + + +public class UfContractInfoDTO { + + private int id; + private int requestId; + private int workflowType; + private String contractNo; + private String fileNo; + private String fileName; + private int signedNum; + private int shouldSignedNum; + private int contractStatus; + private String contractViewUrl; + private String contractDownUrl; + private String workflowMainTable; + private int queueSigned; + private int singleContractFileNum; + private int singleSignedNum; + private String workflowRequestId; + private String workflowDetailTable; + private String signedType; + private String userInfo; + private String contractSignedUrl; + private int mainId; + + public void setId(int id) { + this.id = id; + } + + public void setRequestId(int requestId) { + this.requestId = requestId; + } + + public void setWorkflowType(int workflowType) { + this.workflowType = workflowType; + } + + public void setContractNo(String contractNo) { + this.contractNo = contractNo; + } + + public void setFileNo(String fileNo) { + this.fileNo = fileNo; + } + + public void setFileName(String fileName) { + this.fileName = fileName; + } + + public void setSignedNum(int signedNum) { + this.signedNum = signedNum; + } + + public void setShouldSignedNum(int shouldSignedNum) { + this.shouldSignedNum = shouldSignedNum; + } + + public void setContractStatus(int contractStatus) { + this.contractStatus = contractStatus; + } + + public void setContractViewUrl(String contractViewUrl) { + this.contractViewUrl = contractViewUrl; + } + + public void setContractDownUrl(String contractDownUrl) { + this.contractDownUrl = contractDownUrl; + } + + public void setWorkflowMainTable(String workflowMainTable) { + this.workflowMainTable = workflowMainTable; + } + + public void setQueueSigned(int queueSigned) { + this.queueSigned = queueSigned; + } + + public void setSingleContractFileNum(int singleContractFileNum) { + this.singleContractFileNum = singleContractFileNum; + } + + public void setSingleSignedNum(int singleSignedNum) { + this.singleSignedNum = singleSignedNum; + } + + public void setWorkflowRequestId(String workflowRequestId) { + this.workflowRequestId = workflowRequestId; + } + + public void setWorkflowDetailTable(String workflowDetailTable) { + this.workflowDetailTable = workflowDetailTable; + } + + public void setMainId(int mainId) { + this.mainId = mainId; + } + + public int getId() { + return this.id; + } + + public int getRequestId() { + return this.requestId; + } + + public int getWorkflowType() { + return this.workflowType; + } + + public String getContractNo() { + return this.contractNo; + } + + public String getFileNo() { + return this.fileNo; + } + + public String getFileName() { + return this.fileName; + } + + public int getSignedNum() { + return this.signedNum; + } + + public int getShouldSignedNum() { + return this.shouldSignedNum; + } + + public int getContractStatus() { + return this.contractStatus; + } + + public String getContractViewUrl() { + return this.contractViewUrl; + } + + public String getContractDownUrl() { + return this.contractDownUrl; + } + + public String getWorkflowMainTable() { + return this.workflowMainTable; + } + + public int getQueueSigned() { + return this.queueSigned; + } + + public int getSingleContractFileNum() { + return this.singleContractFileNum; + } + + public int getSingleSignedNum() { + return this.singleSignedNum; + } + + public String getWorkflowRequestId() { + return this.workflowRequestId; + } + + public String getWorkflowDetailTable() { + return this.workflowDetailTable; + } + + public int getMainId() { + return this.mainId; + } + + public String getSignedType() { + return signedType; + } + + public void setSignedType(String signedType) { + this.signedType = signedType; + } + + public String getUserInfo() { + return userInfo; + } + + public void setUserInfo(String userInfo) { + this.userInfo = userInfo; + } + + public String getContractSignedUrl() { + return contractSignedUrl; + } + + public void setContractSignedUrl(String contractSignedUrl) { + this.contractSignedUrl = contractSignedUrl; + } + + @Override + public String toString() { + return "UfContractInfoDTO{" + + "id=" + id + + ", requestId=" + requestId + + ", workflowType=" + workflowType + + ", contractNo='" + contractNo + '\'' + + ", fileNo='" + fileNo + '\'' + + ", fileName='" + fileName + '\'' + + ", signedNum=" + signedNum + + ", shouldSignedNum=" + shouldSignedNum + + ", contractStatus=" + contractStatus + + ", contractViewUrl='" + contractViewUrl + '\'' + + ", contractDownUrl='" + contractDownUrl + '\'' + + ", workflowMainTable='" + workflowMainTable + '\'' + + ", queueSigned=" + queueSigned + + ", singleContractFileNum=" + singleContractFileNum + + ", singleSignedNum=" + singleSignedNum + + ", workflowRequestId='" + workflowRequestId + '\'' + + ", workflowDetailTable='" + workflowDetailTable + '\'' + + ", signedType='" + signedType + '\'' + + ", userInfo='" + userInfo + '\'' + + ", contractSignedUrl='" + contractSignedUrl + '\'' + + ", mainId=" + mainId + + '}'; + } +} \ No newline at end of file diff --git a/src/main/youhong_ai_old_src/com/api/aiyh_pcn/fadada/service/IFaDDService.java b/src/main/youhong_ai_old_src/com/api/aiyh_pcn/fadada/service/IFaDDService.java new file mode 100644 index 0000000..ffa3d57 --- /dev/null +++ b/src/main/youhong_ai_old_src/com/api/aiyh_pcn/fadada/service/IFaDDService.java @@ -0,0 +1,17 @@ +package com.api.aiyh_pcn.fadada.service; + +import com.api.aiyh_pcn.fadada.vo.TableFieldMappingVO; + +import java.util.List; +import java.util.Map; + +/** + * @author @author EBU7-dev1-ay + * @create 2021/9/30 0030 11:19 + * 接口 + */ + +public interface IFaDDService { + Map getConfigParam(String workflowId); + Map checkCertification(Map params); +} diff --git a/src/main/youhong_ai_old_src/com/api/aiyh_pcn/fadada/service/impl/FaDDContractService.java b/src/main/youhong_ai_old_src/com/api/aiyh_pcn/fadada/service/impl/FaDDContractService.java new file mode 100644 index 0000000..c2903e3 --- /dev/null +++ b/src/main/youhong_ai_old_src/com/api/aiyh_pcn/fadada/service/impl/FaDDContractService.java @@ -0,0 +1,1255 @@ +package com.api.aiyh_pcn.fadada.service.impl; + +import aiyh.utils.Util; +import aiyh.utils.entity.ApiConfigDetailDTO; +import aiyh.utils.entity.ApiConfigMainDTO; +import aiyh.utils.httpUtil.ResponeVo; +import aiyh.utils.mapUtil.ParaMap; +import aiyh.utils.sqlUtil.sqlResult.impl.PrepSqlResultImpl; +import aiyh.utils.zwl.common.ToolUtil; +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.JSONObject; +import com.alibaba.fastjson.TypeReference; +import com.alibaba.fastjson.serializer.SerializerFeature; +import com.api.aiyh_pcn.fadada.dao.FaDDContractMapping; +import com.api.aiyh_pcn.fadada.entity.FaDaDaConfigDTO; +import com.api.aiyh_pcn.fadada.entity.PushAPushEmailEntity; +import com.api.aiyh_pcn.fadada.entity.UfContractInfoDTO; +import com.api.aiyh_pcn.fadada.util.FaDDRequestUtils; +import com.fasterxml.jackson.core.JsonProcessingException; +import com.google.common.base.Strings; +import org.apache.axiom.util.base64.Base64Utils; +import org.apache.http.HttpEntity; +import org.h2.util.StringUtils; +import weaver.conn.RecordSet; +import weaver.email.EmailWorkRunnable; +import weaver.general.xcommon.IOUtils; +import weaver.hrm.User; +import weaver.soa.workflow.FileProcessor; +import weaver.workflow.workflow.WorkflowVersion; + +import javax.ws.rs.core.StreamingOutput; +import java.io.IOException; +import java.io.InputStream; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.concurrent.atomic.AtomicReference; +import java.util.regex.Matcher; +import java.util.regex.Pattern; +import java.util.zip.ZipEntry; +import java.util.zip.ZipOutputStream; + +/** + * 法大大集成 + * + * @author EBU7-dev1-ayh + * @create 2021/11/3 0003 14:51 + */ + + +// 写这个代码的时候只有我和上帝知道在写啥 2021/11/10 + +// 好了,现在只有上帝知道了 2022/02/16 + +/* + * 2022/02/18 + *你可能觉得自己看懂下面的代码了, + + *然而你并没有,相信我。 + + *糊弄过去算了,不然你会好多个晚上睡不着觉, + + *嘴里骂着这段注释,觉得自己很聪明, + + *真能“优化”下面的代码。 + + *现在关上文件,去玩点别的吧。 + + */ + +/* + * 听说你要改这里面的逻辑 + * + * 听一句劝,别试图在一座屎山上面拉屎 + * + * 当屎山崩塌的时候,没有一个拉屎的是无辜的 + * + * 当你决定动这个文件的时候,你就要面对无尽的折磨 + * + * */ +public class FaDDContractService { + private final ToolUtil toolUtil = new ToolUtil(); + private final String contractInfoTable = "uf_contract_info"; + private final FaDDContractMapping faDDContractMapping = new FaDDContractMapping(); + + /** + * 获取全版本的流程id,节点id + * + * @param workflowId + * @return + */ + public Map getAllVersion(String workflowId, String markOnly) { + Map data = new HashMap<>(); + if (Strings.isNullOrEmpty(workflowId)) { + data.put("workflowIds", new String[0]); + data.put("nodeIds", new String[0]); + return data; + } + String versionStringByWfid = WorkflowVersion.getVersionStringByWfid(workflowId); + String newWorkflowId = faDDContractMapping.getAllVersion(versionStringByWfid); + if (Strings.isNullOrEmpty(newWorkflowId)) { + data.put("workflowIds", new String[0]); + data.put("nodeIds", new String[0]); + return data; + } + String allVersion = WorkflowVersion.getVersionStringByWfid(newWorkflowId); + if (allVersion == null) { + allVersion = ""; + } + String[] split = allVersion.split(","); + String[] nodes = this.getNodes(workflowId, markOnly); + data.put("workflowIds", split); + data.put("nodeIds", nodes); + return data; + } + + /** + * 获取节点id + * + * @param workflowId + * @return + */ + public String[] getNodes(String workflowId, String markOnly) { + String versionStringByWfid = WorkflowVersion.getVersionStringByWfid(workflowId); + String nods = faDDContractMapping.getNodes(versionStringByWfid, markOnly); + if (nods == null) { + nods = ""; + } + return nods.split(","); + } + + /** + * 获取替换SQL的数据 + * + * @param requestId + * @param workflowId + * @param mainTableName + * @param tableName + * @return + */ + public List> getDataArr( + String requestId, String workflowId, String mainTableName, String tableName) { + Map mainMap = faDDContractMapping.queryMainMap(requestId, mainTableName); + String mainId = Util.null2String(mainMap.get("id")); + List> detailMaps = faDDContractMapping.queryDetailMaps(mainId, tableName); + return getDataArr(requestId, workflowId, tableName, mainMap, detailMaps); + } + + public List> getDataArr( + String requestId, + String workflowId, + String mainTableName, + String tableName, + List> detailMaps) { + Map mainMap = faDDContractMapping.queryMainMap(requestId, mainTableName); + String mainId = Util.null2String(mainMap.get("id")); + return getDataArr(requestId, workflowId, tableName, mainMap, detailMaps); + } + + public List> getDataArr( + String requestId, + String workflowId, + String tableName, + Map mainMap, + List> detailMaps) { + List> dataArr = new ArrayList<>(); + String dt = tableName.substring(tableName.indexOf("_dt") + 3); + String main = "main."; + String detail = "detail_" + dt + "."; + for (Map detailMap : detailMaps) { + Map data = new HashMap<>(); + for (Map.Entry entry : mainMap.entrySet()) { + data.put(main + entry.getKey(), entry.getValue()); + } + for (Map.Entry entry : detailMap.entrySet()) { + data.put(detail + entry.getKey(), entry.getValue()); + } + data.put("requestId", requestId); + data.put("workflowId", workflowId); + dataArr.add(data); + } + return dataArr; + } + + /** + * 获取处理object和List类型后的参数 + * + * @param treeList + * @param dataArr + * @return + */ + public List> objectAndListHandle( + List treeList, List> dataArr) { + List> params = new ArrayList<>(); + for (Map dataMap : dataArr) { + Map param = new HashMap<>(); + for (ApiConfigDetailDTO apiConfigDetailDTO : treeList) { + Object value; + if (apiConfigDetailDTO.getParamType() == 3) { + Map map = new HashMap<>(); + // object类型 + for (ApiConfigDetailDTO child : apiConfigDetailDTO.getChildren()) { + if (child.getChildren() == null || child.getChildren().size() == 0) { + // handleChild(child.getChildren(), dataMap) + map.put(child.getParamName(), changeRuleHandle(child, dataMap)); + } else { + map.put(child.getParamName(), handleChild(child.getChildren(), dataMap)); + } + } + value = map; + } else if (apiConfigDetailDTO.getParamType() == 4) { + String sql = apiConfigDetailDTO.getArraySql(); + String parsingSq = aiyh.utils.Util.parsingSq(sql, dataMap); + // list类型 + if (parsingSq.contains("delete") + || parsingSq.contains("update") + || parsingSq.contains("exec") + || parsingSq.contains("drop") + || parsingSq.contains("truncate")) { + value = new ArrayList<>(); + } else { + RecordSet rs = new RecordSet(); + String replace = + parsingSq + .replace("select ", "select ") + .replaceAll(" and ", " and ") + .replaceAll(" or ", " or ") + .replaceAll(" join ", " join ") + .replaceAll(" in ", " in "); + rs.executeQuery(replace); + value = aiyh.utils.Util.recordeSet2Array(rs, String.class); + } + } else { + value = changeRuleHandle(apiConfigDetailDTO, dataMap); + } + param.put(apiConfigDetailDTO.getParamName(), value); + } + params.add(param); + } + return params; + } + + /** + * 处理子类 + * + * @param children + * @param dataMap + * @return + */ + private Object handleChild(List children, Map dataMap) { + Map params = new HashMap<>(); + for (ApiConfigDetailDTO child : children) { + Object value; + if (child.getChildren() != null) { + value = handleChild(child.getChildren(), dataMap); + } else { + value = changeRuleHandle(child, dataMap); + } + params.put(child.getParamName(), value); + } + return params; + } + + /** + * 根据转换规则生成对应的参数值 + * + * @param apiConfigDetailDTO + * @param dataMap + * @return + */ + private Object changeRuleHandle( + ApiConfigDetailDTO apiConfigDetailDTO, Map dataMap) { + Object value; + String tableName; + String table; + String sql; + String resultSql; + // 判断参数的转换规则 + switch (apiConfigDetailDTO.getChangeRule()) { + case 0: + // 不转换 + case 2: + // 流程字段值 + table = apiConfigDetailDTO.getTablename(); + if (!table.contains("_dt")) { + // 表示字段属于主表 + tableName = "main"; + } else { + // 字段属于明细表 + String dt = table.substring(table.indexOf("_dt") + 3); + tableName = "detail_" + dt; + } + value = dataMap.get(tableName + "." + apiConfigDetailDTO.getWorkflowField()); + break; + case 1: + // 固定值 + value = apiConfigDetailDTO.getParamValue(); + break; + case 3: + // 系统日期 + value = aiyh.utils.Util.getTime("yyyy-MM-dd"); + break; + case 4: + // 系统时间 + value = aiyh.utils.Util.getTime("HH:mm:ss"); + break; + case 5: + // 系统日期-时间 + value = aiyh.utils.Util.getTime("yyyy-MM-dd HH:mm:ss"); + break; + case 6: + // 自定义SQL + case 7: + // 流程字段转SQL + sql = apiConfigDetailDTO.getParamValue(); + resultSql = aiyh.utils.Util.parsingSq(sql, dataMap); + if (resultSql.contains("delete ") + || resultSql.contains("update ") + || resultSql.contains("exec ") + || resultSql.contains("drop ") + || resultSql.contains("truncate ")) { + value = null; + } else { + RecordSet rs = new RecordSet(); + String replace = + resultSql + .replace("select ", "select ") + .replaceAll(" and ", " and ") + .replaceAll(" or ", " or ") + .replaceAll(" join ", " join ") + .replaceAll(" in ", " in "); + rs.executeQuery(replace); + rs.next(); + value = aiyh.utils.Util.null2String(rs.getString(1)); + } + break; + case 8: + // + // 流程名称 + value = aiyh.utils.Util.getWorkflowNameById(String.valueOf(dataMap.get("workflowid"))); + break; + case 9: + // + // 请求标题 + value = aiyh.utils.Util.getRequestTitleById(String.valueOf(dataMap.get("requestid"))); + break; + case 10: + // 流程requestId + value = dataMap.get("requestid"); + break; + default: + value = null; + break; + } + if (apiConfigDetailDTO.getParamType() == 1) { + // Integer + value = Integer.parseInt(String.valueOf(value)); + } else if (apiConfigDetailDTO.getParamType() == 2) { + // Boolean + value = Boolean.parseBoolean(String.valueOf(value)); + } + return value; + } + + /** + * 合同签署回调逻辑处理 + * + * @param contractNo + */ + public void signedCallBack(String contractNo) { + // 查询合同信息表中的数据 + UfContractInfoDTO ufContractInfoDTO = faDDContractMapping.queryContractInfo(contractNo); + toolUtil.writeDebuggerLog("回调,获取到合同信息参数:" + JSON.toJSONString(ufContractInfoDTO)); + Map update = new HashMap<>(); + if (ufContractInfoDTO.getQueueSigned() == 1) { + // 属于顺序签署合同,更新单份合同已签蜀几个文件 + update.put("single_signed_num", ufContractInfoDTO.getSingleSignedNum() + 1); + toolUtil.writeDebuggerLog("单份合同签署成功"); + // 如果单份合同签署数量等于合同文件数量,表示已经签署完成 + if (ufContractInfoDTO.getSingleSignedNum() + 1 + == ufContractInfoDTO.getSingleContractFileNum()) { + toolUtil.writeDebuggerLog("单份合同全部签署成功"); + update.put("signed_num", ufContractInfoDTO.getSignedNum() + 1); + // 查询下一位合同方并发起签署 + if (ufContractInfoDTO.getSignedNum() + 1 < ufContractInfoDTO.getShouldSignedNum()) { + toolUtil.writeDebuggerLog( + "应签署合同比签署合同数量多,需要再次签署!" + (ufContractInfoDTO.getSignedNum() + 1)); + update.put("single_signed_num", 0); + nextContractSigned(ufContractInfoDTO); + } + } + // 如果合同已签数量和应签数量相同,则状态为本方待签 + if (ufContractInfoDTO.getSignedNum() + 1 == ufContractInfoDTO.getShouldSignedNum()) { + update.put("contract_status", 3); + // 判断是否控制签署规则 1-仅本方签署,2-仅对方签署,3-都签署 + if ("1".equals(Util.null2String(ufContractInfoDTO.getSignedType()))) { + update.put("contract_status", 4); + } + if ("2".equals(Util.null2String(ufContractInfoDTO.getSignedType()))) { + update.put("contract_status", 4); + // 仅对方签署完成后,添加用户信息 + // 获取配置表信息 + FaDaDaConfigDTO faDaDaConfigDTO = + faDDContractMapping.queryConfig( + String.valueOf(ufContractInfoDTO.getWorkflowType()), 4); + RecordSet rs = new RecordSet(); + String userInfo = ufContractInfoDTO.getUserInfo(); + User user = JSON.parseObject(userInfo, new TypeReference() { + }); + // 获取流程中的合同字段的文档目录id + rs.executeQuery( + "select formid from workflow_base where id = ?", ufContractInfoDTO.getWorkflowType()); + String formId = Util.recordeSet2Entity(rs, String.class); + String query = + "select doccategory from workflow_fileupload where fieldid = (select id from workflow_billfield where fieldname = ? and billid = ?)"; + rs.executeQuery(query, faDaDaConfigDTO.getContractDoc(), formId); + String docCategorys = Util.null2String(Util.recordeSet2Entity(rs, String.class)); + if (StringUtils.isNullOrEmpty(docCategorys)) { + query = "select doccategory from workflow_base where id = ?"; + rs.executeQuery(query, ufContractInfoDTO.getWorkflowType()); + rs.next(); + docCategorys = Util.null2String(rs.getString(1)); + } + if (StringUtils.isNullOrEmpty(docCategorys)) { + docCategorys = ",,1"; + } + // String[] docSplit = docCategorys.split(","); + // String category = docSplit[docSplit.length - 1]; + // 下载合同到文件服务器中 + String docIds = ""; + try { + docIds = downloadContract2FileSystem(ufContractInfoDTO, docCategorys, user); + } catch (Exception e) { + toolUtil.writeErrorLog("创建文档发生错误:" + e); + } + toolUtil.writeDebuggerLog("生成的文档的id:" + docIds); + // 将id保存到流程字段中 + PrepSqlResultImpl sqlResult = + Util.createSqlBuilder() + .updateSql( + ufContractInfoDTO.getWorkflowMainTable(), + ParaMap.create().put(faDaDaConfigDTO.getContractDoc(), docIds), + Util.createPrepWhereImpl() + .whereAnd("id") + .whereEqual(ufContractInfoDTO.getMainId())); + toolUtil.writeDebuggerLog(sqlResult.getSqlStr() + ",参数:" + sqlResult.getArgs()); + rs.executeUpdate(sqlResult.getSqlStr(), sqlResult.getArgs()); + } + } + } else { + // 全部合同一起发送的签署信息 + // 直接合同已签署+1 + update.put("signed_num", ufContractInfoDTO.getSignedNum() + 1); + // 如果已签文件数等于需要签署的合同数乘以合同文件数相等,则代表对方已经签署完毕 + if (ufContractInfoDTO.getSignedNum() + 1 + == ufContractInfoDTO.getShouldSignedNum() + * ufContractInfoDTO.getSingleContractFileNum()) { + update.put("contract_status", 3); + // 判断是否控制签署规则 1-仅本方签署,2-仅对方签署,3-都签署 + if ("1".equals(Util.null2String(ufContractInfoDTO.getSignedType()))) { + update.put("contract_status", 4); + } + if ("2".equals(Util.null2String(ufContractInfoDTO.getSignedType()))) { + update.put("contract_status", 4); + // 仅对方签署完成后,添加用户信息 + // 获取配置表信息 + FaDaDaConfigDTO faDaDaConfigDTO = + faDDContractMapping.queryConfig( + String.valueOf(ufContractInfoDTO.getWorkflowType()), 4); + RecordSet rs = new RecordSet(); + String userInfo = ufContractInfoDTO.getUserInfo(); + User user = JSON.parseObject(userInfo, new TypeReference() { + }); + // 获取流程中的合同字段的文档目录id + rs.executeQuery( + "select formid from workflow_base where id = ?", ufContractInfoDTO.getWorkflowType()); + String formId = Util.recordeSet2Entity(rs, String.class); + String query = + "select doccategory from workflow_fileupload where fieldid = (select id from workflow_billfield where fieldname = ? and billid = ?)"; + rs.executeQuery(query, faDaDaConfigDTO.getContractDoc(), formId); + String docCategorys = Util.null2String(Util.recordeSet2Entity(rs, String.class)); + if (StringUtils.isNullOrEmpty(docCategorys)) { + query = "select doccategory from workflow_base where id = ?"; + rs.executeQuery(query, ufContractInfoDTO.getWorkflowType()); + rs.next(); + docCategorys = Util.null2String(rs.getString(1)); + } + if (StringUtils.isNullOrEmpty(docCategorys)) { + docCategorys = ",,1"; + } + // String[] docSplit = docCategorys.split(","); + // String category = docSplit[docSplit.length - 1]; + // 下载合同到文件服务器中 + String docIds = ""; + try { + docIds = downloadContract2FileSystem(ufContractInfoDTO, docCategorys, user); + } catch (Exception e) { + toolUtil.writeErrorLog("创建文档发生错误:" + e); + } + toolUtil.writeDebuggerLog("生成的文档的id:" + docIds); + // 将id保存到流程字段中 + PrepSqlResultImpl sqlResult = + Util.createSqlBuilder() + .updateSql( + ufContractInfoDTO.getWorkflowMainTable(), + ParaMap.create().put(faDaDaConfigDTO.getContractDoc(), docIds), + Util.createPrepWhereImpl() + .whereAnd("id") + .whereEqual(ufContractInfoDTO.getMainId())); + toolUtil.writeDebuggerLog(sqlResult.getSqlStr() + ",参数:" + sqlResult.getArgs()); + rs.executeUpdate(sqlResult.getSqlStr(), sqlResult.getArgs()); + } + } + } + + // 更新状态 + PrepSqlResultImpl sqlResult = + Util.createSqlBuilder() + .updateSql( + "uf_contract_info", + update, + Util.createPrepWhereImpl().whereAnd("id").whereEqual(ufContractInfoDTO.getId())); + RecordSet rs = new RecordSet(); + toolUtil.writeDebuggerLog( + String.format( + "合同签署回调,更新合同状态,更新语句{%s},更新参数{%s}", sqlResult.getSqlStr(), sqlResult.getArgs())); + rs.executeUpdate(sqlResult.getSqlStr(), sqlResult.getArgs()); + // 查询合同状态,更新明细表 + /* Map data = new HashMap<>(); + data.put("contractNo","6a265befb3944d93a7a8b32b8d5ca33d"); + Map faResult = null; + try { + faResult = FaDDRequestUtils.queryDetailContractStatus(data); + String code = Util.null2String(faResult.get("code")); + if(!"200".equals(code)){ + throw new RuntimeException("查询合同失败,失败原因:" + faResult); + } + Map resultData = (Map) faResult.get("data"); + List> contractSignerList = (List>) resultData.get("contractSignerList"); + for (Map signer : contractSignerList) { + if("-1".equals(signer.get("isSender"))){ + continue; + } + String customerId = Util.null2String(signer.get("customerId")); + String signStatus = Util.null2String(signer.get("signStatus")); + if(!"1".equals(signStatus)){ + continue; + } + // 更新数据库 + update.clear(); + update.put("signed_status",2); + // 查询明细表id + } + } catch (JsonProcessingException e) { + e.printStackTrace(); + toolUtil.writeErrorLog("查询合同失败,失败原因:" + e); + }*/ + } + + + public void signedCallBackError(Map params) { + String contractNo = String.valueOf(params.get("docNo")); + UfContractInfoDTO ufContractInfoDTO = faDDContractMapping.queryContractInfo(contractNo); + toolUtil.writeDebuggerLog("回调,获取到合同信息参数:" + JSON.toJSONString(ufContractInfoDTO)); + String backWritField = Util.getCusConfigValue(ufContractInfoDTO.getWorkflowMainTable()); + if (StringUtils.isNullOrEmpty(backWritField)) { + return; + } + String formatJson = JSONObject.toJSONString(params, SerializerFeature.PrettyFormat, SerializerFeature.WriteDateUseDateFormat); + boolean flag = faDDContractMapping.updateBackInfo(ufContractInfoDTO.getWorkflowMainTable(), + ufContractInfoDTO.getWorkflowRequestId(), backWritField, formatJson); + if (!flag) { + toolUtil.writeDebuggerLog("回调信息回写表单失败!" + params); + } + } + + public void resigned(Map params) { + String contractNo = String.valueOf(params.get("docNo")); + String requestId = String.valueOf(params.get("requestId")); + UfContractInfoDTO ufContractInfoDTO = faDDContractMapping.queryContractInfo(contractNo); + + toolUtil.writeDebuggerLog("重新签署,获取到合同信息参数:" + JSON.toJSONString(ufContractInfoDTO)); + String query = + "select * from " + + ufContractInfoDTO.getWorkflowDetailTable() + + " where mainid = ? and signed_status is not null"; + RecordSet rs = new RecordSet(); + rs.executeQuery(query, ufContractInfoDTO.getMainId()); + List> detailMaps = Util.recordSet2MapList(rs); + toolUtil.writeDebuggerLog("查询到明细数据:" + JSON.toJSONString(detailMaps)); + query = "select * from " + ufContractInfoDTO.getWorkflowMainTable() + " where requestid = ?"; + RecordSet rs1 = new RecordSet(); + rs1.executeQuery(query, ufContractInfoDTO.getWorkflowRequestId()); + Map mainMap = Util.recordSet2Map(rs1); + if (mainMap == null) { + toolUtil.writeErrorLog("mainMap 查询到null -------> " + JSON.toJSONString(ufContractInfoDTO)); + throw new RuntimeException("mainMap查询到null!"); + } + // 获取配置表信息 + FaDaDaConfigDTO faDaDaConfigDTO = + faDDContractMapping.queryConfig(String.valueOf(ufContractInfoDTO.getWorkflowType()), 3); + // 查询接口配置树形结构 + ApiConfigMainDTO apiConfigMainDTO = Util.queryApiConfigTree(faDaDaConfigDTO.getParamsConfig()); + // 查询签署数据 + List> dataArr = + getDataArr( + ufContractInfoDTO.getWorkflowRequestId(), + String.valueOf(ufContractInfoDTO.getWorkflowType()), + ufContractInfoDTO.getWorkflowMainTable(), + ufContractInfoDTO.getWorkflowDetailTable(), + detailMaps); + // 处理数据 + List> maps = objectAndListHandle(apiConfigMainDTO.getDetails(), dataArr); + if (maps == null) { + toolUtil.writeDebuggerLog("service签署合同错误,错误原因:maps为null!"); + throw new RuntimeException("service签署合同错误,错误原因:maps为null!"); + } + if (maps.size() == 0) { + return; + } + Map updateData = new HashMap<>(); + Map map = maps.get(maps.size() - 1); + // 如果进行控制签署规则 + if (faDaDaConfigDTO.getSignedType() == 1) { + if (Integer.parseInt(Util.null2String(mainMap.get(faDaDaConfigDTO.getFieldControl1()))) + == faDaDaConfigDTO.getOnlyOther()) { + // 仅对方签署 + if (maps.size() == 1) { + // map.put("signType", 1); + // 如果是最后一个人了,就直接归档 + map.put("autoArchive", 1); + } + } + } + /* if (faDaDaConfigDTO.getSignedType() == 1) { + // 需要控制签署规则 + if (Integer.parseInt(Util.null2String(mainMap.get(faDaDaConfigDTO.getFieldControl1()))) == faDaDaConfigDTO.getOnlyOther()) { + // 只需要对方签署 + map.put("autoArchive", 1); + } + // 双方签署 + }*/ + // 签署下一次 + toolUtil.writeDebuggerLog("下一个供应商签署合同,签署数据:" + JSON.toJSONString(map)); + List> resultList = signedRequest(map, apiConfigMainDTO); + List signedList = new ArrayList<>(); + // 遍历将数据保存到合同信息表中 + for (Map result : resultList) { + signedList.add(String.valueOf(result.get("signerUrl"))); + } + // 将合同签署地址保存到建模信息中 + updateData.put("contract_signed_url", String.join(" ; ", signedList)); + // 将合同签署信息更新到合同信息表中 + updateData.put("single_signed_num", 0); + PrepSqlResultImpl sqlResult = + Util.createSqlBuilder() + .updateSql( + contractInfoTable, + updateData, + Util.createPrepWhereImpl() + .whereAnd("workflow_request_id") + .whereEqual(ufContractInfoDTO.getWorkflowRequestId())); + rs.executeUpdate(sqlResult.getSqlStr(), sqlResult.getArgs()); + updateData.clear(); + // 更新明细表合同信息 明细表添加字段,signed_status(合同方签署状态) + // 签署状态,1 已发送待签署,2 已签蜀 + updateData.put("signed_status", 1); + sqlResult = + Util.createSqlBuilder() + .updateSql( + ufContractInfoDTO.getWorkflowDetailTable(), + updateData, + Util.createPrepWhereImpl() + .whereAnd("id") + .whereEqual(String.valueOf(map.get("id")))); + rs.executeUpdate(sqlResult.getSqlStr(), sqlResult.getArgs()); + } + + /** + * 查询下一个合同方并发起合同签署 + * + * @param ufContractInfoDTO + */ + private void nextContractSigned(UfContractInfoDTO ufContractInfoDTO) { + String query = + "select * from " + + ufContractInfoDTO.getWorkflowDetailTable() + + " where mainid = ? and signed_status is null"; + RecordSet rs = new RecordSet(); + rs.executeQuery(query, ufContractInfoDTO.getMainId()); + List> detailMaps = Util.recordSet2MapList(rs); + toolUtil.writeDebuggerLog("查询到明细数据:" + JSON.toJSONString(detailMaps)); + query = "select * from " + ufContractInfoDTO.getWorkflowMainTable() + " where requestid = ?"; + RecordSet rs1 = new RecordSet(); + rs1.executeQuery(query, ufContractInfoDTO.getWorkflowRequestId()); + Map mainMap = Util.recordSet2Map(rs1); + if (mainMap == null) { + toolUtil.writeErrorLog("mainMap 查询到null -------> " + JSON.toJSONString(ufContractInfoDTO)); + throw new RuntimeException("mainMap查询到null!"); + } + // 获取配置表信息 + FaDaDaConfigDTO faDaDaConfigDTO = + faDDContractMapping.queryConfig(String.valueOf(ufContractInfoDTO.getWorkflowType()), 3); + // 查询接口配置树形结构 + ApiConfigMainDTO apiConfigMainDTO = Util.queryApiConfigTree(faDaDaConfigDTO.getParamsConfig()); + // 查询签署数据 + List> dataArr = + getDataArr( + ufContractInfoDTO.getWorkflowRequestId(), + String.valueOf(ufContractInfoDTO.getWorkflowType()), + ufContractInfoDTO.getWorkflowMainTable(), + ufContractInfoDTO.getWorkflowDetailTable(), + detailMaps); + // 处理数据 + List> maps = objectAndListHandle(apiConfigMainDTO.getDetails(), dataArr); + if (maps == null) { + toolUtil.writeDebuggerLog("service签署合同错误,错误原因:maps为null!"); + throw new RuntimeException("service签署合同错误,错误原因:maps为null!"); + } + if (maps.size() == 0 || maps.size() <= 1) { + return; + } + Map updateData = new HashMap<>(); + Map map = maps.get(1); + // 如果进行控制签署规则 + if (faDaDaConfigDTO.getSignedType() == 1) { + if (Integer.parseInt(Util.null2String(mainMap.get(faDaDaConfigDTO.getFieldControl1()))) + == faDaDaConfigDTO.getOnlyOther()) { + // 仅对方签署 + if (maps.size() == 1) { + // map.put("signType", 1); + // 如果是最后一个人了,就直接归档 + map.put("autoArchive", 1); + } + } + } + /* if (faDaDaConfigDTO.getSignedType() == 1) { + // 需要控制签署规则 + if (Integer.parseInt(Util.null2String(mainMap.get(faDaDaConfigDTO.getFieldControl1()))) == faDaDaConfigDTO.getOnlyOther()) { + // 只需要对方签署 + map.put("autoArchive", 1); + } + // 双方签署 + }*/ + // 签署下一次 + toolUtil.writeDebuggerLog("下一个供应商签署合同,签署数据:" + JSON.toJSONString(map)); + List> resultList = signedRequest(map, apiConfigMainDTO); + List signedList = new ArrayList<>(); + // 遍历将数据保存到合同信息表中 + for (Map result : resultList) { + signedList.add(String.valueOf(result.get("signerUrl"))); + } + // 将合同签署地址保存到建模信息中 + updateData.put("contract_signed_url", String.join(" ; ", signedList)); + // 将合同签署信息更新到合同信息表中 + updateData.put("single_signed_num", 0); + PrepSqlResultImpl sqlResult = + Util.createSqlBuilder() + .updateSql( + contractInfoTable, + updateData, + Util.createPrepWhereImpl() + .whereAnd("workflow_request_id") + .whereEqual(ufContractInfoDTO.getWorkflowRequestId())); + rs.executeUpdate(sqlResult.getSqlStr(), sqlResult.getArgs()); + updateData.clear(); + // 更新明细表合同信息 明细表添加字段,signed_status(合同方签署状态) + // 签署状态,1 已发送待签署,2 已签蜀 + updateData.put("signed_status", 1); + sqlResult = + Util.createSqlBuilder() + .updateSql( + ufContractInfoDTO.getWorkflowDetailTable(), + updateData, + Util.createPrepWhereImpl() + .whereAnd("id") + .whereEqual(String.valueOf(map.get("id")))); + rs.executeUpdate(sqlResult.getSqlStr(), sqlResult.getArgs()); + } + + /** + * 合同签署发送请求 + * + * @param map + * @param apiConfigMainDTO + */ + private List> signedRequest(Map map, ApiConfigMainDTO apiConfigMainDTO) { + String contractNos = Util.null2String(map.get("contractNo")); + String[] split = contractNos.split(","); + List> resultList = new ArrayList<>(); + // RecordSet rs = new RecordSet(); + for (String s : split) { + map.put("contractNo", s); + ResponeVo responeVo = FaDDRequestUtils.signedContract(map, apiConfigMainDTO.getApiUrl()); + Map response = null; + try { + response = responeVo.getEntityMap(); + } catch (JsonProcessingException e) { + e.printStackTrace(); + } + if (!"200".equals(response.get("code"))) { + toolUtil.writeDebuggerLog("法大大接口签署合同失败!"); + throw new RuntimeException("法大大接口签署合同失败!"); + } + resultList.add((Map) response.get("data")); + } + return resultList; + } + + /** + * 查询合同的状态信息 + * + * @param requestId + * @return + */ + public Map querySignedStatus(String requestId) { + // 查询合同状态 + String query = "select * from " + contractInfoTable + " where workflow_request_id = ?"; + RecordSet rs = new RecordSet(); + rs.executeQuery(query, requestId); + Map result = Util.recordSet2Map(rs); + boolean isAllSinged = false; + boolean isSingedOneself = false; + if (result == null) { + toolUtil.writeDebuggerLog("查询到状态为null;sql:" + query + " ---> " + requestId); + return ParaMap.create().put("isAllSinged", false).put("isSingedOneself", false); + } + // this.toolUtil.writeDebuggerLog(result.toString()); + // 等待对方签署 + /* if("2".equals(result.get("contract_status"))){ + isAllSinged = false; + }*/ + // 等待我方签署 + if ("3".equals(Util.null2String(result.get("contract_status")))) { + isAllSinged = true; + } + // 签署完毕 + if ("4".equals(Util.null2String(result.get("contract_status")))) { + isAllSinged = true; + isSingedOneself = true; + } + return ParaMap.create().put("isAllSinged", isAllSinged).put("isSingedOneself", isSingedOneself); + } + + public void signedContractOwn(String requestId, User user) { + // 查询合同信息 + UfContractInfoDTO ufContractInfoDTO = + faDDContractMapping.queryContractInfoByRequestId(requestId); + // 获取配置表信息 + FaDaDaConfigDTO faDaDaConfigDTO = + faDDContractMapping.queryConfig(String.valueOf(ufContractInfoDTO.getWorkflowType()), 4); + // 查询接口配置树形结构 + ApiConfigMainDTO apiConfigMainDTO = Util.queryApiConfigTree(faDaDaConfigDTO.getParamsConfig()); + // 查询签署数据 + List> dataArr = + getDataArr( + ufContractInfoDTO.getWorkflowRequestId(), + String.valueOf(ufContractInfoDTO.getWorkflowType()), + ufContractInfoDTO.getWorkflowMainTable(), + ufContractInfoDTO.getWorkflowDetailTable()); + // 处理数据 + List> maps = objectAndListHandle(apiConfigMainDTO.getDetails(), dataArr); + if (maps == null) { + toolUtil.writeErrorLog("service签署合同错误,错误原因:maps为null!"); + throw new RuntimeException("service签署合同错误,错误原因:maps为null!"); + } + if (maps.size() == 0) { + return; + } + Map data = maps.get(0); + String contractNos = String.valueOf(data.get("contractNo")); + String[] split = contractNos.split(","); + List downloadUrlList = new ArrayList<>(); + List viewUrlList = new ArrayList<>(); + for (String s : split) { + data.put("contractNo", s); + ResponeVo responeVo = FaDDRequestUtils.signedContract(data, apiConfigMainDTO.getApiUrl()); + Map response = null; + try { + response = responeVo.getEntityMap(); + } catch (JsonProcessingException e) { + e.printStackTrace(); + } + if (!"200".equals(response.get("code"))) { + this.toolUtil.writeErrorLog("签署参数:" + responeVo.getEntityString()); + throw new RuntimeException("本方签署失败!法大大请求接口错误!"); + } else { + Map result = (Map) response.get("data"); + downloadUrlList.add(Util.null2String(result.get("downloadUrl"))); + viewUrlList.add(Util.null2String(result.get("viewUrl"))); + } + } + // 更新合同状态 + RecordSet rs = new RecordSet(); + Map update = new HashMap<>(); + update.put("contract_status", 4); + update.put("contract_view_url", String.join(";", viewUrlList)); + update.put("contract_down_url", String.join(";", downloadUrlList)); + PrepSqlResultImpl sqlResult = + Util.createSqlBuilder() + .updateSql( + contractInfoTable, + update, + Util.createPrepWhereImpl().whereAnd("workflow_request_id").whereEqual(requestId)); + toolUtil.writeDebuggerLog(sqlResult.getSqlStr() + ",参数:" + sqlResult.getArgs()); + rs.executeUpdate(sqlResult.getSqlStr(), sqlResult.getArgs()); + // 获取流程中的合同字段的文档目录id + rs.executeQuery( + "select formid from workflow_base where id = ?", ufContractInfoDTO.getWorkflowType()); + String formId = Util.recordeSet2Entity(rs, String.class); + String query = + "select doccategory from workflow_fileupload where fieldid = (select id from workflow_billfield where fieldname = ? and billid = ?)"; + rs.executeQuery(query, faDaDaConfigDTO.getContractDoc(), formId); + String docCategorys = Util.null2String(Util.recordeSet2Entity(rs, String.class)); + if (StringUtils.isNullOrEmpty(docCategorys)) { + query = "select doccategory from workflow_base where id = ?"; + rs.executeQuery(query, ufContractInfoDTO.getWorkflowType()); + rs.next(); + docCategorys = Util.null2String(rs.getString(1)); + } + if (StringUtils.isNullOrEmpty(docCategorys)) { + docCategorys = ",,1"; + } + // String[] docSplit = docCategorys.split(","); + // String category = docSplit[docSplit.length - 1]; + // 下载合同到文件服务器中 + String docIds = ""; + try { + docIds = downloadContract2FileSystem(ufContractInfoDTO, docCategorys, user); + } catch (Exception e) { + toolUtil.writeErrorLog("创建文档发生错误:" + e); + } + toolUtil.writeDebuggerLog("生成的文档的id:" + docIds); + // 将id保存到流程字段中 + sqlResult = + Util.createSqlBuilder() + .updateSql( + ufContractInfoDTO.getWorkflowMainTable(), + ParaMap.create().put(faDaDaConfigDTO.getContractDoc(), docIds), + Util.createPrepWhereImpl() + .whereAnd("id") + .whereEqual(ufContractInfoDTO.getMainId())); + toolUtil.writeDebuggerLog(sqlResult.getSqlStr() + ",参数:" + sqlResult.getArgs()); + rs.executeUpdate(sqlResult.getSqlStr(), sqlResult.getArgs()); + } + + public String downloadContract2FileSystem( + UfContractInfoDTO ufContractInfoDTO, String category, User user) { + + /* ImageFileManager fileManager = new ImageFileManager(); + int fileId = fileManager.saveImageFileByInputStream(downloadContract(ufContractInfoDTO.getContractNo(), + String.valueOf(ufContractInfoDTO.getWorkflowType())), ufContractInfoDTO.getFileName());*/ + // 获取配置表信息 + FaDaDaConfigDTO faDaDaConfigDTO = + faDDContractMapping.queryConfig(String.valueOf(ufContractInfoDTO.getWorkflowType()), 5); + ApiConfigMainDTO apiConfigMainDTO = Util.queryApiConfig(faDaDaConfigDTO.getParamsConfig()); + String contractNos = Util.null2String(ufContractInfoDTO.getContractNo()); + String[] split = contractNos.split(","); + List docIds = new ArrayList<>(); + for (String contractNo : split) { + // InputStream inputStream = downloadContract(s, + // String.valueOf(ufContractInfoDTO.getWorkflowType())); + Map data = new HashMap<>(); + data.put("contractNo", contractNo); + AtomicReference content = new AtomicReference<>(); + FaDDRequestUtils.downContract( + data, + response -> { + HttpEntity entity = response.getEntity(); + if (response.getStatusLine().getStatusCode() != 200) { + throw new RuntimeException("法大大请求接口错误!"); + } + try { + content.set(entity.getContent()); + } catch (IOException e) { + e.printStackTrace(); + } + byte[] byteArray = null; + try { + byteArray = IOUtils.toByteArray(content.get()); + } catch (IOException e) { + e.printStackTrace(); + toolUtil.writeErrorLog("文件流处理错误,将inputStream转换为byte数组出错:" + e); + } + this.toolUtil.writeErrorLog(ufContractInfoDTO.toString()); + String base64 = Base64Utils.encode(byteArray); + FileProcessor fileProcessor = new FileProcessor(); + // toolUtil.writeDebuggerLog("base64:" + "base64:" + base64); + toolUtil.writeDebuggerLog("category:" + category); + // toolUtil.writeDebuggerLog("user:" + JSON.toJSONString(user)); + toolUtil.writeDebuggerLog("fileName:" + ufContractInfoDTO.getFileName()); + docIds.add( + String.valueOf( + fileProcessor.Process( + "base64:" + base64, category, user, ufContractInfoDTO.getFileName()))); + }, + apiConfigMainDTO.getApiUrl()); + } + return String.join(",", docIds); + } + + public InputStream downloadContract(String contractNo, String workflowId) { + // 获取配置表信息 + FaDaDaConfigDTO faDaDaConfigDTO = faDDContractMapping.queryConfig(workflowId, 5); + ApiConfigMainDTO apiConfigMainDTO = Util.queryApiConfig(faDaDaConfigDTO.getParamsConfig()); + Map data = new HashMap<>(); + data.put("contractNo", contractNo); + AtomicReference content = new AtomicReference<>(); + FaDDRequestUtils.downContract( + data, + response -> { + HttpEntity entity = response.getEntity(); + if (response.getStatusLine().getStatusCode() != 200) { + throw new RuntimeException("法大大请求接口错误!"); + } + try { + content.set(entity.getContent()); + } catch (IOException e) { + e.printStackTrace(); + } + }, + apiConfigMainDTO.getApiUrl()); + return content.get(); + } + + /** + * 直接从法大大系统下载文件 + * + * @param ufContractInfoDTO 合同相关信息 + * @return + */ + public StreamingOutput download4mFDD(UfContractInfoDTO ufContractInfoDTO) { + // 获取配置表信息 + FaDaDaConfigDTO faDaDaConfigDTO = + faDDContractMapping.queryConfig(String.valueOf(ufContractInfoDTO.getWorkflowType()), 5); + ApiConfigMainDTO apiConfigMainDTO = Util.queryApiConfig(faDaDaConfigDTO.getParamsConfig()); + // 查询合同信息 + // UfContractInfoDTO ufContractInfoDTO = + // faDDContractMapping.queryContractInfoByRequestId(requestId); + String contractNos = Util.null2String(ufContractInfoDTO.getContractNo()); + String fileNames = Util.null2String(ufContractInfoDTO.getFileName()); + String[] contractNoArr = contractNos.split(","); + String[] fileNameArr = fileNames.split(","); + toolUtil.writeDebuggerLog("下载合同download4mFDD!"); + if (contractNoArr.length >= 2) { + // 多个文件,需要下载压缩包 + return outputStream -> { + ZipOutputStream zipOut = new ZipOutputStream(outputStream); + int catchLen = 10 * 1024; + for (int i = 0; i < contractNoArr.length; i++) { + // InputStream inputStream = downloadContract(contractNoArr[i], + // String.valueOf(ufContractInfoDTO.getWorkflowType())); + Map data = new HashMap<>(); + data.put("contractNo", contractNoArr[i]); + AtomicReference content = new AtomicReference<>(); + int finalI = i; + FaDDRequestUtils.downContract( + data, + response -> { + HttpEntity entity = response.getEntity(); + if (response.getStatusLine().getStatusCode() != 200) { + throw new RuntimeException("法大大请求接口错误!"); + } + try { + content.set(entity.getContent()); + zipOut.putNextEntry(new ZipEntry(fileNameArr[finalI])); + byte[] buffer = new byte[catchLen]; + int len = 0; + while ((len = content.get().read(buffer)) != -1) { + zipOut.write(buffer, 0, len); + } + content.get().close(); + zipOut.closeEntry(); + } catch (IOException e) { + e.printStackTrace(); + toolUtil.writeErrorLog("文件压缩处理出现问题!" + e); + } + }, + apiConfigMainDTO.getApiUrl()); + } + zipOut.flush(); + zipOut.close(); + outputStream.flush(); + outputStream.close(); + }; + } + return outputStream -> { + toolUtil.writeDebuggerLog("download4mFDD单文件下载!"); + // InputStream inputStream = + // downloadContract(contractNos,String.valueOf(ufContractInfoDTO.getWorkflowType())); + Map data = new HashMap<>(); + data.put("contractNo", contractNos); + AtomicReference content = new AtomicReference<>(); + FaDDRequestUtils.downContract( + data, + response -> { + HttpEntity entity = response.getEntity(); + if (response.getStatusLine().getStatusCode() != 200) { + throw new RuntimeException("法大大请求接口错误!"); + } + try { + content.set(entity.getContent()); + int catchLen = 10 * 1024; + byte[] buffer = new byte[catchLen]; + int len = 0; + while ((len = content.get().read(buffer)) != -1) { + outputStream.write(buffer, 0, len); + } + content.get().close(); + outputStream.flush(); + outputStream.close(); + } catch (IOException e) { + e.printStackTrace(); + toolUtil.writeErrorLog("单文件下载处理出现问题!" + e); + } + }, + apiConfigMainDTO.getApiUrl()); + }; + } + + public void pushAPush(String requestId) { + UfContractInfoDTO ufContractInfoDTO = faDDContractMapping.queryContractInfoByRequestId(requestId); + String signedUrls = Util.null2String(ufContractInfoDTO.getContractSignedUrl()); + PushAPushEmailEntity pushAPushEmailEntity = queryEmailInfo(ufContractInfoDTO.getWorkflowType(), + ufContractInfoDTO.getWorkflowRequestId()); + String content = pushAPushEmailEntity.getEmailContent().replaceAll("#\\{info.signedUrls}", signedUrls); + try { + EmailWorkRunnable.threadModeReminder(pushAPushEmailEntity.getEmailAddress(), "", "", + pushAPushEmailEntity.getEmailTitle(), + content); + } catch (Exception e) { + toolUtil.writeDebuggerLog(e.toString()); + } + } + + private PushAPushEmailEntity queryEmailInfo(int workflowType, String requestId) { + PushAPushEmailEntity pushAPushEmailEntity = faDDContractMapping.queryEmailInfo(workflowType); + Map workflowData = getWorkflowData(String.valueOf(workflowType), requestId); + String parsingTitle = parsingValue(pushAPushEmailEntity.getEmailTitle(), workflowData); + pushAPushEmailEntity.setEmailTitle(parsingTitle); + String parsingEmail = parsingValue(pushAPushEmailEntity.getEmailAddress(), workflowData); + pushAPushEmailEntity.setEmailAddress(parsingEmail); + try { + String parsingContent = parsingValue(pushAPushEmailEntity.getEmailContent(), workflowData); + pushAPushEmailEntity.setEmailContent(parsingContent); + } catch (Exception e) { + toolUtil.writeDebuggerLog("解析出错:" + e); + } + return pushAPushEmailEntity; + } + + public String parsingValue(String str, Map workflowData) { + String regEx = "\\$\\{(?\\S+?)}"; + Pattern compile = Pattern.compile(regEx); + Matcher matcher = compile.matcher(str); + String parsingValue = str; + parsingValue = parsingValue.replaceAll("\\$\\{sys\\.data}", Util.getTime("yyyy-MM-dd")); + parsingValue = parsingValue.replaceAll("\\$\\{sys\\.time}", Util.getTime("HH:mm:ss")); + parsingValue = parsingValue.replaceAll("\\$\\{sys\\.dataTime}", Util.getTime("yyyy-MM-dd HH:mm:ss")); + while (matcher.find()) { + String key = matcher.group("key"); + String value = Util.null2String(workflowData.get(key)); + parsingValue = parsingValue.replaceFirst(regEx, value); + } + regEx = "#sql\\{\\{(?(\\S\\s)+?)}}"; + compile = Pattern.compile(regEx); + matcher = compile.matcher(str); + while (matcher.find()) { + String key = matcher.group("key"); + String value = parsingSql(key, workflowData); + parsingValue = parsingValue.replaceFirst(regEx, value); + } + return parsingValue; + } + + private String parsingSql(String str, Map workflowData) { + RecordSet rs = new RecordSet(); + String sqlRegEx = "#\\{(?\\S+?)}"; + Pattern sqlCompile = Pattern.compile(sqlRegEx); + Matcher sqlMatcher = sqlCompile.matcher(str); + String parsingSql = str; + parsingSql = parsingSql.replaceAll("#\\{sys\\.data}", "'" + Util.getTime("yyyy-MM-dd") + "'"); + parsingSql = parsingSql.replaceAll("#\\{sys\\.time}", "'" + Util.getTime("HH:mm:ss") + "'"); + parsingSql = parsingSql.replaceAll("#\\{sys\\.dataTime}", "'" + Util.getTime("yyyy-MM-dd HH:mm:ss") + "'"); + List args = new ArrayList<>(); + while (sqlMatcher.find()) { + String key = sqlMatcher.group("key"); + String value = Util.null2String(workflowData.get(key)); + parsingSql = parsingSql.replaceFirst(sqlRegEx, "?"); + args.add(value); + } + String value = ""; + if (str.toLowerCase().trim().startsWith("select")) { + rs.executeQuery(parsingSql, args); + if (rs.next()) { + value = rs.getString(1); + } + } + return value; + } + + public Map getWorkflowData(String workflowId, String requestId) { + String queryMainTable = "select base.id,base.workflowname,base.formid,bill.tablename " + + "from workflow_bill bill join workflow_base base on base.formid = bill.id " + + "where base.id = ?"; + RecordSet rs = new RecordSet(); + rs.executeQuery(queryMainTable, workflowId); + String mainTable = ""; + if (rs.next()) { + mainTable = rs.getString("tablename"); + } else { + toolUtil.writeDebuggerLog("表查询到数据为null," + mainTable + "---》" + queryMainTable); + } + String queryDetailTable = "select bill.id bill_id, base.workflowname,base.formid " + + "main_formid,bill.tablename,bill.orderid from workflow_billdetailtable bill " + + "join workflow_base base on base.formid = bill.billid where base.id = ?"; + rs.executeQuery(queryDetailTable, workflowId); + List> detailTableList = new ArrayList<>(); + while (rs.next()) { + Map map = new HashMap<>(); + map.put("tableName", rs.getString("tablename")); + map.put("tableOrderId", rs.getString("orderid")); + detailTableList.add(map); + } + // 查询主表数据 + String queryMainData = "select * from " + mainTable + " where requestid = ?"; + rs.executeQuery(queryMainData, requestId); + Map mainData = Util.recordSet2Map(rs); + if (mainData == null) { + toolUtil.writeDebuggerLog("查询到数据为null," + mainData + "---》" + queryMainData); + return null; + } + // 查询明细表数据 + for (Map detailTable : detailTableList) { + String queryDetailData = "select * from " + detailTable.get("tableName") + " where mainid = ?"; + rs.executeQuery(queryDetailData, String.valueOf(mainData.get("id"))); + Map detailData = Util.recordSet2Map(rs); + if (detailData == null) { + continue; + } + for (Map.Entry entry : detailData.entrySet()) { + mainData.put("detail_" + detailTable.get("tableOrderId") + "." + entry.getKey(), entry.getValue()); + } + } + mainData.put("requestId", requestId); + mainData.put("workflowId", workflowId); + return mainData; + } + + +} + + + diff --git a/src/main/youhong_ai_old_src/com/api/aiyh_pcn/fadada/service/impl/FaDDServiceImpl.java b/src/main/youhong_ai_old_src/com/api/aiyh_pcn/fadada/service/impl/FaDDServiceImpl.java new file mode 100644 index 0000000..b734522 --- /dev/null +++ b/src/main/youhong_ai_old_src/com/api/aiyh_pcn/fadada/service/impl/FaDDServiceImpl.java @@ -0,0 +1,588 @@ +package com.api.aiyh_pcn.fadada.service.impl; + +import aiyh.utils.Util; +import aiyh.utils.entity.ApiConfigDetailDTO; +import aiyh.utils.entity.ApiConfigMainDTO; +import aiyh.utils.httpUtil.ResponeVo; +import aiyh.utils.zwl.common.ToolUtil; +import com.alibaba.fastjson.JSONObject; +import com.api.aiyh_pcn.fadada.dao.FaDDServiceMapping; +import com.api.aiyh_pcn.fadada.entity.FaDaDaConfigDTO; +import com.api.aiyh_pcn.fadada.service.IFaDDService; +import com.api.aiyh_pcn.fadada.util.FaDDRequestUtils; +import com.api.aiyh_pcn.fadada.vo.TableFieldMappingVO; +import com.fasterxml.jackson.core.JsonProcessingException; +import org.apache.http.Header; +import org.apache.http.HeaderElement; +import org.apache.http.HttpEntity; +import org.apache.http.NameValuePair; +import weaver.conn.RecordSet; +import weaver.workflow.workflow.WorkflowVersion; + +import javax.ws.rs.core.StreamingOutput; +import java.io.IOException; +import java.io.InputStream; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.zip.ZipEntry; +import java.util.zip.ZipOutputStream; + +/** + * @author EBU7-dev1-ayh + * @create 2021/9/30 0030 11:12 core + */ +public class FaDDServiceImpl implements IFaDDService { + private final FaDDServiceMapping faDDServiceMapping = new FaDDServiceMapping(); + private final ToolUtil toolUtil = new ToolUtil(); + // private final String MAIN_TABLE = "formtable_main_17"; + + @Override + public Map getConfigParam(String workflowId) { + FaDaDaConfigDTO faDaDaConfigDTO = faDDServiceMapping.queryConfig(workflowId, 0); + ApiConfigMainDTO apiConfigMainDTO = Util.queryApiConfig(faDaDaConfigDTO.getParamsConfig()); + List tableFieldMappingVOS = new ArrayList<>(); + List details = apiConfigMainDTO.getDetails(); + for (ApiConfigDetailDTO detail : details) { + TableFieldMappingVO tableFieldMappingVO = new TableFieldMappingVO(); + String tableName = ""; + String fieldName = ""; + int id = detail.getId(); + String table = detail.getTablename(); + if (!table.contains("_dt")) { + // 表示字段属于主表 + tableName = "main"; + } else { + // 字段属于明细表 + String dt = table.substring(table.indexOf("_dt") + 3); + tableName = "detail_" + dt; + } + tableFieldMappingVO.setTableName(tableName); + tableFieldMappingVO.setId(id); + int changeRule = detail.getChangeRule(); + if (changeRule == 0) { + // 不转换,需要获取到流程字段,前端获取流程字段对应的值 + fieldName = detail.getWorkflowField(); + tableFieldMappingVO.setField(fieldName); + tableFieldMappingVOS.add(tableFieldMappingVO); + } else if (changeRule == 2) { + // 流程字段值,与不转换一至 + fieldName = detail.getWorkflowField(); + tableFieldMappingVO.setField(fieldName); + tableFieldMappingVOS.add(tableFieldMappingVO); + } + if (changeRule == 7 || changeRule == 6) { + // 7 自定义SQL,与流程转SQL一样 + List tableFieldMappingVOList = new ArrayList<>(); + // 6 流程字段转SQL,需要获取SQL中的字段变量,前端通过字段变量获取值 + // 解析SQL + Map> result = Util.parsingSq2Map(detail.getParamValue()); + for (Map.Entry> entry : result.entrySet()) { + for (String field : entry.getValue()) { + TableFieldMappingVO tf = new TableFieldMappingVO(); + tf.setTableName(entry.getKey()); + tf.setField(field); + tf.setId(id); + tableFieldMappingVOList.add(tf); + } + } + tableFieldMappingVOS.addAll(tableFieldMappingVOList); + } + if (detail.getParamType() == 4) { + // 数组类型的,需要解析数组sql + List tableFieldMappingVOList = new ArrayList<>(); + Map> result = Util.parsingSq2Map(detail.getArraySql()); + for (Map.Entry> entry : result.entrySet()) { + for (String field : entry.getValue()) { + TableFieldMappingVO tf = new TableFieldMappingVO(); + tf.setTableName(entry.getKey()); + tf.setField(field); + tf.setId(id); + tableFieldMappingVOList.add(tf); + } + } + tableFieldMappingVOS.addAll(tableFieldMappingVOList); + } + } + List doDeWeight = + Util.deWeight(tableFieldMappingVOS, e -> e.getTableName() + e.getField()); + Map map = new HashMap<>(); + map.put("tableFieldMappings", doDeWeight); + String checkSource = faDaDaConfigDTO.getCheckSource(); + String sourceTable; + if (!checkSource.contains("_dt")) { + // 表示字段属于主表 + sourceTable = "main"; + map.put("isMain", true); + } else { + // 字段属于明细表 + String dt = checkSource.substring(checkSource.indexOf("_dt") + 3); + sourceTable = "detail_" + dt; + map.put("isMain", false); + } + map.put("sourceTable", sourceTable); + return map; + } + + @Override + public Map checkCertification(Map params) { + Map resultMap = new HashMap<>(); + String workflowId = String.valueOf(params.get("workflowId")); + FaDaDaConfigDTO faDaDaConfigDTO = faDDServiceMapping.queryConfig(workflowId, 0); + ApiConfigMainDTO apiConfigMainDTO = Util.queryApiConfigTree(faDaDaConfigDTO.getParamsConfig()); + List> dataArr = (List>)params.get("dataArr"); + List details = apiConfigMainDTO.getDetails(); + List> datas = objectAndListHandle(details, dataArr); + List> errorList = new ArrayList<>(); + List> nonsupportList = new ArrayList<>(); + for (Map data : datas) { + System.out.println(JSONObject.toJSONString(data)); + Map result = FaDDRequestUtils.checkCompanyInfo(data); + if (result == null) { + // 未查询到数据 + errorList.add(data); + } else { + if ("1001005".equals(String.valueOf(result.get("code"))) + || !"200".equals(String.valueOf(result.get("code")))) { + // 企业信息不存在或者未认证 + nonsupportList.add(data); + } + } + } + if (errorList.size() == 0 && nonsupportList.size() == 0) { + // 所有的都通过 + resultMap.put("allPass", true); + } else { + resultMap.put("allPass", false); + resultMap.put("errorList", errorList); + resultMap.put("nonsupportList", nonsupportList); + } + return resultMap; + } + + private List> objectAndListHandle(List treeList, + List> dataArr) { + List> params = new ArrayList<>(); + for (Map dataMap : dataArr) { + Map param = new HashMap<>(); + for (ApiConfigDetailDTO apiConfigDetailDTO : treeList) { + Object value; + if (apiConfigDetailDTO.getParamType() == 3) { + Map map = new HashMap<>(); + // object类型 + for (ApiConfigDetailDTO child : apiConfigDetailDTO.getChildren()) { + if (child.getChildren() == null || child.getChildren().size() == 0) { + // handleChild(child.getChildren(), dataMap) + map.put(child.getParamName(), changeRuleHandle(child, dataMap)); + } else { + map.put(child.getParamName(), handleChild(child.getChildren(), dataMap)); + } + } + value = map; + } else if (apiConfigDetailDTO.getParamType() == 4) { + String sql = apiConfigDetailDTO.getArraySql(); + String parsingSq = Util.parsingSq(sql, dataMap); + // list类型 + if (parsingSq.contains("delete") || parsingSq.contains("update") || parsingSq.contains("exec") + || parsingSq.contains("drop") || parsingSq.contains("truncate")) { + value = new ArrayList<>(); + } else { + RecordSet rs = new RecordSet(); + rs.executeQuery(parsingSq.replace("select", "select")); + value = Util.recordeSet2Array(rs, String.class); + } + } else { + value = changeRuleHandle(apiConfigDetailDTO, dataMap); + } + param.put(apiConfigDetailDTO.getParamName(), value); + } + params.add(param); + } + return params; + } + + private Object handleChild(List children, Map dataMap) { + Map params = new HashMap<>(); + for (ApiConfigDetailDTO child : children) { + Object value; + if (child.getChildren() != null) { + value = handleChild(child.getChildren(), dataMap); + } else { + value = changeRuleHandle(child, dataMap); + } + params.put(child.getParamName(), value); + } + return params; + } + + private Object changeRuleHandle(ApiConfigDetailDTO apiConfigDetailDTO, Map dataMap) { + Object value; + String tableName; + String table; + String sql; + String resultSql; + // 判断参数的转换规则 + switch (apiConfigDetailDTO.getChangeRule()) { + case 0: + // 不转换 + case 2: + // 流程字段值 + table = apiConfigDetailDTO.getTablename(); + if (!table.contains("_dt")) { + // 表示字段属于主表 + tableName = "main"; + } else { + // 字段属于明细表 + String dt = table.substring(table.indexOf("_dt") + 3); + tableName = "detail_" + dt; + } + value = dataMap.get(tableName + "." + apiConfigDetailDTO.getWorkflowField()); + break; + case 1: + // 固定值 + value = apiConfigDetailDTO.getParamValue(); + break; + case 3: + // 系统日期 + value = Util.getTime("yyyy-MM-dd"); + break; + case 4: + // 系统时间 + value = Util.getTime("HH:mm:ss"); + break; + case 5: + // 系统日期-时间 + value = Util.getTime("yyyy-MM-dd HH:mm:ss"); + break; + case 6: + // 自定义SQL + case 7: + // 流程字段转SQL + sql = apiConfigDetailDTO.getParamValue(); + resultSql = Util.parsingSq(sql, dataMap); + toolUtil.writeErrorLog(dataMap.toString()); + if (resultSql.contains("delete ") || resultSql.contains("update ") || resultSql.contains("exec ") + || resultSql.contains("drop ") || resultSql.contains("truncate ")) { + value = null; + } else { + RecordSet rs = new RecordSet(); + rs.executeQuery(resultSql.replace("select", "select")); + rs.next(); + value = Util.null2String(rs.getString(1)); + toolUtil.writeErrorLog("转换值:" + value); + toolUtil.writeErrorLog("转换SQL:" + resultSql.replace("select", "select")); + } + break; + case 8: + // + // 流程名称 + value = Util.getWorkflowNameById(String.valueOf(dataMap.get("workflowid"))); + break; + case 9: + // + // 请求标题 + value = Util.getRequestTitleById(String.valueOf(dataMap.get("requestid"))); + break; + case 10: + // + // 流程requestId + value = dataMap.get("requestid"); + break; + default: + value = null; + break; + } + if (apiConfigDetailDTO.getParamType() == 1) { + // Integer + value = Integer.parseInt(String.valueOf(value)); + } else if (apiConfigDetailDTO.getParamType() == 2) { + // Boolean + value = Boolean.parseBoolean(String.valueOf(value)); + } + return value; + } + + public void queryContractStatus(String workflowId, String requestId, int type) { + List> maps = faDDServiceMapping.queryDetailInfo(requestId, workflowId, 2); + toolUtil.writeErrorLog("maps+:" + maps); + List> notSignedContracts = new ArrayList<>(); + // 查询是是否签署 + for (Map map : maps) { + // 发送请求查询合同信息 + Map data = new HashMap<>(); + String contracts = String.valueOf(map.get("contract_no")); + if (contracts == null) { + contracts = ""; + } + String[] split = contracts.split(","); + for (String s : split) { + toolUtil.writeErrorLog(s); + data.put("contractNo", s); + Map result = null; + // List statusList = new ArrayList<>(); + try { + Map response = FaDDRequestUtils.queryContractStatus(data); + if (!"200".equals(response.get("code"))) { + throw new RuntimeException("法大大请求接口错误!"); + } + result = (Map)response.get("data"); + this.toolUtil.writeErrorLog("催一催:" + result); + } catch (RuntimeException e) { + e.printStackTrace(); + throw e; + } catch (JsonProcessingException e) { + toolUtil.writeDebuggerLog("转换错误:" + e); + } + if ("1".equals(String.valueOf(result.get("status"))) + || "6".equals(String.valueOf(result.get("status")))) { + // 发送请求催一下 签署合同 + notSignedContracts.add(map); + } else { + // 合同状态发生改变,需要修改数据库中的状态信息 百分百会出问题 + map.put("contract_status", result.get("status")); + // statusList.add() + faDDServiceMapping.updateContractStatus(map, workflowId, 3); + } + } + } + if (type == 0) { + signedContract(workflowId, requestId, notSignedContracts); + } + } + + public void signedContract(String workflowId, String requestId, List> detailMaps) { + String mainTable = faDDServiceMapping.getMainTable(workflowId); + RecordSet rs = new RecordSet(); + String query = "select * from " + mainTable + " where requestid = ?"; + rs.executeQuery(query, requestId); + Map mainMap; + mainMap = Util.recordSet2Map(rs); + String mainId = ""; + if (mainMap != null) { + mainId = String.valueOf(mainMap.get("id")); + } else { + toolUtil.writeErrorLog("没有查询到相关的请求id的数据!"); + } + String detailTable1 = faDDServiceMapping.getDetailTable(workflowId, 3); + query = "select * from " + detailTable1 + " where mainid = ?"; + rs.executeQuery(query, mainId); + /*List> detailMaps; + detailMaps = Util.recordSet2MapList(rs); + if (detailMaps == null) { + toolUtil.writeErrorLog("查询明细失败!maps为null"); + return; + }*/ + FaDaDaConfigDTO faDaDaConfigDTO = faDDServiceMapping.queryConfig(workflowId, 3); + ApiConfigMainDTO apiConfigMainDTO = Util.queryApiConfigTree(faDaDaConfigDTO.getParamsConfig()); + List> dataArr = new ArrayList<>(); + String detailTable; + String dt = detailTable1.substring(detailTable1.indexOf("_dt") + 3); + detailTable = "detail_" + dt; + for (Map detailMap : detailMaps) { + Map dataMap = new HashMap<>(); + for (Map.Entry entry : detailMap.entrySet()) { + dataMap.put(detailTable + "." + entry.getKey(), entry.getValue()); + } + for (Map.Entry entry : mainMap.entrySet()) { + dataMap.put("main" + "." + entry.getKey(), entry.getValue()); + } + dataArr.add(dataMap); + } + List> maps = objectAndListHandle(apiConfigMainDTO.getDetails(), dataArr); + for (Map map : maps) { + toolUtil.writeErrorLog(map.toString()); + String contractNos = Util.null2String(map.get("contractNo")); + String[] split = contractNos.split(","); + for (String s : split) { + map.put("contractNo", s); + ResponeVo responeVo = FaDDRequestUtils.signedContract(map, apiConfigMainDTO.getApiUrl()); + Map response = null; + try { + response = responeVo.getEntityMap(); + } catch (JsonProcessingException e) { + e.printStackTrace(); + } + if (!"200".equals(response.get("code"))) { + throw new RuntimeException("法大大请求接口错误!"); + } + } + } + } + + public StreamingOutput contractDownload(String requestId, String workflowId) { + toolUtil.writeErrorLog("进入service方法!"); + List> maps = null; + // 查询合同信息 + try { + maps = faDDServiceMapping.queryDetailDownInfo(requestId, workflowId, 2); + } catch (Exception e) { + toolUtil.writeErrorLog(String.valueOf(faDDServiceMapping)); + toolUtil.writeErrorLog("调用错误" + e); + } + toolUtil.writeErrorLog(String.valueOf(maps)); + toolUtil.writeErrorLog(JSONObject.toJSONString(maps)); + List> finalMaps = maps; + String versionStringByWfid = WorkflowVersion.getVersionStringByWfid(workflowId); + RecordSet rs = new RecordSet(); + rs.executeQuery( + "select * from uf_contract_config where workflow_type in ( " + versionStringByWfid + " ) and api_type = ?", + 5); + rs.next(); + ApiConfigMainDTO apiConfigMainDTO = Util.queryApiConfig(rs.getString("params_config")); + return outputStream -> { + ZipOutputStream zipOut = new ZipOutputStream(outputStream); + toolUtil.writeErrorLog("进入方法!"); + int catchLen = 10 * 1024; + String base = ""; + for (Map map : finalMaps) { + base = base + map.get("gyshtfmczw") + "/"; + // 获取合同id + String contractNoStr = String.valueOf(map.get("contract_no")); + String contractNameStr = String.valueOf(map.get("file_name")); + String[] contractNos = contractNoStr.split(","); + String[] contractNames = contractNameStr.split(","); + for (int i = 0; i < contractNos.length; i++) { + String contractNo = contractNos[i]; + String contractName = contractNames[i]; + Map data = new HashMap<>(); + data.put("contractNo", contractNo); + // 下载合同 + String finalBase = base; + FaDDRequestUtils.downContract(data, response -> { + HttpEntity entity = response.getEntity(); + if (response.getStatusLine().getStatusCode() != 200) { + throw new RuntimeException("法大大请求接口错误!"); + } + InputStream content = null; + try { + content = entity.getContent(); + Header contentHeader = response.getFirstHeader("Content-disposition"); + String filename = contractName.substring(0, contractName.indexOf(".")) + ".pdf"; + if (contentHeader != null) { + HeaderElement[] values = contentHeader.getElements(); + NameValuePair param = values[0].getParameterByName("filename"); + filename = param.getValue(); + } + zipOut.putNextEntry(new ZipEntry(finalBase + filename)); + byte[] buffer = new byte[catchLen]; + int len = 0; + while ((len = content.read(buffer)) != -1) { + zipOut.write(buffer, 0, len); + } + zipOut.closeEntry(); + } catch (IOException e) { + e.printStackTrace(); + toolUtil.writeErrorLog("压缩错误!" + e + "\n"); + } + }, apiConfigMainDTO.getApiUrl()); + } + } + zipOut.flush(); + zipOut.close(); + }; + } + + public boolean isAllSinged(String requestId, String workflowId) { + List> maps = faDDServiceMapping.queryDetailInfo(requestId, workflowId, 2); + if (maps == null || maps.size() == 0) { + return true; + } + return false; + } + + public boolean isSingedOneself(String requestId, String workflowId) { + List> maps = faDDServiceMapping.querySignedInfo(requestId, workflowId); + if (maps == null || maps.size() == 0) { + return false; + } + return true; + } + + public void signedContractOwn(String workflowId, String requestId) { + String mainTable = faDDServiceMapping.getMainTable(workflowId); + RecordSet rs = new RecordSet(); + String query = "select * from " + mainTable + " where requestid = ?"; + rs.executeQuery(query, requestId); + Map mainMap; + mainMap = Util.recordSet2Map(rs); + String mainId = ""; + if (mainMap != null) { + mainId = String.valueOf(mainMap.get("id")); + } else { + toolUtil.writeErrorLog("没有查询到相关的请求id的数据!"); + } + String detailTable1 = faDDServiceMapping.getDetailTable(workflowId, 4); + query = "select * from " + detailTable1 + " where mainid = ?"; + rs.executeQuery(query, mainId); + List> detailMaps; + detailMaps = Util.recordSet2MapList(rs); + this.toolUtil.writeErrorLog("查询到的数据:" + detailMaps.toString()); + if (detailMaps == null) { + toolUtil.writeErrorLog("查询明细失败!maps为null"); + return; + } + FaDaDaConfigDTO faDaDaConfigDTO = faDDServiceMapping.queryConfig(workflowId, 4); + ApiConfigMainDTO apiConfigMainDTO = Util.queryApiConfigTree(faDaDaConfigDTO.getParamsConfig()); + List> dataArr = new ArrayList<>(); + String detailTable; + String dt = detailTable1.substring(detailTable1.indexOf("_dt") + 3); + detailTable = "detail_" + dt; + toolUtil.writeErrorLog("明细表:" + detailTable); + for (Map detailMap : detailMaps) { + Map dataMap = new HashMap<>(); + for (Map.Entry entry : detailMap.entrySet()) { + dataMap.put(detailTable + "." + entry.getKey(), entry.getValue()); + } + for (Map.Entry entry : mainMap.entrySet()) { + dataMap.put("main" + "." + entry.getKey(), entry.getValue()); + } + dataArr.add(dataMap); + } + toolUtil.writeErrorLog("替换参数值:" + dataArr.toString()); + List> maps = objectAndListHandle(apiConfigMainDTO.getDetails(), dataArr); + for (Map map : maps) { + this.toolUtil.writeErrorLog("签署参数:" + map.toString()); + String contractNos = Util.null2String(map.get("contractNo")); + String[] split = contractNos.split(","); + for (String s : split) { + map.put("contractNo", s); + ResponeVo responeVo = FaDDRequestUtils.signedContract(map, apiConfigMainDTO.getApiUrl()); + Map response = null; + try { + response = responeVo.getEntityMap(); + } catch (JsonProcessingException e) { + e.printStackTrace(); + } + if (!"200".equals(response.get("code"))) { + // throw new RuntimeException("法大大请求接口错误!"); + this.toolUtil.writeErrorLog("签署参数:" + responeVo.getEntityString()); + } + } + } + } + + public Map getAllVersion(String workflowId, String markOnly) { + String versionStringByWfid = WorkflowVersion.getVersionStringByWfid(workflowId); + String newWorkflowId = faDDServiceMapping.getAllVersion(versionStringByWfid); + String allVersion = WorkflowVersion.getVersionStringByWfid(newWorkflowId); + if (allVersion == null) { + allVersion = ""; + } + String[] split = allVersion.split(","); + Map data = new HashMap<>(); + String[] nodes = this.getNodes(workflowId, markOnly); + data.put("workflowIds", split); + data.put("nodeIds", nodes); + return data; + } + + public String[] getNodes(String workflowId, String markOnly) { + String versionStringByWfid = WorkflowVersion.getVersionStringByWfid(workflowId); + String nods = faDDServiceMapping.getNodes(versionStringByWfid, markOnly); + if (nods == null) { + nods = ""; + } + return nods.split(","); + } +} diff --git a/src/main/youhong_ai_old_src/com/api/aiyh_pcn/fadada/typeEnum/DisableEnableType.java b/src/main/youhong_ai_old_src/com/api/aiyh_pcn/fadada/typeEnum/DisableEnableType.java new file mode 100644 index 0000000..b23db12 --- /dev/null +++ b/src/main/youhong_ai_old_src/com/api/aiyh_pcn/fadada/typeEnum/DisableEnableType.java @@ -0,0 +1,27 @@ +package com.api.aiyh_pcn.fadada.typeEnum; + +/** + * @author EBU7-dev1-ayh + * create 2021/12/13 0013 16:07 + */ + + +public enum DisableEnableType { + /** + * 不启用 + */ + disable(0), + /** + * 启用 + */ + enable(1); + private final int value; + + DisableEnableType(int value) { + this.value = value; + } + + public int getValue() { + return this.value; + } +} diff --git a/src/main/youhong_ai_old_src/com/api/aiyh_pcn/fadada/typeEnum/EmailType.java b/src/main/youhong_ai_old_src/com/api/aiyh_pcn/fadada/typeEnum/EmailType.java new file mode 100644 index 0000000..d096c74 --- /dev/null +++ b/src/main/youhong_ai_old_src/com/api/aiyh_pcn/fadada/typeEnum/EmailType.java @@ -0,0 +1,29 @@ +package com.api.aiyh_pcn.fadada.typeEnum; + +/** + * @author @author EBU7-dev1-ay + * create 2021/12/13 0013 15:01 + */ + +public enum EmailType { + /** + * 固定值 + */ + fixedValue(0), + /** + * 查询你SQL + */ + querySql(1); + + private final int value; + + private EmailType(int value) { + this.value = value; + } + + public int getValue() { + return this.value; + } + + +} diff --git a/src/main/youhong_ai_old_src/com/api/aiyh_pcn/fadada/util/FaDDRequestUtils.java b/src/main/youhong_ai_old_src/com/api/aiyh_pcn/fadada/util/FaDDRequestUtils.java new file mode 100644 index 0000000..64eb101 --- /dev/null +++ b/src/main/youhong_ai_old_src/com/api/aiyh_pcn/fadada/util/FaDDRequestUtils.java @@ -0,0 +1,243 @@ +package com.api.aiyh_pcn.fadada.util; + +import aiyh.utils.Util; +import aiyh.utils.httpUtil.HttpArgsType; +import aiyh.utils.httpUtil.ResponeVo; +import aiyh.utils.httpUtil.util.HttpUtils; +import aiyh.utils.zwl.common.ToolUtil; +import cn.hutool.core.util.StrUtil; +import cn.hutool.core.util.URLUtil; +import cn.hutool.json.JSONUtil; +import com.alibaba.fastjson.JSONObject; +import com.api.aiyh_pcn.fadada.dao.FaDDServiceMapping; +import com.fasterxml.jackson.core.JsonProcessingException; +import org.apache.commons.codec.binary.Hex; +import org.apache.http.client.methods.CloseableHttpResponse; +import org.h2.util.StringUtils; +import weaver.aiyh_pcn.fadada.entity.FileInfo; + +import java.io.IOException; +import java.nio.charset.StandardCharsets; +import java.security.MessageDigest; +import java.security.NoSuchAlgorithmException; +import java.util.Base64; +import java.util.HashMap; +import java.util.Map; +import java.util.TreeMap; +import java.util.function.Consumer; + +/** + * @author EBU7-dev1-ayh + * @create 2021/10/13 0013 11:46 + * 法大大请求方法 + */ + + +public class FaDDRequestUtils { + private final static HttpUtils httpUtils = new HttpUtils(); + private final static Map header = httpUtils.getGlobalCache().header; + private final static FaDDServiceMapping faDDServiceMapping = new FaDDServiceMapping(); + private final static ToolUtil TOOL_UTIL = new ToolUtil(); + + static { + String appId = TOOL_UTIL.getSystemParamValue("FDD_appId"); + if (StringUtils.isNullOrEmpty(appId)) { + appId = "100001"; + TOOL_UTIL.writeErrorLog("查询到的FDD_appId为空!"); + } + header.put("appId", appId); + header.put("signType", "SHA256"); + String apiKey = TOOL_UTIL.getSystemParamValue("FDD_apiKey"); + if (StringUtils.isNullOrEmpty(apiKey)) { + apiKey = "TulQxnZSRKeHoQfmeZzOUzGn6KpTDkDK"; + TOOL_UTIL.writeErrorLog("查询到的FDD_apiKey为空!"); + } + header.put("apikey", apiKey); + header.put("Content-Type", HttpArgsType.APPLICATION_JSON); + TOOL_UTIL.writeErrorLog(JSONObject.toJSONString(header)); + } + + // 查询企业认证状态 + public static Map checkCompanyInfo(Map data) { + header.put("sign", builderSign(data)); + try { + ResponeVo responeVo = httpUtils.apiPost("http://apigwaws-lite.porsche-cloudservice.com/env-101/econtract/econtract/contract/api/v1/account/company/info", + data, null); + TOOL_UTIL.writeDebuggerLog("查询企业认真状态:" + JSONObject.toJSONString(data)); + TOOL_UTIL.writeDebuggerLog(responeVo.getEntityString() + "\n"); + if (responeVo.getCode() != 200) { + return null; + } + return responeVo.getEntityMap(); + } catch (IOException e) { + e.printStackTrace(); + return null; + } + } + + + // 创建合同 + + /** + * 创建合同接口 + * @param fileInfo 创建合同文件对象 + * @param url 创建合同地址 + * @return 返回值 + */ + public static synchronized ResponeVo createContract(FileInfo fileInfo, String url) { + Map data = new HashMap<>(); + data.put("contractExtension", fileInfo.getContractExtension()); + data.put("contractTitle", fileInfo.getContractTitle()); + data.put("uploadType", fileInfo.getUploadType()); + data.put("customerNo", fileInfo.getCustomerNo()); + header.put("sign", builderSign(data)); + header.put("Content-Type", "multipart/form-data"); + ResponeVo responeVo = null; + try { + responeVo = httpUtils.apiUploadFile(url, + fileInfo.getFile(), "file", fileInfo.getImagefilename(), data, null); + TOOL_UTIL.writeDebuggerLog("创建合同:" + JSONObject.toJSONString(data)); + TOOL_UTIL.writeDebuggerLog("返回信息:" + responeVo.getEntityString() + "\t 状态码:" + responeVo.getCode()); + } catch (IOException e) { + e.printStackTrace(); + TOOL_UTIL.writeErrorLog(e.toString()); + } + return responeVo; + } + + /** + * 签署合同 + * @param data 签署合同参数 + * @param url 签署合同地址 + * @return 返回 + */ + public static synchronized ResponeVo signedContract(Map data, String url) { + header.put("sign", builderSign(data)); + header.put("Content-Type", "application/json"); + ResponeVo responeVo = null; + try { + responeVo = httpUtils.apiPost(url, + data, null); + TOOL_UTIL.writeDebuggerLog("签署合同:" + JSONObject.toJSONString(data)); + TOOL_UTIL.writeDebuggerLog(responeVo.getEntityString() + "\n"); + } catch (IOException e) { + e.printStackTrace(); + } + return responeVo; + } + + /** + * 下载合同 + * @param data 下载合同参数 + * @param consumer 下载合同回调 + * @param url 下载合同地址 + */ + public static void downContract(Map data, Consumer consumer, String url) { + header.put("sign", builderSign(data)); + header.put("Content-Type", "application/json"); + System.out.println(JSONObject.toJSONString(data)); + try { + httpUtils.apiPost(url, + data, null, consumer); + TOOL_UTIL.writeDebuggerLog("下载合同文件:" + JSONObject.toJSONString(data)); + } catch (IOException e) { + e.printStackTrace(); + } + } + + /** + * 查询合同状态 + * @param data 请求参数 + * @return 请求结果封装 + * @throws JsonProcessingException json转换异常 + */ + public static Map queryContractStatus(Map data) throws JsonProcessingException { + header.put("sign", builderSign(data)); + ResponeVo responeVo = null; + try { + responeVo = httpUtils.apiPost("https://apigwaws-lite.porsche-cloudservice.com/env-101/econtract/econtract/contract/api/v1/contract/sign/status/view", + data, null); + TOOL_UTIL.writeDebuggerLog("查询合同状态:" + JSONObject.toJSONString(data)); + TOOL_UTIL.writeDebuggerLog(responeVo.getEntityString() + "\n"); + } catch (IOException e) { + e.printStackTrace(); + } + return responeVo.getEntityMap(); + } + + /** + * 查询合同详细信息 + * @param data 请求参数 + * @return 返回结果 + * @throws JsonProcessingException + */ + public static Map queryDetailContractStatus(Map data) throws JsonProcessingException { + header.put("sign", builderSign(data)); + ResponeVo responeVo = null; + try { + responeVo = httpUtils.apiPost("https://apigwaws.porsche-cloudservice.com/env-101/por-econtract/econtract/contract/api/v1/contract/sign/detail/view", + data, null); + TOOL_UTIL.writeDebuggerLog("查询合同状态:" + JSONObject.toJSONString(data)); + TOOL_UTIL.writeDebuggerLog(responeVo.getEntityString() + "\n"); + } catch (IOException e) { + e.printStackTrace(); + } + return responeVo.getEntityMap(); + } + + + private static String builderSign(Map data) { + header.put("timestamp", Util.getTime("yyyy-MM-dd HH:mm:ss")); + header.put("bizContent", builderBizContent(data)); + String signStr = "appId=" + header.get("appId") + + "&bizContent=" + header.get("bizContent") + + "&signType=" + header.get("signType") + + "×tamp=" + header.get("timestamp"); + String appKey = TOOL_UTIL.getSystemParamValue("FDD_appKey"); + if (StringUtils.isNullOrEmpty(appKey)) { + TOOL_UTIL.writeErrorLog("查询到的FDD_appKey为空!"); + appKey = "L7P59oqA2An0XgJ1LeMN0fRu1"; + } + TOOL_UTIL.writeDebuggerLog("app签名:" + appKey); + TOOL_UTIL.writeDebuggerLog("signStr:" + signStr); + TOOL_UTIL.writeDebuggerLog("请求头信息:" + JSONObject.toJSONString(header)); + String sha256 = string2SHA256(signStr) + appKey; + return Base64.getEncoder().encodeToString(string2SHA256(sha256).getBytes(StandardCharsets.UTF_8)); + } + /** + * 压缩请求信息 + * @param data 请求数据 + * @return 压缩结果 + */ + public static String builderBizContent(Map data) { + String jsonString = JSONUtil.toJsonStr(data); + TOOL_UTIL.writeDebuggerLog("bizContent进行JSON编码:" + jsonString); + TreeMap treeMap = JSONUtil.parseObj(jsonString).toBean(TreeMap.class); + jsonString = JSONUtil.toJsonStr(treeMap); + TOOL_UTIL.writeDebuggerLog("排序后json编码:" + jsonString); + String encode; + encode = URLUtil.encodeAll(jsonString, StandardCharsets.UTF_8); + TOOL_UTIL.writeDebuggerLog("bizContent进行JSON编码后URLEncoder编码:" + encode); + String s = cn.hutool.core.codec.Base64.encode(StrUtil.bytes(encode, StandardCharsets.UTF_8)); + TOOL_UTIL.writeDebuggerLog("bizContent进行JSON编码后URLEncoder编码后进行base64编码:" + s); + return s; + } + + private static String string2SHA256(String str) { + MessageDigest messageDigest; + String encdeStr = ""; + try { + messageDigest = MessageDigest.getInstance("SHA-256"); + byte[] hash = messageDigest.digest(str.getBytes(StandardCharsets.UTF_8)); + encdeStr = Hex.encodeHexString(hash); + TOOL_UTIL.writeDebuggerLog("进行SHA-256加密:" + encdeStr); + } catch (NoSuchAlgorithmException e) { + e.printStackTrace(); + } + String s = encdeStr.toUpperCase(); + TOOL_UTIL.writeDebuggerLog("进行SHA-256加密后转为全大写:" + s); + return s; + } + +} + diff --git a/src/main/youhong_ai_old_src/com/api/aiyh_pcn/fadada/vo/TableFieldMappingVO.java b/src/main/youhong_ai_old_src/com/api/aiyh_pcn/fadada/vo/TableFieldMappingVO.java new file mode 100644 index 0000000..e285df5 --- /dev/null +++ b/src/main/youhong_ai_old_src/com/api/aiyh_pcn/fadada/vo/TableFieldMappingVO.java @@ -0,0 +1,47 @@ +package com.api.aiyh_pcn.fadada.vo; + +/** + * @author EBU7-dev1-ayh + * @create 2021/10/11 0011 15:11 + * 表名和表映射、 + */ + + +public class TableFieldMappingVO { + private String tableName; + private String field; + private int id; + + public int getId() { + return id; + } + + public void setId(int id) { + this.id = id; + } + + public String getTableName() { + return tableName; + } + + public void setTableName(String tableName) { + this.tableName = tableName; + } + + public String getField() { + return field; + } + + public void setField(String field) { + this.field = field; + } + + @Override + public String toString() { + return "TableFieldMappingVO{" + + "tableName='" + tableName + '\'' + + ", field='" + field + '\'' + + ", id=" + id + + '}'; + } +} diff --git a/src/main/youhong_ai_old_src/com/api/aiyh_pcn/fadada/web/FaDDContractController.java b/src/main/youhong_ai_old_src/com/api/aiyh_pcn/fadada/web/FaDDContractController.java new file mode 100644 index 0000000..e9faf0c --- /dev/null +++ b/src/main/youhong_ai_old_src/com/api/aiyh_pcn/fadada/web/FaDDContractController.java @@ -0,0 +1,208 @@ +package com.api.aiyh_pcn.fadada.web; + +import aiyh.utils.ApiResult; +import aiyh.utils.LabelHtmlUtils; +import aiyh.utils.Util; +import aiyh.utils.entity.LabelHtmlIndex; +import aiyh.utils.zwl.common.ToolUtil; +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.JSONObject; +import com.alibaba.fastjson.serializer.SerializerFeature; +import com.api.aiyh_pcn.fadada.dao.FaDDContractMapping; +import com.api.aiyh_pcn.fadada.entity.UfContractInfoDTO; +import com.api.aiyh_pcn.fadada.service.impl.FaDDContractService; +import io.swagger.v3.oas.annotations.parameters.RequestBody; +import org.h2.util.StringUtils; +import weaver.hrm.HrmUserVarify; +import weaver.hrm.User; + +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; +import javax.ws.rs.*; +import javax.ws.rs.core.Context; +import javax.ws.rs.core.MediaType; +import javax.ws.rs.core.Response; +import javax.ws.rs.core.StreamingOutput; +import java.nio.charset.StandardCharsets; +import java.util.HashMap; +import java.util.Map; + +/** + * @author EBU7-dev1-ayh + * @create 2021/11/3 0003 14:49 fadada + */ +@Path("/v2/fadada") +public class FaDDContractController { + + private final FaDDContractService faDDService = new FaDDContractService(); + private final FaDDContractMapping faDDContractMapping = new FaDDContractMapping(); + private final ToolUtil toolUtil = new ToolUtil(); + private final LabelHtmlUtils labelHtmlUtils = new LabelHtmlUtils("aiyh.htmlLabel.porsche.FaDDContractController"); + + /** + * 获取流程全版本 + * + * @param workflowId 流程id + * @return 流程全版本id + */ + @Path("/getAllVersion/{workflowId}/{markOnly}") + @GET + @Produces(MediaType.APPLICATION_JSON) + @Consumes(MediaType.APPLICATION_JSON) + public String getAllVersion(@PathParam("workflowId") String workflowId, @PathParam("markOnly") String markOnly) { + try { + Map allVersion = faDDService.getAllVersion(workflowId, markOnly); + return ApiResult.success(allVersion); + } catch (Exception e) { + toolUtil.writeErrorLog("错误:" + e); + return ApiResult.error(e.toString()); + } + } + + /** + * 合同签署回调 + * + * @param params + * @return + */ + @Path("/callback/signed") + @POST + @Produces(MediaType.APPLICATION_JSON) + @Consumes(MediaType.APPLICATION_JSON) + public String signedCallBack(@RequestBody Map params) { + JSONObject.toJSONString(params, SerializerFeature.PrettyFormat, SerializerFeature.WriteDateUseDateFormat); + Map result = new HashMap<>(); + result.put("code", 200); + result.put("msg", "操作成功!"); + try { + toolUtil.writeErrorLog("回调方法,获取到的请求参数:" + JSON.toJSONString(params)); + String resultCode = String.valueOf(params.get("resultCode")); + if (!"1".equals(resultCode)) { + // 签署失败 + toolUtil.writeErrorLog("合同回调:签署失败,失败信息:" + JSON.toJSONString(params)); + faDDService.signedCallBackError(params); + return JSON.toJSONString(result); + } + String contractNo = String.valueOf(params.get("docNo")); + faDDService.signedCallBack(contractNo); + } catch (Exception e) { + toolUtil.writeErrorLog(e.toString()); + return JSON.toJSONString(result); + } + return JSON.toJSONString(result); + } + + /** + * 是否签署完毕 + * + * @param requestId + * @param workflowId + * @return + */ + @Path("/isAllSigned/{workflowId}/{requestId}") + @GET + @Produces(MediaType.APPLICATION_JSON) + @Consumes(MediaType.APPLICATION_JSON) + public String querySignedStatus(@PathParam("requestId") String requestId, + @PathParam("workflowId") String workflowId) { + Map result = faDDService.querySignedStatus(requestId); + return ApiResult.success(result); + } + + /** + * 本方签署 + * + * @param workflowId 流程id + * @param requestId 请求id + * @return 本方签署结果 + */ + @Path("/signedContract/own/{requestId}/{workflowId}") + @GET + @Consumes(MediaType.APPLICATION_JSON) + @Produces(MediaType.APPLICATION_JSON) + public String signedContractOwn(@Context HttpServletRequest request, @Context HttpServletResponse response, + @PathParam("workflowId") String workflowId, @PathParam("requestId") String requestId) { + // TODO 更换labelIndex + User user = HrmUserVarify.getUser(request, response); + try { + faDDService.signedContractOwn(requestId, user); + } catch (Exception e) { + return ApiResult.error(Util.getHtmlLabelName(-87658, user.getLanguage(), "合同签署失败!")); + } + return ApiResult.success(Util.getHtmlLabelName(-87657, user.getLanguage(), "本方签署成功!")); + } + + /** + * 催一催 + * + * @param requestId 请求id + * @return 催一催 + */ + @Path("/signedContract/{requestId}") + @GET + @Consumes(MediaType.APPLICATION_JSON) + @Produces(MediaType.APPLICATION_JSON) + public String signedContract(@Context HttpServletRequest request, @Context HttpServletResponse response, + @PathParam("requestId") String requestId) { + User user = HrmUserVarify.getUser(request, response); + try { + faDDService.pushAPush(requestId); + } catch (Exception e) { + LabelHtmlIndex pushErr = labelHtmlUtils.getLabelHtmlIndex("pushErr"); + toolUtil.writeDebuggerLog(e.toString()); + return ApiResult.error(Util.getHtmlLabelName(pushErr, user)); + } + LabelHtmlIndex pushSuccess = labelHtmlUtils.getLabelHtmlIndex("pushSuccess"); + return ApiResult.success(Util.getHtmlLabelName(pushSuccess, user)); + } + + /** + * 合同下载 + * + * @param requestId 请求id + * @return 合同问价压缩包 + */ + @Path("/contract/download/{requestId}") + @GET + @Produces(MediaType.APPLICATION_OCTET_STREAM) + public Response contractDownload(@PathParam("requestId") String requestId) { + try { + UfContractInfoDTO ufContractInfoDTO = faDDContractMapping.queryContractInfoByRequestId(requestId); + StreamingOutput contractZipStream = faDDService.download4mFDD(ufContractInfoDTO); + // String requestTitle = + // Util.null2String(Util.getRequestTitleById(String.valueOf(requestId))); + String requestTitle = ufContractInfoDTO.getFileName(); + if (StringUtils.isNullOrEmpty(requestTitle)) { + requestTitle = "contracts.pdf"; + } + if (Util.null2String(ufContractInfoDTO.getContractNo()).split(",").length >= 2) { + // 多文件 + return Response.ok(contractZipStream, MediaType.APPLICATION_OCTET_STREAM).type("application/zip") + .header("Content-Disposition", "attachment;filename=\"" + + new String(requestTitle.getBytes("GBK"), StandardCharsets.ISO_8859_1) + ".zip" + "\"").build(); + } else { + // 单文件 + return Response.ok(contractZipStream, MediaType.APPLICATION_OCTET_STREAM).type("application/pdf") + .header("Content-Disposition", "attachment;filename=\"" + + new String(requestTitle.getBytes("GBK"), StandardCharsets.ISO_8859_1) + "\"").build(); + } + } catch (Exception e) { + toolUtil.writeErrorLog("文件流转换失败," + Util.getErrString(e)); + return Response.ok(ApiResult.error("出现错误,错误原因: " + e), MediaType.TEXT_PLAIN).build(); + } + } + + @POST + @Path("/resigned") + @Produces(MediaType.APPLICATION_JSON) + @Consumes(MediaType.APPLICATION_JSON) + public String resigned(@RequestBody Map params) { + try { + faDDService.resigned(params); + return ApiResult.success(true); + } catch (Exception e) { + e.printStackTrace(); + return ApiResult.error("系统出错!" + e); + } + } +} diff --git a/src/main/youhong_ai_old_src/com/api/aiyh_pcn/fadada/web/FaDDController.java b/src/main/youhong_ai_old_src/com/api/aiyh_pcn/fadada/web/FaDDController.java new file mode 100644 index 0000000..3fc77cd --- /dev/null +++ b/src/main/youhong_ai_old_src/com/api/aiyh_pcn/fadada/web/FaDDController.java @@ -0,0 +1,262 @@ +package com.api.aiyh_pcn.fadada.web; + +import aiyh.utils.ApiResult; +import aiyh.utils.Util; +import aiyh.utils.mapUtil.ParaMap; +import aiyh.utils.sqlUtil.sqlResult.impl.PrepSqlResultImpl; +import aiyh.utils.zwl.common.ToolUtil; +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.JSONObject; +import com.api.aiyh_pcn.fadada.dao.FaDDServiceMapping; +import com.api.aiyh_pcn.fadada.service.impl.FaDDServiceImpl; +import io.swagger.v3.oas.annotations.parameters.RequestBody; +import org.h2.util.StringUtils; +import weaver.conn.RecordSet; +import weaver.hrm.HrmUserVarify; +import weaver.hrm.User; + +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; +import javax.ws.rs.*; +import javax.ws.rs.core.Context; +import javax.ws.rs.core.MediaType; +import javax.ws.rs.core.Response; +import javax.ws.rs.core.StreamingOutput; +import java.io.UnsupportedEncodingException; +import java.net.URLDecoder; +import java.nio.charset.StandardCharsets; +import java.util.Base64; +import java.util.HashMap; +import java.util.Map; + +/** + * @author EBU7-dev1-ayh + * @create 2021/9/28 0028 16:05 法大大相关接口 + */ +@Path("/fadada") +public class FaDDController { + private final FaDDServiceImpl faDDService = new FaDDServiceImpl(); + private final FaDDServiceMapping faDDServiceMapping = new FaDDServiceMapping(); + private final ToolUtil toolUtil = new ToolUtil(); + + /** + * 查询配置信息 + * + * @param workflowId + * 流程id + * @return 配置信息 + */ + @GET + @Path("/getConfig/{workflowId}") + public String getConfig(@PathParam("workflowId") String workflowId) { + try { + Map configParam = faDDService.getConfigParam(workflowId); + return ApiResult.success(configParam); + } catch (Exception e) { + return ApiResult.error(e.toString()); + } + } + + /** + * 验证企业签署状态 + * + * @param params + * 查验参数 + * @return 企业验证的状态 + */ + @Path("/signature") + @POST + @Consumes(MediaType.APPLICATION_JSON) + @Produces(MediaType.APPLICATION_JSON) + public String checkCertification(@RequestBody Map params) { + try { + Map certificationResult = faDDService.checkCertification(params); + return ApiResult.success(certificationResult); + } catch (Exception e) { + return ApiResult.error(e.toString()); + } + } + + /** + * 催一催 + * + * @param workflowId + * 流程id + * @param requestId + * 请求id + * @return 催一催 + */ + @Path("/signedContract/{languageGroupId}/{requestId}/{workflowId}") + @GET + @Consumes(MediaType.APPLICATION_JSON) + @Produces(MediaType.APPLICATION_JSON) + public String signedContract(@Context HttpServletRequest request, @Context HttpServletResponse response, + @PathParam("workflowId") String workflowId, @PathParam("requestId") String requestId, + @PathParam("languageGroupId") int languageGroupId) { + User user = HrmUserVarify.getUser(request, response); + try { + faDDService.queryContractStatus(workflowId, requestId, 0); + Map language = Util.queryLanguage(languageGroupId, user.getLanguage()); + String info = language.get("rushInfo"); + return ApiResult.success(info); + } catch (Exception e) { + toolUtil.writeErrorLog("错误:" + e); + return ApiResult.error(e.toString()); + } + } + + /** + * 本方签署 + * + * @param workflowId + * 流程id + * @param requestId + * 请求id + * @return 本方签署结果 + */ + @Path("/signedContract/own/{languageGroupId}/{requestId}/{workflowId}") + @GET + @Consumes(MediaType.APPLICATION_JSON) + @Produces(MediaType.APPLICATION_JSON) + public String signedContractOwn(@Context HttpServletRequest request, @Context HttpServletResponse response, + @PathParam("workflowId") String workflowId, @PathParam("requestId") String requestId, + @PathParam("languageGroupId") int languageGroupId) { + User user = HrmUserVarify.getUser(request, response); + try { + faDDService.signedContractOwn(workflowId, requestId); + String mainTable = faDDServiceMapping.getMainTable(workflowId); + // TODO 更新本方签署 + PrepSqlResultImpl sqlResult = + Util.createSqlBuilder().updateSql(mainTable, ParaMap.create().put("signed_oneself", 1), + Util.createPrepWhereImpl().whereAnd("requestid").whereEqual(requestId)); + RecordSet rs = new RecordSet(); + rs.executeUpdate(sqlResult.getSqlStr(), sqlResult.getArgs()); + Map language = Util.queryLanguage(languageGroupId, user.getLanguage()); + String info = language.get("contractSignedInfo"); + return ApiResult.success(info); + } catch (Exception e) { + toolUtil.writeErrorLog("错误:" + e.toString()); + return ApiResult.error(e.toString()); + } + } + + /** + * 合同下载 + * + * @param requestId + * 请求id + * @return 合同问价压缩包 + */ + @Path("/contract/download/{workflowId}/{requestId}") + @GET + @Produces(MediaType.APPLICATION_OCTET_STREAM) + public Response contractDownload(@PathParam("requestId") String requestId, + @PathParam("workflowId") String workflowId) { + toolUtil.writeErrorLog("进入请求方法,获取到请求id:" + requestId); + try { + StreamingOutput contractZipStream = faDDService.contractDownload(requestId, workflowId); + return Response.ok(contractZipStream, MediaType.APPLICATION_OCTET_STREAM).type("application/zip") + .header("Content-Disposition", "attachment;filename=contracts.zip").build(); + } catch (Exception e) { + toolUtil.writeErrorLog("转换失败," + e.toString()); + return Response.ok(ApiResult.error("出现错误,错误原因: " + e), MediaType.APPLICATION_JSON).build(); + } + } + + /** + * 获取流程全版本 + * + * @param workflowId + * 流程id + * @return 流程全版本id + */ + @Path("/getAllVersion/{workflowId}/{markOnly}") + @GET + @Produces(MediaType.APPLICATION_JSON) + @Consumes(MediaType.APPLICATION_JSON) + public String getAllVersion(@PathParam("workflowId") String workflowId, @PathParam("markOnly") String markOnly) { + try { + Map allVersion = faDDService.getAllVersion(workflowId, markOnly); + return ApiResult.success(allVersion); + } catch (Exception e) { + toolUtil.writeErrorLog("错误:" + e.toString()); + return ApiResult.error(e.toString()); + } + } + + /** + * 查验是否全部签订完毕 + * + * @param requestId + * 请求id + * @return 查验结果 + */ + @Path("/isAllSigned/{workflowId}/{requestId}") + @GET + @Produces(MediaType.APPLICATION_JSON) + @Consumes(MediaType.APPLICATION_JSON) + public String isAllSinged(@PathParam("requestId") String requestId, @PathParam("workflowId") String workflowId) { + try { + faDDService.queryContractStatus(workflowId, requestId, 1); + boolean isAllSinged = faDDService.isAllSinged(requestId, workflowId); + boolean isSingedOneself = faDDService.isSingedOneself(requestId, workflowId); + Map result = + ParaMap.create().put("isAllSinged", isAllSinged).put("isSingedOneself", isSingedOneself); + return ApiResult.success(result); + } catch (Exception e) { + toolUtil.writeErrorLog("错误:" + e); + return ApiResult.error(e.toString()); + } + } + + @Path("/getLanguage/{languageGroupId}") + @GET + @Produces(MediaType.APPLICATION_JSON) + public String getLanguage(@Context HttpServletRequest request, @Context HttpServletResponse response, + @PathParam("languageGroupId") int languageGroupId) { + User user = HrmUserVarify.getUser(request, response); + Map map = Util.queryLanguage(languageGroupId, user.getLanguage()); + return ApiResult.success(map); + } + + @Path("/callback/signed") + @POST + @Produces(MediaType.APPLICATION_JSON) + @Consumes(MediaType.APPLICATION_JSON) + public String callBackSigned(@RequestBody Map params) { + toolUtil.writeErrorLog("回调方法:" + JSONObject.toJSONString(params)); + Map result = new HashMap<>(); + String bizContent = String.valueOf(params.get("bizContent")); + if (StringUtils.isNullOrEmpty(bizContent)) { + toolUtil.writeErrorLog("参数没获取到!"); + result.put("code", "200"); + result.put("msg", "操作失败!"); + return JSONObject.toJSONString(result); + } + byte[] decode = Base64.getDecoder().decode(bizContent.getBytes(StandardCharsets.UTF_8)); + String decodeStr = null; + try { + decodeStr = new String(decode, "UTF-8"); + } catch (UnsupportedEncodingException e) { + e.printStackTrace(); + } + String jsonStr = null; + try { + jsonStr = URLDecoder.decode(decodeStr, "UTF-8"); + } catch (UnsupportedEncodingException e) { + e.printStackTrace(); + } + JSONObject jsonObject = JSON.parseObject(jsonStr); + String resultCode = String.valueOf(jsonObject.getString("resultCode")); + String docNo = String.valueOf(jsonObject.getString("docNo")); + if (!"1".equals(resultCode)) { + toolUtil.writeErrorLog("重复签署合同!" + docNo); + } + // Util.createSqlBuilder().updateSql() + + this.toolUtil.writeErrorLog(jsonObject.toJSONString()); + result.put("code", "200"); + result.put("msg", "操作成功!"); + return JSONObject.toJSONString(result); + } +} diff --git a/src/main/youhong_ai_old_src/com/api/aiyh_pcn/multiple_language/MultipleLanguageController.java b/src/main/youhong_ai_old_src/com/api/aiyh_pcn/multiple_language/MultipleLanguageController.java new file mode 100644 index 0000000..2dba688 --- /dev/null +++ b/src/main/youhong_ai_old_src/com/api/aiyh_pcn/multiple_language/MultipleLanguageController.java @@ -0,0 +1,54 @@ +package com.api.aiyh_pcn.multiple_language; + +import aiyh.utils.ApiResult; +import aiyh.utils.Util; +import weaver.hrm.HrmUserVarify; +import weaver.hrm.User; + +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; +import javax.ws.rs.*; +import javax.ws.rs.core.Context; +import javax.ws.rs.core.MediaType; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +/** + *

多语言自定义标签接口

+ *

create 2022/2/10 0010 10:09

+ * + * @author EBU7-dev1-ayh + */ + +@Path("/languageLabel") +public class MultipleLanguageController { + + MultipleLanguageMapper multipleLanguageMapper = Util.getMapper(MultipleLanguageMapper.class); + + @GET + @Path("/getMultipleLanguage/{descLike}") + @Produces(MediaType.APPLICATION_JSON) + public String getMultipleLanguage(@Context HttpServletRequest request, + @Context HttpServletResponse response, + @PathParam("descLike") String descLike) { + + try { + User user = HrmUserVarify.getUser(request, response); + List> labelList = + multipleLanguageMapper.selectCustomerLabel(descLike + "%", user.getLanguage()); + if (labelList == null) { + return ApiResult.success(new HashMap<>(2)); + } + Map result = new HashMap<>(16); + for (Map map : labelList) { + result.put(String.valueOf(map.get("id")), map.get("labelname")); + } + return ApiResult.success(result); + }catch (Exception e){ + Util.getLogger().error("获取用户信息失败!无法获取用户信息,请检查用户是否登录成功!" + Util.getErrString(e)); + return ApiResult.error("获取多语言数据失败!"); + } + } + +} diff --git a/src/main/youhong_ai_old_src/com/api/aiyh_pcn/multiple_language/MultipleLanguageMapper.java b/src/main/youhong_ai_old_src/com/api/aiyh_pcn/multiple_language/MultipleLanguageMapper.java new file mode 100644 index 0000000..49709d9 --- /dev/null +++ b/src/main/youhong_ai_old_src/com/api/aiyh_pcn/multiple_language/MultipleLanguageMapper.java @@ -0,0 +1,31 @@ +package com.api.aiyh_pcn.multiple_language; + +import aiyh.utils.annotation.recordset.ParamMapper; +import aiyh.utils.annotation.recordset.Select; +import aiyh.utils.annotation.recordset.SqlMapper; + +import java.util.List; +import java.util.Map; + +/** + *

+ *

create 2022/2/10 0010 10:13

+ * + * @author EBU7-dev1-ayh + */ + + +@SqlMapper +public interface MultipleLanguageMapper { + + /** + * 查询自定义的标签信息 + * @param descLike 描述 + * @param languageId 语言id + * @return 查询到的标签信息 + */ + @Select("select hi.id,hf.labelname from htmllabelindex hi " + + "left join htmllabelinfo hf on hf.indexid = hi.id " + + "where id < 0 and indexdesc like ${descLike} and languageid = #{languageId}") + public List> selectCustomerLabel(@ParamMapper("descLike") String descLike, @ParamMapper("languageId") int languageId); +} diff --git a/src/main/youhong_ai_old_src/com/api/aiyh_pcn/organization/annotation/FieldMapping.java b/src/main/youhong_ai_old_src/com/api/aiyh_pcn/organization/annotation/FieldMapping.java new file mode 100755 index 0000000..bd3137a --- /dev/null +++ b/src/main/youhong_ai_old_src/com/api/aiyh_pcn/organization/annotation/FieldMapping.java @@ -0,0 +1,19 @@ +package com.api.aiyh_pcn.organization.annotation; + + +import java.lang.annotation.ElementType; +import java.lang.annotation.Retention; +import java.lang.annotation.RetentionPolicy; +import java.lang.annotation.Target; + + +/** + * @author XiaoBokang + * @create 2022/5/2 14:02 + */ + +@Target(ElementType.FIELD) +@Retention(RetentionPolicy.RUNTIME) +public @interface FieldMapping { + String value(); +} diff --git a/src/main/youhong_ai_old_src/com/api/aiyh_pcn/organization/cmd/OrganizationCmd.java b/src/main/youhong_ai_old_src/com/api/aiyh_pcn/organization/cmd/OrganizationCmd.java new file mode 100755 index 0000000..0f57d40 --- /dev/null +++ b/src/main/youhong_ai_old_src/com/api/aiyh_pcn/organization/cmd/OrganizationCmd.java @@ -0,0 +1,392 @@ +package com.api.aiyh_pcn.organization.cmd; + +import com.api.aiyh_pcn.organization.annotation.FieldMapping; +import com.api.aiyh_pcn.organization.entity.OrganizationEntity; +import com.api.aiyh_pcn.organization.utils.LogUtil; +import org.apache.log4j.Logger; +import weaver.conn.RecordSet; +import weaver.general.Util; +import weaver.zwl.common.ToolUtil; + +import java.lang.reflect.Field; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +/** + * @author XiaoBokang + * @create 2022/5/2 13:03 + */ + +public class OrganizationCmd { + + private final Logger log = LogUtil.getLogger(); + + public List queryList() { + RecordSet recordSet = new RecordSet(); + String dbType = recordSet.getDBType(); + List organizationList = new ArrayList<>(); + // 查询总部信息 + String querySql = "select companyname orgName,id orgCode, " + + "(select count(*) from hrmresource where (belongTo is null or belongTo = -1)) totalCount, " + + "(select count(*) from hrmresource where (belongTo is null or belongTo = -1) and status in (0,1,2,3)) employeeCount " + + "from hrmcompany"; + recordSet.executeQuery(querySql); + if (recordSet.next()) { + String companyLeader = new ToolUtil().getSystemParamValue("companyLeader"); + String userId = ""; + String messageUrl = ""; + String orgLeader = ""; + if (!"".equals(companyLeader)) { + String queryManage = "select id,lastname,messagerurl from hrmresource where id = ?"; + RecordSet queryRecordSet = new RecordSet(); + queryRecordSet.executeQuery(queryManage, companyLeader); + if (queryRecordSet.next()) { + userId = queryRecordSet.getString("id"); + messageUrl = queryRecordSet.getString("messagerurl"); + orgLeader = queryRecordSet.getString("lastname"); + } + } + OrganizationEntity organizationEntity = new OrganizationEntity(); + organizationEntity.setOrgName(recordSet.getString("orgName")); + organizationEntity.setOrgCode("sub_0"); + organizationEntity.setHighLevelOrg("root"); + organizationEntity.setSign("3"); + organizationEntity.setTotalCount(recordSet.getString("totalCount")); + organizationEntity.setEmployeeCount(recordSet.getString("employeeCount")); + organizationEntity.setUserId(userId); + organizationEntity.setMessageUrl(messageUrl); + organizationEntity.setOrgLeader(orgLeader); + organizationList.add(organizationEntity); + } + // 查询分部信息 + querySql = "select " + + "sub.id,sub.subcompanyname orgName,hrm.id userId,hrm.lastname orgLeader,hrm.messagerurl messageUrl, " + + this.getConcatStr(dbType, "'sub_'", "sub.id") + " orgCode," + + this.getConcatStr(dbType, "'sub_'", "sub.supsubcomid") + " highLevelOrg, " + +// "concat(\"sub_\",sub.id) orgCode,concat(\"sub_\",sub.supsubcomid) highLevelOrg, " + + "(select count(*) from hrmresource where subcompanyid1 = sub.id and (belongTo is null or belongTo = -1)) totalCount, " + + "(select count(*) from hrmresource where subcompanyid1 = sub.id and (belongTo is null or belongTo = -1) and status in (0,1,2,3)) employeeCount " + + "from hrmsubcompany sub " + + "left join matrixtable_1 m1 on sub.id = m1.id " + + "left join hrmresource hrm on m1.fbfzr = hrm.id " + + "where sub.canceled is null or sub.canceled =0 "; + recordSet.executeQuery(querySql); + while (recordSet.next()) { + OrganizationEntity organizationEntity = recordSetToEntityByEntity(recordSet, OrganizationEntity.class); + organizationEntity.setSign("0"); + organizationList.add(organizationEntity); + } + // 查询部门信息 + querySql = "select " + + "depart.id,depart.departmentname orgName,hrm.id userId,hrm.lastName orgLeader,hrm.messagerurl messageUrl, " + + this.getConcatStr(dbType, "'dep_'", "depart.id") + " orgCode, " + +// "concat(\"dep_\",depart.id) orgCode, " + + "( " + + " case " + + " when supdepid <= 0 or supdepid is null then " + + this.getConcatStr(dbType, "'sub_'", "depart.subcompanyid1") + +// " concat(\"sub_\",depart.subcompanyid1) " + + " else " + this.getConcatStr(dbType, "'dep_'", "depart.supdepid") + + " end " + + ") highLevelOrg, " + + "(select count(*) from hrmresource where departmentid = depart.id and (belongTo is null or belongTo = -1)) totalCount, " + + "(select count(*) from hrmresource where departmentid = depart.id and (belongTo is null or belongTo = -1) and status in (0,1,2,3)) employeeCount " + + "from hrmdepartment depart " + + "inner join hrmsubcompany sub on depart.subcompanyid1 = sub.id " + + "left join matrixtable_2 m2 on depart.id = m2.id " + + "left join hrmresource hrm on m2.bmfzr = hrm.id " + + "where (depart.canceled is null or depart.canceled =0) and (sub.canceled is null or sub.canceled =0) "; + recordSet.executeQuery(querySql); + while (recordSet.next()) { + OrganizationEntity organizationEntity = recordSetToEntityByEntity(recordSet, OrganizationEntity.class); + organizationEntity.setSign("1"); + organizationList.add(organizationEntity); + } + return organizationList; + } + + /** + * 查询总部信息 + * + * @return + */ + public OrganizationEntity getCompanyMsg() { + RecordSet recordSet = new RecordSet(); + OrganizationEntity organizationEntity = null; + // 查询总部信息 + String querySql = "select companyname orgName,id orgCode, " + + "(select count(*) from hrmresource where (belongTo is null or belongTo = -1)) totalCount, " + + "(select count(*) from hrmresource where (belongTo is null or belongTo = -1) and status in (0,1,2,3)) employeeCount " + + "from hrmcompany"; + recordSet.executeQuery(querySql); + if (recordSet.next()) { + String companyLeader = new ToolUtil().getSystemParamValue("companyLeader"); + String userId = ""; + String messageUrl = ""; + String orgLeader = ""; + if (!"".equals(companyLeader)) { + String queryManage = "select id,lastname,messagerurl from hrmresource where id = ?"; + RecordSet queryRecordSet = new RecordSet(); + queryRecordSet.executeQuery(queryManage, companyLeader); + if (queryRecordSet.next()) { + userId = queryRecordSet.getString("id"); + messageUrl = queryRecordSet.getString("messagerurl"); + orgLeader = queryRecordSet.getString("lastname"); + } + } + organizationEntity = new OrganizationEntity(); + organizationEntity.setOrgName(recordSet.getString("orgName")); + organizationEntity.setOrgCode("sub_0"); + organizationEntity.setId("sub_0"); + organizationEntity.setHaveChildren("0"); + organizationEntity.setHighLevelOrg("root"); + organizationEntity.setSign("3"); + organizationEntity.setTotalCount(recordSet.getString("totalCount")); + organizationEntity.setEmployeeCount(recordSet.getString("employeeCount")); + organizationEntity.setUserId(userId); + organizationEntity.setMessageUrl(messageUrl); + organizationEntity.setOrgLeader(orgLeader); + } + return organizationEntity; + } + + /** + * 通过参数查询部门的信息 + * + * @param param 查询条件 + * @return + */ + public List getSubCompanyListByParam(Map param, String sourcePath) { + List organizationList = new ArrayList<>(); + RecordSet recordSet = new RecordSet(); + String dbType = recordSet.getDBType(); + // 查询分部信息 + String querySql = "select " + + "sub.id,sub.subcompanyname orgName,hrm.id userId,hrm.lastname orgLeader,hrm.messagerurl messageUrl, " + + this.getConcatStr(dbType, "'sub_'", "sub.id") + " orgCode," + + this.getConcatStr(dbType, "'sub_'", "sub.supsubcomid") + " highLevelOrg, " + +// "concat(\"sub_\",sub.id) orgCode,concat(\"sub_\",sub.supsubcomid) highLevelOrg, " + + "(select count(*) from hrmresource where subcompanyid1 = sub.id and (belongTo is null or belongTo = -1)) totalCount, " + + "(select count(*) from hrmresource where subcompanyid1 = sub.id and (belongTo is null or belongTo = -1) and status in (0,1,2,3)) employeeCount " + + "from hrmsubcompany sub " + + "left join matrixtable_1 m1 on sub.id = m1.id " + + "left join hrmresource hrm on m1.fbfzr = hrm.id " + + "where (sub.canceled is null or sub.canceled =0) "; + List paramList = new ArrayList<>(); + String whereSql = this.buildWhereSql("", param, paramList); + querySql += whereSql; + log.info("通过参数查询分部信息:" + querySql + " paramList ==>" + paramList); + recordSet.executeQuery(querySql, paramList); + while (recordSet.next()) { + String mainId = recordSet.getString("id"); + OrganizationEntity organizationEntity = recordSetToEntityByEntity(recordSet, OrganizationEntity.class); + organizationEntity.setSign("0"); + int companyChildCount = getCompanyChildCount(mainId); + int companyDepartChildCount = getCompanyDepartChildCount(mainId); + if (companyChildCount > 0 || companyDepartChildCount > 0) { + organizationEntity.setHaveChildren("0"); + } else { + organizationEntity.setHaveChildren("1"); + } + organizationList.add(organizationEntity); + } + return organizationList; + } + + + /** + * 通过参数查询部门的信息 + * + * @param param 查询条件 + * @return + */ + public List getDepartListByParam(Map param, String sourcePath) { + List organizationList = new ArrayList<>(); + RecordSet recordSet = new RecordSet(); + String dbType = recordSet.getDBType(); + // 查询部门信息 + String querySql = "select " + + "job.JOBTITLENAME jobTitleName ,depart.id,depart.departmentname orgName,hrm.id userId,hrm.lastName orgLeader,hrm.messagerurl messageUrl, " + + this.getConcatStr(dbType, "'dep_'", "depart.id") + " orgCode, " + + "( " + + " case " + + " when supdepid <= 0 or supdepid is null then " + + this.getConcatStr(dbType, "'sub_'", "depart.subcompanyid1") + + " else " + this.getConcatStr(dbType, "'dep_'", "depart.supdepid") + + " end " + + ") highLevelOrg, " + + "(select count(*) from hrmresource where departmentid = depart.id and (belongTo is null or belongTo = -1)) totalCount, " + + "(select count(*) from hrmresource where departmentid = depart.id and (belongTo is null or belongTo = -1) and status in (0,1,2,3)) employeeCount " + + "from hrmdepartment depart " + + "inner join hrmsubcompany sub on depart.subcompanyid1 = sub.id " + + "left join matrixtable_2 m2 on depart.id = m2.id " + + "left join hrmresource hrm on m2.bmfzr = hrm.id " + + "left join hrmjobtitles job on job.id = hrm.jobtitle " + + "where (depart.canceled is null or depart.canceled =0) and (sub.canceled is null or sub.canceled =0) "; + List paramList = new ArrayList<>(); + String paramSql = ""; + if (param.containsKey("paramSql")) { + paramSql = Util.null2String(param.get("paramSql")); + param.remove("paramSql"); + } + String whereSql = this.buildWhereSql("", param, paramList); + log.info("通过参数查询部门信息:" + querySql + paramSql + whereSql + " paramList ==>" + paramList); + recordSet.executeQuery(querySql + paramSql + whereSql, paramList); + int index = 0; + while (recordSet.next()) { + String mainId = recordSet.getString("id"); + OrganizationEntity organizationEntity = recordSetToEntityByEntity(recordSet, OrganizationEntity.class); + organizationEntity.setSign("1"); + int departChildCount = getDepartChildCount(mainId); + if (departChildCount > 0) { + organizationEntity.setHaveChildren("0"); + } else { + organizationEntity.setHaveChildren("1"); + } + organizationEntity.setPath(sourcePath + index++ + "_"); + organizationList.add(organizationEntity); + } + return organizationList; + } + + /** + * 构建查询sql语句 + * + * @param tempSql + * @param whereParam 查询条件 + * @param whereParamList 参数信息 + * @return + */ + public String buildWhereSql(String tempSql, Map whereParam, List whereParamList) { + StringBuilder whereBuilder = new StringBuilder(tempSql); + whereParam.forEach((k, v) -> { + if (v == null) { + whereBuilder.append(" and ").append(k); + } else { + whereBuilder.append(" and ").append(k).append(" = ? "); + whereParamList.add(v); + } + }); + return whereBuilder.toString(); + } + + /** + * 通过列名将数据库结果集转换成指定的实体类 + * + * @param recordSet 数据库结果集 + * @param tClass 实体类文件 + * @param 泛型 + * @return + */ + public T recordSetToEntityByEntity(RecordSet recordSet, Class tClass) { + T res = null; + try { + String[] columnNames = recordSet.getColumnName(); + if (tClass.equals(Map.class)) { + Map tempRes = new HashMap<>(); + for (String columnName : columnNames) { + tempRes.put(columnName, recordSet.getString(columnName)); + } + res = (T) tempRes; + } else { + Field[] declaredFields = tClass.getDeclaredFields(); + res = tClass.newInstance(); + for (Field field : declaredFields) { + field.setAccessible(true); + FieldMapping annotation = field.getAnnotation(FieldMapping.class); + if (annotation != null) { + String value = annotation.value(); + String s = recordSet.getString(value); + field.set(res, s); + } + } + } + } catch (Exception e) { + log.info("实体类转换异常:", e); + } + return res; + } + + /** + * 根据数据库类型拼接字符串 + * + * @param dbType 数据库类型 + * @param prefixStr 前缀 + * @param suffixStr 后缀 + * @return + */ + public String getConcatStr(String dbType, String prefixStr, String suffixStr) { + String res = ""; + StringBuilder stringBuilder = new StringBuilder(); + if ("mysql".equals(dbType) || "oracle".equals(dbType)) { + stringBuilder.append("concat(") + .append(prefixStr).append(",") + .append(suffixStr).append(")"); + res = stringBuilder.toString(); + } else if ("sqlserver".equals(dbType)) { + stringBuilder.append("CONVERT(varchar(255),") + .append(prefixStr).append(")").append("+") + .append("CONVERT(varchar(255),") + .append(suffixStr).append(")"); + res = stringBuilder.toString(); + } + return res; + } + + /** + * 查询对应部门子部门数量 + * + * @param departmentId 部门id + * @return + */ + public int getDepartChildCount(String departmentId) { + int count = 0; + String querySql = "select count(*) from hrmdepartment where supdepid = ? and (canceled is null or canceled =0 )"; +// log.info("查询对应部门子部门数量:"+querySql+" departmentId:"+departmentId); + RecordSet recordSet = new RecordSet(); + recordSet.executeQuery(querySql, departmentId); + if (recordSet.next()) { + count = Util.getIntValue(recordSet.getString(1), 0); + } + return count; + } + + /** + * 查询对应分部子部门数量 + * + * @param subCompanyId 分部id + * @return + */ + public int getCompanyDepartChildCount(String subCompanyId) { + int count = 0; + String querySql = "select count(*) from hrmdepartment where subcompanyid1 = ? and (canceled is null or canceled =0 ) and (supdepid <= 0 or supdepid is null)"; +// log.info("查询对应分部子部门数量:"+querySql+" subCompanyId:"+subCompanyId); + RecordSet recordSet = new RecordSet(); + recordSet.executeQuery(querySql, subCompanyId); + if (recordSet.next()) { + count = Util.getIntValue(recordSet.getString(1), 0); + } + return count; + } + + /** + * 查询下级分部数量 + * + * @param subCompanyId 分部id + * @return + */ + public int getCompanyChildCount(String subCompanyId) { + int count = 0; + String querySql = "select count(*) from hrmsubcompany where supsubcomid = ? and (canceled is null or canceled =0 )"; +// log.info("查询下级分部数量:"+querySql+" subCompanyId:"+subCompanyId); + RecordSet recordSet = new RecordSet(); + recordSet.executeQuery(querySql, subCompanyId); + if (recordSet.next()) { + count = Util.getIntValue(recordSet.getString(1), 0); + } + return count; + } + +} diff --git a/src/main/youhong_ai_old_src/com/api/aiyh_pcn/organization/entity/OrganizationEntity.java b/src/main/youhong_ai_old_src/com/api/aiyh_pcn/organization/entity/OrganizationEntity.java new file mode 100755 index 0000000..f899ee1 --- /dev/null +++ b/src/main/youhong_ai_old_src/com/api/aiyh_pcn/organization/entity/OrganizationEntity.java @@ -0,0 +1,94 @@ +package com.api.aiyh_pcn.organization.entity; + +import com.api.aiyh_pcn.organization.annotation.FieldMapping; +import lombok.Data; + +import java.util.List; + +/** + * @author XiaoBokang + * @create 2022/5/2 13:33 + */ + +@Data +public class OrganizationEntity { + + /** + * 唯一标识 + */ + @FieldMapping("orgCode") + private String id; + + /** + * 部门、分部名称 + */ + @FieldMapping("orgName") + private String orgName; + + /** + * 部门、分部编码 + */ + @FieldMapping("orgCode") + private String orgCode; + + /** + * 标识,0:分部,1:部门 + */ + private String sign; + + /** + * 部门、分部负责人名称 + */ + @FieldMapping("orgLeader") + private String orgLeader; + + /** + * 部门、分部负责人ID + */ + @FieldMapping("userId") + private String userId; + + /** + * 部门、分部负责人头像 + */ + @FieldMapping("messageUrl") + private String messageUrl; + + /** + * 上级机构 + */ + @FieldMapping("highLevelOrg") + private String highLevelOrg; + + /** + * 在职人数 + */ + @FieldMapping("employeeCount") + private String employeeCount; + + /** + * 总人数 + */ + @FieldMapping("totalCount") + private String totalCount; + + /** + * 是否有下级机构 0:存在,1:不存在 + */ + private String haveChildren; + + /** + * 路径 + */ + private String path; + + + /** + * 岗位名称 + */ + @FieldMapping("jobTitleName") + private String jobTitleName; + + private List children; + +} diff --git a/src/main/youhong_ai_old_src/com/api/aiyh_pcn/organization/exception/RequestException.java b/src/main/youhong_ai_old_src/com/api/aiyh_pcn/organization/exception/RequestException.java new file mode 100755 index 0000000..34666ba --- /dev/null +++ b/src/main/youhong_ai_old_src/com/api/aiyh_pcn/organization/exception/RequestException.java @@ -0,0 +1,21 @@ +package com.api.aiyh_pcn.organization.exception; + +/** + * @author XiaoBokang + * @create 2022/1/12 11:06 + */ + +public class RequestException extends RuntimeException { + public RequestException(String message) { + super(message); + } + + public RequestException(String message, Throwable cause) { + super(message, cause); + } + + @Override + public synchronized Throwable fillInStackTrace() { + return super.fillInStackTrace(); + } +} diff --git a/src/main/youhong_ai_old_src/com/api/aiyh_pcn/organization/service/OrganizationService.java b/src/main/youhong_ai_old_src/com/api/aiyh_pcn/organization/service/OrganizationService.java new file mode 100755 index 0000000..1e62386 --- /dev/null +++ b/src/main/youhong_ai_old_src/com/api/aiyh_pcn/organization/service/OrganizationService.java @@ -0,0 +1,38 @@ +package com.api.aiyh_pcn.organization.service; + +import com.api.aiyh_pcn.organization.entity.OrganizationEntity; +import weaver.hrm.User; + +import java.util.List; + +/** + * @author XiaoBokang + * @create 2022/5/2 13:02 + */ + +public interface OrganizationService { + + List queryList(User user); + + /** + * 查询组织架构信息两层信息 + * + * @return + */ + List initList(); + + /** + * 查询所有顶层分部 + * + * @return + */ + List getTopList(User user); + + /** + * 查询子级机构信息 + * + * @return + */ + List getChildList(OrganizationEntity organizationEntity); + +} diff --git a/src/main/youhong_ai_old_src/com/api/aiyh_pcn/organization/service/impl/OrganizationServiceImpl.java b/src/main/youhong_ai_old_src/com/api/aiyh_pcn/organization/service/impl/OrganizationServiceImpl.java new file mode 100755 index 0000000..623bce5 --- /dev/null +++ b/src/main/youhong_ai_old_src/com/api/aiyh_pcn/organization/service/impl/OrganizationServiceImpl.java @@ -0,0 +1,153 @@ +package com.api.aiyh_pcn.organization.service.impl; + +import com.api.aiyh_pcn.organization.cmd.OrganizationCmd; +import com.api.aiyh_pcn.organization.entity.OrganizationEntity; +import com.api.aiyh_pcn.organization.service.OrganizationService; +import com.api.aiyh_pcn.organization.utils.CommonUtil; +import org.h2.util.StringUtils; +import weaver.hrm.User; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +/** + * @author XiaoBokang + * @create 2022/5/2 13:03 + */ + +public class OrganizationServiceImpl implements OrganizationService { + + private final OrganizationCmd organizationCmd = new OrganizationCmd(); + + @Override + public List queryList(User user) { + int subcompany = user.getUserSubCompany1(); + List organizationEntityList = organizationCmd.queryList(); + List organizationTree = CommonUtil.listToTree(organizationEntityList, OrganizationEntity::getOrgCode, OrganizationEntity::getHighLevelOrg, + OrganizationEntity::getChildren, OrganizationEntity::setChildren, + supCode -> StringUtils.isNullOrEmpty(supCode) || "root".equals(supCode)); + return organizationTree; + } + + @Override + public List initList() { + List organizationEntityList = new ArrayList<>(); + OrganizationEntity companyMsg = organizationCmd.getCompanyMsg(); + if (companyMsg != null) { + companyMsg.setPath(""); + organizationEntityList.add(companyMsg); + Map param = new HashMap<>(); + // 查询顶层分部 + param.put("sub.supsubcomid", 0); + List topSubCompanyList = organizationCmd.getSubCompanyListByParam(param, ""); + organizationEntityList.addAll(topSubCompanyList); + for (OrganizationEntity organizationEntity : topSubCompanyList) { + String orgCode = organizationEntity.getOrgCode(); + String supId = orgCode.substring(orgCode.lastIndexOf("_") + 1); + // 查询下级分部 + Map queryParam = new HashMap<>(); + queryParam.put("sub.supsubcomid", supId); + List subCompanyListByParam = organizationCmd.getSubCompanyListByParam(queryParam, ""); + organizationEntityList.addAll(subCompanyListByParam); + // 查询下级部门 + queryParam.clear(); + queryParam.put("depart.subcompanyid1", supId); + queryParam.put("paramSql", " and (supdepid <= 0 or supdepid is null)"); + List departListByParam = organizationCmd.getDepartListByParam(queryParam, ""); + organizationEntityList.addAll(departListByParam); + } + } + List organizationTree = CommonUtil.listToTree(organizationEntityList, OrganizationEntity::getOrgCode, OrganizationEntity::getHighLevelOrg, + OrganizationEntity::getChildren, OrganizationEntity::setChildren, + supCode -> StringUtils.isNullOrEmpty(supCode) || "root".equals(supCode)); + initPath(organizationTree, ""); + return organizationTree; + } + + @Override + public List getTopList(User user) { + List organizationEntityList = new ArrayList<>(); + Map param = new HashMap<>(); + // 查询顶层分部 + int userId = user.getUID(); + if (userId == 1) { + param.put("sub.supsubcomid", 0); + } else { + param.put("(sub.id = " + + (user.getUserSubCompany1() <= 0 ? user.getUserSubCompany2() : user.getUserSubCompany1()) + + " or sub.supsubcomid = " + + (user.getUserSubCompany1() <= 0 ? user.getUserSubCompany2() : user.getUserSubCompany1()) + ")", null); + } + List topSubCompanyList = organizationCmd.getSubCompanyListByParam(param, ""); + organizationEntityList.addAll(topSubCompanyList); + for (OrganizationEntity organizationEntity : topSubCompanyList) { + String orgCode = organizationEntity.getOrgCode(); + String supId = orgCode.substring(orgCode.lastIndexOf("_") + 1); + // 查询下级分部 + Map queryParam = new HashMap<>(); + queryParam.put("sub.supsubcomid", supId); + List subCompanyListByParam = organizationCmd.getSubCompanyListByParam(queryParam, ""); + organizationEntityList.addAll(subCompanyListByParam); + // 查询下级部门 + queryParam.clear(); + queryParam.put("depart.subcompanyid1", supId); + queryParam.put("paramSql", " and (supdepid <= 0 or supdepid is null)"); + List departListByParam = organizationCmd.getDepartListByParam(queryParam, ""); + organizationEntityList.addAll(departListByParam); + } + List organizationTree = CommonUtil.listToTree(organizationEntityList, OrganizationEntity::getOrgCode, OrganizationEntity::getHighLevelOrg, + OrganizationEntity::getChildren, OrganizationEntity::setChildren, + supCode -> StringUtils.isNullOrEmpty(supCode) || "sub_0".equals(supCode)); + initPath(organizationTree, ""); + return organizationTree; + } + + /** + * 初始化path + * + * @param organizationTree 组织结构树 + */ + private void initPath(List organizationTree, String parentPath) { + int i = 0; + for (OrganizationEntity organizationEntity : organizationTree) { + List children = organizationEntity.getChildren(); + organizationEntity.setPath(parentPath + i++ + "_"); + if (children == null || children.size() == 0) { + continue; + } + initPath(children, organizationEntity.getPath()); + } + } + + @Override + public List getChildList(OrganizationEntity organizationEntity) { + List organizationEntityList = new ArrayList<>(); + String sign = organizationEntity.getSign(); + String orgCode = organizationEntity.getOrgCode(); + String orgId = orgCode.substring(orgCode.lastIndexOf("_") + 1); + String sourcePath = organizationEntity.getPath(); + if ("0".equals(sign)) { + // 查询下级分部 + Map queryParam = new HashMap<>(); + queryParam.put("sub.supsubcomid", orgId); + List subCompanyListByParam = organizationCmd.getSubCompanyListByParam(queryParam, sourcePath); + organizationEntityList.addAll(subCompanyListByParam); + // 查询下级部门 + queryParam.clear(); + queryParam.put("depart.subcompanyid1", orgId); + queryParam.put("paramSql", " and (supdepid <= 0 or supdepid is null)"); + List departListByParam = organizationCmd.getDepartListByParam(queryParam, sourcePath); + organizationEntityList.addAll(departListByParam); + } else { + // 查询下级部门 + Map queryParam = new HashMap<>(); + queryParam.put("depart.supdepid", orgId); + List departListByParam = organizationCmd.getDepartListByParam(queryParam, sourcePath); + organizationEntityList.addAll(departListByParam); + } + return organizationEntityList; + } + +} diff --git a/src/main/youhong_ai_old_src/com/api/aiyh_pcn/organization/utils/CommonUtil.java b/src/main/youhong_ai_old_src/com/api/aiyh_pcn/organization/utils/CommonUtil.java new file mode 100755 index 0000000..616c11e --- /dev/null +++ b/src/main/youhong_ai_old_src/com/api/aiyh_pcn/organization/utils/CommonUtil.java @@ -0,0 +1,112 @@ +package com.api.aiyh_pcn.organization.utils; + +import java.util.*; +import java.util.function.BiConsumer; +import java.util.function.Function; +import java.util.function.Predicate; + +/** + * @author XiaoBokang + * @create 2022/5/2 17:18 + */ + +public class CommonUtil { + /** + * 将list转化为树形list + * + * @param dataList 元数据 + * @param getIdFn 获取元数据的id + * @param getParentId 获取父类id的方法 + * @param setChildFn 设置子结点方法 + * @param getChildFn 获取子结点方法 + * @param predicate 判断是否属于根结点的方法 + * @param list的泛型 + * @param 元数据id的泛型 + * @return 树形的list + */ + public static List listToTree(List dataList, Function getIdFn, + Function getParentId, Function> getChildFn, + BiConsumer> setChildFn, Predicate predicate) { + if (dataList == null || dataList.isEmpty() || dataList.size() == 1) { + return dataList; + } + return buildTree(dataList, new HashMap<>(dataList.size()), new HashMap<>(dataList.size()), + 0, getIdFn, getParentId, getChildFn, setChildFn, predicate); + } + + /** + * 将list转为树形list + * + * @param dataList 元数据list + * @param dataMap 数据map + * @param childMap 已添加过的子元素 + * @param index 从第几个开始格式化 + * @param getIdFn 获取id的方法 + * @param getParentId 获取父类id的方法 + * @param getChildFn 获取子结点方法 + * @param setChildFn 设置孩子节点的方法 + * @param predicate 判断是否属于根节点的方法 + * @param list的泛型 + * @param 泛型的id的类型 + * @return 树形结构 + */ + private static List buildTree(List dataList, Map dataMap, Map childMap, int index, Function getIdFn, + Function getParentId, Function> getChildFn, + BiConsumer> setChildFn, Predicate predicate) { + List treeList = new ArrayList<>(dataList.size()); + while (index < dataList.size()) { + T item = dataList.get(index); + index++; + K id = getIdFn.apply(item); + K parentId = getParentId.apply(item); + if (dataMap.containsKey(id)) { + continue; + } + dataMap.put(id, item); +// 判断是否属于根节点,如果是根节点,则将数据添加到树中 + if (predicate.test(parentId)) { + if (childMap.containsKey(id)) { + continue; + } + treeList.add(item); + childMap.put(id, item); + } else { +// 如果不是根节点,则通过id查找到父级 + T parent = dataMap.get(parentId); + if (Objects.isNull(parent)) { +// 如果父级为空,则说明他的父级还没有遍历到,需要从之后的数据进行遍历,直到找到父级为止 + List list = buildTree(dataList, dataMap, childMap, index, getIdFn, getParentId, getChildFn, setChildFn, predicate); + parent = dataMap.get(parentId); + if (Objects.isNull(parent)) { +// 如果还是没有查询到父节点,则表明是顶层节点,将他添加到顶层节点中 + treeList.add(item); + } else { +// 如果找到了父节点,则将自己挂到父节点上 + if (childMap.containsKey(id)) { + continue; + } + List childList = Optional.ofNullable(getChildFn.apply(parent)).orElse(new ArrayList<>()); + childList.add(item); + setChildFn.accept(parent, childList); + childMap.put(id, item); + } +// 如果查找的list不为空并且有值,那就说明属于根节点 + if (list != null && list.size() > 0) { + treeList.addAll(list); + } + } else { +// 如果找到了父节点,则将自己挂到父节点上 + if (childMap.containsKey(id)) { + continue; + } + List childList = Optional.ofNullable(getChildFn.apply(parent)).orElse(new ArrayList<>()); + childList.add(item); + setChildFn.accept(parent, childList); + childMap.put(id, item); + } + } + } + return treeList; + } + +} diff --git a/src/main/youhong_ai_old_src/com/api/aiyh_pcn/organization/utils/JsonResult.java b/src/main/youhong_ai_old_src/com/api/aiyh_pcn/organization/utils/JsonResult.java new file mode 100755 index 0000000..9d36723 --- /dev/null +++ b/src/main/youhong_ai_old_src/com/api/aiyh_pcn/organization/utils/JsonResult.java @@ -0,0 +1,75 @@ +package com.api.aiyh_pcn.organization.utils; + +import com.alibaba.fastjson.JSONObject; + + +/** + * @author XiaoBokang + * @create 2021/9/9 19:33 + */ + +public class JsonResult { + + private Integer code; + private String message; + private Object Data; + + public JsonResult(Integer code, String message, Object data) { + this.code = code; + this.message = message; + Data = data; + } + + public static String success(String message) { + return JSONObject.toJSONString(new JsonResult(200, message, null)); + } + + public static String success() { + return JSONObject.toJSONString(new JsonResult(200, "success", null)); + } + + public static String successData(String message, Object data) { + return JSONObject.toJSONString(new JsonResult(200, message, data)); + } + + public static String successData(Object data) { + return JSONObject.toJSONString(new JsonResult(200, "success", data)); + } + + public static String error(int code, String message) { + return JSONObject.toJSONString(new JsonResult(code, message, null)); + } + + public static String error(String message) { + return JSONObject.toJSONString(new JsonResult(500, message, null)); + } + + public static String error() { + return JSONObject.toJSONString(new JsonResult(500, "fail", null)); + } + + + public Integer getCode() { + return code; + } + + public void setCode(Integer code) { + this.code = code; + } + + public String getMessage() { + return message; + } + + public void setMessage(String message) { + this.message = message; + } + + public Object getData() { + return Data; + } + + public void setData(Object data) { + Data = data; + } +} diff --git a/src/main/youhong_ai_old_src/com/api/aiyh_pcn/organization/utils/LogUtil.java b/src/main/youhong_ai_old_src/com/api/aiyh_pcn/organization/utils/LogUtil.java new file mode 100755 index 0000000..0a95780 --- /dev/null +++ b/src/main/youhong_ai_old_src/com/api/aiyh_pcn/organization/utils/LogUtil.java @@ -0,0 +1,45 @@ +package com.api.aiyh_pcn.organization.utils; + +import org.apache.log4j.*; + +import java.io.File; + +/** + * @author XiaoBokang + * @create 2022/3/3 14:16 + */ + +public class LogUtil { + + private static volatile Logger log = null; + + /** + * 获取日志对象 + * + * @return 日志对象 + */ + public static Logger getLogger() { + if (log == null) { + synchronized (LogUtil.class) { + if (log == null) { + DailyRollingFileAppender appender = new DailyRollingFileAppender(); + log = Logger.getLogger("xbk_cus"); + appender.setName("xbk_cus"); + appender.setEncoding("UTF-8"); + appender.setDatePattern("'_'yyyyMMdd'.log'"); + appender.setFile(weaver.general.GCONST.getLogPath() + "cus" + File.separator + "util_cus" + File.separator + "cus.log"); + appender.setThreshold(Priority.DEBUG); + appender.setLayout(new PatternLayout("[%-5p] [%d{yyyy-MM-dd HH:mm:ss,SSS}] [%r] [Thread:%t][%F.%M:%L] ==> : %m %x %n")); + appender.setAppend(true); + appender.activateOptions(); + log.addAppender(appender); + boolean enableDebug = true; + if (!enableDebug) { + log.setLevel(Level.INFO); + } + } + } + } + return log; + } +} diff --git a/src/main/youhong_ai_old_src/com/api/aiyh_pcn/organization/web/OrganizationController.java b/src/main/youhong_ai_old_src/com/api/aiyh_pcn/organization/web/OrganizationController.java new file mode 100755 index 0000000..945b627 --- /dev/null +++ b/src/main/youhong_ai_old_src/com/api/aiyh_pcn/organization/web/OrganizationController.java @@ -0,0 +1,84 @@ +package com.api.aiyh_pcn.organization.web; + +import com.alibaba.fastjson.JSON; +import com.api.aiyh_pcn.organization.entity.OrganizationEntity; +import com.api.aiyh_pcn.organization.service.OrganizationService; +import com.api.aiyh_pcn.organization.service.impl.OrganizationServiceImpl; +import com.api.aiyh_pcn.organization.utils.JsonResult; +import com.api.aiyh_pcn.organization.utils.LogUtil; +import io.swagger.v3.oas.annotations.parameters.RequestBody; +import org.apache.log4j.Logger; +import weaver.hrm.HrmUserVarify; +import weaver.hrm.User; + +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; +import javax.ws.rs.GET; +import javax.ws.rs.POST; +import javax.ws.rs.Path; +import javax.ws.rs.Produces; +import javax.ws.rs.core.Context; +import javax.ws.rs.core.MediaType; +import java.util.List; + + +/** + * @author XiaoBokang + * @create 2022/5/2 12:52 + */ + +@Path("/xbk/organization") +public class OrganizationController { + + private final Logger log = LogUtil.getLogger(); + private final OrganizationService organizationService = new OrganizationServiceImpl(); + + @GET + @Path(("/getList")) + @Produces(MediaType.APPLICATION_JSON) + public String getOrganization(@Context HttpServletRequest request, @Context HttpServletResponse response) { + log.info("进入请求成功"); + try { + User user = HrmUserVarify.getUser(request, response); + List organizationEntityList = organizationService.queryList(user); + log.info("组织结构数据查询结果:" + JSON.toJSONString(organizationEntityList)); + return JsonResult.successData(organizationEntityList); + } catch (Exception e) { + log.info("请求出现异常:", e); + return JsonResult.error(); + } + + } + + @GET + @Path(("/getOrgList")) + @Produces(MediaType.APPLICATION_JSON) + public String getOrganizationList(@Context HttpServletRequest request, @Context HttpServletResponse response) { + log.info("进入请求成功"); + User user = HrmUserVarify.getUser(request, response); + try { + List organizationEntityList = organizationService.getTopList(user); + log.info("组织结构数据查询结果:" + JSON.toJSONString(organizationEntityList)); + return JsonResult.successData(organizationEntityList); + } catch (Exception e) { + log.info("请求出现异常:", e); + return JsonResult.error(); + } + } + + @POST + @Path(("/getChildList")) + @Produces(MediaType.APPLICATION_JSON) + public String getOrgChildList(@Context HttpServletRequest request, @Context HttpServletResponse response, @RequestBody OrganizationEntity organizationEntity) { + log.info("进入请求成功,param ==>" + organizationEntity); + try { + List organizationEntityList = organizationService.getChildList(organizationEntity); + log.info("子级组织结构数据查询结果:" + JSON.toJSONString(organizationEntityList)); + return JsonResult.successData(organizationEntityList); + } catch (Exception e) { + log.info("请求出现异常:", e); + return JsonResult.error(); + } + + } +} diff --git a/src/main/youhong_ai_old_src/com/api/aiyh_pcn/patentWall/controller/ClassificationWallController.java b/src/main/youhong_ai_old_src/com/api/aiyh_pcn/patentWall/controller/ClassificationWallController.java new file mode 100644 index 0000000..212ef7f --- /dev/null +++ b/src/main/youhong_ai_old_src/com/api/aiyh_pcn/patentWall/controller/ClassificationWallController.java @@ -0,0 +1,56 @@ +package com.api.aiyh_pcn.patentWall.controller; + +import aiyh.utils.ApiResult; +import aiyh.utils.Util; +import com.api.aiyh_pcn.patentWall.dao.GovernmentSourceDto; +import com.api.aiyh_pcn.patentWall.service.ClassificationWallService; +import com.api.aiyh_pcn.patentWall.vo.ClassificationWallVo; +import io.swagger.v3.oas.annotations.parameters.RequestBody; +import weaver.hrm.HrmUserVarify; +import weaver.hrm.User; + +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; +import javax.ws.rs.*; +import javax.ws.rs.core.Context; +import javax.ws.rs.core.MediaType; + +/** + *

分类源墙

+ *

create 2022/5/20 17:30

+ * + * @author ayh + */ + +@Path("/aiyh/classification-source") +public class ClassificationWallController { + + private ClassificationWallService service = new ClassificationWallService(); + + + @Path("/source-list") + @POST + @Produces(MediaType.APPLICATION_JSON) + @Consumes(MediaType.APPLICATION_JSON) + public String getSource(@Context HttpServletRequest request, @Context HttpServletResponse response, + @RequestBody GovernmentSourceDto governmentSourceDto){ + try { + User user = HrmUserVarify.getUser(request, response); + ClassificationWallVo classificationWallVo = service.getSource(governmentSourceDto,user); + return ApiResult.success(classificationWallVo); + }catch (Exception e){ + e.printStackTrace(); + Util.getLogger().error("==================查询政府资源失败!==================="); + return ApiResult.error("查询失败!"); + } + } + + @GET + @Path("/clear-catch") + @Produces(MediaType.APPLICATION_JSON) + @Consumes(MediaType.APPLICATION_JSON) + public String clearCatchConfig(){ + service.clearSourceWallConf(); + return ApiResult.success(true); + } +} diff --git a/src/main/youhong_ai_old_src/com/api/aiyh_pcn/patentWall/controller/GovernmentSourceController.java b/src/main/youhong_ai_old_src/com/api/aiyh_pcn/patentWall/controller/GovernmentSourceController.java new file mode 100644 index 0000000..b5789f5 --- /dev/null +++ b/src/main/youhong_ai_old_src/com/api/aiyh_pcn/patentWall/controller/GovernmentSourceController.java @@ -0,0 +1,56 @@ +package com.api.aiyh_pcn.patentWall.controller; + +import aiyh.utils.ApiResult; +import aiyh.utils.Util; +import com.api.aiyh_pcn.patentWall.dao.GovernmentSourceDto; +import com.api.aiyh_pcn.patentWall.service.GovernmentSourceService; +import com.api.aiyh_pcn.patentWall.vo.GovernmentSourceVo; +import io.swagger.v3.oas.annotations.parameters.RequestBody; +import weaver.hrm.HrmUserVarify; +import weaver.hrm.User; + +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; +import javax.ws.rs.*; +import javax.ws.rs.core.Context; +import javax.ws.rs.core.MediaType; + +/** + *

政府资源墙

+ *

create 2022/5/20 17:30

+ * + * @author ayh + */ + +@Path("/aiyh/government-source") +public class GovernmentSourceController { + + private final GovernmentSourceService service = new GovernmentSourceService(); + + + @Path("/source-list") + @POST + @Produces(MediaType.APPLICATION_JSON) + @Consumes(MediaType.APPLICATION_JSON) + public String getSource(@Context HttpServletRequest request, @Context HttpServletResponse response, + @RequestBody GovernmentSourceDto governmentSourceDto){ + try { + User user = HrmUserVarify.getUser(request, response); + GovernmentSourceVo governmentSourceVo = service.getSource(governmentSourceDto,user); + return ApiResult.success(governmentSourceVo); + }catch (Exception e){ + e.printStackTrace(); + Util.getLogger().error("==================查询政府资源失败!==================="); + return ApiResult.error("查询失败!"); + } + } + + @GET + @Path("/clear-catch") + @Produces(MediaType.APPLICATION_JSON) + @Consumes(MediaType.APPLICATION_JSON) + public String clearCatchConfig(){ + service.clearSourceWallConf(); + return ApiResult.success(true); + } +} diff --git a/src/main/youhong_ai_old_src/com/api/aiyh_pcn/patentWall/controller/PatentWallController.java b/src/main/youhong_ai_old_src/com/api/aiyh_pcn/patentWall/controller/PatentWallController.java new file mode 100644 index 0000000..725022d --- /dev/null +++ b/src/main/youhong_ai_old_src/com/api/aiyh_pcn/patentWall/controller/PatentWallController.java @@ -0,0 +1,71 @@ +package com.api.aiyh_pcn.patentWall.controller; + +import aiyh.utils.ApiResult; +import aiyh.utils.Util; +import com.api.aiyh_pcn.patentWall.dto.FilterWhere; +import com.api.aiyh_pcn.patentWall.service.PatentWallService; +import com.api.aiyh_pcn.patentWall.vo.PatentVO; +import com.api.aiyh_pcn.patentWall.vo.SearchInputVO; +import io.swagger.v3.oas.annotations.parameters.RequestBody; +import org.apache.log4j.Logger; +import weaver.hrm.HrmUserVarify; +import weaver.hrm.User; + +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; +import javax.ws.rs.*; +import javax.ws.rs.core.Context; +import javax.ws.rs.core.MediaType; +import java.util.List; + +/** + * @author EBU7-dev1-ayh + * @create 2021/11/25 0025 15:18 + * 专利墙请求入口 + */ + + +@Path("/patten/") +public class PatentWallController { + private final PatentWallService patentWallService = new PatentWallService(); + private final Logger logger = Util.getLogger(); + + @Path("/getSearchList/{prefix}") + @GET + @Produces(MediaType.APPLICATION_JSON) + public String getPatentList(@Context HttpServletRequest request, @Context HttpServletResponse response, + @PathParam("prefix") String prefix){ + try { + User user = HrmUserVarify.getUser(request, response); + int languageId = user.getLanguage(); + List result = patentWallService.getSearchList(prefix,languageId); + return ApiResult.success(result); + }catch (Exception e){ + logger.error("捕获到异常信息:" + Util.getErrString(e)); + return ApiResult.error("捕获到调用异常信息"); + } + } + + @Path("/getList/{prefix}") + @POST + @Produces(MediaType.APPLICATION_JSON) + @Consumes(MediaType.APPLICATION_JSON) + public String getPatentList(@RequestBody List filterWheres, @PathParam("prefix") String prefix){ + try { + List result = patentWallService.getList(filterWheres,prefix); + return ApiResult.success(result); + }catch (Exception e){ + logger.error("捕获到异常信息:" + Util.getErrString(e)); + return ApiResult.error("捕获到调用异常信息"); + } + } + + @Path("/clearConf") + @GET + @Produces(MediaType.APPLICATION_JSON) + public String clearPatentWallConf(){ + patentWallService.clearPatentWallConf(); + patentWallService.clearPatentWallSerachConf(); + return ApiResult.success("清除配置缓存成功!"); + } +} diff --git a/src/main/youhong_ai_old_src/com/api/aiyh_pcn/patentWall/dao/ClassificationWallMapper.java b/src/main/youhong_ai_old_src/com/api/aiyh_pcn/patentWall/dao/ClassificationWallMapper.java new file mode 100644 index 0000000..575dde6 --- /dev/null +++ b/src/main/youhong_ai_old_src/com/api/aiyh_pcn/patentWall/dao/ClassificationWallMapper.java @@ -0,0 +1,71 @@ +package com.api.aiyh_pcn.patentWall.dao; + +import aiyh.utils.annotation.recordset.ParamMapper; +import aiyh.utils.annotation.recordset.Select; +import aiyh.utils.annotation.recordset.SqlMapper; + +import java.util.List; +import java.util.Map; + +/** + *

+ *

create 2022/5/22 17:03

+ * + * @author ayh + */ + +@SqlMapper +public interface ClassificationWallMapper { + + @Select("SELECT u2.* " + + "FROM( " + + " SELECT " + + " @ids AS p_ids, " + + " (SELECT @ids := GROUP_CONCAT(id) FROM $t{table} WHERE FIND_IN_SET(sjleib, @ids)) AS c_ids, " + + " @l := @l+1 AS LEVEL " + + " FROM $t{table}, (SELECT @ids := #{dataId}, @l := 0 ) b " + +// " WHERE @ids IS NOT NULL " + + " ) u1 " + + "JOIN $t{table} u2 " + + "ON FIND_IN_SET(u2.id, u1.p_ids) limit #{start},#{size}") + List> selectDataList( + @ParamMapper("table") String tableName, + @ParamMapper("start") Integer start, + @ParamMapper("size") Integer size, + @ParamMapper("dataId") Integer dataId + ); + + /** + *

查询总数

+ * @param tableName 表明 + * @param dataId 数据ID + * @return + */ + @Select("SELECT count(u2.id) " + + "FROM( " + + " SELECT " + + " @ids AS p_ids, " + + " (SELECT @ids := GROUP_CONCAT(id) FROM $t{table} WHERE FIND_IN_SET(sjleib, @ids)) AS c_ids, " + + " @l := @l+1 AS LEVEL " + + " FROM $t{table}, (SELECT @ids := #{dataId}, @l := 0 ) b " + +// " WHERE @ids IS NOT NULL " + + " ) u1 " + + "JOIN $t{table} u2 " + + "ON FIND_IN_SET(u2.id, u1.p_ids) ") + Integer selectDataCount( + @ParamMapper("table") String tableName, + @ParamMapper("dataId") Integer dataId + ); + + @Select("select * from $t{tableName} limit #{start},#{size}") + List> selectAllDataList( + @ParamMapper("tableName") String tableName, + @ParamMapper("start") Integer start, + @ParamMapper("size") Integer size + ); + + @Select("select count(id) from $t{tableName}") + Integer selectAllDataCount( + @ParamMapper("tableName") String tableName + ); +} diff --git a/src/main/youhong_ai_old_src/com/api/aiyh_pcn/patentWall/dao/GovernmentSourceDto.java b/src/main/youhong_ai_old_src/com/api/aiyh_pcn/patentWall/dao/GovernmentSourceDto.java new file mode 100644 index 0000000..da0fb85 --- /dev/null +++ b/src/main/youhong_ai_old_src/com/api/aiyh_pcn/patentWall/dao/GovernmentSourceDto.java @@ -0,0 +1,18 @@ +package com.api.aiyh_pcn.patentWall.dao; + +import lombok.Data; + +/** + *

+ *

create 2022/5/22 15:32

+ * + * @author ayh + */ + +@Data +public class GovernmentSourceDto { + + private Integer page; + private Integer pageSize; + private Integer dataId; +} diff --git a/src/main/youhong_ai_old_src/com/api/aiyh_pcn/patentWall/dao/PatentWallMapping.java b/src/main/youhong_ai_old_src/com/api/aiyh_pcn/patentWall/dao/PatentWallMapping.java new file mode 100644 index 0000000..106f6b0 --- /dev/null +++ b/src/main/youhong_ai_old_src/com/api/aiyh_pcn/patentWall/dao/PatentWallMapping.java @@ -0,0 +1,44 @@ +package com.api.aiyh_pcn.patentWall.dao; + +import aiyh.utils.Util; +import aiyh.utils.zwl.common.ToolUtil; +import weaver.conn.RecordSet; + +import java.util.List; +import java.util.Map; + +/** + * @author EBU7-dev1-ayh + * @create 2021/11/25 0025 15:28 + */ + +public class PatentWallMapping { + private final ToolUtil toolUtil = new ToolUtil(); + + public List> getAllList(String tableName) { + RecordSet rs = new RecordSet(); + String query = "select * from " + tableName; + rs.executeQuery(query); + return Util.recordSet2MapList(rs); + } + + public List> getListByFilterWhere(StringBuilder whereBuilder, List args, + String tableName) { + RecordSet rs = new RecordSet(); + String query = "select * from " + tableName + whereBuilder.toString().replace(" where add ", " where "); + rs.executeQuery(query, args); + toolUtil.writeDebuggerLog(String.format("执行SQL: {%s} ---> 参数: {%s}", query, args)); + return Util.recordSet2MapList(rs); + } + + public List> getSelectOptions(String dataResource, String dbFieldName) { + RecordSet rs = new RecordSet(); + String query = "select wbf.id,wbf.fieldname,wbf.fieldlabel,wb.tablename, " + "ws.selectname,ws.selectvalue " + + "from workflow_billfield wbf " + "left join workflow_bill wb on wbf.billid = wb.id " + + "left join workflow_selectitem ws on ws.fieldid = wbf.id " + "where wb.tablename = ? and fieldname = ? "; + rs.executeQuery(query, dataResource, dbFieldName); + toolUtil + .writeDebuggerLog(String.format("执行SQL: {%s} ---> 参数: {%s}", query, dataResource + " -- " + dbFieldName)); + return Util.recordSet2MapList(rs); + } +} diff --git a/src/main/youhong_ai_old_src/com/api/aiyh_pcn/patentWall/dao/SourceWallMapper.java b/src/main/youhong_ai_old_src/com/api/aiyh_pcn/patentWall/dao/SourceWallMapper.java new file mode 100644 index 0000000..0f3b596 --- /dev/null +++ b/src/main/youhong_ai_old_src/com/api/aiyh_pcn/patentWall/dao/SourceWallMapper.java @@ -0,0 +1,65 @@ +package com.api.aiyh_pcn.patentWall.dao; + +import aiyh.utils.annotation.recordset.ParamMapper; +import aiyh.utils.annotation.recordset.Select; +import aiyh.utils.annotation.recordset.SqlMapper; + +import java.util.List; +import java.util.Map; + +/** + *

+ *

create 2022/5/22 17:03

+ * + * @author ayh + */ + +@SqlMapper +public interface SourceWallMapper { + + @Select("SELECT u2.* " + + "FROM( " + + " SELECT " + + " @ids AS p_ids, " + + " (SELECT @ids := GROUP_CONCAT(id) FROM uf_zfzy WHERE FIND_IN_SET(sj, @ids)) AS c_ids, " + + " @l := @l+1 AS LEVEL " + + " FROM uf_zfzy, (SELECT @ids := #{dataId}, @l := 0 ) b " + +// " WHERE @ids IS NOT NULL " + + " ) u1 " + + "JOIN uf_zfzy u2 " + + "ON FIND_IN_SET(u2.id, u1.p_ids) limit #{start},#{size}") + List> selectDataList( + @ParamMapper("tableName") String tableName, + @ParamMapper("start") Integer start, + @ParamMapper("size") Integer size, + @ParamMapper("dataId") Integer dataId + ); + + @Select("SELECT count(u2.id) " + + "FROM( " + + " SELECT " + + " @ids AS p_ids, " + + " (SELECT @ids := GROUP_CONCAT(id) FROM uf_zfzy WHERE FIND_IN_SET(sj, @ids)) AS c_ids, " + + " @l := @l+1 AS LEVEL " + + " FROM uf_zfzy, (SELECT @ids := #{dataId}, @l := 0 ) b " + +// " WHERE @ids IS NOT NULL " + + " ) u1 " + + "JOIN uf_zfzy u2 " + + "ON FIND_IN_SET(u2.id, u1.p_ids) ") + Integer selectDataCount( + @ParamMapper("tableName") String tableName, + @ParamMapper("dataId") Integer dataId + ); + + @Select("select * from $t{tableName} limit #{start},#{size}") + List> selectAllDataList( + @ParamMapper("tableName") String tableName, + @ParamMapper("start") Integer start, + @ParamMapper("size") Integer size + ); + + @Select("select count(id) from $t{tableName}") + Integer selectAllDataCount( + @ParamMapper("tableName") String tableName + ); +} diff --git a/src/main/youhong_ai_old_src/com/api/aiyh_pcn/patentWall/dto/FilterWhere.java b/src/main/youhong_ai_old_src/com/api/aiyh_pcn/patentWall/dto/FilterWhere.java new file mode 100644 index 0000000..2373ab2 --- /dev/null +++ b/src/main/youhong_ai_old_src/com/api/aiyh_pcn/patentWall/dto/FilterWhere.java @@ -0,0 +1,20 @@ +package com.api.aiyh_pcn.patentWall.dto; + +import lombok.Getter; +import lombok.Setter; +import lombok.ToString; + +/** + * @author EBU7-dev1-ayh + * @create 2021/11/26 0026 11:35 + * 查询列表筛选条件 + */ + +@Setter +@Getter +@ToString +public class FilterWhere { + private int searchType; + private String dbField; + private String value; +} diff --git a/src/main/youhong_ai_old_src/com/api/aiyh_pcn/patentWall/entity/PatentEntity.java b/src/main/youhong_ai_old_src/com/api/aiyh_pcn/patentWall/entity/PatentEntity.java new file mode 100644 index 0000000..0fae9be --- /dev/null +++ b/src/main/youhong_ai_old_src/com/api/aiyh_pcn/patentWall/entity/PatentEntity.java @@ -0,0 +1,14 @@ +package com.api.aiyh_pcn.patentWall.entity; + +/** + * @author EBU7-dev1-ayh + * create 2021/11/25 0025 15:30 + * + */ + + +public class PatentEntity { + private String id; + private String icon; + private String linkUrl; +} diff --git a/src/main/youhong_ai_old_src/com/api/aiyh_pcn/patentWall/service/ClassificationWallService.java b/src/main/youhong_ai_old_src/com/api/aiyh_pcn/patentWall/service/ClassificationWallService.java new file mode 100644 index 0000000..bde0f1c --- /dev/null +++ b/src/main/youhong_ai_old_src/com/api/aiyh_pcn/patentWall/service/ClassificationWallService.java @@ -0,0 +1,198 @@ +package com.api.aiyh_pcn.patentWall.service; + +import aiyh.utils.Util; +import aiyh.utils.excention.CustomerException; +import com.api.aiyh_pcn.patentWall.dao.ClassificationWallMapper; +import com.api.aiyh_pcn.patentWall.dao.GovernmentSourceDto; +import com.api.aiyh_pcn.patentWall.vo.ClassificationWallVo; +import com.api.aiyh_pcn.patentWall.vo.LinkUrlVO; +import com.api.aiyh_pcn.patentWall.vo.PatentVO; +import org.apache.log4j.Logger; +import weaver.conn.RecordSet; +import weaver.hrm.User; + +import java.beans.BeanInfo; +import java.beans.IntrospectionException; +import java.beans.Introspector; +import java.beans.PropertyDescriptor; +import java.lang.reflect.InvocationTargetException; +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; + +/** + *

分类墙业务处理

+ *

create 2022/5/22 15:10

+ * + * @author ayh + */ +public class ClassificationWallService { + + private Map classificationWallConfig; + private final Logger logger = Util.getLogger(); + + private final ClassificationWallMapper mapper = Util.getMapper(ClassificationWallMapper.class); + /** + * 获取单例的配置文件信息 + * + * @return + */ + private Map getSourceWallSearchConf(String prefix) { + if (this.classificationWallConfig != null) { + return this.classificationWallConfig; + } + synchronized (this) { + if (this.classificationWallConfig == null) { + this.classificationWallConfig = Util.readProperties2Map("classificationWall", "aiyh.classificationWall." + prefix); + } + if (this.classificationWallConfig == null) { + return new HashMap<>(0); + } + return new HashMap<>(this.classificationWallConfig); + } + } + + public void clearSourceWallConf() { + this.classificationWallConfig = null; + } + + public ClassificationWallVo getSource(GovernmentSourceDto governmentSourceDto, User user) { + logger.info("获取到查询参数:" + governmentSourceDto); + Map voMapping = this.getSourceWallSearchConf("voMapping"); + logger.info("获取配置文件信息:"+voMapping); + Integer page = governmentSourceDto.getPage(); + Integer pageSize = governmentSourceDto.getPageSize(); + if (pageSize == null || pageSize <= 0){ + pageSize = 10; + } + if(page == null || page < 0){ + page = 0; + } + Integer dataId = governmentSourceDto.getDataId(); + String dataResource = Util.null2DefaultStr(voMapping.get("dataResource"),""); + String buttonUrl = Util.null2DefaultStr(voMapping.get("addSourceUrl"),""); + String addSourceLabelIndex = Util.null2DefaultStr(voMapping.get("addSourceLabelIndex"),""); + String addSourceLabelName = Util.null2DefaultStr(voMapping.get("addSourceLabelName"),""); + List> dataList; + Integer total; + Integer start = page * pageSize; + if(dataId == null || dataId <= 0){ +// 查询全部 + dataList = mapper.selectAllDataList(dataResource,start,pageSize); + total = mapper.selectAllDataCount(dataResource); + }else{ + dataList = mapper.selectDataList(dataResource,start,pageSize,dataId); + logger.info("查询子级所有数据:" + dataList); + total = mapper.selectDataCount(dataResource, dataId); + } + List list = new ArrayList<>(); + List args = new ArrayList<>(); + for (Map data : dataList) { + Map config = new HashMap<>(voMapping); + for (Map.Entry entry : voMapping.entrySet()) { + String patentVoField = entry.getKey(); + // linkList + String parsing = null; + // 值解析 + if ("linkList".equals(patentVoField)) { + List linkUrlVOS = new ArrayList<>(); + List> linkUrlList = (List>) entry.getValue(); + for (Map linkUrlMap : linkUrlList) { + LinkUrlVO linkUrlVO = new LinkUrlVO(); + BeanInfo beanInfo = null; + try { + beanInfo = Introspector.getBeanInfo(LinkUrlVO.class, Object.class); + } catch (IntrospectionException e) { + throw new CustomerException("ClassificationWallService:获取beanInfo错误",e); + } + PropertyDescriptor[] propertyDescriptors = beanInfo.getPropertyDescriptors(); + for (PropertyDescriptor propertyDescriptor : propertyDescriptors) { + String keyName = propertyDescriptor.getName(); + String parsingValue = String.valueOf(linkUrlMap.get(keyName)); + parsingValue = handleParsingConf(parsingValue, data, args); + // 清除参数信息 + args.clear(); + if (propertyDescriptor.getPropertyType().equals(Integer.class)) { + try { + propertyDescriptor + .getWriteMethod() + .invoke(linkUrlVO, Integer.valueOf(parsingValue)); + } catch (IllegalAccessException | InvocationTargetException e) { + throw new CustomerException("ClassificationWallService:设置值失败,调用beanInfo的set方法错误",e); + } + } else { + try { + propertyDescriptor.getWriteMethod().invoke(linkUrlVO, parsingValue); + } catch (IllegalAccessException | InvocationTargetException e) { + throw new CustomerException("ClassificationWallService:设置值失败,调用beanInfo的set方法错误",e); + } + } + } + linkUrlVOS.add(linkUrlVO); + } + config.replace(patentVoField, linkUrlVOS); + } else { + parsing = String.valueOf(entry.getValue()); + parsing = handleParsingConf(parsing, data, args); + // 修改数据 + config.replace(patentVoField, parsing); + // 清除参数信息 + args.clear(); + } + } + PatentVO patentVO = null; + try { + patentVO = Util.mapToObject(config, PatentVO.class); + patentVO.setLinkList((List) config.get("linkList")); + int language = user.getLanguage(); + if (language == 8){ + patentVO.setTitle(patentVO.getTitleEn()); + } + } catch (Exception e) { + throw new CustomerException("ClassificationWallService:map转为PatentVO失败!",e); + } + list.add(patentVO); + } + ClassificationWallVo classificationWallVo = new ClassificationWallVo(); + classificationWallVo.setAddSourceUrl(buttonUrl); + classificationWallVo.setAddSourceLabelIndex(addSourceLabelIndex); + classificationWallVo.setAddSourceLabelName(addSourceLabelName); + classificationWallVo.setSourceList(list); + classificationWallVo.setTotal(total); + return classificationWallVo; + } + + public String handleParsingConf(String parsing, Map data, List args) { + // 值解析 + // 解析 ${}类型的参数,直接替换 + String pattern = "\\$\\{(?(\\s|\\S)+?)}"; + Pattern compile = Pattern.compile(pattern); + Matcher matcher = compile.matcher(parsing); + while (matcher.find()) { + parsing = parsing.replaceFirst(pattern, Util.null2String(data.get(matcher.group("field")))); + } + // 解析#{}类型的参数,替换为?并按照顺序收集args + pattern = "#\\{(?(\\s|\\S)+?)}"; + compile = Pattern.compile(pattern); + matcher = compile.matcher(parsing); + while (matcher.find()) { + parsing = parsing.replaceFirst(pattern, "?"); + args.add(Util.null2String(data.get(matcher.group("field")))); + } + // 解析#sql{}类型的参数,并执行SQL,获取到SQL的值 + pattern = "#sql\\{(?([\\s\\S])+?)}"; + compile = Pattern.compile(pattern); + matcher = compile.matcher(parsing); + RecordSet rs = new RecordSet(); + while (matcher.find()) { + String sqlStr = matcher.group("sqlStr"); + rs.executeQuery(sqlStr, args); + rs.next(); + parsing = parsing.replaceFirst(pattern, Util.null2String(rs.getString(1))); + } + return parsing; + } +} diff --git a/src/main/youhong_ai_old_src/com/api/aiyh_pcn/patentWall/service/GovernmentSourceService.java b/src/main/youhong_ai_old_src/com/api/aiyh_pcn/patentWall/service/GovernmentSourceService.java new file mode 100644 index 0000000..6e93c9f --- /dev/null +++ b/src/main/youhong_ai_old_src/com/api/aiyh_pcn/patentWall/service/GovernmentSourceService.java @@ -0,0 +1,199 @@ +package com.api.aiyh_pcn.patentWall.service; + +import aiyh.utils.Util; +import aiyh.utils.excention.CustomerException; +import com.api.aiyh_pcn.patentWall.dao.GovernmentSourceDto; +import com.api.aiyh_pcn.patentWall.dao.SourceWallMapper; +import com.api.aiyh_pcn.patentWall.vo.GovernmentSourceVo; +import com.api.aiyh_pcn.patentWall.vo.LinkUrlVO; +import com.api.aiyh_pcn.patentWall.vo.PatentVO; +import org.apache.log4j.Logger; +import weaver.conn.RecordSet; +import weaver.hrm.User; + +import java.beans.BeanInfo; +import java.beans.IntrospectionException; +import java.beans.Introspector; +import java.beans.PropertyDescriptor; +import java.lang.reflect.InvocationTargetException; +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; + +/** + *

+ *

create 2022/5/22 15:10

+ * + * @author ayh + */ +//governmentSourceWall +public class GovernmentSourceService { + + private Map governmentSourceConfig; + private final Logger logger = Util.getLogger(); + + private final SourceWallMapper mapper = Util.getMapper(SourceWallMapper.class); + /** + * 获取单例的配置文件信息 + * + * @return + */ + private Map getSourceWallSearchConf(String prefix) { + if (this.governmentSourceConfig != null) { + return this.governmentSourceConfig; + } + synchronized (this) { + if (this.governmentSourceConfig == null) { + this.governmentSourceConfig = Util.readProperties2Map("governmentSourceWall", "aiyh.sourceWall." + prefix); + } + if (this.governmentSourceConfig == null) { + return new HashMap<>(0); + } + return new HashMap<>(this.governmentSourceConfig); + } + } + + public void clearSourceWallConf() { + this.governmentSourceConfig = null; + } + + public GovernmentSourceVo getSource(GovernmentSourceDto governmentSourceDto, User user) { + logger.info("获取到查询参数:" + governmentSourceDto); + Map voMapping = this.getSourceWallSearchConf("voMapping"); + logger.info("获取配置文件信息:"+voMapping); + Integer page = governmentSourceDto.getPage(); + Integer pageSize = governmentSourceDto.getPageSize(); + if (pageSize == null || pageSize <= 0){ + pageSize = 10; + } + if(page == null || page < 0){ + page = 0; + } + Integer dataId = governmentSourceDto.getDataId(); + String dataResource = Util.null2DefaultStr(voMapping.get("dataResource"),""); + String buttonUrl = Util.null2DefaultStr(voMapping.get("addSourceUrl"),""); + String addSourceLabelIndex = Util.null2DefaultStr(voMapping.get("addSourceLabelIndex"),""); + String addSourceLabelName = Util.null2DefaultStr(voMapping.get("addSourceLabelName"),""); + List> dataList; + Integer total; + Integer start = page * pageSize; + if(dataId == null || dataId <= 0){ +// 查询全部 + dataList = mapper.selectAllDataList(dataResource,start,pageSize); + total = mapper.selectAllDataCount(dataResource); + }else{ + dataList = mapper.selectDataList(dataResource,start,pageSize,dataId); + logger.info("查询子级所有数据:" + dataList); + total = mapper.selectDataCount(dataResource, dataId); + } + List list = new ArrayList<>(); + List args = new ArrayList<>(); + for (Map data : dataList) { + Map config = new HashMap<>(voMapping); + for (Map.Entry entry : voMapping.entrySet()) { + String patentVoField = entry.getKey(); + // linkList + String parsing = null; + // 值解析 + if ("linkList".equals(patentVoField)) { + List linkUrlVOS = new ArrayList<>(); + List> linkUrlList = (List>) entry.getValue(); + for (Map linkUrlMap : linkUrlList) { + LinkUrlVO linkUrlVO = new LinkUrlVO(); + BeanInfo beanInfo = null; + try { + beanInfo = Introspector.getBeanInfo(LinkUrlVO.class, Object.class); + } catch (IntrospectionException e) { + throw new CustomerException("GovernmentSourceService:获取beanInfo错误",e); + } + PropertyDescriptor[] propertyDescriptors = beanInfo.getPropertyDescriptors(); + for (PropertyDescriptor propertyDescriptor : propertyDescriptors) { + String keyName = propertyDescriptor.getName(); + String parsingValue = String.valueOf(linkUrlMap.get(keyName)); + parsingValue = handleParsingConf(parsingValue, data, args); + // 清除参数信息 + args.clear(); + if (propertyDescriptor.getPropertyType().equals(Integer.class)) { + try { + propertyDescriptor + .getWriteMethod() + .invoke(linkUrlVO, Integer.valueOf(parsingValue)); + } catch (IllegalAccessException | InvocationTargetException e) { + throw new CustomerException("GovernmentSourceService:设置值失败,调用beanInfo的set方法错误",e); + } + } else { + try { + propertyDescriptor.getWriteMethod().invoke(linkUrlVO, parsingValue); + } catch (IllegalAccessException | InvocationTargetException e) { + throw new CustomerException("GovernmentSourceService:设置值失败,调用beanInfo的set方法错误",e); + } + } + } + linkUrlVOS.add(linkUrlVO); + } + config.replace(patentVoField, linkUrlVOS); + } else { + parsing = String.valueOf(entry.getValue()); + parsing = handleParsingConf(parsing, data, args); + // 修改数据 + config.replace(patentVoField, parsing); + // 清除参数信息 + args.clear(); + } + } + PatentVO patentVO = null; + try { + patentVO = Util.mapToObject(config, PatentVO.class); + patentVO.setLinkList((List) config.get("linkList")); + int language = user.getLanguage(); + if (language == 8){ + patentVO.setTitle(patentVO.getTitleEn()); + } + } catch (Exception e) { + throw new CustomerException("GovernmentSourceService:map转为PatentVO失败!",e); + } + list.add(patentVO); + } + GovernmentSourceVo governmentSourceVo = new GovernmentSourceVo(); + governmentSourceVo.setAddSourceUrl(buttonUrl); + governmentSourceVo.setAddSourceLabelIndex(addSourceLabelIndex); + governmentSourceVo.setAddSourceLabelName(addSourceLabelName); + governmentSourceVo.setSourceList(list); + governmentSourceVo.setTotal(total); + return governmentSourceVo; + } + + public String handleParsingConf(String parsing, Map data, List args) { + // 值解析 + // 解析 ${}类型的参数,直接替换 + String pattern = "\\$\\{(?(\\s|\\S)+?)}"; + Pattern compile = Pattern.compile(pattern); + Matcher matcher = compile.matcher(parsing); + while (matcher.find()) { + parsing = parsing.replaceFirst(pattern, Util.null2String(data.get(matcher.group("field")))); + } + // 解析#{}类型的参数,替换为?并按照顺序收集args + pattern = "#\\{(?(\\s|\\S)+?)}"; + compile = Pattern.compile(pattern); + matcher = compile.matcher(parsing); + while (matcher.find()) { + parsing = parsing.replaceFirst(pattern, "?"); + args.add(Util.null2String(data.get(matcher.group("field")))); + } + // 解析#sql{}类型的参数,并执行SQL,获取到SQL的值 + pattern = "#sql\\{(?([\\s\\S])+?)}"; + compile = Pattern.compile(pattern); + matcher = compile.matcher(parsing); + RecordSet rs = new RecordSet(); + while (matcher.find()) { + String sqlStr = matcher.group("sqlStr"); + rs.executeQuery(sqlStr, args); + rs.next(); + parsing = parsing.replaceFirst(pattern, Util.null2String(rs.getString(1))); + } + return parsing; + } +} diff --git a/src/main/youhong_ai_old_src/com/api/aiyh_pcn/patentWall/service/PatentWallService.java b/src/main/youhong_ai_old_src/com/api/aiyh_pcn/patentWall/service/PatentWallService.java new file mode 100644 index 0000000..dceb055 --- /dev/null +++ b/src/main/youhong_ai_old_src/com/api/aiyh_pcn/patentWall/service/PatentWallService.java @@ -0,0 +1,373 @@ +package com.api.aiyh_pcn.patentWall.service; + +import aiyh.utils.Util; +import aiyh.utils.zwl.common.ToolUtil; +import com.api.aiyh_pcn.patentWall.dao.PatentWallMapping; +import com.api.aiyh_pcn.patentWall.dto.FilterWhere; +import com.api.aiyh_pcn.patentWall.vo.LinkUrlVO; +import com.api.aiyh_pcn.patentWall.vo.PatentVO; +import com.api.aiyh_pcn.patentWall.vo.SearchInputVO; +import com.api.aiyh_pcn.patentWall.vo.SelectOptionsVo; +import org.apache.log4j.Logger; +import weaver.conn.RecordSet; + +import java.beans.BeanInfo; +import java.beans.IntrospectionException; +import java.beans.Introspector; +import java.beans.PropertyDescriptor; +import java.lang.reflect.InvocationTargetException; +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; + +/** + * @author EBU7-dev1-ayh + * @create 2021/11/25 0025 15:23 + */ +public class PatentWallService { + private final PatentWallMapping patentWallMapping = new PatentWallMapping(); + private final ToolUtil toolUtil = new ToolUtil(); + private final RecordSet rs = new RecordSet(); + private Map patentWallConf; + private Map patentWallSearchConf; + private final Logger logger = Util.getLogger(); + + /** + * 查询搜索框配置信息 + * + * @param prefix 前缀 + * @return 配置信息 + */ + public List getSearchList(String prefix, int languageId) { + Map patentWallSearchConf = getPatentWallSearchConf(prefix + ".search"); + String dataResource = String.valueOf(patentWallSearchConf.get("dataResource")); + List> inputs = + (List>) patentWallSearchConf.get("inputs"); + List searchInputList = new ArrayList<>(); + for (Map input : inputs) { + SearchInputVO searchInputVO = new SearchInputVO(); + int type = Integer.parseInt(Util.null2DefaultStr(input.get("type"), "0")); + String dbFieldName = Util.null2String(input.get("dbFieldName")); + String value = Util.null2String(input.get("value")); + String labelName = Util.null2String(input.get("labelName")); + Integer labelIndex = Integer.valueOf(Util.null2DefaultStr(input.get("labelIndex"), "0")); + Integer searchType = Integer.valueOf(Util.null2DefaultStr(input.get("searchType"), "0")); + Boolean multiple = Boolean.valueOf(Util.null2DefaultStr(input.get("multiple"), "false")); + searchInputVO.setType(type); + searchInputVO.setLabelName(labelName); + searchInputVO.setSearchType(searchType); + searchInputVO.setDbFieldName(dbFieldName); + searchInputVO.setLabelIndex(labelIndex); + searchInputVO.setLabelIndex(labelIndex); + searchInputVO.setMultiple(multiple); + searchInputVO.setValue(value); + searchInputList.add(searchInputVO); + switch (type) { + case 1: + // 下拉框 查询options + List optionsVos = + getSelectOptions(dataResource, dbFieldName, languageId); + searchInputVO.setSelectOptions(optionsVos); + case 2: + // 单行文本 + break; + case 3: + // 日期 + case 4: + // 单人力资源 + break; + case 5: + // 多人力资源 + break; + case 6: + // 流程路径 + break; + case 7: + // 多流程路径 + break; + default: + toolUtil.writeDebuggerLog("未匹配输入框类型!请检查配置文件是否正确!"); + break; + } + } + return searchInputList; + } + + private List getSelectOptions( + String dataResource, String dbFieldName, int languageId) { + List> selectOptions = + patentWallMapping.getSelectOptions(dataResource, dbFieldName); + List optionsVos = new ArrayList<>(); + SelectOptionsVo optionsDefault = new SelectOptionsVo(); + optionsDefault.setSelected(true); + optionsDefault.setKey(""); + optionsDefault.setShowname(""); + optionsVos.add(optionsDefault); + for (Map selectOption : selectOptions) { + SelectOptionsVo optionsVo = new SelectOptionsVo(); + optionsVo.setSelected(false); + optionsVo.setKey(Util.null2DefaultStr(selectOption.get("selectvalue"), "")); + String selectName = Util.null2DefaultStr(selectOption.get("selectname"), ""); + String showName = selectName; + if (selectName.startsWith("~`~`") && selectName.endsWith("`~`~")) { + String pattern = "(`~`" + languageId + " )(?