MobileEntryBillExtendEditHandler.java 40 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274
  1. package com.kingdee.eas.custom.wamke.syncdata.web;
  2. import java.io.IOException;
  3. import java.math.BigDecimal;
  4. import java.net.URL;
  5. import java.text.MessageFormat;
  6. import java.text.SimpleDateFormat;
  7. import java.util.ArrayList;
  8. import java.util.Date;
  9. import java.util.List;
  10. import java.util.Map;
  11. import java.util.TreeMap;
  12. import javax.servlet.http.HttpServletRequest;
  13. import javax.servlet.http.HttpServletResponse;
  14. import org.apache.http.HttpEntity;
  15. import org.apache.http.client.methods.CloseableHttpResponse;
  16. import org.apache.http.client.methods.HttpGet;
  17. import org.apache.http.impl.client.CloseableHttpClient;
  18. import org.apache.http.impl.client.HttpClients;
  19. import org.apache.http.util.EntityUtils;
  20. import org.apache.log4j.Logger;
  21. import org.apache.log4j.Priority;
  22. import org.springframework.ui.ModelMap;
  23. import com.alibaba.fastjson.JSON;
  24. import com.alibaba.fastjson.JSONObject;
  25. import com.kingdee.bos.BOSException;
  26. import com.kingdee.bos.Context;
  27. import com.kingdee.bos.dao.IObjectPK;
  28. import com.kingdee.bos.dao.ormapping.ObjectUuidPK;
  29. import com.kingdee.bos.metadata.entity.EntityViewInfo;
  30. import com.kingdee.bos.metadata.entity.FilterInfo;
  31. import com.kingdee.bos.metadata.entity.FilterItemInfo;
  32. import com.kingdee.eas.base.attachment.AttachmentFactory;
  33. import com.kingdee.eas.base.attachment.AttachmentInfo;
  34. import com.kingdee.eas.base.attachment.BoAttchAssoFactory;
  35. import com.kingdee.eas.base.attachment.IAttachment;
  36. import com.kingdee.eas.base.attachment.IBoAttchAsso;
  37. import com.kingdee.eas.common.EASBizException;
  38. import com.kingdee.eas.custom.utils.HttpUtils;
  39. import com.kingdee.eas.custom.wamke.syncdata.MobileEntryBillInfo;
  40. import com.kingdee.eas.custom.wamke.syncdata.dto.MobileAttachAssembleDto;
  41. import com.kingdee.eas.custom.wamke.syncdata.dto.MobileAttachDto;
  42. import com.kingdee.eas.framework.CoreBaseInfo;
  43. import com.kingdee.eas.util.app.ContextUtil;
  44. import com.kingdee.eas.util.app.DbUtil;
  45. import com.kingdee.jdbc.rowset.IRowSet;
  46. import com.kingdee.shr.attachment.AttachmentState;
  47. import com.kingdee.shr.attachment.AttachmentTypeEnum;
  48. import com.kingdee.shr.attachment.ISHRAttachmentExt;
  49. import com.kingdee.shr.attachment.SHRAttachmentExtCollection;
  50. import com.kingdee.shr.attachment.SHRAttachmentExtFactory;
  51. import com.kingdee.shr.attachment.SHRAttachmentExtInfo;
  52. import com.kingdee.shr.base.syssetting.app.filter.HRFilterUtils;
  53. import com.kingdee.shr.base.syssetting.context.SHRContext;
  54. import com.kingdee.shr.base.syssetting.exception.SHRWebException;
  55. import com.kingdee.shr.base.syssetting.exception.ShrWebBizException;
  56. import com.kingdee.shr.base.syssetting.web.handler.EditHandler;
  57. import com.kingdee.util.StringUtils;
  58. import java.io.FileOutputStream;
  59. import java.io.InputStream;
  60. import java.io.OutputStream;
  61. public class MobileEntryBillExtendEditHandler extends EditHandler {
  62. private static Logger logger = Logger.getLogger(MobileEntryBillExtendEditHandler.class);
  63. // 重载初始化
  64. @Override
  65. public String initalizeAction(HttpServletRequest request,
  66. HttpServletResponse response, ModelMap modelMap)
  67. throws SHRWebException {
  68. logInfo("initalizeAction初始化");
  69. String operateStatus = getOperateStatus(request, modelMap);
  70. if (!(StringUtils.isEmpty(operateStatus))) {
  71. logInfo("初始化得到操作状态为:" + operateStatus);
  72. if ("ADDNEW".equalsIgnoreCase(operateStatus))
  73. throw new SHRWebException("不允许创建数据");
  74. // return addNewAction(request, response, modelMap);
  75. if ("EDIT".equalsIgnoreCase(operateStatus))
  76. throw new SHRWebException("不允许编辑数据");
  77. // return editAction(request, response, modelMap);
  78. if (("VIEW".equalsIgnoreCase(operateStatus))
  79. || ("readonly".equalsIgnoreCase(operateStatus))) {
  80. return super.viewAction(request, response, modelMap);
  81. }
  82. }
  83. return super.viewAction(request, response, modelMap);
  84. }
  85. // 修改保存
  86. @Override
  87. protected IObjectPK runSaveData(HttpServletRequest request,
  88. HttpServletResponse response, CoreBaseInfo model) throws Exception {
  89. logInfo("runSaveData初化");
  90. JSONObject jsonObj = JSON.parseObject(request.getParameter("model"));
  91. MobileEntryBillInfo info = (MobileEntryBillInfo) model;
  92. // 校验是否已存在相面的关联人员,蝶城,负责人类型
  93. String reAuditStatus = mappingAuditStatus(model.get("reApprovalStatus")
  94. .toString());
  95. String auditStatus = mappingAuditStatus(model.get("approvalStatus")
  96. .toString());
  97. IObjectPK pk = super.runSaveData(request, response, model);
  98. // 更新负责人姓名和编号,蝶城
  99. if ((info != null && info.getId() != null) || pk != null) {
  100. String id = pk != null ? pk.toString() : info.getId().toString();
  101. //if(reAuditStatus.equals("DISAPPROVAL") || reAuditStatus.equals("APPROVAL")){
  102. afterRunSaveData(id, auditStatus, reAuditStatus, info);
  103. //}
  104. }
  105. return pk;
  106. }
  107. private void logInfo(String msg) {
  108. System.out.println(msg);
  109. logger.log(Priority.INFO, msg);
  110. }
  111. protected void afterInitModel(HttpServletRequest request,
  112. HttpServletResponse response, CoreBaseInfo coreBaseInfo)
  113. throws SHRWebException {
  114. logInfo("after初始化");
  115. super.afterInitModel(request, response, coreBaseInfo);
  116. logInfo("after初始化-结束");
  117. String billId = getBillId(request);
  118. logInfo("获取billId");
  119. if (!(StringUtils.isEmpty(billId))) {
  120. try {
  121. // 添加附件
  122. coreBaseInfo.put("attachJson", getAttachString(billId));
  123. } catch (Exception e) {
  124. logInfo("添加附件出错:"+e.getMessage());
  125. throw new SHRWebException(e.getMessage());
  126. }
  127. }
  128. }
  129. /**
  130. * 获取附件对象的JSON字符串
  131. *
  132. * @param dataId
  133. * @return
  134. * @throws Exception
  135. */
  136. private String getAttachString(String dataId) throws Exception {
  137. List<MobileAttachDto> allData = getAttachList(dataId);
  138. if (allData.isEmpty()) {
  139. return "";
  140. }
  141. logInfo("json化附件");
  142. String json = JSON.toJSONString(transToDto(allData));
  143. return json.replace("\"", "'");
  144. }
  145. /**
  146. * 获取附件列表
  147. *
  148. * @param dataId
  149. * @return
  150. * @throws Exception
  151. */
  152. private List<MobileAttachDto> getAttachList(String dataId) throws Exception {
  153. String sql = "SELECT * FROM CT_WK_attach WHERE data_id = '" + dataId+ "' and is_delete = 0";
  154. logInfo("获取附件列表");
  155. Context ctx = SHRContext.getInstance().getContext();
  156. IRowSet rowSet = DbUtil.executeQuery(ctx, sql);
  157. List<MobileAttachDto> allData = new ArrayList<MobileAttachDto>();
  158. MobileAttachDto item = null;
  159. logInfo("附件循环");
  160. while (rowSet.next()) {
  161. item = new MobileAttachDto();
  162. item.setId(rowSet.getInt("id"));
  163. item.setAttachName(rowSet.getString("attach_name"));
  164. item.setAttchUrl(rowSet.getString("attach_url"));
  165. item.setAttachType(rowSet.getString("attach_type"));
  166. item.setOssName(rowSet.getString("oss_name"));
  167. allData.add(item);
  168. }
  169. return allData;
  170. }
  171. /**
  172. * 把附件转换成DTO对象
  173. *
  174. * @param allData
  175. * @return
  176. */
  177. private MobileAttachAssembleDto transToDto(List<MobileAttachDto> allData) {
  178. MobileAttachAssembleDto imgDto = new MobileAttachAssembleDto();
  179. imgDto.setIdCard(getMatchAttachList("IdCard", allData));
  180. imgDto.getIdCard().addAll(getMatchAttachList("IdCardBack", allData));
  181. imgDto.setBankCard(getMatchAttachList("Bank", allData));
  182. imgDto.setContract(getMatchAttachList("Contract", allData));
  183. imgDto.setEntryRegistration(getMatchAttachList("EntryRegistration",
  184. allData));
  185. imgDto.setHealth(getMatchAttachList("Health", allData));
  186. imgDto.setSafe(getMatchAttachList("Safe", allData));
  187. imgDto.setInHand(getMatchAttachList("IdCardInHand", allData));
  188. imgDto.setOther(getMatchAttachList("Other", allData));
  189. imgDto.setManagemenetFile(getMatchAttachList("ManagementFile", allData));
  190. imgDto.setInsuranceProve(getMatchAttachList("InsuranceProve", allData));
  191. imgDto.setBehavioralNorm(getMatchAttachList("BehavioralNorm", allData));
  192. imgDto.setRecommendStimulate(getMatchAttachList("RecommendStimulate", allData));
  193. imgDto.setPromiseCommitment(getMatchAttachList("PromiseCommitment", allData));
  194. return imgDto;
  195. }
  196. /**
  197. * 获取指定类型的附件并返回
  198. *
  199. * @param type
  200. * @param data
  201. * @return
  202. */
  203. private List<MobileAttachDto> getMatchAttachList(String type,
  204. List<MobileAttachDto> data) {
  205. List<MobileAttachDto> result = new ArrayList<MobileAttachDto>();
  206. for (MobileAttachDto item : data) {
  207. if (item.getAttachType().equals(type)) {
  208. result.add(item);
  209. }
  210. }
  211. return result;
  212. }
  213. /**
  214. * 更新审批状态字段
  215. *
  216. * @param id
  217. * @param auditType
  218. * @return
  219. * @throws Exception
  220. */
  221. private void afterRunSaveData(String id, String auditType,
  222. String reAuditType, MobileEntryBillInfo info) throws Exception {
  223. // 更新复审字段
  224. Context ctx = SHRContext.getInstance().getContext();
  225. StringBuilder sb = new StringBuilder();
  226. String userid = ContextUtil.getCurrentUserInfo(ctx).getId().toString();
  227. String userName = ContextUtil.getCurrentUserInfo(ctx).getName()
  228. .toString();
  229. sb.append(" UPDATE CT_WK_MobileEntryBill SET CFApprovalStatus = '")
  230. .append(auditType).append("', CFReApprovalStatus = '").append(
  231. reAuditType).append("', CFLastReApprover = '").append(
  232. userName).append("' ").append(
  233. ", CFLastReApproverId = '").append(userid).append("' ")
  234. .append(", FLastUpdateUserID = '").append(userid).append("' ")
  235. .append(", FLastUpdateTime = GETDATE() ").append(
  236. " WHERE FID = '").append(id).append("'");
  237. logInfo("执行SQL" + sb.toString());
  238. DbUtil.execute(ctx, sb.toString());
  239. if(reAuditType.equals("")){
  240. }
  241. // 如果审批通过,则生成入职单
  242. if (reAuditType.equals("APPROVAL")) {
  243. builderEnrollEntryBill(userid, info);
  244. }
  245. }
  246. /**
  247. *
  248. * @param webAuditStatus
  249. * @return
  250. */
  251. private String mappingAuditStatus(String webAuditStatus) {
  252. if (webAuditStatus.equals("待审核") || webAuditStatus.equals("待审批")) {
  253. return "WAIT";
  254. }
  255. if (webAuditStatus.equals("审核不通过")) {
  256. return "DISAPPROVAL";
  257. }
  258. if (webAuditStatus.equals("审核通过")) {
  259. return "APPROVAL";
  260. }
  261. return webAuditStatus;
  262. }
  263. /**
  264. * 生成入职单据
  265. *
  266. * @throws Exception
  267. */
  268. private void builderEnrollEntryBill(String userId, MobileEntryBillInfo info)
  269. throws Exception {
  270. Context ctx = SHRContext.getInstance().getContext();
  271. String billId = getNewIdByType(ctx, "B41CAA3F");
  272. // String entryBillId = getNewIdByType(ctx, "04BEFD73");
  273. // 生成入职单
  274. logInfo("生成入职单");
  275. insertBill(ctx, userId, info, billId);
  276. // 生成入职单分录
  277. logInfo("生成入职单分录");
  278. insertBillEntry(ctx, userId, info, billId);
  279. // 生成附件
  280. logInfo("生成附件");
  281. saveAttach(ctx, userId, info, billId);
  282. }
  283. /**
  284. * 保存附件
  285. *
  286. * @param ctx
  287. * @param userId
  288. * @param info
  289. * @throws Exception
  290. */
  291. private void saveAttach(Context ctx, String userId, MobileEntryBillInfo info, String billId)
  292. throws Exception {
  293. // 获取附件数据
  294. List<MobileAttachDto> attachList = getAttachList(info.getId().toString());
  295. if (attachList.isEmpty()) {
  296. return;
  297. }
  298. getAttachAndTrans(getMatchAttachList("IdCard", attachList), "身份证正面", billId);
  299. getAttachAndTrans(getMatchAttachList("IdCardBack", attachList), "身份证背面", billId);
  300. getAttachAndTrans(getMatchAttachList("Bank", attachList), "银行卡", billId);
  301. getAttachAndTrans(getMatchAttachList("Contract", attachList), "劳动合同", billId);
  302. getAttachAndTrans(getMatchAttachList("EntryRegistration", attachList),
  303. "入职信息登记", billId);
  304. getAttachAndTrans(getMatchAttachList("Health", attachList), "健康承诺书", billId);
  305. getAttachAndTrans(getMatchAttachList("Safe", attachList), "安全受训承诺书", billId);
  306. getAttachAndTrans(getMatchAttachList("IdCardInHand", attachList),
  307. "手持身份证", billId);
  308. getAttachAndTrans(getMatchAttachList("Other", attachList),
  309. "其他档案", billId);
  310. getAttachAndTrans(getMatchAttachList("ManagementFile", attachList),
  311. "保洁员管理规范", billId);
  312. getAttachAndTrans(getMatchAttachList("InsuranceProve", attachList),
  313. "保险/投保证明", billId);
  314. getAttachAndTrans(getMatchAttachList("BehavioralNorm", attachList),
  315. "行为规范", billId);
  316. getAttachAndTrans(getMatchAttachList("Training", attachList),
  317. "训练/验收清单", billId);
  318. getAttachAndTrans(getMatchAttachList("RecommendStimulate", attachList),
  319. "推荐激励受信书", billId);
  320. getAttachAndTrans(getMatchAttachList("PromiseCommitment", attachList),
  321. "上岗承诺书", billId);
  322. }
  323. /**
  324. * 下载附件并转化
  325. *
  326. * @param currentList
  327. * @throws Exception
  328. */
  329. private void getAttachAndTrans(List<MobileAttachDto> currentList,
  330. String fileName, String billId) throws Exception {
  331. logInfo("下载附件并转化:"+fileName+",json:"+JSON.toJSONString(currentList));
  332. // 处理的附件列表
  333. Integer id = null;
  334. String downloadUrl = null;
  335. byte[] fileByte = null;
  336. for (int i = 0; i < currentList.size(); i++) {
  337. // 获取文件下载链接
  338. id = currentList.get(i).getId();
  339. downloadUrl = HttpUtils.sendGet(
  340. "https://shr.onewo.com:8443/shr_mobile/h5/mobile/attach/download/url/"
  341. + id.toString(), null);
  342. if (null == downloadUrl) {
  343. continue;
  344. }
  345. // 生成附件
  346. fileByte = downloadAliyunAttach(downloadUrl);
  347. if (fileByte == null || fileByte.length <= 0) {
  348. continue;
  349. }
  350. logInfo("当前处理第"+i+"个");
  351. makeBosAttach(fileByte, currentList.get(i).getAttachName(), String.format("%s_%s",fileName,(i+1)), billId);
  352. }
  353. }
  354. /**
  355. * 构建员工编号
  356. *
  357. * @return
  358. * @throws Exception
  359. */
  360. private String generatePersonNumber(String idCardNo,Context ctx) throws Exception {
  361. SimpleDateFormat sdf = new SimpleDateFormat("yyMMdd");
  362. String defaultNum = String.format("WY%s%s", sdf.format(new Date()), idCardNo.substring(idCardNo.length() - 4));
  363. if (defaultNum.contains("X") || defaultNum.contains("x")) {
  364. defaultNum = defaultNum.toLowerCase().replace("x", "0").toUpperCase();
  365. }
  366. if (checkNumberPersonExist(ctx,defaultNum) <= 0 && checkNumberPersonEnrollEntry(ctx,defaultNum) <= 0) {
  367. return defaultNum;
  368. }
  369. for (int i = 1; i <= 10000; i++) {
  370. defaultNum = String.format("WY%s%04d", sdf.format(new Date()), i);
  371. if (checkNumberPersonExist(ctx,defaultNum) <= 0 && checkNumberPersonEnrollEntry(ctx,defaultNum) <= 0) {
  372. return defaultNum;
  373. }
  374. }
  375. logInfo("生成员工编号时执行超时异常,身份证号:"+idCardNo);
  376. //这里非常容易死锁超时
  377. return generatePersonNumber(ctx);
  378. }
  379. private Integer checkNumberPersonExist(Context ctx, String code) throws Exception{
  380. String sql = "SELECT COUNT(1) AS Num FROM T_BD_Person WHERE Fnumber = '"+code+"'";
  381. IRowSet rowSet = DbUtil.executeQuery(ctx, sql);
  382. if (rowSet.next()) {
  383. return rowSet.getInt("Num");
  384. }
  385. return 1;
  386. }
  387. private Integer checkNumberPersonEnrollEntry(Context ctx, String code) throws Exception{
  388. String sql = "SELECT COUNT(1) AS Num FROM T_HR_EmpEnrollBizBillEntry WHERE FEMPNUMBER = '"+code+"'";
  389. IRowSet rowSet = DbUtil.executeQuery(ctx, sql);
  390. if (rowSet.next()) {
  391. return rowSet.getInt("Num");
  392. }
  393. return 1;
  394. }
  395. /**
  396. * 获取人员ID
  397. *
  398. * @param ctx
  399. * @param userId
  400. * @return
  401. * @throws Exception
  402. */
  403. private String getPersonIdByPMUserId(Context ctx, String userId)
  404. throws Exception {
  405. String sql = "SELECT TOP 1 FPersonID FROM T_PM_User WHERE FID = '"
  406. + userId + "'";
  407. IRowSet rowSet = DbUtil.executeQuery(ctx, sql);
  408. if (rowSet.next()) {
  409. return rowSet.getString("FPersonID");
  410. }
  411. throw new SHRWebException("获取申请人的人员ID失败");
  412. }
  413. /**
  414. * 生成指定bosType的数据ID
  415. *
  416. * @param ctx
  417. * @param bosType
  418. * @return
  419. * @throws Exception
  420. */
  421. private String getNewIdByType(Context ctx, String bosType) throws Exception {
  422. String sql = " SELECT dbo.newbosId('" + bosType + "') AS id";
  423. IRowSet rowSet = DbUtil.executeQuery(ctx, sql);
  424. if (rowSet.next()) {
  425. return rowSet.getString("id");
  426. }
  427. throw new SHRWebException("生成ID失败,bosType:" + bosType);
  428. }
  429. /**
  430. * 根据编码获取指定表的ID
  431. *
  432. * @param tableName
  433. * @param code
  434. * @param ctx
  435. * @return
  436. */
  437. private String getIdByCode(Context ctx, String tableName, String code)
  438. throws Exception {
  439. String sql = "SELECT FID FROM " + tableName + "WHERE Fnumber = '"
  440. + code + "'";
  441. IRowSet rowSet = DbUtil.executeQuery(ctx, sql);
  442. if (rowSet.next()) {
  443. return rowSet.getString("FID");
  444. }
  445. throw new SHRWebException("获取ID失败,tableName:" + tableName + ",code="
  446. + code);
  447. }
  448. /**
  449. * 添加生成员工入职单据
  450. *
  451. * @param ctx
  452. * @param userId
  453. * 当前操作人ID
  454. * @param billInfo
  455. * 移动入职单信息对象
  456. * @param billId
  457. * 入职单ID
  458. * @throws Exception
  459. */
  460. private void insertBill(Context ctx, String userId,
  461. MobileEntryBillInfo billInfo, String billId) throws Exception {
  462. StringBuilder sb = new StringBuilder();
  463. String adminId = getIdByTableName(ctx, " T_ORG_BaseUnit ", billInfo
  464. .getOrganCode());
  465. // 用户UserID要转换成BDPerson的ID
  466. String personId = getPersonIdByPMUserId(ctx, userId);
  467. sb
  468. .append(" INSERT INTO T_HR_EmpEnrollBizBill(")
  469. .append(
  470. "FApplierID,FApplyDate,FAdminOrgUnitId,FHROrgUnitID,FBillState,FApproveType,FNumber,")
  471. .append(
  472. "FBizDate,FCreatorID,FCreateTime,FLastUpdateUserID,FLastUpdateTime,FControlUnitID,FID,")
  473. .append(
  474. "FZDY8,FZDY9,FZDY10,FIsMultiEntry,FInnerState,FuseDefault) VALUES (")
  475. .append("'")
  476. .append(personId)
  477. .append("', GETDATE(), '")
  478. .append(adminId)
  479. .append("','qi8AAABKUC/M567U',0,0,")
  480. // 入职单号
  481. .append("'")
  482. .append(generateBillNumber(ctx))
  483. .append("',GETDATE(),'")
  484. .append(userId)
  485. .append("',GETDATE(),'")
  486. .append(userId)
  487. .append(
  488. "',GETDATE(),'00000000-0000-0000-0000-000000000000CCE7AED4','")
  489. .append(billId).append("',0,0,0,0,0,1);");
  490. logInfo("当前生成入职单sql为:" + sb.toString());
  491. DbUtil.execute(ctx, sb.toString());
  492. }
  493. /**
  494. * 根据编码获取指定表数据的ID
  495. *
  496. * @param ctx
  497. * @param tableName
  498. * @param code
  499. * @return
  500. * @throws Exception
  501. */
  502. private String getIdByTableName(Context ctx, String tableName, String code)
  503. throws Exception {
  504. String sql = " SELECT TOP 1 FID FROM " + tableName
  505. + " WHERE Fnumber = '" + code + "'";
  506. logInfo("根据编码获取指定表数据的sql:"+sql);
  507. IRowSet rowSet = DbUtil.executeQuery(ctx, sql);
  508. if (rowSet.next()) {
  509. return rowSet.getString("FID");
  510. }
  511. return null;
  512. //throw new SHRWebException("获取指定表的ID失败,表名:" + tableName + ",编码:" + code);
  513. }
  514. private String getIdByNameSignTable(Context ctx, String tableName, String name)
  515. throws Exception {
  516. String sql = " SELECT TOP 1 FID FROM " + tableName
  517. + " WHERE FName_L2 = '" + name + "'";
  518. IRowSet rowSet = DbUtil.executeQuery(ctx, sql);
  519. if (rowSet.next()) {
  520. return rowSet.getString("FID");
  521. }
  522. return null;
  523. //throw new SHRWebException("获取指定表的ID失败,表名:" + tableName + ",编码:" + code);
  524. }
  525. /**
  526. * 生成入职单号
  527. *
  528. * @param ctx
  529. * @return
  530. * @throws Exception
  531. */
  532. private String generateBillNumber(Context ctx) throws Exception {
  533. String updateSql = "UPDATE T_BAS_MaxSerial SET FSERIALNUMBER = FSERIALNUMBER+1 WHERE FCODINGRULEENTRYID = 'IjjBiShXTDOgYw8KsQcLISbvRW8='";
  534. DbUtil.execute(ctx, updateSql);
  535. String sql = "SELECT FSERIALNUMBER from T_BAS_MaxSerial where FCODINGRULEENTRYID = 'IjjBiShXTDOgYw8KsQcLISbvRW8='";
  536. BigDecimal num = null;
  537. SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
  538. Integer r = (int)(Math.floor(Math.random()*100));
  539. String numberString = null;
  540. IRowSet rowSet = DbUtil.executeQuery(ctx, sql);
  541. if (rowSet.next()) {
  542. num = rowSet.getBigDecimal("FSERIALNUMBER");
  543. numberString = String.format("%s%02d-%05d", sdf.format(new Date()), r, num
  544. .intValue());
  545. }
  546. int count = 0;
  547. while (checkNumberExist(ctx, numberString, "T_HR_EmpEnrollBizBill")
  548. && count++ < 10) {
  549. logger.debug("入职单编号" + numberString + "重复");
  550. DbUtil.execute(ctx, updateSql);
  551. rowSet = DbUtil.executeQuery(ctx, sql);
  552. if (rowSet.next()) {
  553. r = (int)(Math.floor(Math.random()*100));
  554. num = rowSet.getBigDecimal("FSERIALNUMBER");
  555. numberString = String.format("%s-%05d", sdf.format(new Date()), r, num.intValue());
  556. }
  557. }
  558. if (count < 10) {
  559. return numberString;
  560. }
  561. throw new SHRWebException("生成入职单编号发生异常");
  562. }
  563. /**
  564. * 生成员工编号
  565. *
  566. * @param ctx
  567. * @return
  568. * @throws Exception
  569. */
  570. private String generatePersonNumber(Context ctx) throws Exception {
  571. String updateSql = "UPDATE T_BAS_MaxSerial SET FSERIALNUMBER = FSERIALNUMBER+1 WHERE FCODINGRULEENTRYID = '88c5a232-0101-1000-e001-cd97c0a8100d26EF456F'";
  572. DbUtil.execute(ctx, updateSql);
  573. String sql = "SELECT FSERIALNUMBER from T_BAS_MaxSerial where FCODINGRULEENTRYID = '88c5a232-0101-1000-e001-cd97c0a8100d26EF456F'";
  574. BigDecimal num = null;
  575. String numberString = null;
  576. IRowSet rowSet = DbUtil.executeQuery(ctx, sql);
  577. if (rowSet.next()) {
  578. num = rowSet.getBigDecimal("FSERIALNUMBER");
  579. numberString = String.format("WY%06d", num.intValue());
  580. }
  581. int count = 0;
  582. while (checkNumberExist(ctx, numberString, "T_BD_Person")
  583. && count++ < 10) {
  584. logger.debug("人员编号" + numberString + "重复");
  585. DbUtil.execute(ctx, updateSql);
  586. rowSet = DbUtil.executeQuery(ctx, sql);
  587. if (rowSet.next()) {
  588. num = rowSet.getBigDecimal("FSERIALNUMBER");
  589. numberString = String.format("WY%06d", num.intValue());
  590. }
  591. }
  592. if (count < 10) {
  593. return numberString;
  594. }
  595. throw new SHRWebException("生成人员编号发生异常");
  596. }
  597. /**
  598. * 检查指定编号是否存在指定表中
  599. *
  600. * @param ctx
  601. * @param number
  602. * @param tableName
  603. * @return
  604. * @throws Exception
  605. */
  606. private boolean checkNumberExist(Context ctx, String number,
  607. String tableName) throws Exception {
  608. String sql = "SELECT COUNT(1) AS Num FROM " + tableName
  609. + " WHERE Fnumber = '" + number + "'";
  610. IRowSet rowSet = DbUtil.executeQuery(ctx, sql);
  611. if (rowSet.next()) {
  612. if (rowSet.getInt("Num") > 0) {
  613. return true;
  614. }
  615. }
  616. return false;
  617. }
  618. /**
  619. * 生成入职单分录
  620. *
  621. * @param ctx
  622. * @param userId
  623. * @param billInfo
  624. * @param billId
  625. * @throws Exception
  626. */
  627. private void insertBillEntry(Context ctx, String userId,
  628. MobileEntryBillInfo billInfo, String billId) throws Exception {
  629. StringBuilder sb = new StringBuilder();
  630. try{
  631. sb
  632. .append("INSERT INTO T_HR_EmpEnrollBizBillEntry(FBillID,FBizDate,FAdminOrgID,FPositionID,FEmpTypeID,");
  633. sb
  634. .append("FPersonID,FEmpNumber,FEmpName,FIdCardNo,FGender,FBirthday,FEnrollDate,FEnrollAgain,");
  635. sb.append("FExistPersonID,FUseOldNumber,FResumeID,FSeq,FID,");
  636. sb
  637. .append("FIsParPerson,FReplaceAdminOrgID,FidCardAddress,FOldAdminOrgID,FOldPositionID,FIsPrimary,FOldEmpTypeID,");
  638. sb
  639. .append("FAffairActReasonID,FHrBizDefineID,FVariationReasonID,FTelNum,FMyFolkID, FIdCardEndDate,FIdCardStartDate,FIdCardIssued,");
  640. sb
  641. .append("FEmployerUnitID,FCompanyID,FUseDefault,FHrOrgUnitID,FIdCardLongEffect,FSourceBillType,");
  642. sb
  643. .append("CFSupplierID1, CFLinkName, CFLinkTelNum, CFLinkRelationID, FBankID, FAccountNum, CFEmpEntrySourceID, CFEMPLOYEEPROJECTI) VALUES (");
  644. SimpleDateFormat rSdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
  645. sb.append("'").append(billId).append("',");
  646. // 业务日期\组织ID\岗位ID
  647. String organId = getIdByTableName(ctx, "T_ORG_BaseUnit", billInfo.getOrganCode());
  648. sb.append("'").append(rSdf.format(billInfo.getEntryTime())).append("',");
  649. sb.append("'").append(organId).append("',");
  650. sb.append("'").append(getIdByTableName(ctx, "T_ORG_Position", billInfo.getPositionCode())).append("',");
  651. // 用工关系默认劳动外包
  652. String useTypeId = getIdByTableName(ctx,"T_HR_BDEMPLOYEETYPE", billInfo.getUseEmployeeTypeCode());
  653. logInfo("用工关系"+billInfo.getUseEmployeeTypeCode()+",查询结果:"+useTypeId);
  654. if(useTypeId!=null){
  655. sb.append("'").append(useTypeId).append("',");
  656. }
  657. else{
  658. sb.append("'qi8AAAAHNf2inoWz',");
  659. }
  660. // 获取员工编码和旧关系数据
  661. Map<String, String> checkResult = checkAndGetOldInfo(ctx, billInfo.getIdcardNo());
  662. Boolean isOldPerson = false;
  663. if ("true".equals(checkResult.get("exist"))) {
  664. isOldPerson = true;
  665. sb.append("'").append(checkResult.get("personId")).append("',");
  666. sb.append("'").append(checkResult.get("personCode")).append("',");
  667. } else {
  668. sb.append("null,");
  669. // 构建人员编号
  670. String personCode = generatePersonNumber(billInfo.getIdcardNo(), ctx);
  671. sb.append("'").append(personCode).append("',");
  672. }
  673. // 姓名/身份证/性别/出生日期/入职时间/是否重入职
  674. sb.append("'").append(billInfo.getPersonName()).append("',");
  675. sb.append("'").append(billInfo.getIdcardNo()).append("',");
  676. sb.append(mapToGender(billInfo.getIdcardNo())).append(",");
  677. Date birthDay = transToBirthday(billInfo.getIdcardNo());
  678. if (birthDay != null) {
  679. sb.append("'").append(rSdf.format(birthDay)).append("',");
  680. } else {
  681. sb.append("null,");
  682. }
  683. sb.append("'").append(rSdf.format(billInfo.getEntryTime())).append("',");
  684. String oldEmpType = null;
  685. // 如果是旧人员
  686. if (isOldPerson) {
  687. sb.append("1,").append("'").append(checkResult.get("personId")).append("',1,");
  688. oldEmpType = getOldEmpType(ctx,checkResult.get("personId"));
  689. } else {
  690. sb.append("0,null,0,");
  691. }
  692. //身份证地址
  693. sb.append("null,1,");
  694. // 生成并添加FID
  695. String fid = getNewIdByType(ctx, "04BEFD73");
  696. // 续存组织要替换为公司的ID
  697. String companyID = getCompanyIDByOrganId(ctx, organId);
  698. // FID/续组织织、身份证地址
  699. sb.append("'").append(fid).append("',0,").append("'").append(companyID);
  700. if(billInfo.getIdcardAddress()!=null&&billInfo.getIdcardAddress()!=""){
  701. sb.append("','").append(billInfo.getIdcardAddress()).append("',");
  702. }
  703. else{
  704. sb.append("',null,");
  705. }
  706. // 是否有原组织/原岗位/
  707. if (isOldPerson) {
  708. sb.append("'").append(checkResult.get("organId")).append("','")
  709. .append(checkResult.get("positionId")).append("',");
  710. } else {
  711. sb.append("null,null,");
  712. }
  713. sb.append("0,").append(oldEmpType == null ? "null" : ("'"+oldEmpType+"'")).append(",");
  714. //如果是重入职,则需要变更关系
  715. if(isOldPerson){
  716. sb.append("'1wXho31/Tsi0LhiLKfCQ+JYRae4=','DawAAAApC9TmaL7Z','sKSMJ3pDTQCtVNKkqB5WnOas36w=',");
  717. }else{
  718. //变动类型,默认入职; 变动操作默认雇佣入职; 变动原因默认:其他
  719. sb.append("'1wXho31/Tsi0LhiLKfCQ+JYRae4=','DawAAAApC9DmaL7Z','sKSMJ3pDTQCtVNKkqB5WnOas36w=',");
  720. }
  721. // 手机号码/民族/身份证起止时间/地址
  722. sb.append("'").append(billInfo.getPhoneNum()).append("',");
  723. logInfo("民族"+billInfo.getNationName()+","+billInfo.getNationCode());
  724. if(billInfo.getNationCode()!=null && billInfo.getNationCode() != "" ){
  725. String folkId =getIdByTableName(ctx, "T_BD_HRFolk", billInfo.getNationCode());
  726. logInfo("民族查询ID:"+folkId);
  727. if(folkId!=null){
  728. sb.append("'").append(folkId).append("',");
  729. }
  730. }
  731. else{
  732. sb.append("null,");
  733. }
  734. //身份证结束时间
  735. if(billInfo.getIdCardEndTime()!=null){
  736. sb.append("'").append(rSdf.format(billInfo.getIdCardEndTime())).append("',");
  737. }
  738. else{
  739. sb.append("null,");
  740. }
  741. //身份证开始时间
  742. if(billInfo.getIdCardStartTime()!=null){
  743. sb.append("'").append(rSdf.format(billInfo.getIdCardStartTime())).append("',");
  744. }
  745. else{
  746. sb.append("null,");
  747. }
  748. //签发机关
  749. if(billInfo.getIdCardIssuingAuthority()!=null){
  750. sb.append("'").append(billInfo.getIdCardIssuingAuthority()).append("',");
  751. }
  752. else{
  753. sb.append("null,");
  754. }
  755. // 用工单位/公司
  756. sb.append("'00000000-0000-0000-0000-000000000000CCE7AED4','"+ companyID + "',1,'qi8AAABKUC/M567U',");
  757. // 身份证是否长期
  758. sb.append(idcardIsLong(billInfo.getIdCardEndTime())).append(",100,");
  759. // 自定义字段
  760. // 供应商/联系人/银行卡
  761. String supplierId = getIdByTableName(ctx, "CT_BD_Gys", billInfo.getSupplierCode() ) ;
  762. if(null!= supplierId && "" != supplierId){
  763. sb.append("'").append(supplierId ).append("',");
  764. }
  765. else{
  766. sb.append("null,");
  767. }
  768. //sb.append("null,");
  769. sb.append("'").append(billInfo.getContactName()).append("',");
  770. sb.append("'").append(billInfo.getContactCellNum()).append("',");
  771. sb.append("'").append( getIdByNameSignTable(ctx, "T_HR_BDRelation", billInfo.getContactRelationName())).append("',");
  772. String bankName = getIdByNameSignTable(ctx, "T_HR_PBank", billInfo.getBankName());
  773. if(bankName!=null)
  774. {
  775. sb.append("'").append(bankName).append("',");
  776. }
  777. else{
  778. sb.append("null,");
  779. }
  780. if(billInfo.getBankCardNo()!=null&&billInfo.getBankCardNo()!=""){
  781. sb.append("'").append(billInfo.getBankCardNo()).append("'");
  782. }
  783. else{
  784. sb.append("null");
  785. }
  786. //入职来源ID
  787. logInfo("入职来源"+billInfo.getEntrySource()+","+billInfo.getEntrySourceId());
  788. if(billInfo.getEntrySourceId()!=null && billInfo.getEntrySourceId() != ""){
  789. String sourceId = getIdByTableName(ctx, "CT_MP_EntrySource", billInfo.getEntrySourceId());
  790. logInfo("入职来源查询ID:"+sourceId);
  791. if(sourceId!=null && sourceId != ""){
  792. sb.append(",'").append(sourceId ).append("'");
  793. }
  794. else{
  795. sb.append(",null");
  796. }
  797. }
  798. else{
  799. sb.append(",null");
  800. }
  801. //战图项目
  802. logInfo("入职来源"+billInfo.getProjectCode()+","+billInfo.getProjectName());
  803. if(billInfo.getProjectCode()!=null ){
  804. String projectId = getIdByTableName(ctx, "CT_MP_EmployeeProjectInfo", billInfo.getProjectCode());
  805. logInfo("入职来源查询ID"+projectId);
  806. if(projectId!=null && projectId != ""){
  807. sb.append(",'").append(projectId ).append("'");
  808. }
  809. else{
  810. sb.append(",null");
  811. }
  812. }
  813. }
  814. catch(Exception e){
  815. logInfo("当前生成入职单sql为:" + sb.toString());
  816. e.printStackTrace();
  817. logInfo(""+e.getMessage());
  818. }
  819. // 结束
  820. sb.append(")");
  821. logInfo("当前生成入职单sql为:" + sb.toString());
  822. DbUtil.execute(ctx, sb.toString());
  823. }
  824. //比较身份证是否长期有效
  825. private String idcardIsLong(Date idCardEndTime){
  826. if(idCardEndTime == null){
  827. return "0";
  828. }
  829. SimpleDateFormat rSdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
  830. if(rSdf.format(idCardEndTime).compareTo("2199-12-30")>=0){
  831. return "1";
  832. }
  833. return "0";
  834. }
  835. private String getOldEmpType(Context ctx, String personId) throws Exception{
  836. String sql = "SELECT TOP 1 FLABORRELATIONSTATEID FROM T_HR_EmpLaborRelation WHERE FPERSONID = '"
  837. + personId+ "' AND FEMPLOYEEMODLEID IN('00000000-0000-0000-0000-000000000006A29E85B3','00000000-0000-0000-0000-000000000007A29E85B3') ORDER BY FLEFFDT DESC";
  838. IRowSet rowset = DbUtil.executeQuery(ctx, sql);
  839. String laborreTypeId = null;
  840. if (rowset.next()) {
  841. laborreTypeId = rowset.getString("FLABORRELATIONSTATEID");
  842. }
  843. return laborreTypeId;
  844. }
  845. /**
  846. * 获取员工入职所在的公司ID
  847. *
  848. * @param ctx
  849. * @param organId
  850. * @return
  851. * @throws Exception
  852. */
  853. private String getCompanyIDByOrganId(Context ctx, String organId)
  854. throws Exception {
  855. String sql = "SELECT TOP 1 FLongNumber FROM T_ORG_BaseUnit WHERE FID = '"
  856. + organId + "'";
  857. StringBuilder sb = new StringBuilder();
  858. logInfo(sql);
  859. IRowSet rowset = DbUtil.executeQuery(ctx, sql);
  860. String longNumber = null;
  861. if (rowset.next()) {
  862. longNumber = rowset.getString("FLongNumber");
  863. }
  864. if (null != longNumber) {
  865. String[] longNumbers = longNumber.split("!");
  866. if (longNumbers.length > 0) {
  867. sb.append(" SELECT TOP 1 a.FID AS FID FROM T_ORG_BaseUNit AS a ");
  868. sb.append(" LEFT JOIN T_ORG_OUPartAdmin AS b ON( a.FID = b.FUNITID ) ");
  869. sb.append(" WHERE b.FLAYERTYPEID ='00000000-0000-0000-0000-00000000000262824988' AND a.Fnumber IN( ");
  870. for (int i = 0; i < longNumbers.length; i++) {
  871. if (i > 0) {
  872. sb.append(",");
  873. }
  874. sb.append("'").append(longNumbers[i]).append("'");
  875. }
  876. sb.append(") order by a.FLEVEL DESC ");
  877. rowset = DbUtil.executeQuery(ctx, sb.toString());
  878. if (rowset.next()) {
  879. return rowset.getString("FID");
  880. }
  881. }
  882. }
  883. throw new SHRWebException("获取员工公司ID时发生异常");
  884. }
  885. /**
  886. * 检查是否是再入职人员(如果是,则获取原职位、原用工关系、用所在组织
  887. */
  888. private Map<String, String> checkAndGetOldInfo(Context ctx, String idCardNo)
  889. throws Exception {
  890. logInfo("获取再入职人员信息");
  891. Map<String, String> result = new TreeMap<String, String>();
  892. result.put("exist", "false");
  893. String sql = "SELECT TOP 1 p.FID userId, p.FNumber userCode, p.FName_L2 userName,dep.FID userOrgId, dep.FNumber userOrgCode, pson.FPrimaryPositionID positionId "
  894. + " FROM t_bd_person p "
  895. + " LEFT JOIN T_HR_PersonPosition pson ON pson.FPersonID = p.fid "
  896. + " LEFT JOIN T_ORG_Admin dep ON dep.fid = pson.FPersonDep "
  897. + " LEFT JOIN T_HR_BDEmployeeType empType ON empType.fid = p.FEmployeeTypeID "
  898. + " WHERE p.FIDCardNO = '"
  899. + idCardNo + "' AND empType.FNumber NOT IN ( '001', '002', 'S02', 'S04', 'S06', '035', 'S11', 'S10' ) ORDER BY p.FCreateTime DESC";
  900. logInfo("获取再入职人员信息SQL:"+sql);
  901. IRowSet rowset = DbUtil.executeQuery(ctx, sql);
  902. if (rowset.next()) {
  903. result.put("exist", "true");
  904. result.put("personId", rowset.getString("userId"));
  905. result.put("organId", rowset.getString("userOrgId"));
  906. result.put("positionId", rowset.getString("positionId"));
  907. // 人员编码
  908. result.put("personCode", rowset.getString("userCode"));
  909. }
  910. //logInfo("返回结果:"+JSON.toJSONString(result));
  911. return result;
  912. }
  913. /**
  914. * 从身份证解析性别:1男2女
  915. *
  916. * @param idcardNo
  917. * @return
  918. */
  919. private Integer mapToGender(String idcardNo) {
  920. if (Integer.parseInt(idcardNo.substring(16, 17)) % 2 == 0) {
  921. return 2;
  922. }
  923. return 1;
  924. }
  925. /**
  926. * 提取出生日期
  927. */
  928. private Date transToBirthday(String idcardNo) {
  929. SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
  930. try {
  931. return sdf.parse(idcardNo.substring(6, 14));
  932. } catch (Exception e) {
  933. return null;
  934. }
  935. }
  936. // /**
  937. // * 保存附件到本地,并返回本地路径
  938. // * @param signedUrl
  939. // */
  940. // private String saveToLocalFile(String signedUrl){
  941. //
  942. // try {
  943. // // 示例URL,你可以替换为任何有效的图片URL
  944. // URL url = new URL(signedUrl);
  945. // InputStream in = url.openStream(); // 获取输入流
  946. //
  947. // String filePath = "/path/to/your/directory/image.jpg"; // 指定本地文件路径
  948. // OutputStream out = new FileOutputStream(filePath); // 创建输出流
  949. //
  950. // // 缓冲区,提高读写效率
  951. // byte[] buffer = new byte[4096];
  952. // int bytesRead;
  953. //
  954. // // 读取输入流,并写入输出流
  955. // while ((bytesRead = in.read(buffer)) != -1) {
  956. // out.write(buffer, 0, bytesRead);
  957. // }
  958. //
  959. // // 关闭流
  960. // out.close();
  961. // in.close();
  962. // System.out.println("保存文件附件失败:"+signedUrl);
  963. // } catch (Exception e) {
  964. // e.printStackTrace();
  965. // }
  966. //
  967. // }
  968. /**
  969. * 转换成SHR中的BOS和attach
  970. *
  971. * @param signedUrl
  972. * @throws Exception
  973. */
  974. private byte[] downloadAliyunAttach(String signedUrl) throws Exception {
  975. CloseableHttpResponse response = null;
  976. CloseableHttpClient client = null;
  977. byte[] data = null;
  978. try {
  979. client = HttpClients.createDefault();
  980. HttpGet get = new HttpGet(signedUrl.toString());
  981. response = client.execute(get);
  982. if (200 != response.getStatusLine().getStatusCode()) {
  983. throw new SHRWebException("下载附件失败");
  984. }
  985. HttpEntity entity = response.getEntity();
  986. data = EntityUtils.toByteArray(entity);
  987. client.close();
  988. } catch (IOException e) {
  989. logger.error(e.getMessage(), e);
  990. } finally {
  991. if (client != null) {
  992. client.close();
  993. }
  994. }
  995. return data;
  996. }
  997. /**
  998. *
  999. * @param request
  1000. * @param multipartFile
  1001. * @return
  1002. * @throws Exception
  1003. * @throws BOSException
  1004. * @throws EASBizException
  1005. * @throws IOException
  1006. * @throws ShrWebBizException
  1007. */
  1008. private void makeBosAttach(byte[] data, String originalName, String signName, String billId )
  1009. throws Exception {
  1010. logInfo("makeBosAttach初始化,原文件:"+originalName+"指定文件名:"+signName);
  1011. IAttachment attachment = AttachmentFactory.getRemoteInstance();
  1012. IBoAttchAsso attchAsso = BoAttchAssoFactory.getRemoteInstance();
  1013. Context ctx = SHRContext.getInstance().getContext();
  1014. String boID = getNewIdByType(ctx, "172F3A47");
  1015. String propertyName = "null0";
  1016. String onlyone = "false";
  1017. String description = "附件";
  1018. String uipk = "com.kingdee.eas.hr.affair.app.EmpEnrollBizBill.form";
  1019. String userId = HRFilterUtils.getCurrentUserId(SHRContext.getInstance()
  1020. .getContext());
  1021. SHRAttachmentExtInfo attchExt = new SHRAttachmentExtInfo();
  1022. if (Boolean.valueOf(onlyone).booleanValue()) {
  1023. FilterInfo filterInfo = new FilterInfo();
  1024. filterInfo.getFilterItems().add(
  1025. new FilterItemInfo("bunding", new StringBuilder().append(
  1026. userId).append('#').append(uipk).toString()));
  1027. filterInfo.getFilterItems().add(
  1028. new FilterItemInfo("propertyName", propertyName));
  1029. EntityViewInfo entityViewInfo = new EntityViewInfo();
  1030. if (!(StringUtils.isEmpty(boID))) {
  1031. filterInfo.getFilterItems().add(
  1032. new FilterItemInfo("boID", boID));
  1033. } else {
  1034. filterInfo.getFilterItems().add(
  1035. new FilterItemInfo("state", Integer.valueOf(20)));
  1036. }
  1037. entityViewInfo.setFilter(filterInfo);
  1038. ISHRAttachmentExt SHRAttchExt = SHRAttachmentExtFactory
  1039. .getRemoteInstance();
  1040. SHRAttachmentExtCollection collection = SHRAttchExt
  1041. .getSHRAttachmentExtCollection(entityViewInfo);
  1042. SHRAttchExt.delete(filterInfo);
  1043. for (int i = 0; i < collection.size(); ++i) {
  1044. String attId = collection.get(i).getAttachment().getId()
  1045. .toString();
  1046. if (!(StringUtils.isEmpty(boID))) {
  1047. attchAsso.delete(MessageFormat.format(
  1048. " where attachment = ''{0}''",
  1049. new Object[] { attId }));
  1050. } else {
  1051. attachment.delete(new ObjectUuidPK(attId));
  1052. }
  1053. }
  1054. }
  1055. String fullname = originalName;
  1056. fullname = checkScriptAttack(fullname);
  1057. //如果无格式
  1058. if(fullname.lastIndexOf(46)<=-1){
  1059. fullname = fullname +".jpg";
  1060. }
  1061. String mainname = fullname.substring(0, fullname.lastIndexOf(46));
  1062. String extname = fullname.substring(fullname.lastIndexOf(46) + 1,
  1063. fullname.length());
  1064. extname = extname.toLowerCase();
  1065. AttachmentInfo ai = new AttachmentInfo();
  1066. ai.setName(signName);
  1067. ai.setSimpleName(extname);
  1068. ai.setDescription(description);
  1069. ai.setFile(data);
  1070. ai.setIsShared(false);
  1071. ai.setSharedDesc("否");
  1072. int size = (int) data.length;
  1073. if (size < 1024)
  1074. ai
  1075. .setSize(new StringBuilder().append(size).append("字节")
  1076. .toString());
  1077. else {
  1078. ai.setSize(new StringBuilder().append(size / 1024).append("KB")
  1079. .toString());
  1080. }
  1081. ai.setSizeInByte(size);
  1082. ai.setAttachID(new StringBuilder().append("").append(
  1083. System.currentTimeMillis()).toString());
  1084. ai.setType(getFileType(fullname));
  1085. attchExt.setAttachment(ai);
  1086. attchExt.setName(fullname);
  1087. attchExt.setPropertyName(propertyName);
  1088. if (propertyName.startsWith("null"))
  1089. attchExt.setType(AttachmentTypeEnum.FORM);
  1090. else {
  1091. attchExt.setType(AttachmentTypeEnum.PROPERTY);
  1092. }
  1093. attchExt.setState(AttachmentState.UNSAVE);
  1094. attchExt.setBunding(new StringBuilder().append(userId).append('#')
  1095. .append(uipk).toString());
  1096. attchExt.setBoID(boID);
  1097. try {
  1098. attachment.addnew(ai);
  1099. } catch (Exception e) {
  1100. logInfo("生成附件时发生异常:"+e.getMessage());
  1101. logger.error(e.getMessage(), e);
  1102. throw new ShrWebBizException(
  1103. "附件上传失败,请您从以下几项检查(如问题还未解决请导出日志提单解决):\n1、数据库空间不足;\n2、磁盘空间不足;\n3、存放附件服务器异常,请检查服务器的网络或配置是否正常。",
  1104. e);
  1105. }
  1106. //生成中间关联表
  1107. buildBosAttach(ctx, billId, ai.getId().toString());
  1108. }
  1109. /**
  1110. * 生成附件中间关联表
  1111. * @param ctx
  1112. * @param billId
  1113. * @param attachId
  1114. * @throws Exception
  1115. */
  1116. private void buildBosAttach(Context ctx, String billId, String attachId ) throws Exception{
  1117. String bosId = getNewIdByType(ctx, "172F3A47");
  1118. String busObjectType = "F4AF4F03";
  1119. StringBuilder sb = new StringBuilder();
  1120. sb.append(" INSERT INTO T_BAS_BOATTCHASSO(FID,FBoID,FAssoType_L2, FAttachmentID, FAssoBusObjType ) VALUES ( ");
  1121. sb.append(" '").append(bosId).append("',");
  1122. sb.append("'").append(billId).append("','Added Accessories',");
  1123. sb.append("'").append(attachId).append("','B41CAA3F')");
  1124. logInfo("生成附件中间表sql:"+sb.toString());
  1125. DbUtil.execute(ctx, sb.toString());
  1126. }
  1127. private String checkScriptAttack(String str) {
  1128. if (!(StringUtils.isEmpty(str))) {
  1129. if (str.contains("<")) {
  1130. str.replaceAll("<", "&lt;");
  1131. }
  1132. if (str.contains(">")) {
  1133. str.replaceAll(">", "&gt;");
  1134. }
  1135. }
  1136. return str;
  1137. }
  1138. private String getFileType(String fullname) {
  1139. String extname = fullname.substring(fullname.lastIndexOf(46) + 1,
  1140. fullname.length());
  1141. if (("doc".equalsIgnoreCase(extname))
  1142. || ("docx".equalsIgnoreCase(extname)))
  1143. return "Microsoft Word 文档";
  1144. if (("xls".equalsIgnoreCase(extname))
  1145. || ("xlsx".equalsIgnoreCase(extname))
  1146. || ("xlsm".equalsIgnoreCase(extname))
  1147. || ("xlsb".equalsIgnoreCase(extname)))
  1148. return "Microsoft Excel 表格";
  1149. if (("ppt".equalsIgnoreCase(extname))
  1150. || ("pptx".equalsIgnoreCase(extname))
  1151. || ("pptm".equalsIgnoreCase(extname)))
  1152. return "Microsoft PowerPoint 幻灯片";
  1153. if ("txt".equalsIgnoreCase(extname)) {
  1154. return "TEXT 文本文件";
  1155. }
  1156. return new StringBuilder().append("未知文件类型(.").append(extname).append(
  1157. ")").toString();
  1158. }
  1159. }