徐昊 8 сар өмнө
parent
commit
ed90f3f9c5

+ 1 - 1
src/main/java/kd/imc/rim/common/helper/RecognitionCheckHelperEx.java

@@ -737,7 +737,7 @@ public class RecognitionCheckHelperEx {
 
     }
 
-    public JSONArray bindAttachInvoice(JSONArray targetArray, JSONObject businessParam) {
+    public JSONArray bindAttachInvoice(JSONArray targetArray, JSONObject businessParam, Map<String, Long> invoiceTypeMap) {
         JSONArray attachArray = new JSONArray();
         if (targetArray.size() == 0) {
             return attachArray;

+ 185 - 30
src/main/java/kd/imc/rim/common/invoice/recognition/impl/RecognitionCheckTaskEx.java

@@ -8,28 +8,36 @@ package kd.imc.rim.common.invoice.recognition.impl;
 import com.alibaba.fastjson.JSON;
 import com.alibaba.fastjson.JSONArray;
 import com.alibaba.fastjson.JSONObject;
+import java.util.ArrayList;
+import java.util.Iterator;
+import java.util.List;
 import java.util.Map;
 import java.util.concurrent.Callable;
 import kd.bos.context.RequestContext;
+import kd.bos.dataentity.entity.DynamicObject;
+import kd.bos.dataentity.entity.DynamicObjectCollection;
+import kd.bos.dataentity.resource.ResManager;
 import kd.bos.dataentity.utils.StringUtils;
 import kd.bos.dlock.DLock;
 import kd.bos.logging.Log;
 import kd.bos.logging.LogFactory;
+import kd.bos.orm.query.QFilter;
 import kd.bos.orm.util.CollectionUtils;
+import kd.bos.servicehelper.BusinessDataServiceHelper;
+import kd.bos.servicehelper.operation.SaveServiceHelper;
+import kd.imc.rim.common.constant.InputInvoiceTypeEnum;
 import kd.imc.rim.common.constant.ResultContant;
 import kd.imc.rim.common.invoice.fpzs.FpzsMainService;
 import kd.imc.rim.common.invoice.recognition.listener.IRecognitionListener;
-import kd.imc.rim.common.service.EInvoiceZipXmlDealService;
-import kd.imc.rim.common.service.ElectAccVoucherService;
-import kd.imc.rim.common.service.ExcelInvoiceUploadService;
-import kd.imc.rim.common.service.RecognitionCheckServiceEx;
+import kd.imc.rim.common.service.*;
+import kd.imc.rim.common.utils.BigDecimalUtil;
 import kd.imc.rim.common.utils.CacheHelper;
 import kd.imc.rim.common.utils.FileUtils;
 import kd.imc.rim.common.utils.MD5;
 import org.apache.commons.lang3.tuple.Pair;
 
 public class RecognitionCheckTaskEx implements Callable<JSONObject> {
-    private static Log logger = LogFactory.getLog(RecognitionCheckTaskEx.class);
+    private static Log logger = LogFactory.getLog(RecognitionCheckTask.class);
     private static int cache_time_out = 1800;
     private JSONObject businessParam;
     private Map<String, Object> customParam;
@@ -41,6 +49,23 @@ public class RecognitionCheckTaskEx implements Callable<JSONObject> {
     public static final String waiting = "waiting";
     public static final String success = "success";
     public static final String fail = "fail";
+    protected static final List<String> telGoodNames = new ArrayList<String>(12) {
+        private static final long serialVersionUID = 2608083843312492007L;
+
+        {
+            this.add("电信服务");
+            this.add("基础电信服务");
+            this.add("语音通话服务");
+            this.add("出租或出售网络元素");
+            this.add("增值电信服务");
+            this.add("短信和彩信服务");
+            this.add("电子数据和信息的传输及应用服务");
+            this.add("互联网接入服务");
+            this.add("广播电视信号传输服务");
+            this.add("卫星电视信号落地转接服务");
+            this.add("其他增值电信服务");
+        }
+    };
 
     public RecognitionCheckTaskEx(RequestContext ctx, String source, String pageId, JSONObject businessParam, Map<String, Object> customParam, String url, String fileName) {
         saveCacheFile(pageId, url, "waiting");
@@ -54,7 +79,7 @@ public class RecognitionCheckTaskEx implements Callable<JSONObject> {
     }
 
     public JSONObject call() throws Exception {
-        logger.info("begin RecognitionCheckTaskEx :{},{}", this.url, this.fileName);
+        logger.info("begin RecognitionCheckTask :{},{}", this.url, this.fileName);
 
         try {
             RequestContext.copyAndSet(this.ctx);
@@ -63,21 +88,33 @@ public class RecognitionCheckTaskEx implements Callable<JSONObject> {
             } else {
                 JSONObject invoiceResult = new JSONObject();
                 Long orgId = RequestContext.get().getOrgId();
+                long rim_user;
                 if (this.customParam != null) {
                     try {
-                        orgId = (Long)this.customParam.get("orgId");
+                        rim_user = BigDecimalUtil.transDecimal(this.customParam.get("orgId")).longValue();
+                        if (rim_user > 0L) {
+                            orgId = rim_user;
+                        }
                     } catch (Exception var12) {
                     }
                 }
 
-                boolean isZipXmlEI = FileUtils.checkFileType(this.fileName, new String[]{"zip", "xml"});
-                if (isZipXmlEI) {
-                    invoiceResult = EInvoiceZipXmlDealService.analysisAndCheckSave(this.url, this.fileName, orgId, this.businessParam, (IRecognitionListener)null);
+                if (this.businessParam != null) {
+                    rim_user = BigDecimalUtil.transDecimal(this.businessParam.get("rim_user")).longValue();
+                    if (rim_user < 1L) {
+                        this.businessParam.put("rim_user", RequestContext.get().getCurrUserId());
+                    }
                 }
 
-                boolean isNeedDeal = FileUtils.checkFileType(this.fileName, new String[]{"zip", "ofd", "xml"});
-                if (isNeedDeal && !"0000".equals(invoiceResult.getString("errcode"))) {
-                    invoiceResult = ElectAccVoucherService.dealVoucher(this.url, this.fileName, orgId, this.businessParam, (IRecognitionListener)null);
+                boolean isNeedDeal = FileUtils.checkFileType(this.fileName, new String[]{"zip", "ofd", "pdf"});
+                if (isNeedDeal) {
+                    ElectAccVoucherServiceEx electAccVoucherService = new ElectAccVoucherServiceEx();
+                    invoiceResult = electAccVoucherService.dealVoucher(this.url, this.fileName, orgId, this.businessParam, (IRecognitionListener)null);
+                }
+
+                boolean isZipXmlEI = FileUtils.checkFileType(this.fileName, new String[]{"zip", "xml"});
+                if (isZipXmlEI && !"0000".equals(invoiceResult.getString("errcode"))) {
+                    invoiceResult = EInvoiceZipXmlDealService.analysisAndCheckSave(this.url, this.fileName, orgId, this.businessParam, (IRecognitionListener)null);
                 }
 
                 String xbrlErrCode = invoiceResult.getString("errcode");
@@ -87,14 +124,15 @@ public class RecognitionCheckTaskEx implements Callable<JSONObject> {
                     if (FileUtils.isExcel(this.fileName)) {
                         invoiceResult = ExcelInvoiceUploadService.getInstance().uploadExcelInvoice(this.url, this.fileName, (IRecognitionListener)null, this.businessParam);
                     } else {
-                        logger.info("RecognitionCheckTaskEx识别url:{}{}", this.fileName, this.url);
+                        logger.info("RecognitionCheckTask识别url:{}{}", this.fileName, this.url);
                         invoiceResult = RecognitionCheckServiceEx.getInstance().recognitionCheckInvoice(this.url, this.fileName, (IRecognitionListener)null, this.businessParam);
                     }
                 }
 
-                logger.info("发票助手本地上传最终数据返回:" + invoiceResult);
+                logger.info("发票助手本地上传最终数据返回:{}-{}", this.pageId, invoiceResult);
                 if (ResultContant.isSuccess(invoiceResult)) {
                     JSONArray invoiceArray = invoiceResult.getJSONArray("data");
+                    classOfInvoice(invoiceArray);
                     JSONArray failInvoiceArray = invoiceResult.getJSONArray("failData");
                     JSONArray attachArray = invoiceResult.getJSONArray("attach");
                     if (!CollectionUtils.isEmpty(failInvoiceArray)) {
@@ -124,13 +162,128 @@ public class RecognitionCheckTaskEx implements Callable<JSONObject> {
                 return invoiceResult;
             }
         } catch (Throwable var13) {
-            logger.info("RecognitionCheckTaskEx throwable:{}", var13);
+            logger.info("RecognitionCheckTask throwable:{}", var13);
             saveCacheFile(this.pageId, this.url, "fail");
-            saveCacheCause(this.pageId, this.url, "fail", "程序错误");
+            saveCacheCause(this.pageId, this.url, "fail", ResManager.loadKDString("程序错误", "RecognitionCheckTask_0", "imc-rim-common", new Object[0]));
             return new JSONObject();
         }
     }
 
+    public static void classOfInvoice(JSONArray invoiceArray) {
+        if (invoiceArray != null) {
+            for(int i = 0; i < invoiceArray.size(); ++i) {
+                JSONObject invoice = invoiceArray.getJSONObject(i);
+                Long invoiceType = invoice.getLong("invoiceType");
+                if (InputInvoiceTypeEnum.needClassOfInvoice(invoiceType)) {
+                    boolean telFlag = telType(invoice);
+                    boolean childFlag = childType(invoice);
+                    if (telFlag && childFlag) {
+                        setInvoiceClass(invoice, "11", "9");
+                    } else if (telFlag) {
+                        setInvoiceClass(invoice, "9");
+                    } else if (childFlag) {
+                        setInvoiceClass(invoice, "11");
+                    }
+                }
+            }
+
+        }
+    }
+
+    private static boolean childType(JSONObject invoice) {
+        boolean flag = false;
+        Long invoiceType = invoice.getLong("invoiceType");
+        if (InputInvoiceTypeEnum.FINANCIAL_INVOICE.getCode().equals(invoiceType)) {
+            String invoicingPartyName = invoice.getString("invoicingPartyName");
+            if (StringUtils.isNotEmpty(invoicingPartyName) && invoicingPartyName.contains("幼儿园")) {
+                flag = true;
+            }
+        } else if (InputInvoiceTypeEnum.ORDINARY_ELECTRON.getCode().equals(invoiceType) || InputInvoiceTypeEnum.ORDINARY_PAPER.getCode().equals(invoiceType) || InputInvoiceTypeEnum.GENERAL_ELECTRON.getCode().equals(invoiceType) || InputInvoiceTypeEnum.ELECTRIC_ORDINARY.getCode().equals(invoiceType)) {
+            JSONArray items = invoice.getJSONArray("items");
+            if (items == null) {
+                return false;
+            }
+
+            for(int i = 0; i < items.size(); ++i) {
+                JSONObject item = items.getJSONObject(i);
+                String goodName = item.getString("goodsName");
+                if (StringUtils.isNotEmpty(goodName) && goodName.contains("保教费")) {
+                    flag = true;
+                    break;
+                }
+            }
+        }
+
+        return flag;
+    }
+
+    private static boolean telType(JSONObject invoice) {
+        Long invoiceType = invoice.getLong("invoiceType");
+        boolean telFlag = false;
+        if (InputInvoiceTypeEnum.ORDINARY_ELECTRON.getCode().equals(invoiceType) || InputInvoiceTypeEnum.SPECIAL_ELECTRON.getCode().equals(invoiceType) || InputInvoiceTypeEnum.ORDINARY_PAPER.getCode().equals(invoiceType) || InputInvoiceTypeEnum.SPECIAL_PAPER.getCode().equals(invoiceType) || InputInvoiceTypeEnum.TOLL_ELECTRON.getCode().equals(invoiceType) || InputInvoiceTypeEnum.ELECTRIC_ORDINARY.getCode().equals(invoiceType) || InputInvoiceTypeEnum.ELECTRIC_SPECIAL.getCode().equals(invoiceType) || InputInvoiceTypeEnum.GENERAL_ELECTRON.getCode().equals(invoiceType)) {
+            JSONArray items = invoice.getJSONArray("items");
+            if (items == null) {
+                return false;
+            }
+
+            boolean flag = false;
+
+            for(int i = 0; i < items.size(); ++i) {
+                JSONObject item = items.getJSONObject(i);
+                String goodName = item.getString("goodsName");
+                Iterator var8 = telGoodNames.iterator();
+
+                while(var8.hasNext()) {
+                    String s = (String)var8.next();
+                    if (goodName.contains(s)) {
+                        telFlag = true;
+                        flag = true;
+                        break;
+                    }
+                }
+
+                if (flag) {
+                    break;
+                }
+            }
+        }
+
+        return telFlag;
+    }
+
+    private static void setInvoiceClass(JSONObject invoice, String... classType) {
+        Long mainId = invoice.getLong("mainId");
+        DynamicObject invoices = BusinessDataServiceHelper.loadSingle("rim_invoice", "id, mul_class, ext_info", new QFilter[]{new QFilter("id", "=", mainId)});
+        if (invoices != null) {
+            String mulClassStr = String.join(",", classType);
+            String extInfo = invoices.getString("ext_info");
+            JSONObject extObject = new JSONObject();
+            if (StringUtils.isNotEmpty(extInfo)) {
+                try {
+                    extObject = JSONObject.parseObject(extInfo);
+                } catch (Exception var13) {
+                    extObject = new JSONObject();
+                }
+            }
+
+            extObject.put("sys_mulclass", mulClassStr);
+            invoices.set("ext_info", extObject.toString());
+            DynamicObjectCollection mul_class = invoices.getDynamicObjectCollection("mul_class");
+            if (CollectionUtils.isEmpty(mul_class)) {
+                String[] var8 = classType;
+                int var9 = classType.length;
+
+                for(int var10 = 0; var10 < var9; ++var10) {
+                    String typeStr = var8[var10];
+                    DynamicObject classInfo = mul_class.addNew();
+                    classInfo.set("fbasedataid_id", typeStr);
+                    SaveServiceHelper.save(new DynamicObject[]{invoices});
+                }
+            }
+        }
+
+    }
+
     public JSONObject getBusinessParam() {
         return this.businessParam;
     }
@@ -187,7 +340,7 @@ public class RecognitionCheckTaskEx implements Callable<JSONObject> {
             return null;
         } else {
             String cacheKey = "scaner_cause_" + pageId;
-            DLock lock = DLock.create("lock_" + cacheKey, "刷新卡片锁");
+            DLock lock = DLock.create("lock_" + cacheKey, ResManager.loadKDString("刷新卡片锁", "RecognitionCheckTask_1", "imc-rim-common", new Object[0]));
             Throwable var6 = null;
 
             JSONObject var10;
@@ -203,7 +356,6 @@ public class RecognitionCheckTaskEx implements Callable<JSONObject> {
                 } while(!lock.tryLock(100L));
 
 
-
                 try {
                     String cache;
                     if ("remove".equals(operate)) {
@@ -262,7 +414,7 @@ public class RecognitionCheckTaskEx implements Callable<JSONObject> {
             return null;
         } else {
             String cacheKey = "scaner_" + pageId;
-            DLock lock = DLock.create("lock_" + cacheKey, "刷新卡片锁");
+            DLock lock = DLock.create("lock_" + cacheKey, ResManager.loadKDString("刷新卡片锁", "RecognitionCheckTask_1", "imc-rim-common", new Object[0]));
             Throwable var5 = null;
 
             try {
@@ -271,6 +423,8 @@ public class RecognitionCheckTaskEx implements Callable<JSONObject> {
                 while(times < 10) {
                     ++times;
                     if (lock.tryLock(100L)) {
+                        long starttime = System.currentTimeMillis();
+
 
                         try {
                             String cache;
@@ -288,10 +442,10 @@ public class RecognitionCheckTaskEx implements Callable<JSONObject> {
                                 obj = JSON.parseObject(cache);
                             }
 
-                            JSONObject var9;
+                            JSONObject var11;
                             if ("query".equals(operate)) {
-                                var9 = obj;
-                                return var9;
+                                var11 = obj;
+                                return var11;
                             }
 
                             if (StringUtils.isNotEmpty(url) && StringUtils.isNotEmpty(operate)) {
@@ -299,23 +453,24 @@ public class RecognitionCheckTaskEx implements Callable<JSONObject> {
                                 CacheHelper.put(cacheKey, obj.toJSONString(), cache_time_out);
                             }
 
-                            var9 = obj;
-                            return var9;
+                            var11 = obj;
+                            return var11;
                         } finally {
+                            logger.info("cacheFile总耗时:{}-{}", pageId, System.currentTimeMillis() - starttime);
                             lock.unlock();
                         }
                     }
                 }
-            } catch (Throwable var28) {
-                var5 = var28;
-                throw var28;
+            } catch (Throwable var30) {
+                var5 = var30;
+                throw var30;
             } finally {
                 if (lock != null) {
                     if (var5 != null) {
                         try {
                             lock.close();
-                        } catch (Throwable var26) {
-                            var5.addSuppressed(var26);
+                        } catch (Throwable var28) {
+                            var5.addSuppressed(var28);
                         }
                     } else {
                         lock.close();

+ 453 - 0
src/main/java/kd/imc/rim/common/service/ElectAccVoucherServiceEx.java

@@ -0,0 +1,453 @@
+//
+// 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<String, String> 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<JSONObject> 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<String, String> 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<String, String> 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<JSONObject> 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});
+    }
+}

+ 125 - 70
src/main/java/kd/imc/rim/common/service/RecognitionCheckServiceEx.java

@@ -1,10 +1,33 @@
+//
+// 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 com.google.common.collect.Maps;
+import java.io.IOException;
+import java.io.InputStream;
+import java.text.DecimalFormat;
+import java.text.SimpleDateFormat;
+import java.util.ArrayList;
+import java.util.Date;
+import java.util.HashMap;
+import java.util.HashSet;
+import java.util.Iterator;
+import java.util.List;
+import java.util.Map;
+import java.util.Set;
+import java.util.concurrent.ExecutionException;
+import java.util.concurrent.Future;
+import java.util.concurrent.TimeUnit;
+import java.util.concurrent.TimeoutException;
+import java.util.stream.Collectors;
 import kd.bos.context.RequestContext;
+import kd.bos.dataentity.resource.ResManager;
 import kd.bos.dataentity.utils.ObjectUtils;
 import kd.bos.dataentity.utils.StringUtils;
 import kd.bos.fileservice.FileServiceFactory;
@@ -15,7 +38,7 @@ import kd.bos.threads.ThreadPools;
 import kd.imc.rim.common.constant.CheckContant;
 import kd.imc.rim.common.constant.InputInvoiceTypeEnum;
 import kd.imc.rim.common.constant.InvoiceUploadErrorType;
-
+import kd.imc.rim.common.helper.RecognitionCheckHelper;
 import kd.imc.rim.common.helper.RecognitionCheckHelperEx;
 import kd.imc.rim.common.invoice.collector.InvoiceCollectService;
 import kd.imc.rim.common.invoice.model.ConvertFieldUtil;
@@ -26,25 +49,14 @@ 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.itextpdf.UrlServiceUtils;
-import kd.imc.rim.file.model.FileConvertResult;
+import kd.imc.rim.file.utils.FileConvertUtils;
 import org.apache.commons.collections.CollectionUtils;
 import org.apache.commons.compress.utils.Lists;
 
-import java.io.IOException;
-import java.io.InputStream;
-import java.text.DecimalFormat;
-import java.text.SimpleDateFormat;
-import java.util.*;
-import java.util.concurrent.ExecutionException;
-import java.util.concurrent.Future;
-import java.util.concurrent.TimeUnit;
-import java.util.concurrent.TimeoutException;
-import java.util.stream.Collectors;
-
 public class RecognitionCheckServiceEx {
     private static RecognitionCheckServiceEx instance = null;
-    private static Log logger = LogFactory.getLog(RecognitionCheckServiceEx.class);
-    private RecognitionCheckHelperEx recognitionCheckHelper = new RecognitionCheckHelperEx();
+    private static Log logger = LogFactory.getLog(RecognitionCheckService.class);
+    private RecognitionCheckHelperEx RecognitionCheckHelperEx = new RecognitionCheckHelperEx();
     private InvoiceCollectService invoiceCollectService = new InvoiceCollectService();
     private static Integer recheckorginPage = 999123413;
     private static ThreadPool uploadThreadPool = ThreadPools.newFixedThreadPool("recognitionUploadThread_2", Runtime.getRuntime().availableProcessors() + 1);
@@ -53,8 +65,8 @@ public class RecognitionCheckServiceEx {
     }
 
     public static RecognitionCheckServiceEx getInstance() {
-        Class var0 = RecognitionCheckServiceEx.class;
-        synchronized(RecognitionCheckServiceEx.class) {
+        Class var0 = RecognitionCheckService.class;
+        synchronized(RecognitionCheckService.class) {
             if (instance == null) {
                 instance = new RecognitionCheckServiceEx();
             }
@@ -65,6 +77,7 @@ public class RecognitionCheckServiceEx {
 
     public JSONObject recognitionCheckInvoice(String fileUrl, String fileName, IRecognitionListener recognitionListener, JSONObject businessParam) {
         logger.info("识别查验fileName:{},businessParam:{}", fileName, businessParam);
+        fileName = kd.imc.rim.common.utils.FileUtilsEx.truncateFileName(fileName, 50);
         this.markDeleteByVerifySave(businessParam);
         boolean isCheck = this.getCheckFlag(businessParam);
         return this.extracted_new(fileUrl, fileName, recognitionListener, businessParam, isCheck);
@@ -89,14 +102,14 @@ public class RecognitionCheckServiceEx {
         JSONArray attachResult;
         try {
             long fileStartTime = System.currentTimeMillis();
-            FormFileEntity fileEntity = this.recognitionCheckHelper.getFormFileEntity(fileUrl, fileName);
+            FormFileEntity fileEntity = this.RecognitionCheckHelperEx.getFormFileEntity(fileUrl, fileName);
             if (!fileEntity.getSuccess()) {
                 this.handle(recognitionListener, listener);
                 return InvoiceUploadErrorType.getSplitErrorResult();
             }
 
             int totalPage = CollectionUtils.isEmpty(fileEntity.getSubFileList()) ? 1 : fileEntity.getSubFileList().size();
-            Map<String, Object> extMap = this.recognitionCheckHelper.getRecognitionCheckExtMap(businessParam);
+            Map<String, Object> extMap = this.RecognitionCheckHelperEx.getRecognitionCheckExtMap(businessParam);
             String originalStateDefault = fileEntity.getOriginalStateDefault();
             if ("1".equals(originalStateDefault)) {
                 extMap.put("originalStateDefault", originalStateDefault);
@@ -104,13 +117,13 @@ public class RecognitionCheckServiceEx {
 
             String fileType = fileEntity.getFileType();
             Map<Integer, Object> subFileFutureMap = this.syncUploadSubFile(fileEntity);
-            logger.info("RecognitionCheckServiceEx 文件解析耗时:{}", System.currentTimeMillis() - fileStartTime);
+            logger.info("RecognitionCheckService 文件解析耗时:{}", System.currentTimeMillis() - fileStartTime);
 
             List recognitionResultList;
             try {
                 long recognitionStartTime = System.currentTimeMillis();
-                recognitionResultList = this.recognitionCheckHelper.recognitionInvoiceFile(fileEntity, extMap);
-                logger.info("RecognitionCheckServiceEx 识别总耗时:{}", System.currentTimeMillis() - recognitionStartTime);
+                recognitionResultList = this.RecognitionCheckHelperEx.recognitionInvoiceFile(fileEntity, extMap);
+                logger.info("RecognitionCheckService 识别总耗时:{}", System.currentTimeMillis() - recognitionStartTime);
                 this.checkOriginal(fileEntity, subFileFutureMap, recognitionResultList);
                 finalResult = JSONObject.parseArray(JSONObject.toJSONString(recognitionResultList));
             } catch (Throwable var26) {
@@ -122,14 +135,12 @@ public class RecognitionCheckServiceEx {
                 logger.info("识别程序错误:", var26);
                 return InvoiceUploadErrorType.getRecognitionErrorResult();
             }
-            //改了的地方
-            isCheck=false;
 
             if (isCheck && recognitionResultList.size() > 0) {
                 try {
                     long checkStartTime = System.currentTimeMillis();
-                    List<JSONObject> checkResultList = this.recognitionCheckHelper.checkInvoiceByRecognitionInfo(recognitionResultList, extMap);
-                    logger.info("RecognitionCheckServiceEx 查验总耗时:{}", System.currentTimeMillis() - checkStartTime);
+                    List<JSONObject> checkResultList = this.RecognitionCheckHelperEx.checkInvoiceByRecognitionInfo(recognitionResultList, extMap);
+                    logger.info("RecognitionCheckService 查验总耗时:{}", System.currentTimeMillis() - checkStartTime);
                     finalResult = JSONObject.parseArray(JSONObject.toJSONString(checkResultList));
                 } catch (Throwable var25) {
                     this.handle(recognitionListener, listener);
@@ -143,6 +154,7 @@ public class RecognitionCheckServiceEx {
             fileBaseInfo.put("fileUrl", fileUrl);
             fileBaseInfo.put("fileName", fileName);
             fileBaseInfo.put("size", fileEntity.getFileSize());
+            fileBaseInfo.put("fileHash", fileEntity.getFileHash());
             finalResult = this.putFileInfo(fileBaseInfo, finalResult, subFileFutureMap, originalStateDefault);
             attachResult = this.dealSaleList(finalResult, businessParam);
             boolean isHandleAttach = attachResult.size() > 0 && finalResult.size() == 0;
@@ -153,6 +165,7 @@ public class RecognitionCheckServiceEx {
 
             try {
                 if (fileBaseInfo.get("totalPage") == null) {
+                    totalPage = this.getTotalPage(finalResult, attachResult);
                     fileBaseInfo.put("totalPage", totalPage);
                 }
 
@@ -163,24 +176,24 @@ public class RecognitionCheckServiceEx {
                 logger.info("发票保存错误:", var24);
             }
         } catch (IOException var27) {
-            logger.info("RecognitionCheckServiceEx IOException :{}", var27);
+            logger.info("RecognitionCheckService IOException :{}", var27);
             this.handle(recognitionListener, listener);
             return InvoiceUploadErrorType.getSplitErrorResult();
         } catch (MsgException var28) {
-            logger.info("RecognitionCheckServiceEx MsgException :{}", var28);
+            logger.info("RecognitionCheckService MsgException :{}", var28);
             this.handle(recognitionListener, listener);
             JSONObject errorInfo = new JSONObject();
             errorInfo.put("errcode", var28.getErrorCode());
             errorInfo.put("description", var28.getMessage());
             return errorInfo;
         } catch (Throwable var29) {
-            logger.info("RecognitionCheckServiceEx BaseErrorResult Throwable:{}", var29);
+            logger.info("RecognitionCheckService BaseErrorResult Throwable:{}", var29);
             this.handle(recognitionListener, listener);
             return InvoiceUploadErrorType.getBaseErrorResult();
         }
 
         boolean resultFlag = finalResult.size() != 0 || attachResult.size() != 0;
-        logger.info("RecognitionCheckServiceEx 识别查验入库总耗时:{}", System.currentTimeMillis() - startTime);
+        logger.info("RecognitionCheckService 识别查验入库总耗时:{}", System.currentTimeMillis() - startTime);
         if (resultFlag) {
             return InvoiceUploadErrorType.getSuccessResult(finalResult, attachResult);
         } else {
@@ -206,17 +219,12 @@ public class RecognitionCheckServiceEx {
 
             for(i = 1; i < recognitionResultList.size(); ++i) {
                 JSONObject invoice = (JSONObject)recognitionResultList.get(i);
-                Long invoiceType1 = invoice.getLong("invoiceType");
-                if (InputInvoiceTypeEnum.OTHER_INVOICE.getCode().equals(invoiceType1)) {
-                    String title = invoice.getString("title");
-                    boolean saleTitle = !StringUtils.isEmpty(title) && title.indexOf("清单") > 0;
-                    if (!saleTitle) {
-                        return;
-                    }
+                if (!RecognitionCheckHelper.isSalePage(invoice)) {
+                    return;
                 }
             }
 
-            FileUploadAndSignTask task = new FileUploadAndSignTask(fileEntity.getFileUrl(), (byte[])null, "pdf", true, RequestContext.get());
+            FileUploadAndSignTask task = new FileUploadAndSignTask(fileEntity.getFileUrl(), (byte[])null, fileEntity.getFileName(), "pdf", fileEntity.getFileHash(), true, RequestContext.get());
             task.setSignOnly(true);
             Future<JSONObject> subUploadFuture = uploadThreadPool.submit(task);
             subFileFutureMap.put(recheckorginPage, subUploadFuture);
@@ -224,6 +232,24 @@ public class RecognitionCheckServiceEx {
 
     }
 
+    private int getTotalPage(JSONArray finalResult, JSONArray attachArray) {
+        Set<Integer> pageNumSet = new HashSet(8);
+        int i;
+        if (finalResult != null && !finalResult.isEmpty()) {
+            for(i = 0; i < finalResult.size(); ++i) {
+                pageNumSet.add(finalResult.getJSONObject(i).getInteger("pageNo"));
+            }
+        }
+
+        if (attachArray != null && !attachArray.isEmpty()) {
+            for(i = 0; i < attachArray.size(); ++i) {
+                pageNumSet.add(attachArray.getJSONObject(i).getInteger("pageNo"));
+            }
+        }
+
+        return pageNumSet.size();
+    }
+
     private void handleAttach(JSONArray attachResult, IRecognitionListener recognitionListener, String fileUrl, String fileName, int totalPage) {
         if (attachResult != null && attachResult.size() != 0) {
             if (recognitionListener != null) {
@@ -250,14 +276,15 @@ public class RecognitionCheckServiceEx {
         if (finalResult.size() == 0) {
             return new JSONArray();
         } else {
-            JSONArray targetArray = this.recognitionCheckHelper.getTargetArray(finalResult);
-            finalResult.removeAll(targetArray);
             Map<String, String> configMap = ImcConfigUtil.getValue("rim_recog_check");
             String isDealSaleList = (String)configMap.get("is_dealsalelist");
             if ("0".equals(isDealSaleList)) {
                 return new JSONArray();
             } else {
-                JSONArray attachArray = this.recognitionCheckHelper.bindAttachInvoice(targetArray, businessParam);
+                JSONArray targetArray = this.RecognitionCheckHelperEx.getTargetArray(finalResult);
+                finalResult.removeAll(targetArray);
+                Map<String, Long> invoiceTypeMap = this.getInvoiceTypeMapAndRemoveFinancialDetail(finalResult);
+                JSONArray attachArray = this.RecognitionCheckHelperEx.bindAttachInvoice(targetArray, businessParam, invoiceTypeMap);
                 List<String> finishList = Lists.newArrayList();
                 if (attachArray.size() > 0) {
                     for(int i = 0; i < attachArray.size(); ++i) {
@@ -269,7 +296,7 @@ public class RecognitionCheckServiceEx {
                             StringBuilder attachNo = new StringBuilder();
                             attachNo.append(invoiceCode).append('_').append(invoiceNo);
                             if (!finishList.contains(attachNo.toString())) {
-                                JSONObject numObject = this.recognitionCheckHelper.calcSaleListComplete(invoiceCode, invoiceNo, attachNo.toString());
+                                JSONObject numObject = this.RecognitionCheckHelperEx.calcSaleListComplete(invoiceCode, invoiceNo, attachNo.toString());
                                 int salelistSum = numObject.getInteger("salelistSum");
                                 if (salelistSum == 0) {
                                     salelistSum = attachInfo.getInteger("page_sum");
@@ -288,6 +315,40 @@ public class RecognitionCheckServiceEx {
         }
     }
 
+    private Map<String, Long> getInvoiceTypeMapAndRemoveFinancialDetail(JSONArray finalResult) {
+        Map<String, Long> invoiceTypeMap = new HashMap(8);
+        boolean notFINANCIAL = false;
+
+        for(int i = 0; i < finalResult.size(); ++i) {
+            JSONObject invoiceInfo = finalResult.getJSONObject(i);
+            Long invoiceType = invoiceInfo.getLong("invoiceType");
+            if (!InputInvoiceTypeEnum.OTHER_INVOICE.getCode().equals(invoiceType)) {
+                invoiceTypeMap.put(StringUtils.trimToEmpty(invoiceInfo.getString("invoiceCode")) + StringUtils.trimToEmpty(invoiceInfo.getString("invoiceNo")), invoiceType);
+            } else if (!InputInvoiceTypeEnum.FINANCIAL_INVOICE.getCode().equals(invoiceType) && !InputInvoiceTypeEnum.OTHER_INVOICE.getCode().equals(invoiceType)) {
+                notFINANCIAL = true;
+            }
+        }
+
+        if (invoiceTypeMap.size() > 0 && !notFINANCIAL) {
+            List<JSONObject> list = new ArrayList(8);
+
+            for(int i = 0; i < finalResult.size(); ++i) {
+                JSONObject invoiceInfo = finalResult.getJSONObject(i);
+                Long invoiceType = invoiceInfo.getLong("invoiceType");
+                String title = invoiceInfo.getString("title");
+                if (!RecognitionCheckHelper.isSalePage(invoiceInfo) && InputInvoiceTypeEnum.OTHER_INVOICE.getCode().equals(invoiceType) && StringUtils.isNotEmpty(title) && title.indexOf("明细") > 0) {
+                    list.add(invoiceInfo);
+                }
+            }
+
+            if (!list.isEmpty()) {
+                finalResult.removeAll(list);
+            }
+        }
+
+        return invoiceTypeMap;
+    }
+
     public void handle(IRecognitionListener recognitionListener, RecognitionListenerResult listener) {
         if (recognitionListener != null) {
             recognitionListener.handle(listener);
@@ -331,7 +392,9 @@ public class RecognitionCheckServiceEx {
 
         for(int i = 0; i < finalResult.size(); ++i) {
             JSONObject invoiceInfo = (JSONObject)finalResult.get(i);
+            Long invoiceType = invoiceInfo.getLong("invoiceType");
             invoiceInfo.put("fileName", fileBaseInfo.get("fileName"));
+            invoiceInfo.put("fileHash", fileBaseInfo.get("fileHash"));
             int pageNo = (Integer)invoiceInfo.get("pageNo");
             Object feature = subFileFutureMap.get(pageNo);
             if (feature != null) {
@@ -344,17 +407,17 @@ public class RecognitionCheckServiceEx {
                     }
                 }
 
-                String path;
                 if (fileReuslt != null) {
-                    path = fileReuslt.getString("isOriginal");
+                    String isOriginal = fileReuslt.getString("isOriginal");
                     if (!"1".equals(invoiceInfo.getString("originalState"))) {
-                        if ("true".equals(path)) {
+                        if ("true".equals(isOriginal)) {
                             invoiceInfo.put("originalState", "1");
                         } else {
                             invoiceInfo.put("originalState", "0");
                         }
                     }
 
+                    invoiceInfo.put("subFileName", fileReuslt.getString("subFileName"));
                     invoiceInfo.put("snapshotUrl", fileReuslt.getString("snapshotUrl"));
                     invoiceInfo.put("imageUrl", fileReuslt.getString("imageUrl"));
                     invoiceInfo.put("ofdUrl", fileReuslt.getString("ofdUrl"));
@@ -374,32 +437,12 @@ public class RecognitionCheckServiceEx {
                     }
 
                     invoiceInfo.put("synConvert", fileReuslt.getString("synConvert"));
-                } else if (!StringUtils.isEmpty(updateFileUrl)) {
-                    path = FileUploadUtils.getSnapshotPathByUploadUrl(updateFileUrl);
-                    String imageUrl = path + ".jpg";
-                    if ("pdf".equals(updateFileType)) {
-                        invoiceInfo.put("pdfUrl", updateFileUrl);
-                        invoiceInfo.put("snapshotUrl", imageUrl);
-                        invoiceInfo.put("imageUrl", imageUrl);
-                        invoiceInfo.put("synConvert", true);
-                        invoiceInfo.put("fileType", "1");
-                        FileUploadAndSignTask.saveFileAws(new FileConvertResult(), updateFileUrl, "1");
-                    } else if ("ofd".equals(updateFileType)) {
-                        invoiceInfo.put("ofdUrl", updateFileUrl);
-                        invoiceInfo.put("pdfUrl", path + ".pdf");
-                        invoiceInfo.put("snapshotUrl", imageUrl);
-                        invoiceInfo.put("imageUrl", imageUrl);
-                        invoiceInfo.put("synConvert", true);
-                        invoiceInfo.put("fileType", "4");
-                        FileUploadAndSignTask.saveFileAws(new FileConvertResult(), updateFileUrl, "4");
-                    } else {
-                        invoiceInfo.put("snapshotUrl", updateFileUrl);
-                        invoiceInfo.put("imageUrl", updateFileUrl);
-                    }
+                } else {
+                    invoiceInfo.put("synConvert", true);
                 }
 
                 logger.info("获取文件处理结果等待时长{},{}", System.currentTimeMillis() - start, fileReuslt);
-                if (returnFirst) {
+                if (returnFirst && !InputInvoiceTypeEnum.HGJKS.getCode().equals(invoiceType)) {
                     JSONArray finalResult2 = new JSONArray();
                     invoiceInfo.put("originalState", "1");
                     finalResult2.add(invoiceInfo);
@@ -465,6 +508,7 @@ public class RecognitionCheckServiceEx {
             result.put("fileType", "2");
             result.put("imageUrl", fileFile.getFileUrl());
             result.put("snapshotUrl", fileFile.getFileUrl());
+            result.put("subFileName", fileFile.getFileName());
             return result;
         } else {
             try {
@@ -473,7 +517,11 @@ public class RecognitionCheckServiceEx {
 
                 try {
                     byte[] streamByte = FileUtils.getByte(fileInputStream);
-                    subUploadFuture = uploadThreadPool.submit(new FileUploadAndSignTask(fileFile.getFileUrl(), streamByte, fileFile.getFileType(), fileFile.getSignatureFlag(), context));
+                    if (StringUtils.isEmpty(fileFile.getFileHash())) {
+                        fileFile.setFileHash(FileConvertUtils.getSHA256(streamByte));
+                    }
+
+                    subUploadFuture = uploadThreadPool.submit(new FileUploadAndSignTask(fileFile.getFileUrl(), streamByte, fileFile.getFileName(), fileFile.getFileType(), fileFile.getFileHash(), fileFile.getSignatureFlag(), context));
                 } catch (Throwable var16) {
                     var6 = var16;
                     throw var16;
@@ -573,6 +621,12 @@ public class RecognitionCheckServiceEx {
 
                         this.invoiceCollectService.saveInvoice(invoiceInfo, fileUrl, fileHash);
                     } catch (Exception var28) {
+                        String errorMsg = ResManager.loadKDString("发票数据保存异常,请联系管理员", "RecognitionCheckService_0", "imc-rim-common", new Object[0]);
+                        if (var28 instanceof MsgException) {
+                            errorMsg = ((MsgException)var28).getErrorMsg();
+                        }
+
+                        invoiceInfo.put("errorMsg", errorMsg);
                         mayErrorResult.add(invoiceInfo);
                     }
 
@@ -580,7 +634,7 @@ public class RecognitionCheckServiceEx {
                     Map<String, String> configMap = ImcConfigUtil.getValue("rim_recog_check");
                     String isDealSaleList = (String)configMap.get("is_dealsalelist");
                     if ("1".equals(isSaleListInvoice) && !"0".equals(isDealSaleList)) {
-                        this.recognitionCheckHelper.dealInvoiceAttachRelation(invoiceInfo);
+                        this.RecognitionCheckHelperEx.dealInvoiceAttachRelation(invoiceInfo);
                     }
 
                     logger.info("发票助手本地上传保存发票后的数据:" + invoiceInfo);
@@ -659,6 +713,7 @@ public class RecognitionCheckServiceEx {
         if (businessParam != null) {
             isCheck = !"1".equals(businessParam.getString("notCheck"));
         }
+
         if (!isCheck) {
             businessParam.put("errcode", "4999");
             businessParam.put("description", CheckContant.getCheckResultDesc("4999"));

+ 867 - 0
src/main/java/kd/imc/rim/common/utils/FileUtilsEx.java

@@ -0,0 +1,867 @@
+//
+// Source code recreated from a .class file by IntelliJ IDEA
+// (powered by FernFlower decompiler)
+//
+
+package kd.imc.rim.common.utils;
+
+import com.alibaba.fastjson.JSON;
+import com.alibaba.fastjson.JSONObject;
+import java.io.ByteArrayInputStream;
+import java.io.ByteArrayOutputStream;
+import java.io.File;
+import java.io.IOException;
+import java.io.InputStream;
+import java.net.MalformedURLException;
+import java.net.URL;
+import java.security.MessageDigest;
+import java.sql.ResultSet;
+import java.util.Date;
+import kd.bos.cache.CacheFactory;
+import kd.bos.dataentity.entity.DynamicObject;
+import kd.bos.db.DB;
+import kd.bos.db.DBRoute;
+import kd.bos.db.ResultSetHandler;
+import kd.bos.fileservice.FileService;
+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 org.apache.commons.codec.binary.Base64;
+import org.apache.commons.codec.binary.Hex;
+import org.apache.commons.io.FilenameUtils;
+import org.apache.commons.lang.StringUtils;
+import org.apache.commons.lang3.tuple.Pair;
+import org.apache.http.Header;
+import org.apache.http.HttpEntity;
+import org.apache.http.client.ClientProtocolException;
+import org.apache.http.client.HttpClient;
+import org.apache.http.client.methods.CloseableHttpResponse;
+import org.apache.http.client.methods.HttpGet;
+import org.apache.http.impl.client.CloseableHttpClient;
+
+public class FileUtilsEx {
+    private static Log logger = LogFactory.getLog(HttpUtil.class);
+    public static final String FILE_TYPE_PDF = "pdf";
+    public static final String FILE_TYPE_OFD = "ofd";
+    public static final String FILE_TYPE_JPG = "jpg";
+    public static final String FILE_TYPE_XML = "xml";
+    private static final String USER_DIR = "user.dir";
+    private static final String FILE_TEMP = "fileTemp";
+    public static final String BASE_UPLOAD_ABS_PATH;
+
+    public FileUtilsEx() {
+    }
+
+    public static boolean isImage(String fileType) {
+        return "png".equalsIgnoreCase(fileType) || "bmp".equalsIgnoreCase(fileType) || "jpg".equalsIgnoreCase(fileType) || "jpeg".equalsIgnoreCase(fileType) || "webp".equalsIgnoreCase(fileType);
+    }
+
+    public static String getSHA256(InputStream file) {
+        Object var2;
+        try {
+            MessageDigest MD5 = MessageDigest.getInstance("SHA-256");
+            byte[] buffer = new byte[8192];
+
+            int length;
+            while((length = file.read(buffer)) != -1) {
+                MD5.update(buffer, 0, length);
+            }
+
+            String var4 = new String(Hex.encodeHex(MD5.digest()));
+            return var4;
+        } catch (Exception var14) {
+            var2 = null;
+        } finally {
+            try {
+                if (file != null) {
+                    file.close();
+                }
+            } catch (IOException var13) {
+            }
+
+        }
+
+        return (String)var2;
+    }
+
+    public static String downLoadAndUpload(String fileUrl) {
+        return downLoadAndUpload(fileUrl, (String)null);
+    }
+
+    public static InputStream getInputStreamByGet(String url) throws ClientProtocolException, IOException {
+        return getInputStreamByGet(url, 60000, 60000);
+    }
+
+    private static InputStream getInputStreamByGet(String url, int connectionTimeout, int readTimeout) throws ClientProtocolException, IOException {
+        String proxy = HttpUtil.getProxy(url, (String)null);
+        CloseableHttpClient httpclient = HttpUtil.getConnection(proxy, false, connectionTimeout, readTimeout);
+        HttpGet httpGet = HttpUtil.getHttpGet(HttpUtil.replaceUrl(url));
+        CloseableHttpResponse response = httpclient.execute(httpGet);
+        return response.getEntity().getContent();
+    }
+
+    public static String downLoadAndUploadTemp(String fileUrl, String fileName) {
+        String tempSavePath = "";
+        if (!StringUtils.isEmpty(fileUrl) && fileUrl.indexOf("http") == 0) {
+            AwsFpyService service = AwsFpyService.newInstance();
+            HttpClient client = HttpUtil.getConnection(service.getProxy(), false);
+            HttpGet get = HttpUtil.getHttpGet(HttpUtil.replaceUrl(fileUrl));
+            CloseableHttpResponse response = null;
+
+            try {
+                long start = System.currentTimeMillis();
+                response = (CloseableHttpResponse)client.execute(get);
+                int statusCode = response.getStatusLine().getStatusCode();
+                if (200 == statusCode) {
+                    String fileType = "";
+                    fileType = getSuffixFromDisposition(response);
+                    if (StringUtils.isEmpty(fileType)) {
+                        fileType = getSuffixFromContentType(response);
+                    }
+
+                    HttpEntity entity = response.getEntity();
+                    if (StringUtils.isEmpty(fileName)) {
+                        fileName = UUID.randomUUIDZero() + '.' + fileType;
+                    } else if (fileName.indexOf(46) < 0) {
+                        fileName = fileName + '.' + fileType;
+                    }
+
+                    tempSavePath = CacheFactory.getCommonCacheFactory().getTempFileCache().saveAsUrl(fileName, entity.getContent(), 5000);
+                } else {
+                    if (302 == statusCode) {
+                        Header header = response.getFirstHeader("location");
+                        String newUrl = header.getValue();
+                        logger.info("重定向:" + newUrl);
+                        String var12 = downLoadAndUpload(newUrl, fileName);
+                        return var12;
+                    }
+
+                    logger.error(String.format("下载文件失败[%s]%s", statusCode, fileUrl));
+                }
+
+                logger.info(String.format("下载文件耗时[%s]%s", System.currentTimeMillis() - start, fileUrl));
+            } catch (IOException var28) {
+                logger.error("下载文件失败" + fileUrl, var28);
+            } finally {
+                if (response != null) {
+                    try {
+                        response.close();
+                    } catch (IOException var27) {
+                    }
+                }
+
+                try {
+                    get.abort();
+                    get.releaseConnection();
+                } catch (Exception var26) {
+                }
+
+            }
+
+            return tempSavePath;
+        } else {
+            return fileUrl;
+        }
+    }
+
+    public static String downLoadAndUpload(String fileUrl, String fileName) {
+        return (String)downLoadAndUpload(fileUrl, fileName, true, false);
+    }
+
+    public static JSONObject downLoadAndUploadWithFileType(String fileUrl, String fileName) {
+        return (JSONObject)downLoadAndUpload(fileUrl, fileName, true, true);
+    }
+
+    public static String downLoadAndUpload(String fileUrl, String fileName, boolean proxy) {
+        return (String)downLoadAndUpload(fileUrl, fileName, proxy, false);
+    }
+
+    public static Object downLoadAndUpload(String fileUrl, String fileName, boolean proxy, boolean needFileType) {
+        String tempSavePath = "";
+        String urlFileType = "";
+        if (!StringUtils.isEmpty(fileUrl) && fileUrl.indexOf("http") == 0) {
+            String fileId = MD5.md5Hex(fileUrl);
+            JSONObject pathAndType;
+            if (needFileType) {
+                pathAndType = queryFilePathAndType(fileId);
+                if (pathAndType != null) {
+                    return pathAndType;
+                }
+            } else {
+                String path = queryFilePath(fileId);
+                if (!StringUtils.isEmpty(path)) {
+                    return path;
+                }
+            }
+
+            pathAndType = null;
+            AwsFpyService service = AwsFpyService.newInstance();
+            CloseableHttpClient client;
+            if (proxy) {
+                client = HttpUtil.getConnection(service.getProxy(), false);
+            } else {
+                client = HttpUtil.getConnection((String)null, false);
+            }
+
+            HttpGet get = HttpUtil.getHttpGet(HttpUtil.replaceUrl(fileUrl));
+            CloseableHttpResponse response1 = null;
+            CloseableHttpResponse response302 = null;
+
+            try {
+                urlFileType = getFileType(fileUrl);
+                if (!StringUtils.isEmpty(urlFileType) && !"do".equals(urlFileType)) {
+                    fileName = UUID.randomUUIDZero() + '.' + urlFileType;
+                }
+
+                long start = System.currentTimeMillis();
+                response1 = (CloseableHttpResponse)client.execute(get);
+                int statusCode1 = response1.getStatusLine().getStatusCode();
+                if (200 == statusCode1) {
+                    Pair<String, String> pair = dealResponse(response1, fileName, fileUrl);
+                    tempSavePath = (String)pair.getLeft();
+                    if (StringUtils.isNotEmpty((String)pair.getRight())) {
+                        urlFileType = (String)pair.getRight();
+                    }
+                } else if (302 == statusCode1) {
+                    Header header = response1.getFirstHeader("location");
+                    String newUrl = header.getValue();
+                    logger.info("重定向:" + newUrl);
+                    if (StringUtils.isEmpty(fileName)) {
+                        urlFileType = getFileType(newUrl);
+                        if (!StringUtils.isEmpty(urlFileType)) {
+                            fileName = UUID.randomUUIDZero() + '.' + urlFileType;
+                        }
+                    }
+
+                    HttpGet newget = HttpUtil.getHttpGet(HttpUtil.replaceUrl(newUrl));
+                    response302 = (CloseableHttpResponse)client.execute(newget);
+                    int statusCode2 = response302.getStatusLine().getStatusCode();
+                    if (200 == statusCode2) {
+                        Pair<String, String> pair = dealResponse(response302, fileName, newUrl);
+                        tempSavePath = (String)pair.getLeft();
+                        if (StringUtils.isNotEmpty((String)pair.getRight())) {
+                            urlFileType = (String)pair.getRight();
+                        }
+                    } else {
+                        logger.error("下载文件失败302[{}]{}:{}", new Object[]{statusCode2, newUrl, JSON.toJSONString(response302)});
+                    }
+                } else {
+                    logger.error("下载文件失败[{}]{}:{}", new Object[]{statusCode1, fileUrl, JSON.toJSONString(response1)});
+                }
+
+                logger.info("下载文件耗时[{}]{}", System.currentTimeMillis() - start, fileUrl);
+            } catch (IOException var36) {
+                logger.error("下载文件失败" + fileUrl, var36);
+            } finally {
+                if (response1 != null) {
+                    try {
+                        response1.close();
+                    } catch (IOException var35) {
+                    }
+                }
+
+                if (response302 != null) {
+                    try {
+                        response302.close();
+                    } catch (IOException var34) {
+                    }
+                }
+
+                try {
+                    get.abort();
+                    get.releaseConnection();
+                } catch (Exception var33) {
+                }
+
+            }
+
+            if (!StringUtils.isEmpty(tempSavePath)) {
+                saveFilePath(fileUrl, tempSavePath, fileId, urlFileType);
+            }
+
+            if (needFileType) {
+                JSONObject result = new JSONObject();
+                result.put("file_url", tempSavePath);
+                result.put("file_type", urlFileType);
+                return result;
+            } else {
+                return tempSavePath;
+            }
+        } else if (needFileType) {
+            JSONObject result = new JSONObject();
+            result.put("file_url", fileUrl);
+            return result;
+        } else {
+            return fileUrl;
+        }
+    }
+
+    public static Pair<String, byte[]> downLoadFileToByte(String fileUrl, String fileName) {
+        return downLoadFileToByte(fileUrl, fileName, true);
+    }
+
+    public static Pair<String, byte[]> downLoadFileToByte(String fileUrl, String fileName, boolean proxy) {
+        logger.info("downLoadFileToByte,fileUrl:{}, fileName:{}", fileUrl, fileName);
+        if (!StringUtils.isEmpty(fileUrl) && fileUrl.indexOf("http") == 0) {
+            byte[] fileByte = null;
+            String urlFileType = "";
+            HttpClient client = null;
+            AwsFpyService service = AwsFpyService.newInstance();
+            if (proxy) {
+                client = HttpUtil.getConnection(service.getProxy(), false);
+            } else {
+                client = HttpUtil.getConnection((String)null, false);
+            }
+
+            HttpGet get = HttpUtil.getHttpGet(HttpUtil.replaceUrl(fileUrl));
+            CloseableHttpResponse response1 = null;
+            CloseableHttpResponse response302 = null;
+
+            try {
+                urlFileType = getFileType(fileUrl);
+                if (!StringUtils.isEmpty(urlFileType) && !"do".equals(urlFileType)) {
+                    fileName = UUID.randomUUIDZero() + '.' + urlFileType;
+                }
+
+                long start = System.currentTimeMillis();
+                response1 = (CloseableHttpResponse)client.execute(get);
+                int statusCode1 = response1.getStatusLine().getStatusCode();
+                if (200 == statusCode1) {
+                    HttpEntity entity1 = response1.getEntity();
+                    fileByte = getByte(entity1.getContent());
+                    if (StringUtils.isEmpty(urlFileType)) {
+                        urlFileType = getSuffixFromDisposition(response1);
+                    }
+                } else if (302 == statusCode1) {
+                    Header header = response1.getFirstHeader("location");
+                    String newUrl = header.getValue();
+                    logger.info("重定向:" + newUrl);
+                    if (StringUtils.isEmpty(fileName)) {
+                        urlFileType = getFileType(newUrl);
+                    }
+
+                    HttpGet newget = HttpUtil.getHttpGet(HttpUtil.replaceUrl(newUrl));
+                    response302 = (CloseableHttpResponse)client.execute(newget);
+                    int statusCode2 = response302.getStatusLine().getStatusCode();
+                    if (200 == statusCode2) {
+                        HttpEntity entity2 = response302.getEntity();
+                        fileByte = getByte(entity2.getContent());
+                        if (StringUtils.isEmpty(urlFileType)) {
+                            urlFileType = getSuffixFromDisposition(response302);
+                        }
+                    } else {
+                        logger.error("下载文件失败302[{}]{}:{}", new Object[]{statusCode2, newUrl, JSON.toJSONString(response302)});
+                    }
+                } else {
+                    logger.error("下载文件失败[{}]{}:{}", new Object[]{statusCode1, fileUrl, JSON.toJSONString(response1)});
+                }
+
+                logger.info("下载文件耗时[{}]{}", System.currentTimeMillis() - start, fileUrl);
+            } catch (IOException var34) {
+                logger.error("下载文件失败" + fileUrl, var34);
+            } finally {
+                if (response1 != null) {
+                    try {
+                        response1.close();
+                    } catch (IOException var33) {
+                    }
+                }
+
+                if (response302 != null) {
+                    try {
+                        response302.close();
+                    } catch (IOException var32) {
+                    }
+                }
+
+                try {
+                    get.abort();
+                    get.releaseConnection();
+                } catch (Exception var31) {
+                }
+
+            }
+
+            return Pair.of(urlFileType, fileByte);
+        } else {
+            return null;
+        }
+    }
+
+    private static Pair<String, String> dealResponse(CloseableHttpResponse response, String fileName, String fileUrl) throws UnsupportedOperationException, IOException {
+        String fileType = getSuffixFromDisposition(response);
+        if (StringUtils.isEmpty(fileType)) {
+            fileType = getSuffixFromContentType(response);
+            if ("ofd".equals(fileType)) {
+                String fileTypeFromName = getFileType(fileName);
+                if (!StringUtils.isEmpty(fileType)) {
+                    fileType = fileTypeFromName;
+                }
+            }
+        }
+
+        HttpEntity entity = response.getEntity();
+        if (StringUtils.isEmpty(fileName)) {
+            fileName = UUID.randomUUIDZero() + '.' + fileType;
+        } else if (fileName.indexOf(46) < 0) {
+            fileName = fileName + '.' + fileType;
+        }
+
+        if (StringUtils.isEmpty(fileType) && fileName.indexOf(46) < 0) {
+            logger.error("文件类型错误取消上传:" + fileUrl);
+            return Pair.of(((Object)null).toString(), fileType);
+        } else {
+            byte[] fileByte = getByte(entity.getContent());
+            ByteArrayInputStream bs = new ByteArrayInputStream(fileByte);
+            Throwable var7 = null;
+
+            Pair var9;
+            try {
+                String url = FileUploadUtils.upload(FileUploadUtils.getInvoiceDir("invoice") + fileName, fileName, bs);
+                var9 = Pair.of(url, fileType);
+            } catch (Throwable var18) {
+                var7 = var18;
+                throw var18;
+            } finally {
+                if (bs != null) {
+                    if (var7 != null) {
+                        try {
+                            bs.close();
+                        } catch (Throwable var17) {
+                            var7.addSuppressed(var17);
+                        }
+                    } else {
+                        bs.close();
+                    }
+                }
+
+            }
+
+            return var9;
+        }
+    }
+
+    public static void saveFilePath(String fileUrl, String attachPath, String fileId, String urlFileType) {
+        try {
+            DynamicObject downResult = BusinessDataServiceHelper.newDynamicObject("rim_download_file");
+            downResult.set("fileid", fileId);
+            downResult.set("http_url", fileUrl);
+            downResult.set("file_url", attachPath);
+            downResult.set("create_time", new Date());
+            downResult.set("file_type", convertFileType(urlFileType));
+            SaveServiceHelper.save(new DynamicObject[]{downResult});
+        } catch (Exception var5) {
+        }
+
+    }
+
+    public static String convertFileType(String fileType) {
+        logger.info("下载文件类型{}", fileType);
+        if (!"1".equals(fileType) && !"pdf".equals(fileType)) {
+            if (!"4".equals(fileType) && !"ofd".equals(fileType)) {
+                return !"9".equals(fileType) && !"xml".equals(fileType) ? "jpg" : "xml";
+            } else {
+                return "ofd";
+            }
+        } else {
+            return "pdf";
+        }
+    }
+
+    public static String convertFileTypeNum(String fileType) {
+        if (!"1".equals(fileType) && !"pdf".equals(fileType)) {
+            if (!"4".equals(fileType) && !"ofd".equals(fileType)) {
+                return !"9".equals(fileType) && !"xml".equals(fileType) ? "2" : "9";
+            } else {
+                return "4";
+            }
+        } else {
+            return "1";
+        }
+    }
+
+    public static String queryFilePath(String fileId) {
+        if (!StringUtils.isEmpty(fileId)) {
+            QFilter filter = new QFilter("fileid", "=", fileId);
+            DynamicObject obj = QueryServiceHelper.queryOne("rim_download_file", "id,file_url", new QFilter[]{filter});
+            if (obj != null && !StringUtils.isEmpty(obj.getString("file_url"))) {
+                return obj.getString("file_url");
+            }
+        }
+
+        return null;
+    }
+
+    public static JSONObject queryFilePathAndType(String fileId) {
+        if (!StringUtils.isEmpty(fileId)) {
+            JSONObject result = new JSONObject();
+            QFilter filter = new QFilter("fileid", "=", fileId);
+            DynamicObject obj = QueryServiceHelper.queryOne("rim_download_file", "id,file_url,file_type", new QFilter[]{filter});
+            if (obj != null && !StringUtils.isEmpty(obj.getString("file_url"))) {
+                result.put("file_url", obj.getString("file_url"));
+                result.put("file_type", obj.getString("file_type"));
+                return result;
+            }
+        }
+
+        return null;
+    }
+
+    private static String getSuffixFromDisposition(CloseableHttpResponse response) {
+        Header[] headers = response.getHeaders("Content-Disposition");
+        if (headers == null) {
+            headers = response.getHeaders("content-disposition");
+        }
+
+        if (headers != null) {
+            Header[] var2 = headers;
+            int var3 = headers.length;
+
+            for(int var4 = 0; var4 < var3; ++var4) {
+                Header header = var2[var4];
+                String value = header.getValue().replace("\"", "");
+                logger.info("getSuffixFromDisposition headervalue:{}", value);
+                int nameIndex = value.indexOf("filename");
+                if (nameIndex > 0 && value.length() > 10) {
+                    String fileName = value.substring(nameIndex + 10, value.length());
+                    fileName = fileName.replace(";", "");
+                    if (fileName.lastIndexOf(46) > 0) {
+                        return fileName.substring(fileName.lastIndexOf(46) + 1);
+                    }
+                }
+            }
+        }
+
+        return null;
+    }
+
+    private static String getSuffixFromContentType(CloseableHttpResponse response) {
+        Header[] headers = response.getHeaders("Content-Type");
+        if (headers != null) {
+            Header[] var2 = headers;
+            int var3 = headers.length;
+
+            for(int var4 = 0; var4 < var3; ++var4) {
+                Header header = var2[var4];
+                if (header.getValue().indexOf("pdf") > 0) {
+                    return "pdf";
+                }
+
+                if (header.getValue().indexOf("octet") > 0) {
+                    return "ofd";
+                }
+
+                if (header.getValue().indexOf("image/png") >= 0) {
+                    return "png";
+                }
+
+                if (header.getValue().indexOf("image/gif") >= 0) {
+                    return "gif";
+                }
+
+                if (header.getValue().indexOf("image") >= 0) {
+                    return "jpg";
+                }
+            }
+        }
+
+        return null;
+    }
+
+    public static ByteArrayOutputStream cloneInputStream(InputStream input) {
+        try {
+            ByteArrayOutputStream baos = new ByteArrayOutputStream();
+            byte[] buffer = new byte[1024];
+
+            int len;
+            while((len = input.read(buffer)) > -1) {
+                baos.write(buffer, 0, len);
+            }
+
+            baos.flush();
+            return baos;
+        } catch (IOException var4) {
+            logger.error("获取开票人异常:" + var4.getMessage(), var4);
+            return null;
+        }
+    }
+
+    public static boolean isExcel(String fileName) {
+        return checkFileType(fileName, "xls", "xlsx");
+    }
+
+    public static boolean checkFileType(String fileName, String... types) {
+        if (fileName != null && types != null && types.length >= 1) {
+            String fileType = getFileType(fileName);
+            if ("".equals(fileType)) {
+                return false;
+            } else {
+                String[] var3 = types;
+                int var4 = types.length;
+
+                for(int var5 = 0; var5 < var4; ++var5) {
+                    String str = var3[var5];
+                    if (fileType.equalsIgnoreCase(str)) {
+                        return true;
+                    }
+                }
+
+                return false;
+            }
+        } else {
+            return false;
+        }
+    }
+
+    public static String getFileType(String fileName) {
+        try {
+            URL url = new URL(fileName);
+            return FilenameUtils.getExtension(url.getPath());
+        } catch (MalformedURLException var2) {
+            return FilenameUtils.getExtension(fileName);
+        }
+    }
+
+    public static String getRealPath(String fileId) {
+        if (StringUtils.isEmpty(fileId)) {
+            return "";
+        } else {
+            String path = "";
+
+            try {
+                String sql = "select fpath from t_bas_filepathmapping where FFILEID = ? ";
+                path = (String)DB.query(DBRoute.base, sql, new String[]{fileId}, new ResultSetHandler<String>() {
+                    public String handle(ResultSet rs) throws Exception {
+                        String path;
+                        for(path = ""; rs.next(); path = rs.getString("fpath")) {
+                        }
+
+                        return path;
+                    }
+                });
+            } catch (Exception var3) {
+                logger.info("查询真实地址失败:" + var3);
+            }
+
+            return path;
+        }
+    }
+
+    public static Pair<String, byte[]> getFileContent(String fileUrl) {
+        return getFileContent(fileUrl, Boolean.TRUE);
+    }
+
+    public static Pair<String, byte[]> getFileContent(String fileUrl, Boolean proxy) {
+        if (StringUtils.isEmpty(fileUrl)) {
+            return null;
+        } else if (fileUrl.indexOf("http") != 0) {
+            FileService service = FileServiceFactory.getAttachmentFileService();
+            if (service.exists(fileUrl)) {
+                String fileType = getFileType(fileUrl);
+                if (StringUtils.isEmpty(fileType)) {
+                    String path = getRealPath(fileUrl);
+                    fileType = getFileType(path);
+                }
+
+                return Pair.of(fileType, getByte(service.getInputStream(fileUrl)));
+            } else {
+                logger.info("文件不存在:" + fileUrl);
+                return null;
+            }
+        } else {
+            AwsFpyService service = AwsFpyService.newInstance();
+            HttpClient client = HttpUtil.getConnection(proxy ? service.getProxy() : null, false);
+            HttpGet get = HttpUtil.getHttpGet(HttpUtil.replaceUrl(fileUrl));
+            CloseableHttpResponse response = null;
+            CloseableHttpResponse response302 = null;
+
+            Pair var10;
+            try {
+                long start = System.currentTimeMillis();
+                response = (CloseableHttpResponse)client.execute(get);
+                int statusCode = response.getStatusLine().getStatusCode();
+                if (200 != statusCode) {
+                    if (302 == statusCode) {
+                        Header header = response.getFirstHeader("location");
+                        String newUrl = header.getValue();
+                        logger.info("重定向:" + newUrl);
+                        HttpGet get302 = HttpUtil.getHttpGet(HttpUtil.replaceUrl(newUrl));
+                        response302 = (CloseableHttpResponse)client.execute(get302);
+                        int statusCode302 = response302.getStatusLine().getStatusCode();
+                        if (200 == statusCode302) {
+                            Pair var14 = getContentFromResonse(fileUrl, response302);
+                            return var14;
+                        }
+
+                        logger.error(String.format("下载文件失败302[%s]%s:%s", statusCode, newUrl, JSON.toJSONString(response302)));
+                    }
+
+                    logger.info("下载文件耗时[{}]{},{}", new Object[]{System.currentTimeMillis() - start, statusCode, fileUrl});
+                    return null;
+                }
+
+                var10 = getContentFromResonse(fileUrl, response);
+            } catch (IOException var38) {
+                logger.error("下载文件失败" + fileUrl, var38);
+                return null;
+            } finally {
+                if (response != null) {
+                    try {
+                        response.close();
+                    } catch (IOException var37) {
+                    }
+                }
+
+                if (response302 != null) {
+                    try {
+                        response302.close();
+                    } catch (IOException var36) {
+                    }
+                }
+
+                try {
+                    get.abort();
+                    get.releaseConnection();
+                } catch (Exception var35) {
+                }
+
+            }
+
+            return var10;
+        }
+    }
+
+    private static Pair<String, byte[]> getContentFromResonse(String fileUrl, CloseableHttpResponse response) throws IOException {
+        String fileType = getSuffixFromDisposition(response);
+        if (StringUtils.isEmpty(fileType)) {
+            fileType = getSuffixFromContentType(response);
+            if ("ofd".equals(fileType)) {
+                fileType = getFileType(fileUrl);
+                if (StringUtils.isEmpty(fileType)) {
+                    fileType = "ofd";
+                }
+            }
+        }
+
+        HttpEntity entity = response.getEntity();
+        return Pair.of(fileType, getByte(entity.getContent()));
+    }
+
+    public static byte[] getAttachmentByte(String savePath) {
+        FileService service = FileServiceFactory.getAttachmentFileService();
+
+        try {
+            InputStream bos = service.getInputStream(savePath);
+            Throwable var3 = null;
+
+            byte[] var4;
+            try {
+                var4 = getByte(bos);
+            } catch (Throwable var14) {
+                var3 = var14;
+                throw var14;
+            } finally {
+                if (bos != null) {
+                    if (var3 != null) {
+                        try {
+                            bos.close();
+                        } catch (Throwable var13) {
+                            var3.addSuppressed(var13);
+                        }
+                    } else {
+                        bos.close();
+                    }
+                }
+
+            }
+
+            return var4;
+        } catch (IOException var16) {
+            return null;
+        }
+    }
+
+    public static byte[] getByte(InputStream inputStream) {
+        try {
+            ByteArrayOutputStream bos = new ByteArrayOutputStream();
+            Throwable var2 = null;
+
+            try {
+                byte[] buffer = new byte[1024];
+//                Boolean len = false;
+                int len;
+                while((len = inputStream.read(buffer)) != -1) {
+                    bos.write(buffer, 0, len);
+                }
+
+                byte[] var5 = bos.toByteArray();
+                return var5;
+            } catch (Throwable var15) {
+                var2 = var15;
+                throw var15;
+            } finally {
+                if (bos != null) {
+                    if (var2 != null) {
+                        try {
+                            bos.close();
+                        } catch (Throwable var14) {
+                            var2.addSuppressed(var14);
+                        }
+                    } else {
+                        bos.close();
+                    }
+                }
+
+            }
+        } catch (IOException var17) {
+            return null;
+        }
+    }
+
+    public static String encodeBase64File(InputStream inputFile) throws Exception {
+        if (inputFile == null) {
+            return null;
+        } else {
+            ByteArrayOutputStream output = new ByteArrayOutputStream();
+            byte[] buffer = new byte[4096];
+//            int n = false;
+
+            int n;
+            while(-1 != (n = inputFile.read(buffer))) {
+                output.write(buffer, 0, n);
+            }
+
+            String retStr = Base64.encodeBase64String(output.toByteArray());
+            return retStr;
+        }
+    }
+
+    public static String truncateFileName(String fileName, int maxLength) {
+        if (StringUtils.isEmpty(fileName)) {
+            return fileName;
+        } else if (fileName.length() <= maxLength) {
+            return fileName;
+        } else {
+            int dotIndex = fileName.lastIndexOf(46);
+            String extension = "";
+            String nameWithoutExtension;
+            if (dotIndex != -1) {
+                nameWithoutExtension = fileName.substring(0, dotIndex);
+                extension = fileName.substring(dotIndex);
+            } else {
+                nameWithoutExtension = fileName;
+            }
+
+            int availableLength = maxLength - extension.length();
+            return availableLength <= 0 ? "" : nameWithoutExtension.substring(0, Math.min(availableLength, nameWithoutExtension.length())) + extension;
+        }
+    }
+
+    static {
+        BASE_UPLOAD_ABS_PATH = System.getProperty("user.dir") + File.separator + "fileTemp" + File.separator;
+    }
+}

+ 0 - 1
src/main/java/kd/imc/rim/formplugin/collector/InvoiceCollectPluginEx.java

@@ -13,7 +13,6 @@ import kd.bos.orm.util.CollectionUtils;
 import kd.bos.threads.ThreadPools;
 import kd.bos.util.StringUtils;
 import kd.imc.rim.common.constant.CollectTypeEnum;
-import kd.imc.rim.common.invoice.collector.InvoiceCollectTask;
 import kd.imc.rim.common.invoice.collector.InvoiceCollectTaskNew;
 import kd.imc.rim.common.service.DialogService;
 import kd.imc.rim.common.utils.BigDecimalUtil;