// // Source code recreated from a .class file by IntelliJ IDEA // (powered by FernFlower decompiler) // package kd.imc.rim.common.service; import com.alibaba.fastjson.JSON; import com.alibaba.fastjson.JSONArray; import com.alibaba.fastjson.JSONObject; import java.io.ByteArrayInputStream; import java.io.IOException; import java.io.InputStream; import java.nio.charset.StandardCharsets; import java.util.Date; import java.util.Iterator; import java.util.Map; import java.util.Objects; import java.util.concurrent.Future; import kd.bos.context.RequestContext; import kd.bos.dataentity.entity.DynamicObject; import kd.bos.dataentity.resource.ResManager; import kd.bos.dataentity.utils.ObjectUtils; import kd.bos.db.tx.TX; import kd.bos.db.tx.TXHandle; import kd.bos.dlock.DLock; import kd.bos.fileservice.FileServiceFactory; import kd.bos.logging.Log; import kd.bos.logging.LogFactory; import kd.bos.orm.query.QFilter; import kd.bos.servicehelper.BusinessDataServiceHelper; import kd.bos.servicehelper.QueryServiceHelper; import kd.bos.servicehelper.operation.SaveServiceHelper; import kd.bos.threads.ThreadPool; import kd.bos.threads.ThreadPools; import kd.bos.util.StringUtils; import kd.imc.rim.common.constant.InputInvoiceTypeEnum; import kd.imc.rim.common.constant.ResultContant; import kd.imc.rim.common.constant.XbrlTypeConstant; import kd.imc.rim.common.helper.ElectAccVoucherHelper; import kd.imc.rim.common.helper.RecognitionCheckHelper; import kd.imc.rim.common.invoice.collector.InvoiceCollectService; import kd.imc.rim.common.invoice.recognition.listener.IRecognitionListener; import kd.imc.rim.common.invoice.recognition.listener.RecognitionListenerResult; import kd.imc.rim.common.invoice.recognitionnew.task.FileUploadAndSignTask; import kd.imc.rim.common.invoice.save.InvoiceSaveService; import kd.imc.rim.common.message.exception.MsgException; import kd.imc.rim.common.utils.*; import kd.imc.rim.common.utils.extract.ZipExtractUtil; import kd.imc.rim.file.utils.FileConvertUtils; import kd.imc.rim.common.utils.FileUtilsEx; public class ElectAccVoucherServiceEx { private static Log logger = LogFactory.getLog(ElectAccVoucherService.class); private static final String awsRecognitionImpl = "kd.imc.rim.common.invoice.recognitionnew.impl.AwsRecognitionService"; private static ThreadPool xbrlUploadThreadPool = ThreadPools.newFixedThreadPool("xbrlUploadThreadPool", 10); private ElectAccVoucherHelper electAccVoucherHelper = new ElectAccVoucherHelper(); public ElectAccVoucherServiceEx() { } public JSONObject dealVoucher(String fileUrl, String fileName, Object orgId, JSONObject businessParam, IRecognitionListener recognitionListener) throws IOException { JSONObject result = new JSONObject(); boolean isVoucherOrg = checkOrg(orgId); if (!isVoucherOrg) { result.put("errcode", "0004"); result.put("description", ResManager.loadKDString("非电子会计凭证试点企业", "ElectAccVoucherService_0", "imc-rim-common", new Object[0])); return result; } else if (!StringUtils.isEmpty(fileUrl) && !StringUtils.isEmpty(fileName)) { logger.info("电子会计凭证解析开始:{}", fileName); return this.extracted(fileUrl, fileName, orgId, businessParam, recognitionListener); } else { return result; } } private JSONObject extracted(String fileUrl, String fileName, Object orgId, JSONObject businessParam, IRecognitionListener recognitionListener) throws IOException { JSONObject result = new JSONObject(); Map configMap = ImcConfigUtil.getValue("rim_recog_check"); String recognitionImplStr = (String)configMap.get("rimpl"); boolean isAwsRecognition = StringUtils.isEmpty(recognitionImplStr) || "kd.imc.rim.common.invoice.recognitionnew.impl.AwsRecognitionService".equals(recognitionImplStr); RecognitionCheckHelper recognitionCheckHelper = new RecognitionCheckHelper(); FormFileEntity fileEntity = recognitionCheckHelper.getFormFileEntity(fileUrl, fileName); try { InputStream fileInputStream = FileServiceFactory.getAttachmentFileService().getInputStream(fileEntity.getFileUrl()); Throwable var13 = null; try { byte[] fileByte = FileUtilsEx.getByte(fileInputStream); String fileType = FileUtilsEx.getFileType(fileName); Future xbrlUploadSubmit = null; if (!"zip".equalsIgnoreCase(fileType)) { xbrlUploadSubmit = xbrlUploadThreadPool.submit(new FileUploadAndSignTask(fileEntity.getFileUrl(), fileByte, fileEntity.getFileName(), fileEntity.getFileType(), fileEntity.getFileHash(), fileEntity.getSignatureFlag(), RequestContext.get())); } JSONObject checkZipFileResult = this.checkZipFile(fileByte, fileType); if (Objects.nonNull(checkZipFileResult)) { JSONObject var66 = checkZipFileResult; return var66; } else { long startTime = System.currentTimeMillis(); JSONObject var67; if (isAwsRecognition) { result = this.electAccVoucherHelper.getByAwsAPI(orgId, fileByte, fileName); } else { result = this.electAccVoucherHelper.getByAnalysis(fileType, fileByte); boolean signPassFlag = result.getBoolean("signPassFlag"); if (!signPassFlag) { result.put("errcode", "0004"); result.put("description", ResManager.loadKDString("电子会计凭证验签不通过", "ElectAccVoucherService_1", "imc-rim-common", new Object[0])); var67 = result; return var67; } } if (!"0000".equals(result.getString("errcode"))) { var67 = result; return var67; } else { String xbrlInfo = result.getString("xbrlInfo"); JSONObject resultInvoice = this.electAccVoucherHelper.toInvoiceJson(xbrlInfo, orgId); if (resultInvoice == null) { result.put("errcode", "0005"); result.put("description", ResManager.loadKDString("电子会计凭证转换失败", "ElectAccVoucherService_2", "imc-rim-common", new Object[0])); JSONObject var68 = result; return var68; } else { String voucherFileUrl = getVoucherFileUrl(fileType, fileByte, xbrlInfo); if (resultInvoice.containsKey("isUploadOriginal") && !resultInvoice.getBoolean("isUploadOriginal") && xbrlUploadSubmit != null) { uploadGet(xbrlUploadSubmit, resultInvoice); } if (resultInvoice.containsKey("isUploadOriginal") && resultInvoice.getBoolean("isUploadOriginal")) { resultInvoice.put("originalState", "1"); } else if (!"zip".equalsIgnoreCase(fileType)) { resultInvoice.put("originalState", "1"); resultInvoice.put("originalTime", new Date()); } else { resultInvoice.put("originalState", "0"); } String serialNo = resultInvoice.getString("serialNo"); if (StringUtils.isEmpty(serialNo)) { serialNo = UUID.randomUUID(); resultInvoice.put("serialNo", serialNo); } if ("zip".equalsIgnoreCase(fileType)) { resultInvoice.put("isZipFile", Boolean.TRUE); } resultInvoice.put("fileType", FileUtilsEx.convertFileTypeNum(fileType)); resultInvoice.put("fileName", fileName); TXHandle h = TX.required(); Throwable var26 = null; try { String errorMsg; try { String xbrlType = resultInvoice.getString("xbrlType"); errorMsg = resultInvoice.getString("invoiceDate"); Long invoiceType = resultInvoice.getLong("invoiceType"); String xbrlName = this.getTargetName(serialNo, xbrlType, invoiceType, errorMsg); if (xbrlName == null) { xbrlName = fileName; } saveVoucher(serialNo, xbrlName, voucherFileUrl, xbrlType); resultInvoice = this.saveInvoice(businessParam, resultInvoice, fileUrl, fileByte); } catch (Throwable var60) { logger.info("保存电子会计凭证出错:{}", var60); h.markRollback(); errorMsg = ResManager.loadKDString("电子会计凭证保存异常或者发票数据保存异常,请联系管理员", "ElectAccVoucherService_9", "imc-rim-common", new Object[0]); if (var60 instanceof MsgException) { errorMsg = ((MsgException)var60).getErrorMsg(); } resultInvoice.put("errorMsg", errorMsg); if (businessParam != null && "1".equals(businessParam.getString("throwSaveError"))) { throw var60; } } } catch (Throwable var61) { var26 = var61; throw var61; } finally { if (h != null) { if (var26 != null) { try { h.close(); } catch (Throwable var59) { var26.addSuppressed(var59); } } else { h.close(); } } } if (resultInvoice.get("mainId") != null) { DynamicObject invoiceObject = BusinessDataServiceHelper.loadSingle(resultInvoice.get("mainId"), "rim_invoice"); String invoiceType = resultInvoice.getString("invoiceType"); InvoiceSaveService service = InvoiceSaveService.newInstance(invoiceType); if (service != null) { service.setMainInvoiceInfo(invoiceObject); SaveServiceHelper.save(new DynamicObject[]{invoiceObject}); } } RecognitionCheckService.setInvoiceSeq(resultInvoice, businessParam, 0, 0); result.put("errcode", "0000"); result.put("description", ResManager.loadKDString("操作成功", "ElectAccVoucherService_8", "imc-rim-common", new Object[0])); JSONArray resultArray = new JSONArray(); resultInvoice.put("fileType", FileUtilsEx.convertFileTypeNum(FileUtils.getFileType(fileName))); resultArray.add(resultInvoice); result.put("data", resultArray); RecognitionListenerResult listener = new RecognitionListenerResult(fileUrl, fileName, 1, 1, resultArray); if (recognitionListener != null) { recognitionListener.handle(listener); } logger.info("电子会计凭证总耗时:{}", System.currentTimeMillis() - startTime); return result; } } } } catch (Throwable var63) { var13 = var63; throw var63; } finally { if (fileInputStream != null) { if (var13 != null) { try { fileInputStream.close(); } catch (Throwable var58) { var13.addSuppressed(var58); } } else { fileInputStream.close(); } } } } catch (Throwable var65) { logger.info("解析电子会计凭证出错:{}", var65); result.put("errcode", "0002"); result.put("description", ResManager.loadKDString("解析电子会计凭证出错", "ElectAccVoucherService_4", "imc-rim-common", new Object[0])); return result; } } private String getTargetName(String serialNo, String xbrlType, Long invoiceType, String invoiceDate) { String prefix = ""; if (StringUtils.isNotEmpty(invoiceDate)) { invoiceDate = invoiceDate.replaceAll("-", ""); } if (XbrlTypeConstant.AIR_ELE.getCode().equals(xbrlType)) { prefix = "atr_issuer_"; } else if (XbrlTypeConstant.BANK_RECEIPT.getCode().equals(xbrlType)) { prefix = "bker_issuer_"; } else if (XbrlTypeConstant.BANK_STATEMENT.getCode().equals(xbrlType)) { prefix = "bkrs_issuer_"; } else if (XbrlTypeConstant.FINANCIAL.getCode().equals(xbrlType)) { prefix = "efi_issuer_"; } else if (XbrlTypeConstant.TRAIN_ELE.getCode().equals(xbrlType)) { prefix = "rai_issuer_"; } else if (XbrlTypeConstant.COVERINGWARRANT.getCode().equals(xbrlType)) { prefix = "ntrev_gpm_issuer_"; } else if (XbrlTypeConstant.E_VAT.getCode().equals(xbrlType)) { if (InputInvoiceTypeEnum.ORDINARY_ELECTRON.getCode().equals(invoiceType)) { prefix = "inv_ord_issuer_"; } else { prefix = "inv_spcl_issuer_"; } } return StringUtils.isEmpty(prefix) ? null : prefix + invoiceDate + '_' + serialNo + ".xml"; } private JSONObject checkZipFile(byte[] fileByte, String fileType) { if ("zip".equalsIgnoreCase(fileType)) { int fileLimit = 2; Map zipFileMap = ZipExtractUtil.extractFileForXml(fileByte); if (zipFileMap.isEmpty()) { return ResultContant.createJSONObject("0002", ResManager.loadKDString("解析zip压缩包为空", "ElectAccVoucherService_5", "imc-rim-common", new Object[0])); } if (zipFileMap.size() != fileLimit) { return ResultContant.createJSONObject("0003", String.format(ResManager.loadKDString("解析zip压缩包只包含%1$s个文件", "ElectAccVoucherService_6", "imc-rim-common", new Object[0]), zipFileMap.size())); } Iterator var5 = zipFileMap.entrySet().iterator(); while(var5.hasNext()) { Map.Entry map = (Map.Entry)var5.next(); String key = (String)map.getKey(); boolean checkFileType = FileUtils.checkFileType(key, new String[]{"xml", "sign"}); if (!checkFileType) { return ResultContant.createJSONObject("0003", ResManager.loadKDString("解析zip压缩包只能包含xml/sign文件", "ElectAccVoucherService_7", "imc-rim-common", new Object[0])); } } } return null; } private JSONObject saveInvoice(JSONObject businessParam, JSONObject resultInvoice, String fileUrl, byte[] fileByte) { Long tax_org = null; if (null != businessParam) { resultInvoice.putAll(businessParam); tax_org = businessParam.getLong("tax_org"); } if (!ObjectUtils.isEmpty(tax_org)) { resultInvoice.put("tax_org", tax_org); } InvoiceCollectService invoiceCollectService = new InvoiceCollectService(); String fileHash = FileConvertUtils.getSHA256(fileByte); if (StringUtils.isEmpty(resultInvoice.getString("serialNo"))) { resultInvoice.put("serialNo", UUID.randomUUID()); } DLock lock = DLock.create(resultInvoice.getString("invoiceNo") + "saveVoucher", "saveVoucherLock"); Throwable var9 = null; try { if (lock.tryLock(10000L)) { if (!resultInvoice.containsKey("checkStatus")) { resultInvoice.put("checkStatus", "1"); } resultInvoice = invoiceCollectService.saveInvoice(resultInvoice, fileUrl, fileHash); CacheHelper.put(resultInvoice.getString("invoiceNo") + "saveVoucher", resultInvoice.toJSONString(), 10000); } else { JSONObject cacheObject = JSON.parseObject(CacheHelper.get(resultInvoice.getString("invoiceNo") + "saveVoucher")); if (cacheObject != null) { resultInvoice = cacheObject; CacheHelper.remove(cacheObject.getString("invoiceNo") + "saveVoucher"); } } } catch (Throwable var18) { var9 = var18; throw var18; } finally { if (lock != null) { if (var9 != null) { try { lock.close(); } catch (Throwable var17) { var9.addSuppressed(var17); } } else { lock.close(); } } } return resultInvoice; } public static boolean checkOrg(Object orgId) { boolean isVoucherOrg = false; try { if (orgId != null) { DynamicObject orgObject = BusinessDataServiceHelper.loadSingle(orgId, "bdm_org"); if (orgObject != null && "1".equals(orgObject.get("epinfo.isvoucher"))) { isVoucherOrg = true; } } } catch (Throwable var3) { logger.info("获取企业电子会计凭证开关出错:{}", var3); isVoucherOrg = false; } return isVoucherOrg; } private static String getVoucherFileUrl(String fileType, byte[] fileByte, String xbrlInfo) throws IOException { String fileUploadUrl; if ("zip".equalsIgnoreCase(fileType)) { fileUploadUrl = FileConvertUtils.upload(fileByte, fileType); } else { ByteArrayInputStream xbrlStream = new ByteArrayInputStream(xbrlInfo.getBytes(StandardCharsets.UTF_8)); Throwable var5 = null; try { fileUploadUrl = FileConvertUtils.upload(FileUtils.getByte(xbrlStream), "xml"); } catch (Throwable var14) { var5 = var14; throw var14; } finally { if (xbrlStream != null) { if (var5 != null) { try { xbrlStream.close(); } catch (Throwable var13) { var5.addSuppressed(var13); } } else { xbrlStream.close(); } } } } return fileUploadUrl; } private static void uploadGet(Future xbrlUploadSubmit, JSONObject resultInvoice) { try { JSONObject result = (JSONObject)xbrlUploadSubmit.get(); if (result != null) { resultInvoice.put("imageUrl", result.getString("imageUrl")); resultInvoice.put("ofdUrl", result.getString("ofdUrl")); resultInvoice.put("pdfUrl", result.getString("pdfUrl")); resultInvoice.put("snapshotUrl", result.getString("imageUrl")); } } catch (Exception var3) { logger.info("电子会计凭证文件上传出错:{}", var3); } } public static void saveVoucher(String serialNo, String xbrlName, String fileUploadUrl, String xbrlType) { DynamicObject voucherObject = QueryServiceHelper.queryOne("rim_invoice_voucher", "id, serial_no, xbrl_name, xbrl_url, xbrl_type, receive_xbrl_url, receive_xbrl_name, create_time, update_time", new QFilter[]{new QFilter("serial_no", "=", serialNo)}); if (voucherObject == null) { voucherObject = BusinessDataServiceHelper.newDynamicObject("rim_invoice_voucher"); voucherObject.set("serial_no", serialNo); voucherObject.set("xbrl_name", xbrlName); voucherObject.set("xbrl_url", fileUploadUrl); voucherObject.set("xbrl_type", xbrlType); voucherObject.set("receive_xbrl_url", ""); voucherObject.set("receive_xbrl_name", ""); voucherObject.set("create_time", new Date()); voucherObject.set("update_time", new Date()); } else { voucherObject = BusinessDataServiceHelper.loadSingle(voucherObject.get("id"), "rim_invoice_voucher"); voucherObject.set("xbrl_name", xbrlName); voucherObject.set("xbrl_url", fileUploadUrl); voucherObject.set("xbrl_type", xbrlType); voucherObject.set("update_time", new Date()); } SaveServiceHelper.save(new DynamicObject[]{voucherObject}); } }