Ver código fonte

代码优化

lishiqiang 6 dias atrás
pai
commit
d99bbf0ab5

+ 1 - 0
ship-module-trade/ship-module-trade-api/src/main/java/com/yc/ship/module/trade/enums/ErrorCodeConstants.java

@@ -34,6 +34,7 @@ public interface ErrorCodeConstants {
     ErrorCode OPERATE_PASSWORD_FAILED = new ErrorCode(15_001_1, "操作密码校验失败");
     ErrorCode PASSWORD_DECRYPT_FAILED = new ErrorCode(15_001_2, "操作密码解密失败");
     ErrorCode INSURANCE_NOT_EXISTS = new ErrorCode(15_002, "订单保险信息不存在");
+    ErrorCode ORDER_NOT_EXISTS = new ErrorCode(15_002, "保险订单不存在");
     ErrorCode INSURE_FAILED = new ErrorCode(15_002_01, "保险投保失败");
     ErrorCode INSURE_CANCEL_FAILED = new ErrorCode(15_002_02, "保险退保失败");
 

+ 3 - 3
ship-module-trade/ship-module-trade-biz/src/main/java/com/yc/ship/module/trade/controller/admin/insurance/InsuranceController.java

@@ -83,7 +83,7 @@ public class InsuranceController {
     @OperateLog(type = API)
     @PreAuthorize("@ss.hasPermission('trade:insurance:query')")
     public CommonResult queryEpolicyList(@RequestParam("id") Long id) {
-        insuranceService.queryEpolicyList(id);
+        insuranceService.queryInsuranceByOrderId(id);
         return success(true);
     }
 
@@ -92,8 +92,8 @@ public class InsuranceController {
     @Operation(summary = "退保")
     @OperateLog(type = API)
     @PreAuthorize("@ss.hasPermission('trade:insurance:apply')")
-    public CommonResult<Boolean>  cancelInsurance(@RequestParam("orderId") Long orderId){
-        insuranceService.applyCancelInsurance(orderId);
+    public CommonResult<Boolean>  cancelInsurance(@RequestParam("id") Long id){
+        insuranceService.applyCancelInsurance(id);
         return success(true);
     }
 }

+ 11 - 4
ship-module-trade/ship-module-trade-biz/src/main/java/com/yc/ship/module/trade/framework/mq/TradeMqReceiver.java

@@ -371,42 +371,49 @@ public class TradeMqReceiver {
 
     @RabbitListener(queues = TradeMqConfig.DL_QUEUE_INSURANCE_QUERY, concurrency = "2")
     @TenantIgnore
-    public void processInsuranceQuery(String data) {
+    public void processInsuranceQuery(String data, Message message, Channel channel) throws IOException {
         log.error("收到保险查询结果消息 :" + data);
         try {
             CommonResult commonResult = insuranceUtil.queryInsurance(data);
             if (!commonResult.isSuccess()) {
                 log.error("保险查询结果消息通知出现错误{}", commonResult.getMsg());
-                tradePublishUtils.publishInsuranceQueryMsg(data, 1000*60);
+                channel.basicReject(message.getMessageProperties().getDeliveryTag(), false);
             } else {
                 String checkedData = (String) commonResult.getCheckedData();
+                log.error("保险查询结果消息通知返回数据{}", checkedData);
                 JSONObject jsonObject = JSONObject.parseObject(checkedData);
                 BigDecimal paiedAmount = jsonObject.getBigDecimal("paiedAmount");
                 JSONArray policies = jsonObject.getJSONArray("policies");
                 if(policies == null) {
+                    channel.basicReject(message.getMessageProperties().getDeliveryTag(), false);
                     return;
                 }
                 JSONObject policy = policies.getJSONObject(0);
                 if(policy == null) {
+                    channel.basicReject(message.getMessageProperties().getDeliveryTag(), false);
                     return;
                 }
                 String status = policy.getString("status");
                 if("PROCESSING".equals(status)) {
                     log.error("保险查询结果,投保中,继续查询");
-                    tradePublishUtils.publishInsuranceQueryMsg(data, 1000 * 60);
+                    channel.basicReject(message.getMessageProperties().getDeliveryTag(), true);
                 } else if("FAIL".equals(status)) {
                     log.error("保险查询结果,投保失败,不再查询");
+                    channel.basicReject(message.getMessageProperties().getDeliveryTag(), false);
                 } else if("SUCCESS".equals(status)) {
                     log.error("保险查询结果,投保成功,不再查询");
                     Long externalPolicyNumber = policy.getLong("externalPolicyNumber");
                     String policyNo = policy.getString("policyNo");
                     insuranceService.handleInsuranceQuery(paiedAmount, policyNo, externalPolicyNumber, status);
+                    channel.basicReject(message.getMessageProperties().getDeliveryTag(), false);
                 }
             }
-
+            channel.basicReject(message.getMessageProperties().getDeliveryTag(), false);
         } catch (Exception e) {
             log.error("保险查询结果消息MQ通知出现错误", e);
+            channel.basicReject(message.getMessageProperties().getDeliveryTag(), true);
         }
 
+
     }
 }

+ 3 - 11
ship-module-trade/ship-module-trade-biz/src/main/java/com/yc/ship/module/trade/framework/mq/TradePublishUtils.java

@@ -218,16 +218,8 @@ public class TradePublishUtils {
         }
     }
 
-    /**
-     * 发送保险查询通知
-     * @param data
-     * @param delay
-     */
-    public void publishInsuranceQueryMsg(String data, long delay){
-        log.info("发送结算消息OrderId:{}, 延时毫秒:{},发送时间:{}", data, delay, DateUtil.now());
-        template.convertAndSend(DL_EXCHANGE_INSURANCE, DL_QUEUE_INSURANCE_QUERY, data, message -> {
-            message.getMessageProperties().setHeader("x-delay",delay == 0 ? 60 * 1000 : delay);
-            return message;
-        });
+
+    public void publishInsuranceQueryMsg(String message){
+        template.convertAndSend(EXCHANGE_ORDER, DL_QUEUE_INSURANCE_QUERY, message);
     }
 }

+ 11 - 6
ship-module-trade/ship-module-trade-biz/src/main/java/com/yc/ship/module/trade/job/InsuranceJob.java

@@ -1,9 +1,12 @@
 package com.yc.ship.module.trade.job;
 
 import com.yc.ship.framework.quartz.core.handler.JobHandler;
+import com.yc.ship.module.trade.service.insurance.InsuranceService;
 import lombok.extern.slf4j.Slf4j;
 import org.springframework.stereotype.Component;
 
+import javax.annotation.Resource;
+
 /**
  * 保险购买定时任务
  * 1. 查询需要购买保险的订单,只有确认状态并且开航前一天才可购买保险
@@ -11,17 +14,19 @@ import org.springframework.stereotype.Component;
 @Component
 @Slf4j
 public class InsuranceJob implements JobHandler {
+
+    @Resource
+    private InsuranceService insuranceService;
+
     /**
      * 执行定时任务
-     * 1.该定时任务会每天去查询开航前一天的航次,
-     * 2.根据航次去查询确认状态的订单,
-     * 3.购买保险
-     * @param param 传入的参数(当前未使用)
-     * @return 固定返回字符串"成功"
-     * @throws Exception 任务异常
+     * 定时查询保险状态
      */
     @Override
     public String execute(String param) {
+        log.info("开始执行保单查询定时任务");
+        insuranceService.queryInsuranceQuey();
+        log.info("结束执行保单查询定时任务");
         return "success";
     }
 }

+ 9 - 6
ship-module-trade/ship-module-trade-biz/src/main/java/com/yc/ship/module/trade/service/insurance/InsuranceService.java

@@ -1,10 +1,7 @@
 package com.yc.ship.module.trade.service.insurance;
 
 
-import com.yc.ship.framework.common.pojo.CommonResult;
 import com.yc.ship.framework.common.pojo.PageResult;
-import com.yc.ship.module.trade.api.insurance.dto.InsuranceApplyReqDTO;
-import com.yc.ship.module.trade.api.insurance.dto.InsuredRespDTO;
 import com.yc.ship.module.trade.controller.admin.insurance.vo.InsurancePageReqVO;
 import com.yc.ship.module.trade.controller.admin.insurance.vo.InsuranceRespVO;
 import com.yc.ship.module.trade.dal.dataobject.insurance.InsuranceDO;
@@ -19,8 +16,8 @@ import java.util.List;
  */
 public interface InsuranceService {
 
-    String INSURANCE_KEY ="order_insurance:apply_";
-    String INSURANCE_CANCEL_KEY ="order_insurance:cancel_";
+    String INSURANCE_KEY = "order_insurance:apply_";
+    String INSURANCE_CANCEL_KEY = "order_insurance:cancel_";
 
     /**
      * 获得订单保险信息
@@ -32,6 +29,7 @@ public interface InsuranceService {
 
     /**
      * 通过订单id获取保险信息
+     *
      * @param orderIdList
      * @return
      */
@@ -55,12 +53,17 @@ public interface InsuranceService {
     /**
      * 取消投保
      */
-    void applyCancelInsurance(Long orderId);
+    void applyCancelInsurance(Long id);
+
+    void queryInsuranceByOrderId(Long id);
+
+    void queryInsuranceQuey();
 
     /**
      * 查询电子保单
      */
     void queryEpolicyList(Long id);
+
     void queryEpolicyAll();
 
     InsuranceDO getByOrderId(Long orderId);

+ 52 - 30
ship-module-trade/ship-module-trade-biz/src/main/java/com/yc/ship/module/trade/service/insurance/InsuranceServiceImpl.java

@@ -6,6 +6,7 @@ import cn.hutool.core.map.MapUtil;
 import cn.hutool.http.HttpUtil;
 import cn.hutool.json.JSONObject;
 import cn.hutool.json.JSONUtil;
+import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
 import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
 import com.baomidou.mybatisplus.core.metadata.IPage;
 import com.baomidou.mybatisplus.core.toolkit.IdWorker;
@@ -17,7 +18,6 @@ import com.yc.ship.module.infra.api.config.ConfigApi;
 import com.yc.ship.module.product.dal.dataobject.voyage.VoyageDO;
 import com.yc.ship.module.product.service.voyage.VoyageService;
 import com.yc.ship.module.trade.api.insurance.dto.*;
-import com.yc.ship.module.trade.controller.admin.insurance.vo.InsuranceData;
 import com.yc.ship.module.trade.controller.admin.insurance.vo.InsurancePageReqVO;
 import com.yc.ship.module.trade.controller.admin.insurance.vo.InsuranceRespVO;
 import com.yc.ship.module.trade.controller.admin.order.vo.order.TradeOrderRespVO;
@@ -32,7 +32,6 @@ import com.yc.ship.module.trade.framework.mq.TradePublishUtils;
 import com.yc.ship.module.trade.utils.InsuranceRequestHelper;
 import com.yc.ship.module.trade.utils.InsuranceUtil;
 import lombok.extern.slf4j.Slf4j;
-import org.redisson.api.RLock;
 import org.redisson.api.RedissonClient;
 import org.springframework.beans.factory.annotation.Value;
 import org.springframework.stereotype.Service;
@@ -45,11 +44,11 @@ import java.util.ArrayList;
 import java.util.Date;
 import java.util.List;
 import java.util.Map;
-import java.util.concurrent.TimeUnit;
 
 import static com.yc.ship.framework.common.exception.util.ServiceExceptionUtil.exception;
 import static com.yc.ship.framework.common.exception.util.ServiceExceptionUtil.exception0;
-import static com.yc.ship.module.trade.enums.ErrorCodeConstants.*;
+import static com.yc.ship.module.trade.enums.ErrorCodeConstants.INSURANCE_NOT_EXISTS;
+import static com.yc.ship.module.trade.enums.ErrorCodeConstants.ORDER_NOT_EXISTS;
 
 
 /**
@@ -181,35 +180,31 @@ public class InsuranceServiceImpl implements InsuranceService {
 
         //验证投保信息
         CommonResult commonResult = insuranceUtil.validateInsuranceRequest(insuranceApplyReqDTO);
-        if(!commonResult.isSuccess()) {
-            throw exception0(commonResult.getCode(),commonResult.getMsg());
+        if (!commonResult.isSuccess()) {
+            throw exception0(commonResult.getCode(), commonResult.getMsg());
         }
         // 开始投保
         commonResult = insuranceUtil.sendInsuranceApply(insuranceApplyReqDTO);
-        if(!commonResult.isSuccess()) {
-            throw exception0(commonResult.getCode(),commonResult.getMsg());
+        if (!commonResult.isSuccess()) {
+            throw exception0(commonResult.getCode(), commonResult.getMsg());
         }
         //保存投保信息
         InsuranceDO insuranceDO = new InsuranceDO();
         insuranceDO.setOrderId(orderId);
-//            insuranceDO.setAgencyOrderId(applyReqVO.getAgencyOrderId());
         insuranceDO.setInsuranceStatus(InsuranceStatusEnum.INSURE.getValue());
         insuranceDO.setInsuredNum(insuredList.size());
-//            insuranceDO.setHolderName(applyReqVO.getHolderName());
-//            insuranceDO.setHolderNo(applyReqVO.getHolderNo());
-//            insuranceDO.setRationType(applyReqVO.getRationType());
-//            insuranceDO.setRiskCode(riskCode);
-//            insuranceDO.setInsuranceEffectDate(LocalDateTime.ofInstant(applyReqVO.getTravelDate().toInstant(), ZoneId.systemDefault()));
+        insuranceDO.setInsuranceNo(orderInfo.getOrderNo());
         Long id = IdWorker.getId(insuranceDO);
         insuranceDO.setId(id);
         insuranceMapper.insert(insuranceDO);
         // 发送查询投保接口通知
-        tradePublishUtils.publishInsuranceQueryMsg(orderInfo.getOrderNo(),0);
+        tradePublishUtils.publishInsuranceQueryMsg(orderInfo.getOrderNo());
         return true;
     }
 
     /**
      * 处理系统证件枚举与保险证件枚举转换
+     *
      * @param credentialType
      * @return
      */
@@ -222,7 +217,14 @@ public class InsuranceServiceImpl implements InsuranceService {
             case 1:
                 transCredentialType = 3;
                 break;
-            case 2: case 3: case 4: case 6: case 7: case 8: case 9: case 99:
+            case 2:
+            case 3:
+            case 4:
+            case 6:
+            case 7:
+            case 8:
+            case 9:
+            case 99:
                 transCredentialType = 6;
                 break;
             case 5:
@@ -239,13 +241,17 @@ public class InsuranceServiceImpl implements InsuranceService {
      */
     @Override
     @Transactional
-    public void applyCancelInsurance(Long orderId) {
-        TradeOrderRespVO orderInfo = tradeOrderMapper.getOrderInfo(orderId);
+    public void applyCancelInsurance(Long id) {
+        InsuranceDO insuranceDO = insuranceMapper.selectById(id);
+        if(insuranceDO == null){
+            throw exception(INSURANCE_NOT_EXISTS);
+        }
+        TradeOrderRespVO orderInfo = tradeOrderMapper.getOrderInfo(insuranceDO.getOrderId());
+        if(orderInfo == null){
+            throw exception(ORDER_NOT_EXISTS);
+        }
         VoyageDO voyage = voyageService.getVoyage(orderInfo.getVoyageId());
 
-        //获取投保记录,投保保单号
-        InsuranceDO insuranceDO = insuranceMapper.selectByOrderId(orderId);
-
         InsuranceCancelReqDTO insuranceCancelReqDTO = new InsuranceCancelReqDTO();
         insuranceCancelReqDTO.setService("cancel");
         insuranceCancelReqDTO.setReplyUrl(notifyUrl);
@@ -267,8 +273,8 @@ public class InsuranceServiceImpl implements InsuranceService {
 
         // 开始退保
         CommonResult commonResult = insuranceUtil.sendInsuranceCancel(insuranceCancelReqDTO);
-        if(!commonResult.isSuccess()) {
-            throw exception0(commonResult.getCode(),commonResult.getMsg());
+        if (!commonResult.isSuccess()) {
+            throw exception0(commonResult.getCode(), commonResult.getMsg());
         }
     }
 
@@ -297,11 +303,11 @@ public class InsuranceServiceImpl implements InsuranceService {
         insuranceDO.setAmount(amount);
         insuranceDO.setPolicyNo(policyNo);
         Integer insuranceStatus = InsuranceStatusEnum.INSURE.getValue();
-        if("SUCCESS".equals(status)) {
+        if ("SUCCESS".equals(status)) {
             insuranceStatus = InsuranceStatusEnum.SUCCESS.getValue();
-        } else if ("FAIL".equals(status)){
+        } else if ("FAIL".equals(status)) {
             insuranceStatus = InsuranceStatusEnum.FAIL.getValue();
-        }else if ("PROCESSING".equals(status)){
+        } else if ("PROCESSING".equals(status)) {
             insuranceStatus = InsuranceStatusEnum.INSURE.getValue();
         }
         insuranceDO.setInsuranceStatus(insuranceStatus);
@@ -311,6 +317,22 @@ public class InsuranceServiceImpl implements InsuranceService {
         tradeOrderMapper.updateById(tradeOrderDO);
     }
 
+    @Override
+    public void queryInsuranceByOrderId(Long id) {
+        InsuranceDO insuranceDO = insuranceMapper.selectById(id);
+        CommonResult commonResult = insuranceUtil.queryInsuranceNew(insuranceDO.getInsuranceNo(),insuranceDO.getOrderId());
+        if (!commonResult.isSuccess()) {
+            throw exception0(commonResult.getCode(), commonResult.getMsg());
+        }
+    }
+
+
+    @Override
+    public void queryInsuranceQuey() {
+        List<InsuranceDO> list = insuranceMapper.selectList(new LambdaQueryWrapper<InsuranceDO>().eq(InsuranceDO::getInsuranceStatus, 0).ge(InsuranceDO::getCreateTime, DateUtil.yesterday()));
+        list.forEach(insuranceDO -> insuranceUtil.queryInsurance(insuranceDO.getInsuranceNo()));
+    }
+
     /**
      * 电子保单查询
      */
@@ -351,14 +373,14 @@ public class InsuranceServiceImpl implements InsuranceService {
             //加密加签
             InsuranceRequestHelper.encryptAndSign(insuranceRequest, publicKey, privateKey);
             String url = configApi.getConfigValueByKey("insurance.url");
-            log.error("电子保险查询 data=" + JSONUtil.toJsonStr(insuranceRequest));
+            log.error("电子保险查询 data={}", JSONUtil.toJsonStr(insuranceRequest));
             String result = HttpUtil.createPost(url + "/QUERYEPOLICY").contentType("application/json").body(JSONUtil.toJsonStr(insuranceRequest)).timeout(15000).execute().body();
-            log.error("电子保险查询 result=" + result);
+            log.error("电子保险查询 result={}", result);
             JSONObject insuranceResponse = JSONUtil.parseObj(result);
 
             InsuranceRequestHelper.checkSignAndDecrypt(insuranceResponse, publicKey, privateKey);
             // 0:失败 1:成功
-            if (insuranceResponse != null && "200".equals(insuranceResponse.get("code"))) {
+            if ("200".equals(insuranceResponse.get("code"))) {
                 String data = insuranceResponse.get("data").toString();
                 if (data != null) {
                     Map queryEpolicyResult = JSONUtil.toBean(data, Map.class);
@@ -379,7 +401,7 @@ public class InsuranceServiceImpl implements InsuranceService {
                 }
             }
         } catch (Exception e) {
-            log.error("电子保单查询error:" + e.getMessage());
+            log.error("电子保单查询error:{}", e.getMessage());
         }
     }
 

+ 203 - 0
ship-module-trade/ship-module-trade-biz/src/main/java/com/yc/ship/module/trade/service/invoice/impl/InvoiceGroupServiceImpl.java

@@ -597,6 +597,209 @@ public class InvoiceGroupServiceImpl implements InvoiceGroupService {
         String salesName = configApi.getPlatformConfigValueByKey("newinvoice.sales.name");
         String batchNo = IdUtil.fastSimpleUUID();
 
+        JSONObject requestBody = new JSONObject();
+        JSONArray reqDDZ = new JSONArray();
+        JSONObject reqDDPC = new JSONObject();
+        //订单请求批次号
+        reqDDPC.set("DDQQPCH", batchNo);
+        //纳税人识别号
+        reqDDPC.set("NSRSBH", taxNum);
+        //发票种类代码01-专用发票 02-普通发票
+        if (invoiceList.get(0).getInvoiceType() == null) {
+            reqDDPC.set("FPLXDM", "002");
+        } else {
+            reqDDPC.set("FPLXDM", DigitalInvoiceTypeEnum.valueOf(invoiceList.get(0).getInvoiceType()).getCode());
+        }
+        requestBody.set("DDPCXX", reqDDPC);
+        invoiceList.forEach(invoice -> {
+            JSONObject jsonObject = new JSONObject();
+            JSONObject reqObj = new JSONObject();
+            //订单请求流水号
+            reqObj.set("DDQQLSH", invoice.getFpqqlsh());
+            //开票类型(0蓝字发票 1红字发票)
+            reqObj.set("KPLX", type);
+            //销货方纳税人识别号
+            reqObj.set("XHFSBH", taxNum);
+            //销货方名称
+            reqObj.set("XHFMC", salesName);
+            //销货方地址
+            reqObj.set("XHFDZ", "");
+            //销货方电话
+            reqObj.set("XHFDH", "");
+            //销货方银行名称
+            reqObj.set("XHFYH", configApi.getPlatformConfigValueByKey("newinvoice.sales.bank"));
+            //销货方银行账号
+            reqObj.set("XHFZH", configApi.getPlatformConfigValueByKey("newinvoice.sales.bankaccount"));
+
+            reqObj.set("DDH", invoice.getTransactionNo());
+
+            //开票员,以电子税局绑定人员为准
+            reqObj.set("KPR", invoice.getBuyerClerk());
+
+            //购买方编码
+            reqObj.set("GMFYH", "");
+            //购买方纳税人识别号
+            reqObj.set("GMFSBH", invoice.getBuyerTaxCode());
+            //购买方名称(当GMFBM为空并且开票方式为自动开票时必填。如果FPLXDM为002,且GMFLX为03(个人)时,GMFMC必须以(个人)字样结尾”(”为全角)
+            reqObj.set("GMFMC", invoice.getBuyerName());
+            //购买方地址
+            reqObj.set("GMFDZ", invoice.getBuyerAddress());
+            //购买方电话
+            reqObj.set("GMFDH", invoice.getBuyerPhone());
+            //购买方银行名称
+            reqObj.set("GMFYH", invoice.getBuyerBank());
+            //购买方电话
+            reqObj.set("GMFZH", invoice.getBuyerAccount());
+            //购买方类型(01企业,02机关事业单位,03个人,04其他,如不填写,默认为04)
+            if (invoice.getTitleType() != null) {
+                if (invoice.getTitleType() == 0) {
+                    //购买方名称(当GMFBM为空并且开票方式为自动开票时必填。如果FPLXDM为002,且GMFLX为03(个人)时,GMFMC必须以(个人)字样结尾”(”为全角)
+                    reqObj.set("GMFMC", invoice.getBuyerName() + "(个人)");
+                    reqObj.set("GMFLX", "03");
+                } else if (invoice.getTitleType() == 1) {
+                    reqObj.set("GMFLX", "01");
+                }
+            } else {
+                reqObj.set("GMFLX", "04");
+            }
+//            reqObj.set("GMFLX", invoice.getTitleType());
+            //购货方手机
+            reqObj.set("GMFSJH", invoice.getBuyerTel());
+            //购方邮箱,如果填写,发票类别为电子发票时会自动发送邮件
+            reqObj.set("GMFDZYX", invoice.getBuyerEmail());
+
+            JSONArray detailArray = new JSONArray();
+            List<InvoiceInventoryDO> inventoryList = invoiceInventoryService.getInvoiceInventoryListByInvoiceId(invoice.getId());
+            JSONObject detailObj;
+            BigDecimal taxExcludedAmount = BigDecimal.ZERO;
+            BigDecimal se = BigDecimal.ZERO;
+            BigDecimal taxIncludedAmount = BigDecimal.ZERO;
+            if (inventoryList.isEmpty()) {
+                int index = 1;
+                detailObj = new JSONObject();
+                detailObj.set("XH", index);
+                String GoodsCode = configApi.getPlatformConfigValueByKey("newinvoice.goods.code");
+                String spbm = StrUtil.padAfter(GoodsCode, 19, "0");
+                //商品编码
+                detailObj.set("SPBM", spbm);
+                String spmc = configApi.getPlatformConfigValueByKey("newinvoice.goods.simpleCode");
+                //项目名称
+                detailObj.set("XMMC", spmc);
+                //税率
+                BigDecimal taxRate = new BigDecimal(configApi.getPlatformConfigValueByKey("newinvoice.taxRate"));
+                detailObj.set("SL", taxRate);
+                //含税金额
+                taxIncludedAmount = invoice.getPrice();
+                if (type == 1) {
+                    taxIncludedAmount = BigDecimal.ZERO.subtract(invoice.getPrice());
+                }
+//                String dylzfpmxxh = String.valueOf(IdWorker.getId()).substring(0,8);
+//                detailObj.set("DYLZFPMXXH", dylzfpmxxh);
+                //不含税金额
+                taxExcludedAmount = taxIncludedAmount.divide(new BigDecimal(1).add(taxRate), 2, RoundingMode.HALF_UP);
+                //金额
+                detailObj.set("JE", taxIncludedAmount.setScale(2, RoundingMode.HALF_UP));
+                //税额
+                se = taxIncludedAmount.subtract(taxExcludedAmount);
+                detailObj.set("SE", se.setScale(2, RoundingMode.HALF_UP));
+                //扣除额
+                detailObj.set("KCE", "");
+                //行性质。0-正常行 1-折扣行 2-被折扣行
+                detailObj.set("FPHXZ", "0");
+                //含税标志
+                detailObj.set("HSBZ", "1");
+                //空:非零税率,1:免税,2:不征税 3:普通零税率
+                detailObj.set("LSLBS", "");
+                //0:不使用,1:使用,SPID为空时必填
+                detailObj.set("YHZCBS", 0);
+                detailArray.add(detailObj);
+
+                InvoiceInventorySaveReqVO saveReqVO = new InvoiceInventorySaveReqVO();
+                saveReqVO.setInvoiceId(invoice.getId());
+                saveReqVO.setSort(index);
+                saveReqVO.setAmount(taxIncludedAmount);
+                saveReqVO.setTax(se);
+                saveReqVO.setCode(spbm);
+                saveReqVO.setName(spmc);
+                saveReqVO.setTaxRate(taxRate);
+                saveReqVO.setFphxz(0);
+                saveReqVO.setHsbz(1);
+                saveReqVO.setYhzcbs(0);
+//                saveReqVO.setDylzfpmxxh(dylzfpmxxh);
+                InvoiceInventoryDO invoiceInventoryDO = invoiceInventoryService.createInvoiceInventory(saveReqVO);
+                inventoryList = new ArrayList<>(3);
+                inventoryList.add(invoiceInventoryDO);
+            } else {
+                for (InvoiceInventoryDO invoiceInventoryDO : inventoryList) {
+                    detailObj = new JSONObject();
+                    detailObj.set("XH", invoiceInventoryDO.getSort());
+                    //商品编码
+                    detailObj.set("SPBM", invoiceInventoryDO.getCode());
+                    //项目名称
+                    detailObj.set("XMMC", invoiceInventoryDO.getName());
+                    //税率
+                    detailObj.set("SL", invoiceInventoryDO.getTaxRate());
+                    //含税金额
+                    BigDecimal thisTaxIncludedAmount = invoiceInventoryDO.getAmount();
+                    if (type == 1) {
+                        detailObj.set("DYLZFPMXXH", invoiceInventoryDO.getDylzfpmxxh());
+                        thisTaxIncludedAmount = BigDecimal.ZERO.subtract(invoiceInventoryDO.getAmount());
+                    }
+                    //金额
+                    detailObj.set("JE", thisTaxIncludedAmount.setScale(2, RoundingMode.HALF_UP));
+                    //不含税金额
+                    BigDecimal thisTaxExcludedAmount = thisTaxIncludedAmount.divide(new BigDecimal(1).add(invoiceInventoryDO.getTaxRate()), 2, RoundingMode.HALF_UP);
+                    //税额
+                    BigDecimal thisSe = thisTaxIncludedAmount.subtract(thisTaxExcludedAmount);
+                    detailObj.set("SE", thisSe.setScale(2, RoundingMode.HALF_UP));
+                    //扣除额
+                    detailObj.set("KCE", invoiceInventoryDO.getDeductionAmount() == null ? "" : invoiceInventoryDO.getDeductionAmount());
+                    //行性质。0-正常行 1-折扣行 2-被折扣行
+                    detailObj.set("FPHXZ", invoiceInventoryDO.getFphxz());
+                    //含税标志
+                    detailObj.set("HSBZ", invoiceInventoryDO.getHsbz());
+                    //空:非零税率,1:免税,2:不征税 3:普通零税率
+                    detailObj.set("LSLBS", invoiceInventoryDO.getLslbs() == null ? "" : invoiceInventoryDO.getLslbs());
+                    //0:不使用,1:使用,SPID为空时必填
+                    detailObj.set("YHZCBS", invoiceInventoryDO.getYhzcbs());
+                    detailArray.add(detailObj);
+
+                    taxExcludedAmount = taxExcludedAmount.add(thisTaxExcludedAmount);
+                    se = se.add(thisSe);
+                    taxIncludedAmount = taxIncludedAmount.add(thisTaxIncludedAmount);
+                }
+            }
+            //合计金额
+            reqObj.set("HJJE", taxExcludedAmount.setScale(2, RoundingMode.HALF_UP));
+            //合计税额
+            reqObj.set("HJSE", se.setScale(2, RoundingMode.HALF_UP));
+            if (StringUtils.isNotBlank(remark)) {
+                //备注
+                reqObj.set("BZ", remark);
+            }
+            //价税合计
+            reqObj.set("JSHJ", taxIncludedAmount.setScale(2, RoundingMode.HALF_UP));
+            //系统来源
+            reqObj.set("SX_XTLY", StrUtil.isNotBlank(sysSource) ? sysSource : "SX_LYEQ");
+//            reqObj.set("DDMXXX", detailArray);
+            jsonObject.set("DDTXX", reqObj);
+            jsonObject.set("DDMXXX", detailArray);
+//            reqDDZ.add(reqObj);
+            reqDDZ.add(jsonObject);
+            invoice.setCHjse(se);
+            invoice.setCBhsje(taxExcludedAmount);
+        });
+        requestBody.set("DDZXX", reqDDZ);
+        return requestBody;
+    }
+
+
+
+    private JSONObject buildRequestParamNew(List<InvoiceDO> invoiceList, Integer type, String sysSource, String remark) {
+        String taxNum = configApi.getPlatformConfigValueByKey("newinvoice.group.tax");
+        String salesName = configApi.getPlatformConfigValueByKey("newinvoice.sales.name");
+        String batchNo = IdUtil.fastSimpleUUID();
+
         JSONObject requestBody = new JSONObject();
         JSONArray reqDDZ = new JSONArray();
         JSONObject reqDDPC = new JSONObject();

+ 74 - 0
ship-module-trade/ship-module-trade-biz/src/main/java/com/yc/ship/module/trade/utils/InsuranceUtil.java

@@ -1,19 +1,24 @@
 package com.yc.ship.module.trade.utils;
 
+import com.alibaba.fastjson.JSONArray;
 import com.alibaba.fastjson.JSONObject;
 import com.anji.captcha.util.MD5Util;
 import com.yc.ship.framework.common.pojo.CommonResult;
 import com.yc.ship.framework.common.util.http.HttpUtils;
 import com.yc.ship.module.trade.api.insurance.dto.InsuranceApplyReqDTO;
 import com.yc.ship.module.trade.api.insurance.dto.InsuranceCancelReqDTO;
+import com.yc.ship.module.trade.service.insurance.InsuranceService;
 import lombok.extern.slf4j.Slf4j;
+import org.apache.commons.lang3.StringUtils;
 import org.springframework.http.*;
 import org.springframework.stereotype.Component;
 import org.springframework.util.LinkedMultiValueMap;
 import org.springframework.util.MultiValueMap;
 import org.springframework.web.client.RestTemplate;
 
+import javax.annotation.Resource;
 import java.io.UnsupportedEncodingException;
+import java.math.BigDecimal;
 import java.nio.charset.StandardCharsets;
 import java.util.HashMap;
 import java.util.LinkedHashMap;
@@ -47,6 +52,9 @@ public class InsuranceUtil {
      */
     private RestTemplate restTemplate;
 
+    @Resource
+    private InsuranceService insuranceService;
+
     /**
      * 构造函数
      */
@@ -249,6 +257,40 @@ public class InsuranceUtil {
 
     public CommonResult queryInsurance(String orderNo) {
         try {
+            if(StringUtils.isBlank(orderNo)) {
+                return CommonResult.error(500, "订单号不能为空");
+            }
+            Map<String, String> request = new LinkedHashMap<>();
+            request.put("appId", APPID);
+            request.put("externalOrderNo", orderNo);
+            request.put("key", KEY);
+            String sign = MD5Util.md5(APPID + orderNo + KEY);
+
+            MultiValueMap<String, String> params = new LinkedMultiValueMap<>();
+            params.add("appId", APPID);
+            params.add("externalOrderNo", orderNo);
+            params.add("sign", sign);
+            String url = HOST + QUERY_URL + "?appId=" + APPID + "&externalOrderNo=" + orderNo + "&sign=" + sign;
+            log.error("发送查询请求到阳光系统: {}", url);
+            String s = HttpUtils.get(url, null);
+            log.error("阳光系统查询响应内容: {}", s);
+            //{"phase":"INSURE","externalOrderNo":"tys-20261001-YC-14",
+            // "paiedAmount":"10.00","total":"1","insuredCount":"1","insureProcessingCount":"0",
+            // "cancelledCount":"0","cancelProcessingCount":"0","refundedAmount":"0.0",
+            // "cipher":"26e2e422d370653274ee74ef3edc7f93","policies":[{"externalPolicyNumber":"2037220248460828673",
+            // "service":"applyTeam","status":"SUCCESS","msg":"投保成功","policyNo":"HW61927008L7JB7J8Q00"}]}
+            return CommonResult.success(s);
+        } catch (Exception e) {
+            log.error("发送查询请求失败", e);
+            return CommonResult.error(500, "发送查询请求失败: " + e.getMessage());
+        }
+    }
+
+    public CommonResult queryInsuranceNew(String orderNo,Long orderId) {
+        try {
+            if(StringUtils.isBlank(orderNo)) {
+                return CommonResult.error(500, "订单号不能为空");
+            }
             Map<String, String> request = new LinkedHashMap<>();
             request.put("appId", APPID);
             request.put("externalOrderNo", orderNo);
@@ -263,6 +305,38 @@ public class InsuranceUtil {
             log.error("发送查询请求到阳光系统: {}", url);
             String s = HttpUtils.get(url, null);
             log.error("阳光系统查询响应内容: {}", s);
+            //{"phase":"INSURE","externalOrderNo":"tys-20261001-YC-14",
+            // "paiedAmount":"10.00","total":"1","insuredCount":"1","insureProcessingCount":"0",
+            // "cancelledCount":"0","cancelProcessingCount":"0","refundedAmount":"0.0",
+            // "cipher":"26e2e422d370653274ee74ef3edc7f93","policies":[{"externalPolicyNumber":"2037220248460828673",
+            // "service":"applyTeam","status":"SUCCESS","msg":"投保成功","policyNo":"HW61927008L7JB7J8Q00"}]}
+
+            String msg = "";
+            JSONObject jsonObject = JSONObject.parseObject(s);
+            BigDecimal paiedAmount = jsonObject.getBigDecimal("paiedAmount");
+            JSONArray policies = jsonObject.getJSONArray("policies");
+            if(policies == null) {
+                msg = "查询失败";
+                insuranceService.handleInsuranceQuery(paiedAmount, "", orderId, "FAIL");
+                return CommonResult.error(500, msg);
+            }
+            JSONObject policy = policies.getJSONObject(0);
+            if(policy == null) {
+                insuranceService.handleInsuranceQuery(paiedAmount, "", orderId, "FAIL");
+                return CommonResult.error(500, "查询失败");
+            }
+            String status = policy.getString("status");
+            if("PROCESSING".equals(status)) {
+                log.error("保险查询结果,投保中,继续查询");
+            } else if("FAIL".equals(status)) {
+                log.error("保险查询结果,投保失败,不再查询");
+                insuranceService.handleInsuranceQuery(paiedAmount, "", orderId, "FAIL");
+            } else if("SUCCESS".equals(status)) {
+                log.error("保险查询结果,投保成功,不再查询");
+                Long externalPolicyNumber = policy.getLong("externalPolicyNumber");
+                String policyNo = policy.getString("policyNo");
+                insuranceService.handleInsuranceQuery(paiedAmount, policyNo, externalPolicyNumber, status);
+            }
             return CommonResult.success(s);
         } catch (Exception e) {
             log.error("发送查询请求失败", e);