Browse Source

【电票】【退货单 红票获取】

wuyx 1 year ago
parent
commit
9f21b2841f

+ 1 - 1
src/main/java/com/uas/eis/dto/QueryInvoiceResultDTO.java

@@ -83,7 +83,7 @@ public class QueryInvoiceResultDTO extends QSqlDTO {
     public String updatePdfUrlSql(){//更新 红票PDFURL附件
         String sql = "";
         if(StringUtil.hasText(serialNo)){
-            sql= "update ElecInvoice set EI_REDPDFURL = "+stringField(pdfUrl)+ " where EI_REFNO = "+getBlueRefno();
+            sql= "update ElecInvoice set EI_REDPDFURL = "+stringField(pdfUrl)+ " where ei_allelectronicinvoicenumber = "+getBlueRefno()+" and ei_relativerefno = "+stringField(allElectronicInvoiceNumber);
         }
         return sql;
     }

+ 2 - 0
src/main/java/com/uas/eis/service/ERPService.java

@@ -21,4 +21,6 @@ public interface ERPService {
     Map<String, Object> rushRed(String master, int id);
     Map<String, Object> queryInvoiceRedConfirm(Map<String,Object> m);
     Map<String,Object> queryRedPdfUrl(List<String> serialNosAll, Map<String,Object> m);
+
+    Map<String, Object> getRedReturnElecInvoices(Map<String,Object> m);
 }

+ 378 - 247
src/main/java/com/uas/eis/service/Impl/ERPServiceImpl.java

@@ -32,7 +32,7 @@ import java.util.stream.Stream;
 @Service
 public class ERPServiceImpl implements ERPService {
     private final Logger logger = LoggerFactory.getLogger(this.getClass());
-    private static Map<String,String> tokenConfig = TokenProperties.getAllProperty();
+    private static Map<String, String> tokenConfig = TokenProperties.getAllProperty();
 
     @Autowired
     private BaseDao baseDao;
@@ -43,36 +43,37 @@ public class ERPServiceImpl implements ERPService {
     private CommonService commonService;
     @Autowired
     private NuoNuoSDKService nuoNuoSDKService;
+
     @Override
     public Map<String, Object> pushInvoiceOrder(String master, int id) {
         Map<String, Object> map = new HashMap<String, Object>();
-        Object[] obs=baseDao.getFieldsDataByCondition("YITOA_DATACENTER.dock_invoice_config",new String[]{"appKey","appSecret","token","taxnum"},"username='"+master+"'");
-        String url=donlimConfig.getRoute();
+        Object[] obs = baseDao.getFieldsDataByCondition("YITOA_DATACENTER.dock_invoice_config", new String[]{"appKey", "appSecret", "token", "taxnum"}, "username='" + master + "'");
+        String url = donlimConfig.getRoute();
         System.out.println(url);
         String appKey = donlimConfig.getAppKey();
         String appSecret = donlimConfig.getAppSecret();
-        String token =  donlimConfig.getToken();
-        String taxnum=  donlimConfig.getTaxnum();
-        if(donlimConfig.isProd()){
-             appKey =  obs[0].toString();
-             appSecret =  obs[1].toString();
-             token = obs[2].toString();// 访问令牌
-             taxnum = obs[3].toString();// 授权企业税号
+        String token = donlimConfig.getToken();
+        String taxnum = donlimConfig.getTaxnum();
+        if (donlimConfig.isProd()) {
+            appKey = obs[0].toString();
+            appSecret = obs[1].toString();
+            token = obs[2].toString();// 访问令牌
+            taxnum = obs[3].toString();// 授权企业税号
         }
-        logger.info("pushInvoiceOrder begin: master {} ,id {} ",master,id);
+        logger.info("pushInvoiceOrder begin: master {} ,id {} ", master, id);
         SpObserver.putSp(master);
         SqlRowList rs_main = baseDao.queryForRowSet("select * from invoiceOrder left join customer on io_cucode=cu_code " +
                 " left join YITOA_DATACENTER.custinvoicemsg on ci_cucode = cu_code " +
-                " where io_id="+id);
-        if(rs_main.next()){
+                " where io_id=" + id);
+        if (rs_main.next()) {
             //String autoInvoiceFlag= baseDao.isDBSetting("InvoiceOrder", "autoInvoice")?"true":"false";
             //数据组装
-            InvoiceOrderDTO invoiceOrderDTO=new InvoiceOrderDTO();
+            InvoiceOrderDTO invoiceOrderDTO = new InvoiceOrderDTO();
             invoiceOrderDTO.setOrderType(rs_main.getGeneralString("IO_ORDERTYPE"));
-            invoiceOrderDTO.setAutoInvoiceFlag(rs_main.getGeneralString("io_autoinvoice") );//自动开票
+            invoiceOrderDTO.setAutoInvoiceFlag(rs_main.getGeneralString("io_autoinvoice"));//自动开票
             invoiceOrderDTO.setRepeatCall("0");
 
-            OrderDTO orderDTO=new OrderDTO();
+            OrderDTO orderDTO = new OrderDTO();
             orderDTO.setOriginalOrderNo(rs_main.getGeneralString("io_code"));
             orderDTO.setAddDate(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(rs_main.getDate("io_date")));
             orderDTO.setInvoiceLine(rs_main.getGeneralString("io_invoiceline"));
@@ -94,10 +95,10 @@ public class ERPServiceImpl implements ERPService {
             orderDTO.setYfphm(rs_main.getGeneralString("io_Yfphm"));
             invoiceOrderDTO.setOrderInfo(orderDTO);
 
-            SqlRowList rs_det = baseDao.queryForRowSet("select * from invoiceOrderdet_view where id_ioid="+id+" order by id_detno");
-            List<OrderDetDTO> dets=new ArrayList<>();//商品列表
-            while(rs_det.next()){
-                OrderDetDTO orderDetDTO=new OrderDetDTO();
+            SqlRowList rs_det = baseDao.queryForRowSet("select * from invoiceOrderdet_view where id_ioid=" + id + " order by id_detno");
+            List<OrderDetDTO> dets = new ArrayList<>();//商品列表
+            while (rs_det.next()) {
+                OrderDetDTO orderDetDTO = new OrderDetDTO();
                 orderDetDTO.setRowNo(rs_det.getGeneralString("id_id"));//唯一值
                 orderDetDTO.setGoodsName(rs_det.getGeneralString("pr_detail"));
                 orderDetDTO.setSpec(rs_det.getGeneralString("pr_spec"));
@@ -117,31 +118,31 @@ public class ERPServiceImpl implements ERPService {
             //调用对接
             NNOpenSDK sdk = NNOpenSDK.getIntance();
             String method = "nuonuo.OpeMplatform.saveOrder"; // API方法名
-            String content =sdk.convertToUtf8(JSONArray.toJSONString(invoiceOrderDTO));
+            String content = sdk.convertToUtf8(JSONArray.toJSONString(invoiceOrderDTO));
             String senid = UUID.randomUUID().toString().replace("-", ""); // 唯一标识,32位随机码,无需修改,保持默认即可
             String result = sdk.sendPostSyncRequest(url, senid, appKey, appSecret, token, taxnum, method, content);
-            logger.info("pushInvoiceOrder resultString {}, token {}",result,token);
-            Map<Object, Object> res=JSONUtil.toMap(result);
+            logger.info("pushInvoiceOrder resultString {}, token {}", result, token);
+            Map<Object, Object> res = JSONUtil.toMap(result);
             System.out.println(result);
-            Object status=res.get("status");
-            Object message=res.get("message");
-            if(status !=null && "0000".equals(status.toString())){//调用成功
-                baseDao.execute("update invoiceOrder set io_dockstatus='对接成功',IO_INVOICESTATUS=0 where io_id="+id);
-                commonService.logSRecord("开票订单对接",id);
-            }else if(status !=null && "9999".equals(status.toString()) && message != null && message.toString().contains("已存在原始订单")){
-                baseDao.execute("update invoiceOrder set io_dockstatus='对接成功',IO_INVOICESTATUS=0 where io_id="+id);
-                commonService.logFRecord("开票订单对接","("+status+")"+message,id);
-            }else{
-                baseDao.execute("update invoiceOrder set io_dockstatus='对接失败' where io_id="+id);
-                commonService.logFRecord("开票订单对接","("+status+")"+message,id);
+            Object status = res.get("status");
+            Object message = res.get("message");
+            if (status != null && "0000".equals(status.toString())) {//调用成功
+                baseDao.execute("update invoiceOrder set io_dockstatus='对接成功',IO_INVOICESTATUS=0 where io_id=" + id);
+                commonService.logSRecord("开票订单对接", id);
+            } else if (status != null && "9999".equals(status.toString()) && message != null && message.toString().contains("已存在原始订单")) {
+                baseDao.execute("update invoiceOrder set io_dockstatus='对接成功',IO_INVOICESTATUS=0 where io_id=" + id);
+                commonService.logFRecord("开票订单对接", "(" + status + ")" + message, id);
+            } else {
+                baseDao.execute("update invoiceOrder set io_dockstatus='对接失败' where io_id=" + id);
+                commonService.logFRecord("开票订单对接", "(" + status + ")" + message, id);
             }
-            logger.info("pushInvoiceOrder master {} ,id {} status {} message {}",master,id,status,message);
+            logger.info("pushInvoiceOrder master {} ,id {} status {} message {}", master, id, status, message);
             map.put("success", true);
             map.put("status", status);
             map.put("message", message);
             return map;
-        }else{//数据无效
-            logger.info("pushInvoiceOrder err {对接源信息无效} ,master {} , id {} status {} message {}",master,id);
+        } else {//数据无效
+            logger.info("pushInvoiceOrder err {对接源信息无效} ,master {} , id {} status {} message {}", master, id);
             map.put("success", false);
             map.put("message", "对接源信息无效");
             return map;
@@ -150,33 +151,33 @@ public class ERPServiceImpl implements ERPService {
 
     @Override
     public Map<String, Object> invoiceOrderSubmitKp(String master, int id) {
-        Object[] obs=baseDao.getFieldsDataByCondition("YITOA_DATACENTER.dock_invoice_config",new String[]{"appKey","appSecret","token","taxnum"},"username='"+master+"'");
-        String url=donlimConfig.getRoute();
+        Object[] obs = baseDao.getFieldsDataByCondition("YITOA_DATACENTER.dock_invoice_config", new String[]{"appKey", "appSecret", "token", "taxnum"}, "username='" + master + "'");
+        String url = donlimConfig.getRoute();
         System.out.println(url);
         String appKey = donlimConfig.getAppKey();
         String appSecret = donlimConfig.getAppSecret();
-        String token =  donlimConfig.getToken();
-        String taxnum=  donlimConfig.getTaxnum();
-        if(donlimConfig.isProd()){
-            appKey =  obs[0].toString();
-            appSecret =  obs[1].toString();
+        String token = donlimConfig.getToken();
+        String taxnum = donlimConfig.getTaxnum();
+        if (donlimConfig.isProd()) {
+            appKey = obs[0].toString();
+            appSecret = obs[1].toString();
             token = obs[2].toString();// 访问令牌
             taxnum = obs[3].toString();// 授权企业税号
         }
         SpObserver.putSp(master);
-        SqlRowList rs_main = baseDao.queryForRowSet("select * from invoiceOrder left join customer on io_cucode=cu_code where io_id="+id);
-        if(rs_main.next()){
+        SqlRowList rs_main = baseDao.queryForRowSet("select * from invoiceOrder left join customer on io_cucode=cu_code where io_id=" + id);
+        if (rs_main.next()) {
             NNOpenSDK sdk = NNOpenSDK.getIntance();
             String method = "nuonuo.OpeMplatform.submitKp"; // API方法名
-            String code= rs_main.getGeneralString("io_code");
-            Map<String,String> reqParam=new HashMap<>();
-            reqParam.put("orderNo",code);
-            String content=JSONArray.toJSONString(reqParam);
+            String code = rs_main.getGeneralString("io_code");
+            Map<String, String> reqParam = new HashMap<>();
+            reqParam.put("orderNo", code);
+            String content = JSONArray.toJSONString(reqParam);
             String senid = UUID.randomUUID().toString().replace("-", ""); // 唯一标识,32位随机码,无需修改,保持默认即可
             String result = sdk.sendPostSyncRequest(url, senid, appKey, appSecret, token, taxnum, method, content);
             System.out.println(result);
-        }else{//数据无效
-            logger.info("findOrderState err {对接源信息无效} ,master {} , id {} status {} message {}",master,id);
+        } else {//数据无效
+            logger.info("findOrderState err {对接源信息无效} ,master {} , id {} status {} message {}", master, id);
         }
 
         return null;
@@ -185,50 +186,51 @@ public class ERPServiceImpl implements ERPService {
     @Override
     public Map<String, Object> findOrderState(String master, int id) {
         Map<String, Object> map = new HashMap<String, Object>();
-        Object[] obs=baseDao.getFieldsDataByCondition("YITOA_DATACENTER.dock_invoice_config",new String[]{"appKey","appSecret","token","taxnum"},"username='"+master+"'");
-        if(obs==null){
+        Object[] obs = baseDao.getFieldsDataByCondition("YITOA_DATACENTER.dock_invoice_config", new String[]{"appKey", "appSecret", "token", "taxnum"}, "username='" + master + "'");
+        if (obs == null) {
             return null;//对接信息为配置
         }
-        String url=donlimConfig.getRoute();
+        String url = donlimConfig.getRoute();
         String appKey = donlimConfig.getAppKey();
         String appSecret = donlimConfig.getAppSecret();
-        String token =  donlimConfig.getToken();
-        String taxnum=  donlimConfig.getTaxnum();
-        if(donlimConfig.isProd()){
-            appKey =  obs[0].toString();
-            appSecret =  obs[1].toString();
+        String token = donlimConfig.getToken();
+        String taxnum = donlimConfig.getTaxnum();
+        if (donlimConfig.isProd()) {
+            appKey = obs[0].toString();
+            appSecret = obs[1].toString();
             token = obs[2].toString();// 访问令牌
             taxnum = obs[3].toString();// 授权企业税号
         }
         SpObserver.putSp(master);
-        SqlRowList rs_main = baseDao.queryForRowSet("select * from invoiceOrder left join customer on io_cucode=cu_code where io_id="+id);
-        if(rs_main.next()){
-            String code= rs_main.getGeneralString("io_code");
+        SqlRowList rs_main = baseDao.queryForRowSet("select * from invoiceOrder left join customer on io_cucode=cu_code where io_id=" + id);
+        if (rs_main.next()) {
+            String code = rs_main.getGeneralString("io_code");
             NNOpenSDK sdk = NNOpenSDK.getIntance();
             String method = "nuonuo.OpeMplatform.findOrderState"; // API方法名
-            Map<String,String> reqParam=new HashMap<>();
-            reqParam.put("originalOrderNo",code);
-            reqParam.put("saleTaxNum",taxnum);
-            String content=JSONArray.toJSONString(reqParam);
+            Map<String, String> reqParam = new HashMap<>();
+            reqParam.put("originalOrderNo", code);
+            reqParam.put("saleTaxNum", taxnum);
+            String content = JSONArray.toJSONString(reqParam);
             String senid = UUID.randomUUID().toString().replace("-", ""); // 唯一标识,32位随机码,无需修改,保持默认即可
             String result = sdk.sendPostSyncRequest(url, senid, appKey, appSecret, token, taxnum, method, content);
             System.out.println(result);
-            FindOrderStateResp resp = JSON.parseObject(result , new TypeReference<FindOrderStateResp>() {});
+            FindOrderStateResp resp = JSON.parseObject(result, new TypeReference<FindOrderStateResp>() {
+            });
             System.out.println(resp.getCode());
             System.out.println(resp.getMessage());
-            if("该订单不存在".equals(resp.getMessage())){
-                baseDao.execute("update invoiceOrder set IO_INVOICESTATUS = '-1' where io_id = '"+id+"'");
-            }else{
-                baseDao.execute("update invoiceOrder set IO_INVOICESTATUS = '"+resp.getData().getInvoiceStatus()+"'"
-                        +",io_errorMsg='"+StringUtil.nvl(resp.getData().getErrorMsg(),"")+"'"
-                        +" where io_id = '"+id+"'");
+            if ("该订单不存在".equals(resp.getMessage())) {
+                baseDao.execute("update invoiceOrder set IO_INVOICESTATUS = '-1' where io_id = '" + id + "'");
+            } else {
+                baseDao.execute("update invoiceOrder set IO_INVOICESTATUS = '" + resp.getData().getInvoiceStatus() + "'"
+                        + ",io_errorMsg='" + StringUtil.nvl(resp.getData().getErrorMsg(), "") + "'"
+                        + " where io_id = '" + id + "'");
             }
 
             map.put("success", true);
             map.put("result", result);
             return map;
-        }else{//数据无效
-            logger.info("findOrderState err {对接源信息无效} ,master {} , id {} status {} message {}",master,id);
+        } else {//数据无效
+            logger.info("findOrderState err {对接源信息无效} ,master {} , id {} status {} message {}", master, id);
         }
         return null;
     }
@@ -236,57 +238,57 @@ public class ERPServiceImpl implements ERPService {
     @Override
     public Map<String, Object> cancelInvoiceOrder(String master, int id) {
         Map<String, Object> map = new HashMap<String, Object>();
-        Object[] obs=baseDao.getFieldsDataByCondition("YITOA_DATACENTER.dock_invoice_config",new String[]{"appKey","appSecret","token","taxnum"},"username='"+master+"'");
-        if(obs==null){
+        Object[] obs = baseDao.getFieldsDataByCondition("YITOA_DATACENTER.dock_invoice_config", new String[]{"appKey", "appSecret", "token", "taxnum"}, "username='" + master + "'");
+        if (obs == null) {
             return null;//对接信息为配置
         }
-        String url=donlimConfig.getRoute();
+        String url = donlimConfig.getRoute();
         System.out.println(url);
         String appKey = donlimConfig.getAppKey();
         String appSecret = donlimConfig.getAppSecret();
-        String token =  donlimConfig.getToken();
-        String taxnum=  donlimConfig.getTaxnum();
-        if(donlimConfig.isProd()){
+        String token = donlimConfig.getToken();
+        String taxnum = donlimConfig.getTaxnum();
+        if (donlimConfig.isProd()) {
             System.out.println("prod");
-            appKey =  obs[0].toString();
-            appSecret =  obs[1].toString();
+            appKey = obs[0].toString();
+            appSecret = obs[1].toString();
             token = obs[2].toString();// 访问令牌
             taxnum = obs[3].toString();// 授权企业税号
-        }else{
+        } else {
             System.out.println("dev");
         }
         SpObserver.putSp(master);
-        SqlRowList rs_main = baseDao.queryForRowSet("select * from invoiceOrder left join customer on io_cucode=cu_code where io_id="+id);
-        if(rs_main.next()){
-            String code= rs_main.getGeneralString("io_code");
-            Map<String,String> reqParam=new HashMap<>();
-            reqParam.put("originalOrderNo",code);
-            reqParam.put("saleTaxNum",taxnum);
+        SqlRowList rs_main = baseDao.queryForRowSet("select * from invoiceOrder left join customer on io_cucode=cu_code where io_id=" + id);
+        if (rs_main.next()) {
+            String code = rs_main.getGeneralString("io_code");
+            Map<String, String> reqParam = new HashMap<>();
+            reqParam.put("originalOrderNo", code);
+            reqParam.put("saleTaxNum", taxnum);
 
-            String content=JSONArray.toJSONString(reqParam);
+            String content = JSONArray.toJSONString(reqParam);
             NNOpenSDK sdk = NNOpenSDK.getIntance();
             String method = "nuonuo.OpeMplatform.deleteOrder"; // API方法名
             String senid = UUID.randomUUID().toString().replace("-", ""); // 唯一标识,32位随机码,无需修改,保持默认即可
             String result = sdk.sendPostSyncRequest(url, senid, appKey, appSecret, token, taxnum, method, content);
-            Map<Object, Object> res=JSONUtil.toMap(result);
+            Map<Object, Object> res = JSONUtil.toMap(result);
             System.out.println(result);
-            Object status=res.get("status");
-            Object message=res.get("message");
-            if(status !=null && "0000".equals(status.toString())){//调用成功
-                baseDao.execute("update invoiceOrder set io_dockstatus='' where io_id="+id);
-                baseDao.execute("insert into invoicedockLog(id_,code_,date_,result_,err_,keyvalue_)values(invoicedockLog_seq.nextval,'开票订单删除',sysdate,'SUCCEED','',"+id+") ");
+            Object status = res.get("status");
+            Object message = res.get("message");
+            if (status != null && "0000".equals(status.toString())) {//调用成功
+                baseDao.execute("update invoiceOrder set io_dockstatus='' where io_id=" + id);
+                baseDao.execute("insert into invoicedockLog(id_,code_,date_,result_,err_,keyvalue_)values(invoicedockLog_seq.nextval,'开票订单删除',sysdate,'SUCCEED',''," + id + ") ");
                 map.put("success", true);
                 map.put("message", message);
-            }else{
-                baseDao.execute("update invoiceOrder set io_dockstatus='取消失败' where io_id="+id);
-                baseDao.execute("insert into invoicedockLog(id_,code_,date_,result_,err_,keyvalue_)values(invoicedockLog_seq.nextval,'开票订单删除',sysdate,'FAILED','("+status+")"+message+"',"+id+") ");
+            } else {
+                baseDao.execute("update invoiceOrder set io_dockstatus='取消失败' where io_id=" + id);
+                baseDao.execute("insert into invoicedockLog(id_,code_,date_,result_,err_,keyvalue_)values(invoicedockLog_seq.nextval,'开票订单删除',sysdate,'FAILED','(" + status + ")" + message + "'," + id + ") ");
                 map.put("success", false);
-                map.put("message", "("+status+")"+message);
+                map.put("message", "(" + status + ")" + message);
             }
-            logger.info("cancelInvoiceOrder master {} ,id {} status {} message {}",master,id,status,message);
+            logger.info("cancelInvoiceOrder master {} ,id {} status {} message {}", master, id, status, message);
             return map;
-        }else{//数据无效
-            logger.info("cancelInvoiceOrder err {对接源信息无效} ,master {} , id {} status {} message {}",master,id);
+        } else {//数据无效
+            logger.info("cancelInvoiceOrder err {对接源信息无效} ,master {} , id {} status {} message {}", master, id);
         }
         return null;
     }
@@ -294,39 +296,44 @@ public class ERPServiceImpl implements ERPService {
     @Override
     public Map<String, Object> getElecInvoicesById(String master, Integer id) {
         Map<String, Object> map = new HashMap<String, Object>();
-        Object[] obs=baseDao.getFieldsDataByCondition("YITOA_DATACENTER.dock_invoice_config",new String[]{"appKey","appSecret","token","taxnum"},"username='"+master+"'");
-        if(obs==null){
+        Object[] obs = baseDao.getFieldsDataByCondition("YITOA_DATACENTER.dock_invoice_config", new String[]{"appKey", "appSecret", "token", "taxnum"}, "username='" + master + "'");
+        if (obs == null) {
             return null;//对接信息为配置
         }
 //        System.out.println(url);
         String appKey = donlimConfig.getAppKey();
         String appSecret = donlimConfig.getAppSecret();
-        String token =  donlimConfig.getToken();
-        String taxnum=  donlimConfig.getTaxnum();
-        logger.info("ElecI-getElecInvoicesById:master {} isProd {}",SpObserver.getSp(),donlimConfig.isProd());
-        if(donlimConfig.isProd()){
-            appKey =  obs[0].toString();
-            appSecret =  obs[1].toString();
+        String token = donlimConfig.getToken();
+        String taxnum = donlimConfig.getTaxnum();
+        logger.info("ElecI-getElecInvoicesById:master {} isProd {}", SpObserver.getSp(), donlimConfig.isProd());
+        if (donlimConfig.isProd()) {
+            appKey = obs[0].toString();
+            appSecret = obs[1].toString();
             token = obs[2].toString();// 访问令牌
             taxnum = obs[3].toString();// 授权企业税号
         }
-        Map<String,Object> m = new HashMap<>();
-        m.put("appKey",appKey);
-        m.put("appSecret",appSecret);
-        m.put("token",token);
-        m.put("taxnum",taxnum);
+        Map<String, Object> m = new HashMap<>();
+        m.put("appKey", appKey);
+        m.put("appSecret", appSecret);
+        m.put("token", token);
+        m.put("taxnum", taxnum);
         SpObserver.putSp(master);
-        SqlRowList ioList = baseDao.queryForRowSet("select io_id,io_code from "+master+".invoiceOrder left join "+master+".customer on io_cucode=cu_code " +
-                " where io_id = "+id);
-        while(ioList.next()) {
-            m.put("io_id",ioList.getGeneralInt("io_id"));
-            m.put("io_code",ioList.getGeneralString("io_code"));
+        SqlRowList ioList = baseDao.queryForRowSet("select io_id,io_code,io_ordertype from " + master + ".invoiceOrder left join " + master + ".customer on io_cucode=cu_code " +
+                " where io_id = " + id);
+        while (ioList.next()) {
+            m.put("io_id", ioList.getGeneralInt("io_id"));
+            m.put("io_code", ioList.getGeneralString("io_code"));
+            m.put("io_ordertype", ioList.getGeneralInt("io_ordertype"));
             map = getElecInvoices(m);
         }
         return map;
     }
+
     @Override
-    public Map<String, Object> getElecInvoices(Map<String,Object> m){
+    public Map<String, Object> getElecInvoices(Map<String, Object> m) {
+        if (Integer.valueOf(m.get("io_ordertype").toString()).equals(2)) {
+            return getRedReturnElecInvoices(m);
+        }
         String taxnum = m.get("taxnum").toString();
         int ioid = Integer.valueOf(m.get("io_id").toString());
         String ioCode = m.get("io_code").toString();
@@ -339,61 +346,66 @@ public class ERPServiceImpl implements ERPService {
             foriReq.setOriginalOrderNo(ioCode);//订单编号
             foriReq.setSaleTaxNum(taxnum);//销方税号
             foriReq.setNeedInvoiceSourceDetail("1");//是否需要发票所来源的订单明细,1-是, 0-否(不填默认 0) 当为0时,将不回传orderDetailCallBackVOS。先默认不需要明细
-            FindOrderRelationInvoiceResp resp = nuoNuoSDKService.findOrderRelationInvoice(foriReq,m);
+            FindOrderRelationInvoiceResp resp = nuoNuoSDKService.findOrderRelationInvoice(foriReq, m);
             errCode = resp.getStatus();
             errMsg = resp.getMessage();
-            logger.info("ElecI-DownLoad-master: {} ,id {} status {} message {}",SpObserver.getSp(),ioid,errCode,errMsg);
-            if("0000".equals(errCode)){//调用成功
+            logger.info("ElecI-DownLoad-master: {} ,id {} status {} message {}", SpObserver.getSp(), ioid, errCode, errMsg);
+            if ("0000".equals(errCode)) {//调用成功
                 //记录发票明细
-                baseDao.execute(getElecInvoicesSqls(ioid,resp.getData()));
+                baseDao.execute(getElecInvoicesSqls(ioid, resp.getData()));
                 //红字
-                commonService.logSRecord("订单关联发票对接",ioid);
-            }else if(!"8958".equals(errCode)){//  {"status":"8958","message":"该订单对应的开票单不存在","data":null} 没有开票单的不记录对接失败日志
-                if(errMsg.length() > 3980){
-                    errMsg = errMsg.substring(0,3980);
+                commonService.logSRecord("订单关联发票对接", ioid);
+            } else if (!"8958".equals(errCode)) {//  {"status":"8958","message":"该订单对应的开票单不存在","data":null} 没有开票单的不记录对接失败日志
+                if (errMsg.length() > 3980) {
+                    errMsg = errMsg.substring(0, 3980);
                 }
-                baseDao.execute("update invoiceOrder set io_errorMsg='订单关联发票查询失败: "+errMsg+"' where io_id="+ioid);
-                commonService.logFRecord("订单关联发票对接","("+errCode+")"+errMsg,ioid);
+                baseDao.execute("update invoiceOrder set io_errorMsg='订单关联发票查询失败: " + errMsg + "' where io_id=" + ioid);
+                commonService.logFRecord("订单关联发票对接", "(" + errCode + ")" + errMsg, ioid);
             }
-        }catch (Exception e){
+        } catch (Exception e) {
             e.printStackTrace();
             errMsg = "发票获取异常";
-            if(StringUtil.hasText(e.getMessage())){
+            if (StringUtil.hasText(e.getMessage())) {
                 errMsg = e.getMessage();
-            }else if(e.getCause()!=null&&StringUtil.hasText(e.getCause().getMessage())){
+            } else if (e.getCause() != null && StringUtil.hasText(e.getCause().getMessage())) {
                 errMsg = e.getCause().getMessage();
             }
-            logger.info("ElecI-DownLoad-master: {} ,id {} message {}",SpObserver.getSp(),ioid,errMsg);
-            commonService.logFRecord("订单关联发票对接",errMsg.replaceAll("'","''"),ioid);
+            logger.info("ElecI-DownLoad-master: {} ,id {} message {}", SpObserver.getSp(), ioid, errMsg);
+            commonService.logFRecord("订单关联发票对接", errMsg.replaceAll("'", "''"), ioid);
         }
         //获取红字发票PDF地址
         List<String> serialNosAll = baseDao.queryForList("select ei_redsid from ElecInvoice " +
-                "where ei_ioid = "+ioid+" and EI_RELATIVEREFNO is not null and ei_redpdfurl is null and nvl(EI_BILLSTATUS,' ') in (' ','01','04')",String.class);
-        if (!CollectionUtil.isEmpty(serialNosAll)){
-            queryRedPdfUrl(serialNosAll,m);
+                "where ei_ioid = " + ioid + " and EI_RELATIVEREFNO is not null and ei_redpdfurl is null and nvl(EI_BILLSTATUS,' ') in (' ','01','04')", String.class);
+        if (!CollectionUtil.isEmpty(serialNosAll)) {
+            queryRedPdfUrl(serialNosAll, m);
         }
-//        queryRedPdfUrl()
-        if(StringUtil.hasText(errMsg)&&!"调用成功".equals(errMsg)){
+        if (StringUtil.hasText(errMsg) && !"调用成功".equals(errMsg)) {
             res.put("success", false);
             res.put("errCode", errCode);
             res.put("errMsg", errMsg);
-        }else {
+        } else {
             res.put("success", true);
         }
         return res;
     }
-    private List<String> getElecInvoicesSqls(int ioid,List<FindOrderRelationInvoiceDTO> data){
+
+    private List<String> getElecInvoicesSqls(int ioid, List<FindOrderRelationInvoiceDTO> data) {
         List<String> sqls = new ArrayList<String>();
-        boolean syncToBillOut = baseDao.isDBSetting("BillOut","syncToBillOut");
+        boolean syncToBillOut = baseDao.isDBSetting("BillOut", "syncToBillOut");
         for (int i = 0; i < data.size(); i++) {
             FindOrderRelationInvoiceDTO friDto = data.get(i);
-            sqls.addAll(friDto.toMergeSql(ioid,(i+1)));
+            sqls.addAll(friDto.toMergeSql(ioid, (i + 1)));
         }
-        sqls.add("update invoiceOrder set io_refno = (select (min(ei_refno)||(case when max(ei_refno) <> min(ei_refno) then '-'||max(ei_refno) else '' end)) from ELECINVOICE where ei_ioid = io_id and EI_INVOICETYPE= 1 and nvl(ei_rushredstate,0) <> 1)" +
-                "where io_id = "+ioid);
+        sqls.add(" update invoiceOrder set io_refno = (" +
+                "  select (min(ei_refno)||(case when max(ei_refno) <> min(ei_refno) then '-'||max(ei_refno) else '' end)) " +
+                "  from ELECINVOICE  " +
+                "     where ei_ioid = io_id and EI_INVOICETYPE = 1 " +
+                "        and ( nvl(ei_rushredstate,0) <> 1 or (nvl(ei_rushredstate,0) = 1 and exists (Select 1 from invoiceOrder redio where redio.io_ordertype=2 and redio.io_yfphm = ei_refno)) ) " +
+                "     ) " +
+                "  where io_id = " + ioid);
         //更新开票记录
-        if(syncToBillOut){
-            sqls.add("update BillOut set bi_refno = (select max(io_refno) from invoiceOrder where io_id = "+ioid+" and io_biid = bi_id) where bi_id in (select io_biid from invoiceOrder where io_id = "+ioid+" and io_refno is not null)");
+        if (syncToBillOut) {
+            sqls.add("update BillOut set bi_refno = (select max(io_refno) from invoiceOrder where io_id = " + ioid + " and io_biid = bi_id) where bi_id in (select io_biid from invoiceOrder where io_id = " + ioid + " and io_refno is not null)");
         }
 //        System.out.println("sqls:");
 //        System.out.println(sqls.toString());
@@ -403,32 +415,32 @@ public class ERPServiceImpl implements ERPService {
     @Override
     public Map<String, Object> rushRed(String master, int id) {
         Map<String, Object> map = new HashMap<String, Object>();
-        Object[] obs=baseDao.getFieldsDataByCondition("YITOA_DATACENTER.dock_invoice_config",new String[]{"appKey","appSecret","token","taxnum"},"username='"+master+"'");
-        String url=donlimConfig.getRoute();
+        Object[] obs = baseDao.getFieldsDataByCondition("YITOA_DATACENTER.dock_invoice_config", new String[]{"appKey", "appSecret", "token", "taxnum"}, "username='" + master + "'");
+        String url = donlimConfig.getRoute();
         String appKey = donlimConfig.getAppKey();
         String appSecret = donlimConfig.getAppSecret();
-        String token =  donlimConfig.getToken();
-        String taxnum=  donlimConfig.getTaxnum();
-        if(donlimConfig.isProd()){
-            appKey =  obs[0].toString();
-            appSecret =  obs[1].toString();
+        String token = donlimConfig.getToken();
+        String taxnum = donlimConfig.getTaxnum();
+        if (donlimConfig.isProd()) {
+            appKey = obs[0].toString();
+            appSecret = obs[1].toString();
             token = obs[2].toString();// 访问令牌
             taxnum = obs[3].toString();// 授权企业税号
         }
-        Map<String,Object> m = new HashMap<>();
-        m.put("appKey",appKey);
-        m.put("appSecret",appSecret);
-        m.put("token",token);
-        m.put("taxnum",taxnum);
-        logger.info("rushRed begin: master {} ,id {} ",master,id);
+        Map<String, Object> m = new HashMap<>();
+        m.put("appKey", appKey);
+        m.put("appSecret", appSecret);
+        m.put("token", token);
+        m.put("taxnum", taxnum);
+        logger.info("rushRed begin: master {} ,id {} ", master, id);
         SpObserver.putSp(master);
         StringBuffer errmsg = new StringBuffer();
         StringBuffer remindmsg = new StringBuffer();
-        SqlRowList rs_main = baseDao.queryForRowSet("select * from invoiceOrder left join customer on io_cucode=cu_code left join elecinvoice on io_id=ei_ioid where io_id="+id+" and nvl(ei_redapplyid,' ')=' ' and nvl(EI_INVOICESTATE,0)=1 and nvl(EI_INVOICETYPE,0)=1 ");
-        if (rs_main.hasNext()){
+        SqlRowList rs_main = baseDao.queryForRowSet("select * from invoiceOrder left join customer on io_cucode=cu_code left join elecinvoice on io_id=ei_ioid where io_id=" + id + " and nvl(ei_redapplyid,' ')=' ' and nvl(EI_INVOICESTATE,0)=1 and nvl(EI_INVOICETYPE,0)=1 ");
+        if (rs_main.hasNext()) {
             int scount = 0;
-            while(rs_main.next()){
-                RedInvoiceReq redInvoiceReq=new RedInvoiceReq();
+            while (rs_main.next()) {
+                RedInvoiceReq redInvoiceReq = new RedInvoiceReq();
                 redInvoiceReq.setBlueInvoiceLine(rs_main.getGeneralString("io_invoiceline"));//蓝票发票种类
                 redInvoiceReq.setApplySource("0");//申请方(录入方)身份: 0 销方 1 购方
                 redInvoiceReq.setSellerTaxNo(donlimConfig.getTaxnum());//销方税号
@@ -438,54 +450,55 @@ public class ERPServiceImpl implements ERPService {
                 //redInvoiceReq.setAutoInvoice("1");//测试是否能自动红冲目前参数无效
                 redInvoiceReq.setBlueElecInvoiceNumber(rs_main.getGeneralString("ei_allelectronicinvoicenumber"));
                 NNOpenSDK sdk = NNOpenSDK.getIntance();
-                String content =sdk.convertToUtf8(JSONArray.toJSONString(redInvoiceReq));
+                String content = sdk.convertToUtf8(JSONArray.toJSONString(redInvoiceReq));
                 String method = "nuonuo.OpeMplatform.saveInvoiceRedConfirm"; // API方法名
                 String senid = UUID.randomUUID().toString().replace("-", ""); // 唯一标识,32位随机码,无需修改,保持默认即可
                 String resp = sdk.sendPostSyncRequest(url, senid, appKey, appSecret, token, taxnum, method, content);
-                Map<Object, Object> res=JSONUtil.toMap(resp);
-                Object code=res.get("code");
-                Object describe=res.get("describe");
-                Object result=res.get("result");
-                logger.info("rushRed master {} ,id {} code {} describe {} applycode {}",master,id,code,describe,result);
-                if(code !=null && "E0000".equals(code.toString())){//调用成功
-                    baseDao.execute("update elecinvoice set ei_redapplyid='"+result.toString()+"' where ei_id="+rs_main.getGeneralInt("ei_id"));
+                Map<Object, Object> res = JSONUtil.toMap(resp);
+                Object code = res.get("code");
+                Object describe = res.get("describe");
+                Object result = res.get("result");
+                logger.info("rushRed master {} ,id {} code {} describe {} applycode {}", master, id, code, describe, result);
+                if (code != null && "E0000".equals(code.toString())) {//调用成功
+                    baseDao.execute("update elecinvoice set ei_redapplyid='" + result.toString() + "' where ei_id=" + rs_main.getGeneralInt("ei_id"));
                     scount++;
-                    commonService.logSRecord("红字确认单申请("+rs_main.getGeneralString("ei_refno")+")",id);
-                }else{
+                    commonService.logSRecord("红字确认单申请(" + rs_main.getGeneralString("ei_refno") + ")", id);
+                } else {
                     //E9755 describe 该发票存在进行中的红字确认单,暂时不能冲红
-                    commonService.logFRecord("红字确认单申请("+rs_main.getGeneralInt("ei_id")+")","("+code+")"+describe,id);
-                    errmsg.append("("+code+")"+describe).append("</br>");
+                    commonService.logFRecord("红字确认单申请(" + rs_main.getGeneralInt("ei_id") + ")", "(" + code + ")" + describe, id);
+                    errmsg.append("(" + code + ")" + describe).append("</br>");
                 }
             }
             //没有自动开红票 但是可以拿状态
-            if(scount > 0){
-                m.put("io_id",id);
-                m.put("ei_id",0);
+            if (scount > 0) {
+                m.put("io_id", id);
+                m.put("ei_id", 0);
                 //获取红字确认状态等信息,若自动开票成功,则同时获取红票信息
                 Map<String, Object> mm = queryInvoiceRedConfirm(m);
-                if("false".equals(mm.get("success"))&&StringUtil.hasText(mm.get("errMsg"))){
+                if ("false".equals(mm.get("success")) && StringUtil.hasText(mm.get("errMsg"))) {
                     remindmsg.append(mm.get("errMsg"));
                 }
             }
         } else {//数据无效
-            logger.info("rushRed err {对接源信息无效} ,master {} , id {} status {} message {}",master,id);
+            logger.info("rushRed err {对接源信息无效} ,master {} , id {} status {} message {}", master, id);
             errmsg.append("对接源信息无效");
             return map;
         }
-        if(errmsg.length()>0){
+        if (errmsg.length() > 0) {
             map.put("success", false);
-            if(remindmsg.length()>0){
+            if (remindmsg.length() > 0) {
                 errmsg.append(remindmsg.toString());
             }
             map.put("message", errmsg.toString());
-        }else {
+        } else {
             map.put("success", true);
-            if(remindmsg.length()>0){
+            if (remindmsg.length() > 0) {
                 map.put("message", remindmsg.toString());
             }
         }
         return map;
     }
+
     /*
         条件:蓝票、有确认单号、待确认或者无需确认的情况下 持续获取红票相关信息
         按照红冲确认单查询对应状态
@@ -494,22 +507,22 @@ public class ERPServiceImpl implements ERPService {
         冲红原因: 1销货退回 2开票有误 3服务中止 4销售折让
      */
     @Override
-    public Map<String, Object> queryInvoiceRedConfirm(Map<String,Object> m) {
+    public Map<String, Object> queryInvoiceRedConfirm(Map<String, Object> m) {
         int ioid = Integer.valueOf(m.get("io_id").toString());
         int eiid = Integer.valueOf(m.get("ei_id").toString());
         Map<String, Object> res = new HashMap<String, Object>();
         StringBuffer errmsg = new StringBuffer();
         SqlRowList bluePiao = baseDao.queryForRowSet("select ei_id,ei_redapplyid,ei_billStatus,ei_billNo,ei_billUuid,ei_taxExcludedAmount,ei_taxAmount,ei_redReason " +
                 "from elecinvoice " +
-                "where ei_ioid = '"+ioid+"' "+(eiid>0?"and ei_id = "+eiid:"")
-                +" and EI_INVOICETYPE = '1' and ei_redapplyid is not null and EI_RELATIVEREFNO is null and nvl(ei_billStatus,' ') in (' ','01','02','03','15') " +
+                "where ei_ioid = '" + ioid + "' " + (eiid > 0 ? "and ei_id = " + eiid : "")
+                + " and EI_INVOICETYPE = '1' and ei_redapplyid is not null and EI_RELATIVEREFNO is null and nvl(ei_billStatus,' ') in (' ','01','02','03','15') " +
                 "order by ei_Detno");
-        if(bluePiao.hasNext()){
+        if (bluePiao.hasNext()) {
             boolean isRushRedBill = false;
-            while (bluePiao.next()){
-                String redApplyId =bluePiao.getGeneralString("ei_redapplyid");
+            while (bluePiao.next()) {
+                String redApplyId = bluePiao.getGeneralString("ei_redapplyid");
                 eiid = bluePiao.getGeneralInt("ei_id");
-                m.put("ei_id",eiid);
+                m.put("ei_id", eiid);
                 QueryInvoiceRedConfirmReq qircReq = new QueryInvoiceRedConfirmReq();
                 qircReq.setIdentity("0");
                 qircReq.setBillId(redApplyId);
@@ -517,116 +530,234 @@ public class ERPServiceImpl implements ERPService {
                 String describe = "";
                 String logCode = "发票红字确认状态查询";
                 try {
-                    QueryInvoiceRedConfirmResp qircResp = nuoNuoSDKService.queryInvoiceRedConfirm(qircReq,m);
+                    QueryInvoiceRedConfirmResp qircResp = nuoNuoSDKService.queryInvoiceRedConfirm(qircReq, m);
                     rCode = qircResp.getCode();
                     describe = qircResp.getDescribe();
-                    logger.info("ElecI-queryInvoiceRedConfirmByCode:master {} ,redApplyid {} rCode {} describe {} total {}",SpObserver.getSp(),redApplyId,rCode,describe,qircResp.getResult().getTotal());
-                    if("E0000".equals(rCode)){//调用成功 记录发票明细 1135624457459470336
+                    logger.info("ElecI-queryInvoiceRedConfirmByCode:master {} ,redApplyid {} rCode {} describe {} total {}", SpObserver.getSp(), redApplyId, rCode, describe, qircResp.getResult().getTotal());
+                    if ("E0000".equals(rCode)) {//调用成功 记录发票明细 1135624457459470336
                         List<String> sqls = new ArrayList<>();
                         List<QueryInvoiceRedConfirmDTO> qircList = qircResp.getResult().getList();
                         for (int i = 0; i < qircList.size(); i++) {
                             QueryInvoiceRedConfirmDTO qircfDTO = qircList.get(i);
                             //先获取红票状态 不一致才更新
                             sqls.add("update elecinvoice set " +
-                                    "ei_billStatus='"+qircfDTO.getBillStatus()+"' " +
-                                    ",ei_billNo='"+StringUtil.nvl(qircfDTO.getBillNo(),"")+"' " + //990000008655037292
-                                    ",ei_billUuid='"+StringUtil.nvl(qircfDTO.getBillUuid(),"")+"' " +
-                                    ",ei_redsid='"+StringUtil.nvl(qircfDTO.getInvoiceSerialNum(),"")+"' " +
-                                    ",ei_redorderno='"+StringUtil.nvl(qircfDTO.getOrderNo(),"")+"' " +
-                                    ",ei_taxExcludedAmount='"+StringUtil.nvl(qircfDTO.getTaxExcludedAmount(),"0")+"' " +
-                                    ",ei_taxAmount='"+StringUtil.nvl(qircfDTO.getTaxAmount(),"0")+"' " +
-                                    ",ei_redReason='"+StringUtil.nvl(qircfDTO.getRedReason(),"")+"' " +
-                                    ",ei_openStatus='"+StringUtil.nvl(qircfDTO.getOpenStatus(),"0")+"' " +
-                                    " where ei_id = "+eiid);
+                                    "ei_billStatus='" + qircfDTO.getBillStatus() + "' " +
+                                    ",ei_billNo='" + StringUtil.nvl(qircfDTO.getBillNo(), "") + "' " + //990000008655037292
+                                    ",ei_billUuid='" + StringUtil.nvl(qircfDTO.getBillUuid(), "") + "' " +
+                                    ",ei_redsid='" + StringUtil.nvl(qircfDTO.getInvoiceSerialNum(), "") + "' " +
+                                    ",ei_redorderno='" + StringUtil.nvl(qircfDTO.getOrderNo(), "") + "' " +
+                                    ",ei_taxExcludedAmount='" + StringUtil.nvl(qircfDTO.getTaxExcludedAmount(), "0") + "' " +
+                                    ",ei_taxAmount='" + StringUtil.nvl(qircfDTO.getTaxAmount(), "0") + "' " +
+                                    ",ei_redReason='" + StringUtil.nvl(qircfDTO.getRedReason(), "") + "' " +
+                                    ",ei_openStatus='" + StringUtil.nvl(qircfDTO.getOpenStatus(), "0") + "' " +
+                                    " where ei_id = " + eiid);
                             //针对自动开票场景:若开票,则记录红票数据,调用查询接口批量更新
-                            if("1".equals(qircfDTO.getOpenStatus())){ //已开具红字发票标记: 1:已开具 0:未开具 //orderNo 20230731182154174492
+                            if ("1".equals(qircfDTO.getOpenStatus())) { //已开具红字发票标记: 1:已开具 0:未开具 //orderNo 20230731182154174492
                                 isRushRedBill = true;
                                 // serialNos 流水号 -- EI_SID -- invoiceSerialNum ; orderNos 开票单号 --- EI_ORDERNO -- ORDERNO
                             }
                         }
                         baseDao.execute(sqls);
                         describe = "";
-                    }else{
-                        if(describe.length() > 3980){
-                            describe = describe.substring(0,3980);
+                    } else {
+                        if (describe.length() > 3980) {
+                            describe = describe.substring(0, 3980);
                         }
                         errmsg.append(describe).append("</br>");
-                        baseDao.execute("update elecinvoice set EI_EXCEPTIONMESSAGE='"+logCode+": "+describe+"' where ei_id = "+eiid+" ");
-                        commonService.logFRecord(logCode,describe,eiid);
+                        baseDao.execute("update elecinvoice set EI_EXCEPTIONMESSAGE='" + logCode + ": " + describe + "' where ei_id = " + eiid + " ");
+                        commonService.logFRecord(logCode, describe, eiid);
                     }
-                }catch (Exception e){
+                } catch (Exception e) {
                     e.printStackTrace();
                     describe = "未知异常";
-                    if(StringUtil.hasText(e.getMessage())){
+                    if (StringUtil.hasText(e.getMessage())) {
                         describe = e.getMessage();
-                    }else if(e.getCause()!=null&&StringUtil.hasText(e.getCause().getMessage())){
+                    } else if (e.getCause() != null && StringUtil.hasText(e.getCause().getMessage())) {
                         describe = e.getCause().getMessage();
                     }
-                    commonService.logFRecord(logCode,"发票红冲状态查询:"+describe.replaceAll("'","''"),eiid);
+                    commonService.logFRecord(logCode, "发票红冲状态查询:" + describe.replaceAll("'", "''"), eiid);
                 }
-                if(StringUtil.hasText(describe)){
+                if (StringUtil.hasText(describe)) {
                     errmsg.append(describe);
                 }
             }
-            if(isRushRedBill){
-                Map<String,Object> elM = new HashMap<>();
-                elM.put("appKey",m.get("appKey"));
-                elM.put("appSecret",m.get("appSecret"));
-                elM.put("token",m.get("token"));
-                elM.put("taxnum",m.get("taxnum"));
-                elM.put("io_id",ioid);
-                elM.put("io_code",m.get("io_code"));
-                Map<String,Object> r = getElecInvoices(elM);
-                if(StringUtil.hasText(r.get("errMsg"))){
-                    baseDao.execute("update elecinvoice set EI_EXCEPTIONMESSAGE='"+r.get("errCode")+": "+r.get("errMsg")+"' where EI_INVOICETYPE = '1' and ei_redapplyid is not null and EI_RELATIVEREFNO is null and ei_ioid = "+ioid);
+            if (isRushRedBill) {
+                Map<String, Object> elM = new HashMap<>();
+                elM.put("appKey", m.get("appKey"));
+                elM.put("appSecret", m.get("appSecret"));
+                elM.put("token", m.get("token"));
+                elM.put("taxnum", m.get("taxnum"));
+                elM.put("io_id", ioid);
+                elM.put("io_code", m.get("io_code"));
+                Map<String, Object> r = getElecInvoices(elM);
+                if (StringUtil.hasText(r.get("errMsg"))) {
+                    baseDao.execute("update elecinvoice set EI_EXCEPTIONMESSAGE='" + r.get("errCode") + ": " + r.get("errMsg") + "' where EI_INVOICETYPE = '1' and ei_redapplyid is not null and EI_RELATIVEREFNO is null and ei_ioid = " + ioid);
                 }
             }
         }
-        if(errmsg.length()>0){
+        if (errmsg.length() > 0) {
             res.put("success", false);
-            res.put("errMsg",errmsg.toString());
-        }else {
+            res.put("errMsg", errmsg.toString());
+        } else {
             res.put("success", true);
         }
         return res;
     }
+
     //根据红票流水号 获取红票号及其他信息
-    public Map<String,Object> queryRedPdfUrl(List<String> serialNosAll,Map<String,Object> m){
-        Map<String,Object> res = new HashMap<>();
+    public Map<String, Object> queryRedPdfUrl(List<String> serialNosAll, Map<String, Object> m) {
+        Map<String, Object> res = new HashMap<>();
         String describe = "";
         try {
-            logger.info("ElecI-queryRedPdfUrl:master {} ,serialNosAll {}",SpObserver.getSp(),serialNosAll.toString());
+            logger.info("ElecI-queryRedPdfUrl:master {} ,serialNosAll {}", SpObserver.getSp(), serialNosAll.toString());
             List<String> rSql = new ArrayList<String>();
-            if(serialNosAll.size()>0){
+            if (serialNosAll.size() > 0) {
                 Stream.iterate(0, n -> n + 1)
                         .limit((int) Math.ceil((double) serialNosAll.size() / 50)).forEach(page -> {
                     List<String> serialNos = serialNosAll.stream().skip(page * 50).limit(50).collect(Collectors.toList());
                     QueryInvoiceResultReq qirReq = new QueryInvoiceResultReq();
                     qirReq.setIsOfferInvoiceDetail("0");
                     qirReq.setSerialNos(serialNos);
-                    QueryInvoiceResultResp qirResp = nuoNuoSDKService.queryInvoiceResult(qirReq,m);
+                    QueryInvoiceResultResp qirResp = nuoNuoSDKService.queryInvoiceResult(qirReq, m);
                     List<QueryInvoiceResultDTO> list = qirResp.getResult();
-                    if(!CollectionUtil.isEmpty(list)){
+                    if (!CollectionUtil.isEmpty(list)) {
                         for (int i = 0; i < list.size(); i++) {
                             String sql = list.get(i).updatePdfUrlSql();
-                            if(!"".equals(sql)){
+                            if (!"".equals(sql)) {
                                 rSql.add(sql);
                             }
                         }
                     }
                 });
             }
-//            System.out.println("rSql:"+rSql.toString());
+//            System.out.println("rSql:" + rSql.toString());
             baseDao.execute(rSql);
-        }catch (Exception e){
+        } catch (Exception e) {
             e.printStackTrace();
             describe = "未知异常";
-            if(StringUtil.hasText(e.getMessage())){
+            if (StringUtil.hasText(e.getMessage())) {
                 describe = e.getMessage();
-            }else if(e.getCause()!=null&&StringUtil.hasText(e.getCause().getMessage())){
+            } else if (e.getCause() != null && StringUtil.hasText(e.getCause().getMessage())) {
                 describe = e.getCause().getMessage();
             }
-            commonService.logFRecord("查询红票详情",describe.replaceAll("'","''"),0);
+            commonService.logFRecord("查询红票详情", describe.replaceAll("'", "''"), 0);
+        }
+        return res;
+    }
+
+    //退货单 订单开票 根据来源蓝票获取红票信息:写入退货的发票明细、更新来源蓝票对应红票信息、及退货开票记录中
+    @Override
+    public Map<String, Object> getRedReturnElecInvoices(Map<String, Object> m) {
+        String taxnum = m.get("taxnum").toString();
+        int ioid = Integer.valueOf(m.get("io_id").toString());
+        String ioCode = m.get("io_code").toString();
+        Map<String, Object> res = new HashMap<String, Object>();
+        String errCode = "-999";
+        String errMsg = "";
+        SqlRowList ioReturn = baseDao.queryForRowSet("select io_id,io_code,io_relatesaleorderno,io_yfphm,io_biid,io_bicode from invoiceOrder " +
+                " where IO_INVOICESTATUS = 2 and io_ordertype = 2 and io_id =  " + ioid);
+        if (!ioReturn.next()) {
+            errMsg = "退货订单:" + ioCode + "(" + ioid + ")不存在";
+            logger.info("RedReturnElecI-DownLoad-master: {} ,id {} status {} message {}", SpObserver.getSp(), ioid, errMsg);
+            commonService.logFRecord("退货订单关联发票对接", errMsg, ioid);
+        }
+        String relatesaleorderno = ioReturn.getGeneralString("io_relatesaleorderno");//关联蓝票订单号
+        String oldInvoiceNumber = ioReturn.getGeneralString("io_yfphm");//原蓝票发票号码
+        Integer biid = ioReturn.getGeneralInt("io_biid");
+        String bicode = ioReturn.getGeneralString("io_bicode");
+        SqlRowList ioBlue = baseDao.queryForRowSet("select ei_id,ei_ioid from ElecInvoice " +
+                "where EI_IOCODE ='" + relatesaleorderno + "' and EI_ALLELECTRONICINVOICENUMBER ='" + oldInvoiceNumber + "'");
+        if (!ioBlue.next()) {
+            errMsg = "原订单:" + relatesaleorderno + "不存在";
+            logger.info("RedReturnElecI-DownLoad-master: {} ,id {} status {} message {}", SpObserver.getSp(), ioid, errMsg);
+            commonService.logFRecord("退货订单关联发票对接", errMsg, ioid);
+        }
+        Integer eiBlue = ioBlue.getGeneralInt("ei_id");
+        try {
+            Map<String, Object> mBlue = new HashMap<>();
+            mBlue.put("taxnum", taxnum);
+            mBlue.put("appKey", m.get("appKey"));
+            mBlue.put("appSecret", m.get("appSecret"));
+            mBlue.put("token", m.get("token"));
+            FindOrderRelationInvoiceReq foriReqBlue = new FindOrderRelationInvoiceReq();
+            foriReqBlue.setOriginalOrderNo(relatesaleorderno);//订单编号
+            foriReqBlue.setSaleTaxNum(taxnum);//销方税号
+            foriReqBlue.setNeedInvoiceSourceDetail("1");//是否需要发票所来源的订单明细,1-是, 0-否(不填默认 0) 当为0时,将不回传orderDetailCallBackVOS。先默认不需要明细
+            FindOrderRelationInvoiceResp resp = nuoNuoSDKService.findOrderRelationInvoice(foriReqBlue, mBlue);
+            errCode = resp.getStatus();
+            errMsg = resp.getMessage();
+            logger.info("RedReturnElecI-DownLoad-master: {} ,id {} status {} message {}", SpObserver.getSp(), ioid, errCode, errMsg);
+            errCode = resp.getStatus();
+            errMsg = resp.getMessage();
+            logger.info("RedReturnElecI-DownLoad-master: {} ,id {} status {} message {}", SpObserver.getSp(), ioid, errCode, errMsg);
+            if ("0000".equals(errCode)) {//调用成功
+                List<String> sqls = new ArrayList<>();
+                List<FindOrderRelationInvoiceDTO> data = resp.getData();
+                for (int i = 0; i < data.size(); i++) {
+                    FindOrderRelationInvoiceDTO friDto = data.get(i);
+                    if (friDto.getAllElectronicInvoiceNumber().equals(oldInvoiceNumber)) {
+                        List<RelateRedInvoiceDTO> relateRedInvoiceList = friDto.getRelateRedInvoiceList();
+                        for (int j = 0; j < relateRedInvoiceList.size(); j++) {
+                            RelateRedInvoiceDTO relateRedInvoiceDTO = relateRedInvoiceList.get(j);
+                            if (StringUtil.hasText(relateRedInvoiceDTO.getAllElectronicInvoiceNumber())) {
+                                sqls.add("delete ElecInvoice where ei_ioid = " + ioid);
+                                sqls.add("insert into ElecInvoice (EI_ID, EI_DETNO, EI_IOID, EI_IOCODE, EI_BIID, EI_BICODE " +
+                                        "   , EI_SID, EI_ORDERNO, EI_CREATETIME, EI_INVOICETYPE, EI_INVOICELINE, EI_SPECIFICFACTOR, EI_INVOICESTATE, EI_EXCEPTIONMESSAGE, EI_INVOICECODE, EI_INVOICENUMBER, EI_ALLELECTRONICINVOICENUMBER, EI_OLDINVOICECODE, EI_OLDINVOICENUMBER, EI_OLDALLELECTRONICINVOICENU, EI_INVOICETIME, EI_INVALIDTIME" +
+                                        "   , EI_PDFURL, EI_PDFATTACH, EI_OFDURL, EI_IMAGEURL, EI_CALCEXCLUDINGTAXAMOUNT, EI_CALCTAXAMOUNT, EI_CALEORDERAMOUNT, EI_SELLERTAXNO, EI_SELLERNAME, EI_TAXNO, EI_BUYERNAME, EI_REMARK, EI_CLERKER, EI_PAYEE, EI_CHECKER, EI_BFIELD1, EI_BFIELD2, EI_BFIELD3, EI_INDATE, EI_UPDATEDATE, EI_REFNO" +
+                                        "   ,EI_BILLSTATUS,ei_rushredstate,ei_redsid,ei_relativerefno,ei_taxamount,ei_taxexcludedamount) " +
+                                        "SELECT ElecInvoice_Seq.nextval,1," + ioid + ",'" + ioCode + "'," + biid + ",'" + bicode + "' " +
+                                        "   , EI_SID, EI_ORDERNO, EI_CREATETIME, EI_INVOICETYPE, EI_INVOICELINE, EI_SPECIFICFACTOR, EI_INVOICESTATE, EI_EXCEPTIONMESSAGE, EI_INVOICECODE, EI_INVOICENUMBER, EI_ALLELECTRONICINVOICENUMBER, EI_OLDINVOICECODE, EI_OLDINVOICENUMBER, EI_OLDALLELECTRONICINVOICENU, EI_INVOICETIME, EI_INVALIDTIME" +
+                                        "   , EI_PDFURL, EI_PDFATTACH, EI_OFDURL, EI_IMAGEURL, EI_CALCEXCLUDINGTAXAMOUNT, EI_CALCTAXAMOUNT, EI_CALEORDERAMOUNT, EI_SELLERTAXNO, EI_SELLERNAME, EI_TAXNO, EI_BUYERNAME, EI_REMARK, EI_CLERKER, EI_PAYEE, EI_CHECKER, EI_BFIELD1, EI_BFIELD2, EI_BFIELD3, EI_INDATE, EI_UPDATEDATE, EI_REFNO" +
+                                        "   ,'01' EI_BILLSTATUS,"+friDto.getRushRedState()+" ei_rushredstate,'"+relateRedInvoiceDTO.getSid()+"' ei_redsid,'"+relateRedInvoiceDTO.getAllElectronicInvoiceNumber()+"' ei_relativerefno,"+relateRedInvoiceDTO.getOrderAmount()+" ei_taxamount,"+relateRedInvoiceDTO.getExcludingTaxAmount()+" ei_taxexcludedamount " +
+                                        "FROM ElecInvoice b WHERE EI_ID = " + eiBlue);
+                                sqls.add("update ElecInvoice set EI_BILLSTATUS='01'" +
+                                        ",ei_rushredstate=" + friDto.getRushRedState() + "" +
+                                        ",ei_redsid='" + relateRedInvoiceDTO.getSid() + "' " +
+                                        ",ei_relativerefno='" + relateRedInvoiceDTO.getAllElectronicInvoiceNumber() + "' " +
+                                        ",ei_taxamount=" + relateRedInvoiceDTO.getOrderAmount() +
+                                        ",ei_taxexcludedamount=" + relateRedInvoiceDTO.getExcludingTaxAmount() +
+                                        " where EI_ID = '" + eiBlue + "'");
+                                sqls.add("update InvoiceOrder set io_refno='" + relateRedInvoiceDTO.getAllElectronicInvoiceNumber() + "' where io_id=" + ioid);
+                                sqls.add("update billout set bi_refno='" + relateRedInvoiceDTO.getAllElectronicInvoiceNumber() + "' where bi_code='" + bicode + "'");
+                            }
+                        }
+                    }
+                }
+                //记录发票明细
+                System.out.println(sqls.toString());
+                baseDao.execute(sqls);
+                //红字
+                commonService.logSRecord("退货订单关联发票对接", ioid);
+            } else {//  {"status":"8958","message":"该订单对应的开票单不存在","data":null} 没有开票单的不记录对接失败日志
+                if (errMsg.length() > 3850) {
+                    errMsg = errMsg.substring(0, 3850);
+                }
+                baseDao.execute("update invoiceOrder set io_errorMsg='订单关联发票查询失败: " + errMsg + "' where io_id=" + ioid);
+                commonService.logFRecord("退货订单关联发票对接", "蓝发票信息获取:(" + errCode + ")" + errMsg, ioid);
+            }
+        } catch (Exception e) {
+            e.printStackTrace();
+            errMsg = "发票获取异常";
+            if (StringUtil.hasText(e.getMessage())) {
+                errMsg = e.getMessage();
+            } else if (e.getCause() != null && StringUtil.hasText(e.getCause().getMessage())) {
+                errMsg = e.getCause().getMessage();
+            }
+            logger.info("RedReturnElecI-DownLoad-master: {} ,id {} message {}", SpObserver.getSp(), ioid, errMsg);
+            commonService.logFRecord("退货订单关联发票对接", errMsg.replaceAll("'", "''"), ioid);
+        }
+        //获取红字发票PDF地址
+        List<String> serialNosAll = baseDao.queryForList("select ei_redsid from ElecInvoice " +
+                "where ei_id = " + eiBlue + " and EI_RELATIVEREFNO is not null and ei_redpdfurl is null and nvl(EI_BILLSTATUS,' ') in (' ','01','04')", String.class);
+        if (!CollectionUtil.isEmpty(serialNosAll)) {
+            queryRedPdfUrl(serialNosAll, m);
+        }
+        if (StringUtil.hasText(errMsg) && !"调用成功".equals(errMsg)) {
+            res.put("success", false);
+            res.put("errCode", errCode);
+            res.put("errMsg", errMsg);
+        } else {
+            res.put("success", true);
         }
         return res;
     }

+ 56 - 27
src/main/java/com/uas/eis/task/ElecInvoiceTask.java

@@ -1,39 +1,21 @@
 package com.uas.eis.task;
 
-import com.alibaba.fastjson.JSON;
-import com.alibaba.fastjson.JSONArray;
-import com.alibaba.fastjson.TypeReference;
-import com.alibaba.fastjson.serializer.SerializerFeature;
 import com.uas.eis.config.DonlimConfig;
-import com.uas.eis.config.PNSConfig;
 import com.uas.eis.core.config.SpObserver;
-import com.uas.eis.core.support.TokenProperties;
 import com.uas.eis.dao.BaseDao;
-import com.uas.eis.dao.FindOrderStateResp;
 import com.uas.eis.dao.SqlRowList;
-import com.uas.eis.dto.FindOrderRelationInvoiceDTO;
-import com.uas.eis.dto.FindOrderRelationInvoiceReq;
-import com.uas.eis.dto.FindOrderRelationInvoiceResp;
-import com.uas.eis.entity.PNSSendData;
-import com.uas.eis.entity.PNSSendResp;
 import com.uas.eis.service.CommonService;
 import com.uas.eis.service.ERPService;
 import com.uas.eis.utils.*;
-import net.sf.json.JSONObject;
-import nuonuo.open.sdk.NNOpenSDK;
 import org.apache.commons.lang.StringUtils;
 import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
 import org.springframework.beans.factory.annotation.Autowired;
-import org.springframework.dao.EmptyResultDataAccessException;
-import org.springframework.http.HttpStatus;
-import org.springframework.jdbc.core.BeanPropertyRowMapper;
 import org.springframework.scheduling.annotation.Scheduled;
 import org.springframework.stereotype.Component;
 
 import java.io.FileOutputStream;
 import java.io.InputStream;
-import java.io.OutputStream;
 import java.net.URL;
 import java.net.URLConnection;
 import java.util.*;
@@ -93,16 +75,15 @@ public class ElecInvoiceTask {
                 m.put("taxnum",taxnum);
                 logger.info("ElecI-DownLoad: master: {} Begin ",master);
                 SpObserver.putSp(master);
-                SqlRowList ioList = baseDao.queryForRowSet("select io_id,io_code from(select io_id,io_code from "+master+".invoiceOrder " +
-                        " where io_status = '已审核' " +
-                        "   and nvl(IO_DOCKSTATUS,' ') = '对接成功' " +
-                        "   and (IO_INVOICESTATUS = 6 or (IO_INVOICESTATUS = 2 and io_refno is null)) " +
-                        //有红票的也要获取
+                SqlRowList ioList = baseDao.queryForRowSet("select io_id,io_code,io_ordertype from(select io_id,io_code,io_ordertype from "+master+".invoiceOrder " +
+                        " where io_status = '已审核' and nvl(IO_DOCKSTATUS,' ') = '对接成功' " +
+                        "   and (IO_INVOICESTATUS = 6 or (IO_INVOICESTATUS = 2 and io_refno is null and io_ordertype = 1)) " +//仅蓝票,红票另外获取
                         "order by io_id desc) where rownum <= 100");
                 logger.info("ElecI-DownLoad: master: {} size: {} ",master,ioList.getResultList().size());
                 while (ioList.next()){
                     m.put("io_id",ioList.getGeneralInt("io_id"));
                     m.put("io_code",ioList.getGeneralString("io_code"));
+                    m.put("io_ordertype",ioList.getGeneralInt("io_ordertype"));
                     erpService.getElecInvoices(m);
                 }
                 logger.info("ElecI-DownLoad: master: {} End ",master);
@@ -235,6 +216,7 @@ public class ElecInvoiceTask {
             logger.info("ElecI-RedConfirmStateUpdate End");
         }
     }
+    //红票PDF地址获取
     @Scheduled(cron = "0 0/2 * * * ?")
     public void redPdfUrlUpdate(){
         List<Object[]> obsList=baseDao.getFieldsDatasByCondition("YITOA_DATACENTER.dock_invoice_config",new String[]{"appKey","appSecret","token","taxnum","username"},"1=1");
@@ -265,7 +247,7 @@ public class ElecInvoiceTask {
                 m.put("taxnum",taxnum);
                 logger.info("ElecI-redPdfUrlUpdate: master: {} Begin ",master);
                 SpObserver.putSp(master);
-                List<String> serialNosAll = baseDao.queryForList("select ei_redsid from ElecInvoice where EI_RELATIVEREFNO is not null and ei_redpdfurl is null and nvl(EI_BILLSTATUS,' ') in ('01','04')",String.class);
+                List<String> serialNosAll = baseDao.queryForList("select ei_redsid from ElecInvoice left join InvoiceOrder on ei_ioid = io_id where io_ordertype=1 and EI_RELATIVEREFNO is not null and ei_redpdfurl is null and nvl(EI_BILLSTATUS,' ') in ('01','04')",String.class);
                 if (serialNosAll == null){
                     logger.info("ElecI-redPdfUrlUpdate: master: {} size: {} ",master,0);
                 }else {
@@ -290,9 +272,9 @@ public class ElecInvoiceTask {
                 String master = obs[4].toString();
                 logger.info("ElecI-AttachSave: master: {} Begin ",master);
                 SpObserver.putSp(master);
-                SqlRowList ioList = baseDao.queryForRowSet("select * from (select ei_id,ei_redpdfurl,ei_relativerefno,ei_ioid,cu_name" +
+                SqlRowList ioList = baseDao.queryForRowSet("select * from (select ei_id,ei_redpdfurl,ei_relativerefno,ei_ioid,cu_name,ei_allelectronicinvoicenumber " +
                         " from ELECINVOICE LEFT JOIN InvoiceOrder ON io_id = ei_ioid LEFT JOIN CUSTOMER ON CU_CODE = io_cucode " +
-                        "where ei_redpdfurl is not null and ei_redpdfattach is null " +
+                        "where io_ordertype=1 and ei_redpdfurl is not null and ei_redpdfattach is null " +
                         " order by ei_id ) where rownum <= 100 ");//一次最多500
                 logger.info("ElecI-AttachSave: master: {} size: {} ",master,ioList.getResultList().size());
                 List<Integer> ioids = new ArrayList<>();
@@ -326,7 +308,9 @@ public class ElecInvoiceTask {
 //                        System.out.println("size:"+size);
                         //存文件 filepath
                         int id = commonService.saveFilePath(fileBasePath, (int) size, fileName, "管理员");
-                        baseDao.execute("update ELECINVOICE set ei_redpdfattach ='"+id+";' where ei_id = "+ioList.getGeneralInt("ei_id"));
+                        baseDao.execute("update ELECINVOICE set ei_redpdfattach ='"+id+";' where ei_relativerefno='"+ioList.getGeneralString("ei_relativerefno")+"' and ei_allelectronicinvoicenumber = "+ioList.getGeneralString("ei_allelectronicinvoicenumber"));
+                        //关联退货单 开票订单信息更新
+                        baseDao.execute("update Invoiceorder set io_attach = "+id+";' where io_ordertype=2 and io_relatesaleorderno='"+ioList.getGeneralString("ei_allelectronicinvoicenumber")+"' and io_refno = '"+ioList.getGeneralString("ei_relativerefno")+"'");
                         System.out.println("下载成功");
                     } catch (Exception e) {
                         e.printStackTrace();
@@ -344,4 +328,49 @@ public class ElecInvoiceTask {
             logger.info("ElecI-AttachSave End");
         }
     }
+
+    //退货单 红票获取
+    @Scheduled(cron = "0 0/2 * * * ?")
+    public void saleReturnElecInvoiceDownLoad(){
+        List<Object[]> obsList=baseDao.getFieldsDatasByCondition("YITOA_DATACENTER.dock_invoice_config",new String[]{"appKey","appSecret","token","taxnum","username"},"1=1");
+        if(!CollectionUtil.isEmpty(obsList)){
+            logger.info("RedReturnElecI-DownLoad Begin");
+            for (Object[] obs: obsList) {
+                if(obs == null){
+                    continue;
+                }
+                String master = obs[4].toString();
+                String appKey = donlimConfig.getAppKey();
+                String appSecret = donlimConfig.getAppSecret();
+                String token =  donlimConfig.getToken();
+                String taxnum=  donlimConfig.getTaxnum();
+                if(donlimConfig.isProd()){
+                    System.out.println("prod");
+                    appKey =  obs[0].toString();
+                    appSecret =  obs[1].toString();
+                    token = obs[2].toString();// 访问令牌
+                    taxnum = obs[3].toString();// 授权企业税号
+                }else{
+                    System.out.println("dev");
+                }
+                Map<String,Object> m = new HashMap<>();
+                m.put("appKey",appKey);
+                m.put("appSecret",appSecret);
+                m.put("token",token);
+                m.put("taxnum",taxnum);
+                logger.info("RedReturnElecI-DownLoad: master: {} Begin ",master);
+                SpObserver.putSp(master);
+                SqlRowList ioList = baseDao.queryForRowSet("select io_id,io_code from (select io_id,io_code from "+master+".invoiceOrder " +
+                        " where io_status = '已审核' and nvl(IO_DOCKSTATUS,' ') = '对接成功' and (io_invoicestatus = 2 and io_refno is null and io_ordertype = 2) order by io_id desc) where rownum <= 100");
+                logger.info("RedReturnElecI-DownLoad: master: {} size: {} ",master,ioList.getResultList().size());
+                while (ioList.next()){
+                    m.put("io_id",ioList.getGeneralInt("io_id"));
+                    m.put("io_code",ioList.getGeneralString("io_code"));
+                    erpService.getRedReturnElecInvoices(m);
+                }
+                logger.info("RedReturnElecI-DownLoad: master: {} End ",master);
+            }
+            logger.info("RedReturnElecI-DownLoad End");
+        }
+    }
 }

+ 18 - 9
src/test/java/com/uas/eis/UasEisApplicationTests.java

@@ -103,7 +103,7 @@ public class UasEisApplicationTests {
 	 */
 	@Test
 	public void TestfindOrderState() {
-		String OrderCode = "SZ23070031";
+		String OrderCode = "SZ24030025";
 		SqlRowList io = baseDao.queryForRowSet("SELECT io_id FROM N_HUASL_SZ.invoiceOrder where IO_STATUS ='已审核' and IO_DOCKSTATUS = '对接成功' " +
 //				"and nvl(IO_INVOICESTATUS,0) in(0,1,6) " +
 				"and io_code = '"+OrderCode+"'" +
@@ -129,18 +129,20 @@ public class UasEisApplicationTests {
 	@Test
 	public void Test5() {
 		NNOpenSDK sdk = NNOpenSDK.getIntance();
-		String taxnum ="339901999999199";////测试
-		String appKey = "78607195";
-		String appSecret = "26A860C451744A21";
+		String taxnum ="91440300319521190W";////测试
+		String appKey = "47646161";
+		String appSecret = "B6681C05C3EA4408";
 		String method = "nuonuo.OpeMplatform.findOrderRelationInvoice"; // API方法名
 		String url = "https://sdk.nuonuo.com/open/v1/services";//SDK请求地址
-		String token = "77f21f617f87135fcd97ef1ueud3dxdi";
+		String token = "3792fb46bc927024c7f6a504fzow07cs";
 		Map<String,Object> reqParam=new HashMap<>();
-		reqParam.put("needInvoiceSourceDetail","0");// 是否需要发票所来源的订单明细,1-是, 0-否(不填默认 0) 当为0时,将不回传orderDetailCallBackVOS
+		reqParam.put("needInvoiceSourceDetail","1");// 是否需要发票所来源的订单明细,1-是, 0-否(不填默认 0) 当为0时,将不回传orderDetailCallBackVOS
 		//SZ23070026
 		//betaRTC-202105-003180-209
-		reqParam.put("originalOrderNo","SZ23070042");//部分待处理-没开票 {"status":"8958","message":"该订单对应的开票单不存在","data":null}
-		reqParam.put("saleTaxNum","339901999999199");
+//		reqParam.put("originalOrderNo","SZ24030025");//部分待处理-没开票 {"status":"8958","message":"该订单对应的开票单不存在","data":null}
+//		reqParam.put("originalOrderNo","SZ24020177");//部分待处理-没开票 {"status":"8958","message":"该订单对应的开票单不存在","data":null}
+		reqParam.put("originalOrderNo","SZ24020188");//部分待处理-没开票 {"status":"8958","message":"该订单对应的开票单不存在","data":null}
+		reqParam.put("saleTaxNum","91440300319521190W");
 		// invoiceState = 1 开票状态,合并冲销时为空 1:开票成功 2:开票失败
 		//exceptionMessage 开票异常信息,开票失败状态时返回
 		String content=JSONArray.toJSONString(reqParam);
@@ -154,7 +156,8 @@ public class UasEisApplicationTests {
 	@Test
 	public void TestDownLoadElecInvoice(){
 //		20230731182154174492 SZ23070033
-		Map<String, Object> m = erpService.getElecInvoicesById("N_HUASL_SZ", 7);
+//		Map<String, Object> m = erpService.getElecInvoicesById("N_HUASL_SZ", 1150);//退货单 发票获取
+		Map<String, Object> m = erpService.getElecInvoicesById("N_HUASL_SZ", 881);//有退货单的蓝票 发票获取
 		System.out.println(JSONObject.toJSONString(m));
 //		elecInvoiceTask.elecInvoiceDownLoad();
 	}
@@ -244,4 +247,10 @@ public class UasEisApplicationTests {
 	public void TestElecInvoiceRedAttachSave(){
 		elecInvoiceTask.elecInvoiceRedAttachSave();
 	}
+
+	//退货单 红票获取
+	@Test
+	public void TestsaleReturnElecInvoiceDownLoad(){
+		elecInvoiceTask.saleReturnElecInvoiceDownLoad();
+	}
 }