Selaa lähdekoodia

1、修改srm单据上传附件接口

wanghaiwu 2 kuukautta sitten
vanhempi
säilyke
15ef33a357

+ 179 - 0
code/jyyy/nckd-jimin-jyyy-fi/src/main/java/nckd/jimin/jyyy/fi/common/XmlUtils.java

@@ -0,0 +1,179 @@
+package nckd.jimin.jyyy.fi.common;
+import com.alibaba.fastjson.JSONArray;
+import com.alibaba.fastjson.JSONObject;
+import com.thoughtworks.xstream.XStream;
+import com.thoughtworks.xstream.core.util.QuickWriter;
+import com.thoughtworks.xstream.io.HierarchicalStreamWriter;
+import com.thoughtworks.xstream.io.xml.PrettyPrintWriter;
+import com.thoughtworks.xstream.io.xml.XmlFriendlyNameCoder;
+import com.thoughtworks.xstream.io.xml.XppDriver;
+import org.apache.commons.lang3.StringUtils;
+import org.dom4j.*;
+
+import java.io.Writer;
+import java.util.List;
+
+/**
+ * xml 转Json 工具类
+ *
+ */
+public class XmlUtils {
+    /**
+     * String 转 org.dom4j.Document
+     *
+     * @param xml
+     * @return
+     * @throws DocumentException
+     */
+    private static Document strToDocument(String xml) throws DocumentException {
+        return DocumentHelper.parseText(xml);
+    }
+
+    /**
+     * xml 转  com.alibaba.fastjson.JSONObject
+     *
+     * @param xml
+     * @return
+     * @throws DocumentException
+     */
+    public static JSONObject documentToJSONObject(String xml) {
+        JSONObject jsonObject = null;
+        try {
+            jsonObject = elementToJSONObject(strToDocument(xml).getRootElement());
+        } catch (DocumentException e) {
+            e.printStackTrace();
+        } finally {
+            return jsonObject;
+        }
+    }
+
+    /**
+     * org.dom4j.Element 转  com.alibaba.fastjson.JSONObject
+     *
+     * @param node
+     * @return
+     */
+    public static JSONObject elementToJSONObject(Element node) {
+        JSONObject result = new JSONObject();
+        // 当前节点的名称、文本内容和属性
+        List<Attribute> listAttr = node.attributes();// 当前节点的所有属性的list
+        for (Attribute attr : listAttr) {// 遍历当前节点的所有属性
+            result.put(attr.getName(), attr.getValue());
+        }
+        // 递归遍历当前节点所有的子节点
+        List<Element> listElement = node.elements();// 所有一级子节点的list
+        if (!listElement.isEmpty()) {
+            for (Element e : listElement) {// 遍历所有一级子节点
+                if (e.attributes().isEmpty() && e.elements().isEmpty()) {// 判断一级节点是否有属性和子节点
+                    result.put(e.getName(), e.getTextTrim());// 沒有则将当前节点作为上级节点的属性对待
+                } else {
+                    if (!result.containsKey(e.getName())) {// 判断父节点是否存在该一级节点名称的属性
+                        result.put(e.getName(), new JSONArray());// 没有则创建
+                    }
+                    ((JSONArray) result.get(e.getName())).add(elementToJSONObject(e));// 将该一级节点放入该节点名称的属性对应的值中
+                }
+            }
+        }
+        return result;
+    }
+
+    /**
+     * 创建XStream
+     */
+    private static XStream createXstream() {
+        XStream xstream = new XStream(new MyXppDriver(false));
+        xstream.autodetectAnnotations(true);
+        return xstream;
+    }
+
+    /**
+     * 支持注解转化XML
+     */
+    public static String toXML(Object obj, Class<?> cls) {
+        if (obj == null) {
+            return null;
+        }
+        XStream xstream = createXstream();
+        xstream.processAnnotations(cls);
+        return getDefaultXMLHeader() + xstream.toXML(obj);
+    }
+
+    /**
+     * Object 转化 XML
+     */
+    public static String toXML(Object obj) {
+        if (obj == null) {
+            return null;
+        }
+        XStream xstream = createXstream();
+        return getDefaultXMLHeader() + xstream.toXML(obj);
+    }
+
+    /**
+     * XML转化为JAVA对象
+     */
+    @SuppressWarnings("unchecked")
+    public static <T> T xml2Obj(String xml, Class<?> cls) {
+        if (StringUtils.isBlank(xml)) {
+            return null;
+        }
+        XStream xstream = createXstream();
+        if (cls != null) {
+            xstream.processAnnotations(cls);
+        }
+        return (T) xstream.fromXML(xml);
+    }
+
+    /**
+     * XML转化为JAVA对象
+     */
+    public static <T> T xml2Obj(String xml) {
+        return xml2Obj(xml, null);
+    }
+
+    private static String getDefaultXMLHeader() {
+        return "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n";
+    }
+
+    /**
+     * @author lixining
+     * @version $Id: XmlUtils.java, v 0.1 2015年8月18日 上午9:46:57 lixining Exp $
+     * @description XppDriver
+     */
+    public static class MyXppDriver extends XppDriver {
+        boolean useCDATA = false;
+
+        MyXppDriver(boolean useCDATA) {
+            super(new XmlFriendlyNameCoder("__", "_"));
+            this.useCDATA = useCDATA;
+        }
+
+        @Override
+        public HierarchicalStreamWriter createWriter(Writer out) {
+            if (!useCDATA) {
+                return super.createWriter(out);
+            }
+            return new PrettyPrintWriter(out) {
+                boolean cdata = true;
+
+                @Override
+                public void startNode(String name, @SuppressWarnings("rawtypes") Class clazz) {
+                    super.startNode(name, clazz);
+                }
+
+                @Override
+                protected void writeText(QuickWriter writer, String text) {
+                    if (cdata) {
+                        writer.write(cDATA(text));
+                    } else {
+                        writer.write(text);
+                    }
+                }
+
+                private String cDATA(String text) {
+                    return "<![CDATA[" + text + "]]>";
+                }
+            };
+        }
+    }
+}

+ 186 - 26
code/jyyy/nckd-jimin-jyyy-fi/src/main/java/nckd/jimin/jyyy/fi/webapi/SRMSynAttacmentApiPlugin.java

@@ -10,19 +10,21 @@ import kd.bos.openapi.common.custom.annotation.ApiController;
 import kd.bos.openapi.common.custom.annotation.ApiParam;
 import kd.bos.openapi.common.custom.annotation.ApiPostMapping;
 import kd.bos.openapi.common.result.CustomApiResult;
+import kd.bos.servicehelper.DispatchServiceHelper;
 import kd.imc.rim.common.message.exception.MsgException;
 import kd.imc.rim.common.utils.FileUploadUtils;
 import kd.imc.rim.common.utils.FileUtils;
 import kd.imc.rim.common.utils.MD5;
+import nckd.jimin.jyyy.fi.common.XmlUtils;
 import nckd.jimin.jyyy.fi.plugin.operate.SRMHelperUtils;
 
 import javax.validation.Valid;
 import java.io.*;
 import java.net.HttpURLConnection;
 import java.net.URL;
-import java.util.Base64;
-import java.util.Map;
-import java.util.UUID;
+import java.nio.file.Files;
+import java.nio.file.Paths;
+import java.util.*;
 
 @ApiController(
         desc = "对接SRM预付款、付款附件,上传到发票",
@@ -46,36 +48,136 @@ public class SRMSynAttacmentApiPlugin implements Serializable {
 //            return returnResult("E", "失败,获取token失败," + tokenMap.get("msg"), null);
 //        }
 //        String token = tokenMap.get("msg").toString();
+//
+//        token = "8862dff0-cf8c-432e-9b4f-453e66604226";
+//
+//
+//        if(StringUtils.isEmpty(request)){
+//            return returnResult("E", "参数不能为空,", null);
+//        }
+//        request = parseXMLString(request);
+//
+//        request = request.replace("\r\n", "");
+//
+//        try {
+//            JSONObject requestJSON = XmlUtils.documentToJSONObject(request);
+//            JSONArray fileArray = requestJSON.getJSONArray("BillBody")
+//                    .getJSONObject(0).getJSONArray("Document")
+//                    .getJSONObject(0).getJSONArray("Files")
+//                    .getJSONObject(0).getJSONArray("File");
+//
+//            for(int i = 0; i < fileArray.size(); i++){
+//                JSONObject fileItem = fileArray.getJSONObject(i);
+//                String fileSize = fileItem.getString("FILE_SIZE");
+//                String fileName = fileItem.getString("FILE_NAME");
+//                String fileType = fileItem.getString("FILE_TYPE");
+//                String fileUrl = fileItem.getString("URL");
+//            }
+//
+//        } catch(Exception e){
+//            return returnResult("E", "xml参数异常" + e.getMessage(), null);
+//        }
+//
+//
+////        String token = accesstoken;
+//        JSONObject returnData = new JSONObject();
+//
+//        String downloadUrl = "https://gateway.test.isrm.going-link.com/hfle/v1/19694/files/download?bucketName=private-bucket&url=https://isrm-test-private-bucket.obs.cn-east-2.myhuaweicloud.com:443/2025-05/cusz-attachment-default/19694/744f2e7425f7468283578f48879bb4be@%E5%B1%B1%E7%A6%BE%E8%AE%A2%E5%8D%95%E6%A8%A1%E6%9D%BF.pdf";
+//
+////        downloadUrl = "https://gateway.test.isrm.going-link.com/hfle/v1/19694/files/download?bucketName=private-bucket&url=https://isrm-test-private-bucket.obs.cn-east-2.myhuaweicloud.com:443/2025-05/ssta-settle-header/19694/209b30126cd742049241198ddd7b13b9@%E8%B4%B9%E6%8E%A7%E4%BB%98%E6%AC%BE%E5%8D%95%E6%B5%8B%E8%AF%95%E9%99%84%E4%BB%B6.docx";
+//        downloadUrl = downloadUrl + "&access_token=" + token;
+//
+//        logger.info("SRMSynAttacmentApiPlugin:downloadUrl " + downloadUrl);
+//
 
-        String token = accesstoken;
-        JSONObject returnData = new JSONObject();
+        InputStream inputStream = null;
+        try {
+//            URL url = new URL(downloadUrl);
+//            //这里没有使用 封装后的ResponseEntity 就是也是因为这里不适合一次性的拿到结果,放不下content,会造成内存溢出
+//            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
+//
+//            int size = connection.getContentLength();
+//
+//            //使用bufferedInputStream 缓存流的方式来获取下载文件,不然大文件会出现内存溢出的情况
+//            inputStream = new BufferedInputStream(connection.getInputStream());
 
-        String downloadUrl = "https://gateway.test.isrm.going-link.com/hfle/v1/19694/files/download?bucketName=private-bucket&url=https://isrm-test-private-bucket.obs.cn-east-2.myhuaweicloud.com:443/2025-05/cusz-attachment-default/19694/744f2e7425f7468283578f48879bb4be@%E5%B1%B1%E7%A6%BE%E8%AE%A2%E5%8D%95%E6%A8%A1%E6%9D%BF.pdf";
-        downloadUrl = downloadUrl + "&access_token=" + token;
+            inputStream = Files.newInputStream(Paths.get("C:\\Users\\Administrator\\Desktop\\testsrmatt\\test.pdf"));
 
-        logger.info("SRMSynAttacmentApiPlugin:downloadUrl " + downloadUrl);
+            String base64 = InputStreamToBase64String(inputStream);
+            byte[] bytes = InputStreamToBytes(inputStream);
+
+            String fileName = fileName("pdf");
+
+//            fileName = "pdg测试.pdf";
+
+//            String fileUrl1 = upFileOfBytes(bytes, "1", fileName);
+
+            String fileUrl = upFileOfBase64(base64, "10", fileName);
+
+
+            //保存关系
+            Map<String, Object> map = new HashMap<String, Object>();
+            map.put("billId", "2219015625274035200");
+            map.put("billNo", "DGBX-250520-0082");
+            map.put("billType", "er_publicreimbursebill");
+            map.put("entityId", "6B2CW570E+4");
+            map.put("viewPage", "er_publicreimbursebill");
+            map.put("billUser", "18679139819");
+            map.put("userName", "18679139819");
+            map.put("resource", "1");
+//            map.put("status", "");
+//            map.put("updateAttachRelation","1");
+//            map.put("updateInvoiceOrg","1");
+//            int total = getModel().getEntryRowCount("entryentity");
+//            if(total == 0){
+//                total = 2;
+//            }
+            List<Map<String, Object>> list = new ArrayList<Map<String, Object>>();
+//            for (int i = 0; i < total; i++) {
+//                Map<String, Object> map11 = new HashMap<String, Object>();
+//                map11.put("amount", "12");
+//                map11.put("serialNo", getModel().getValue("serial_no", i));
+//                map11.put("deductionFlag", "1");
+//                map11.put("deductionTaxAmount", "23");
+//                map11.put("effectiveTaxAmount", "23");
+//                map11.put("entryId", "121212");
+//                map11.put("status", status);
+//                list.add(map11);
+//            }
+            map.put("invoiceData", list);
+            Map<String, Object> extInfo = new HashMap<String, Object>();
+//            extInfo.put("二开字段标识", "二开字段值");
+            map.put("extInfo", extInfo);
+
+            List<Map<String, Object>> coverList = new ArrayList<>();
+
+            Map<String, Object> coverMap = new HashMap<>();
+
+            coverMap.put("attachName", "测试pdf");
+            coverMap.put("attachType", "1");
+            coverMap.put("attachUrl", fileUrl);
+
+            coverList.add(coverMap);
+
+            map.put("attachData", coverList);
+
+//            connection.disconnect();
+            inputStream.close();
 
-        InputStream inputStream = null;
-        try {
-            URL url = new URL(downloadUrl);
-            //这里没有使用 封装后的ResponseEntity 就是也是因为这里不适合一次性的拿到结果,放不下content,会造成内存溢出
-            HttpURLConnection connection =(HttpURLConnection) url.openConnection();
 
-            connection.getContentLength();
+            JSONObject result = DispatchServiceHelper.invokeBizService("imc", "rim", "FpzsService", "save", map);
+            if ("0000".equals(result.getString("errcode"))) {
+                return returnResult("S", "保存成功", null);
+            } else {
+                return returnResult("S", "保存失败" + result.getString("description"), null);
+            }
 
-            //使用bufferedInputStream 缓存流的方式来获取下载文件,不然大文件会出现内存溢出的情况
-            inputStream = new BufferedInputStream(connection.getInputStream());
 
-            String base64 = InputStreamToBase64String(inputStream);
 
-            String fileName = fileName("1");
-            String fileUrl = upFileOfBase64(base64, fileName, "测试srm上传发票附件");
+//            returnData.put("fileUrl", fileUrl == null ? "" : fileUrl);
+//            returnData.put("downloadUrl", downloadUrl);
 
-            returnData.put("fileUrl", fileUrl == null ? "" : fileUrl);
-            returnData.put("downloadUrl", downloadUrl);
 
-            connection.disconnect();
-            inputStream.close();
         } catch (Exception e){
             e.printStackTrace();
         } finally {
@@ -84,7 +186,7 @@ public class SRMSynAttacmentApiPlugin implements Serializable {
 //            IOUtils.closeQuietly(inputStream);
         }
 
-        return returnResult("S", "成功", returnData);
+        return returnResult("S", "成功", null);
     }
 
     private String upFileOfBase64(String base64, String fileType, String fileName) {
@@ -102,6 +204,23 @@ public class SRMSynAttacmentApiPlugin implements Serializable {
         return path;
     }
 
+    private String upFileOfBytes(byte[] bytes, String fileType, String fileName) {
+        String url = FileUploadUtils.getInvoiceDir("invoice") + fileName;
+        String fileId = MD5.SHA256Hex(fileType + bytes.toString());
+        String path = FileUtils.queryFilePath(fileId);
+        if (StringUtils.isEmpty(path)) {
+            path = FileUploadUtils.uploadBytes(url, fileName, bytes);
+            FileUtils.saveFilePath("", path, fileId, fileType);
+        }
+
+        logger.info("SRMSynAttacmentApiPlugin 上传服务器:fileName:" + fileName + ", url:" + url + ", fileId: " + fileId);
+        logger.info("SRMSynAttacmentApiPlugin:" + (path == null ? "path is null" : path));
+
+        return path;
+    }
+
+
+
     private String fileName(String fileType) {
         String fileName = String.valueOf(UUID.randomUUID());
         String filePix = "";
@@ -117,6 +236,8 @@ public class SRMSynAttacmentApiPlugin implements Serializable {
             filePix = ".ofd";
         } else if (FileUtils.isImage(fileType)) {
             filePix = ".jpg";
+        } else {
+            filePix = "." + fileType;
         }
 
         if (StringUtils.isEmpty(filePix)) {
@@ -134,8 +255,8 @@ public class SRMSynAttacmentApiPlugin implements Serializable {
      */
     private String InputStreamToBase64String(InputStream inputStream){
         ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
-//        byte[] buffer = new byte[1024]; // 创建一个缓冲区,大小可以根据需要调整
-        byte[] buffer = new byte[1024 * 1024 * 5];// 5MB
+        byte[] buffer = new byte[1024]; // 创建一个缓冲区,大小可以根据需要调整
+//        byte[] buffer = new byte[1024 * 1024 * 5];// 5MB
         int bytesRead;
         try {
             // 读取数据到缓冲区,直到没有更多数据可读
@@ -164,6 +285,45 @@ public class SRMSynAttacmentApiPlugin implements Serializable {
 
     }
 
+    private byte[] InputStreamToBytes(InputStream inputStream){
+        ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
+        byte[] buffer = new byte[1024]; // 创建一个缓冲区,大小可以根据需要调整
+//        byte[] buffer = new byte[1024 * 1024 * 5];// 5MB
+        int bytesRead;
+        try {
+            // 读取数据到缓冲区,直到没有更多数据可读
+            while (true) {
+                try {
+                    if (!((bytesRead = inputStream.read(buffer)) != -1)) break;
+                } catch (IOException e) {
+                    throw new RuntimeException(e);
+                }
+                byteArrayOutputStream.write(buffer, 0, bytesRead);
+            }
+
+            // 将ByteArrayOutputStream的内容转换成byte数组
+            byte[] bytes = byteArrayOutputStream.toByteArray();
+
+            byteArrayOutputStream.close();
+
+            return bytes;
+        } catch (IOException e) {
+            throw new RuntimeException(e);
+        }
+
+
+    }
+
+
+    public static String parseXMLString(String xml) {
+        int strIndex = xml.indexOf("<?xml ");
+        int endIndex = xml.indexOf("</DATA>");
+        String conStr = xml.substring(strIndex, endIndex + 7);
+//        String dataStr = staStr + conStr;
+
+        return conStr;
+//        parseXML(dataStr);
+    }
 
     /**
      * 自定义返回data对象