sen
2026-01-29 fea2d693c33fdbcb4c8304a96a4e584829cb437b
service/src/main/java/com/ruoyi/cwgl/service/impl/InvoiceManageServiceImpl.java
@@ -2,7 +2,6 @@
import java.math.BigDecimal;
import java.util.*;
import java.util.stream.Collectors;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.http.HttpUtil;
@@ -17,6 +16,8 @@
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.cwgl.domain.*;
import com.ruoyi.cwgl.domain.dto.CallbackReceiptDto;
import com.ruoyi.cwgl.mapper.*;
import com.ruoyi.cwgl.service.IInvoiceBillDetailService;
import com.ruoyi.cwgl.service.IInvoiceBusinessService;
import com.ruoyi.system.service.ISystemDataNoService;
import org.springframework.beans.factory.annotation.Autowired;
@@ -32,7 +33,6 @@
import com.ruoyi.common.enums.DataSourceType;
import com.ruoyi.common.core.service.BaseService;
import com.ruoyi.cwgl.mapper.InvoiceManageMapper;
import com.ruoyi.cwgl.service.IInvoiceManageService;
import com.ruoyi.cwgl.service.IInvoiceManageLogService;
import com.ruoyi.common.core.text.Convert;
@@ -51,7 +51,14 @@
    private InvoiceManageMapper invoiceManageMapper;
    @Resource
    private InvoiceBillDetailMapper invoiceBillDetailMapper;
    @Resource
    private IInvoiceBillDetailService invoiceBillDetailService;
    @Resource
    private IInvoiceManageLogService invoiceManageLogService;
    @Autowired
    private ISystemDataNoService systemDataNoService;
@@ -67,7 +74,17 @@
    private String invoicingAddress;
    @Value("${custom.gdpaasApi.returnAddress}")
    private String returnAddress;
    @Autowired
    private IInvoiceBusinessService invoiceBusinessService;
    @Resource
    private ReceivableInvoiceBusinessMapper receivableInvoiceBusinessMapper;
    @Resource
    private ReceivableBillManagementMapper receivableBillManagementMapper;
    @Resource
    private PayableInvoiceBusinessMapper payableInvoiceBusinessMapper;
    @Resource
    private PayableBillManagementMapper payableBillManagementMapper;
    /**
     * 查询发票管理
     *
@@ -174,7 +191,11 @@
    @Override
    public int updateInvoiceManage(InvoiceManage invoiceManage) {
        invoiceManage.setUpdateTime(DateUtils.getNowDate());
        // 删除原有的发票明细
        invoiceManageMapper.deleteInvoiceDetailByInvoiceManageId(invoiceManage.getId());
        // 删除原有的发票业务商品明细
        invoiceBillDetailService.deleteInvoiceBillDetailByInvoiceManageId(invoiceManage.getId());
        // 插入新的明细记录
        insertInvoiceDetail(invoiceManage);
        int rows = invoiceManageMapper.updateInvoiceManage(invoiceManage);
@@ -263,6 +284,20 @@
                invoiceManageMapper.batchInvoiceDetail(list);
            }
        }
        // 新增发票业务商品明细信息
        List<InvoiceBillDetail> invoiceBillDetails = invoiceManage.getInvoiceBillDetails();
        if (StringUtils.isNotNull(invoiceBillDetails)) {
            List<InvoiceBillDetail> billDetailList = new ArrayList<InvoiceBillDetail>();
            for (InvoiceBillDetail invoiceBillDetail : invoiceBillDetails) {
                invoiceBillDetail.setInvoiceManageId(id);
                invoiceBillDetail.setCreateTime(new Date());
                billDetailList.add(invoiceBillDetail);
            }
            if (billDetailList.size() > 0) {
                invoiceBillDetailMapper.insertInvoiceBillDetailBatch(billDetailList);
            }
        }
    }
    /**
@@ -310,7 +345,7 @@
    }
    @Override
    public AjaxResult applyInvoice(Integer id, List<InvoiceBillDetail> invoiceBillDetails) {
    public AjaxResult applyInvoice(Integer id) {
        InvoiceManage invoiceManage = selectInvoiceManageById(id);
        if (invoiceManage == null) {
            throw new ServiceException("发票记录不存在");
@@ -319,17 +354,16 @@
            throw new ServiceException("请勿重复开票");
        }
        List<InvoiceDetail> invoiceDetailList = invoiceManage.getInvoiceDetailList();
        if (CollectionUtil.isEmpty(invoiceDetailList)) {
            throw new ServiceException("收费明细无数据");
        List<InvoiceBillDetail> invoiceBillDetails = invoiceManage.getInvoiceBillDetails();
        if (CollectionUtil.isEmpty(invoiceBillDetails)) {
            throw new ServiceException("商品明细无数据无法开发票");
        }
        // 记录申请开票日志
        recordApplyInvoiceLog(invoiceManage);
        componentInvoice(invoiceManage.getInvoiceNo(),"FP",invoiceManage,invoiceBillDetails);
        return AjaxResult.success("申请开票成功");
        return  componentInvoice(invoiceManage.getInvoiceNo(),"FP",invoiceManage,invoiceBillDetails);
    }
    public AjaxResult componentInvoice(String orderNo, String businessType, InvoiceManage invoiceManage, List<InvoiceBillDetail> invoiceBillDetails) {
@@ -362,8 +396,8 @@
        for (InvoiceBillDetail billingDetail : invoiceBillDetails) {
            InvoiceDetailApi invoiceDetail = new InvoiceDetailApi();
            invoiceDetail.setGoodsName(invoiceDetail.getGoodsName());
            invoiceDetail.setGoodsCode(billingDetail.getGoodsCode());
            invoiceDetail.setGoodsName(billingDetail.getGoodsName());
            invoiceDetail.setWithTaxFlag(billingDetail.getWithTaxFlag().toString());
            invoiceDetail.setTaxRate("0.06");
@@ -377,7 +411,10 @@
        order.setInvoiceDetail(invoiceDetailList);
        invoicingVo.setOrder(order);
        String body = JSONObject.toJSONString(invoicingVo);
        String json = HttpUtil.post(invoicingAddress + "?businessType=" + businessType + "&returnUrl=" + returnAddress, body);
        String urlString = invoicingAddress + "?businessType=" + businessType + "&returnUrl=" + returnAddress;
        logger.info("请求body{}",body);
        logger.info("请求地址{}",urlString);
        String json = HttpUtil.post(urlString, body);
        if (json == null) {
            logger.info("开票失败");
@@ -385,7 +422,7 @@
        }
        JSONObject jsonObject = JSONObject.parseObject(json);
        String code = jsonObject.getString("code");
        logger.info("开票返回{}",jsonObject);
        String invoiceSerialNum = null;
        InvoiceBusiness record = new InvoiceBusiness();
        record.setReqData(JSONObject.toJSONString(invoicingVo));
@@ -399,9 +436,241 @@
            logger.info("开票成功发票序列号为{}", invoiceSerialNum);
            record.setInvoiceSerialNum(invoiceSerialNum);
            record.setInvoiceManageId(invoiceManage.getId());
            invoiceBusinessService.insertInvoiceBusiness(record);
            return AjaxResult.success();
        }
        return AjaxResult.error("开票失败");
    }
    /**
     * 应收账单申请开票
     *
     * @param invoiceManage 发票管理对象
     * @param id 应收账单ID
     * @return 结果
     */
    @Override
    public AjaxResult applyReceivableInvoice(InvoiceManage invoiceManage, Integer id) {
        List<InvoiceBillDetail> invoiceReceivableBillDetails = invoiceManage.getInvoiceBillDetails();
        if (CollectionUtil.isEmpty(invoiceReceivableBillDetails)) {
            throw new ServiceException("应收账单商品明细无数据无法开发票");
        }
        // 获取应收账单信息
        ReceivableBillManagement receivableBill = receivableBillManagementMapper.selectReceivableBillManagementById(id);
        if (receivableBill == null) {
            throw new ServiceException("应收账单记录不存在");
        }
        // 查询应收账单的应结算金额
        BigDecimal totalAmount = receivableBill.getTotalAmount();
        if (totalAmount == null || totalAmount.compareTo(BigDecimal.ZERO) <= 0) {
            throw new ServiceException("应收账单应结算金额无效");
        }
        // 查询receivable_invoice_business表中的开票金额
        ReceivableInvoiceBusiness query = new ReceivableInvoiceBusiness();
        query.setHeadId(id);
        List<ReceivableInvoiceBusiness> existingInvoices = receivableInvoiceBusinessMapper.selectReceivableInvoiceBusinessList(query);
        // 计算已开票金额
        BigDecimal invoicedAmount = existingInvoices.stream()
                .map(ReceivableInvoiceBusiness::getInvoicingAmount)
                .filter(Objects::nonNull)
                .reduce(BigDecimal.ZERO, BigDecimal::add);
        // 计算本次开票金额
        BigDecimal currentInvoiceAmount = invoiceReceivableBillDetails.stream()
                .map(InvoiceBillDetail::getPrice)
                .filter(Objects::nonNull)
                .reduce(BigDecimal.ZERO, BigDecimal::add);
        // 校验开票金额不能超过应结算金额
        BigDecimal totalInvoicedAmount = invoicedAmount.add(currentInvoiceAmount);
        if (totalInvoicedAmount.compareTo(totalAmount) > 0) {
            throw new ServiceException("开票金额" + currentInvoiceAmount + "加上已开票金额" + invoicedAmount +
                    "超过应结算金额" + totalAmount + ",无法开票");
        }
        String noByKey = systemDataNoService.getNoByKey(SystemDataNoEnum.YSFP);
        // 在receivable_invoice_business表中添加开票数据
        ReceivableInvoiceBusiness receivableInvoiceBusiness = new ReceivableInvoiceBusiness();
        receivableInvoiceBusiness.setHeadId(id);
        receivableInvoiceBusiness.setOrderSn(noByKey); // 使用noByKey作为orderSn
        receivableInvoiceBusiness.setInvoiceType("应收发票");
        receivableInvoiceBusiness.setInvoiceCompanyName(receivableBill.getCustomerName());
        receivableInvoiceBusiness.setInvoicingAmount(currentInvoiceAmount);
        receivableInvoiceBusiness.setStatus(0); // 初始状态
        receivableInvoiceBusiness.setCreateTime(new java.util.Date());
        // 保存到receivable_invoice_business表
        receivableInvoiceBusinessMapper.insertReceivableInvoiceBusiness(receivableInvoiceBusiness);
        // 记录应收账单申请开票日志
        recordReceivableApplyInvoiceLog(receivableBill, invoiceReceivableBillDetails);
        return componentInvoice(noByKey, "FP_RECEIVABLE", invoiceManage, invoiceReceivableBillDetails);
    }
    /**
     * 应付账单申请开票
     *
     * @param invoiceManage 发票管理对象
     * @param id 应付账单ID
     * @return 结果
     */
    @Override
    public AjaxResult applyPayableInvoice(InvoiceManage invoiceManage, Integer id) {
        List<InvoiceBillDetail> invoiceBillDetails = invoiceManage.getInvoiceBillDetails();
        if (CollectionUtil.isEmpty(invoiceBillDetails)) {
            throw new ServiceException("应付账单商品明细无数据无法开发票");
        }
        // 获取应付账单信息
        PayableBillManagement payableBill = payableBillManagementMapper.selectPayableBillManagementById(id);
        if (payableBill == null) {
            throw new ServiceException("应付账单记录不存在");
        }
        // 查询应付账单的应结算金额
        BigDecimal totalAmount = payableBill.getTotalAmount();
        if (totalAmount == null || totalAmount.compareTo(BigDecimal.ZERO) <= 0) {
            throw new ServiceException("应付账单应结算金额无效");
        }
        // 查询payable_invoice_business表中的开票金额
        PayableInvoiceBusiness query = new PayableInvoiceBusiness();
        query.setHeadId(id);
        List<PayableInvoiceBusiness> existingInvoices = payableInvoiceBusinessMapper.selectPayableInvoiceBusinessList(query);
        // 计算已开票金额
        BigDecimal invoicedAmount = existingInvoices.stream()
                .map(PayableInvoiceBusiness::getInvoicingAmount)
                .filter(Objects::nonNull)
                .reduce(BigDecimal.ZERO, BigDecimal::add);
        // 计算本次开票金额
        BigDecimal currentInvoiceAmount = invoiceBillDetails.stream()
                .map(InvoiceBillDetail::getPrice)
                .filter(Objects::nonNull)
                .reduce(BigDecimal.ZERO, BigDecimal::add);
        // 校验开票金额不能超过应结算金额
        BigDecimal totalInvoicedAmount = invoicedAmount.add(currentInvoiceAmount);
        if (totalInvoicedAmount.compareTo(totalAmount) > 0) {
            throw new ServiceException("开票金额" + currentInvoiceAmount + "加上已开票金额" + invoicedAmount +
                    "超过应结算金额" + totalAmount + ",无法开票");
        }
        String noByKey = systemDataNoService.getNoByKey(SystemDataNoEnum.YFFP);
        // 在payable_invoice_business表中添加开票数据
        PayableInvoiceBusiness payableInvoiceBusiness = new PayableInvoiceBusiness();
        payableInvoiceBusiness.setHeadId(id);
        payableInvoiceBusiness.setOrderSn(noByKey); // 使用noByKey作为orderSn
        payableInvoiceBusiness.setInvoiceType("pc");
        payableInvoiceBusiness.setInvoiceCompanyName(payableBill.getSupplierName());
        payableInvoiceBusiness.setInvoicingAmount(currentInvoiceAmount);
        payableInvoiceBusiness.setStatus(0); // 初始状态
        payableInvoiceBusiness.setCreateTime(new java.util.Date());
        // 保存到payable_invoice_business表
        payableInvoiceBusinessMapper.insertPayableInvoiceBusiness(payableInvoiceBusiness);
        recordPayableApplyInvoiceLog(payableBill,invoiceBillDetails);
        // 调用现有的 componentInvoice 接口
        return componentInvoice(noByKey, "FP_PAYABLE", invoiceManage, invoiceBillDetails);
    }
    /**
     * 记录应收账单申请开票日志
     *
     * @param receivableBill 应收账单对象
     * @param invoiceBillDetails 应收账单商品明细列表
     */
    private void recordReceivableApplyInvoiceLog(ReceivableBillManagement receivableBill,List<InvoiceBillDetail> invoiceBillDetails) {
        try {
            InvoiceManageLog log = new InvoiceManageLog();
            log.setInvoiceManageId(receivableBill.getId());
            log.setOperator(SecurityUtils.getUsername());
            log.setOperationTime(new java.util.Date());
            // 构建操作描述,包含开票金额、关联应收账单编号和对应开票金额
            StringBuilder descBuilder = new StringBuilder();
            descBuilder.append("应收账单申请开票: ");
            if (receivableBill.getTotalAmount() != null) {
                descBuilder.append("账单总金额=").append(receivableBill.getTotalAmount()).append("; ");
            }
            // 获取关联应收账单信息
            if (invoiceBillDetails != null && !invoiceBillDetails.isEmpty()) {
                for (InvoiceBillDetail detail : invoiceBillDetails) {
                    if (detail.getGoodsName() != null) {
                        descBuilder.append("商品名称=").append(detail.getGoodsName());
                    }
                    if (detail.getPrice() != null) {
                        descBuilder.append(", 商品金额=").append(detail.getPrice());
                    }
                    descBuilder.append("; ");
                }
            }
            log.setOperationDesc(descBuilder.toString());
            log.setCreateTime(new java.util.Date());
            invoiceManageLogService.insertInvoiceManageLog(log);
        } catch (Exception e) {
            logger.error("记录应收账单申请开票日志失败: {}", e.getMessage());
        }
    }
    /**
     * 记录应付账单申请开票日志
     *
     * @param payableBill 应付账单对象
     * @param invoiceBillDetails 应付账单商品明细列表
     */
    private void recordPayableApplyInvoiceLog(PayableBillManagement payableBill, List<InvoiceBillDetail> invoiceBillDetails) {
        try {
            InvoiceManageLog log = new InvoiceManageLog();
            log.setInvoiceManageId(payableBill.getId());
            log.setOperator(SecurityUtils.getUsername());
            log.setOperationTime(new java.util.Date());
            // 构建操作描述,包含开票金额、关联应付账单编号和对应开票金额
            StringBuilder descBuilder = new StringBuilder();
            descBuilder.append("应付账单申请开票: ");
            if (payableBill.getTotalAmount() != null) {
                descBuilder.append("账单总金额=").append(payableBill.getTotalAmount()).append("; ");
            }
            // 获取关联应付账单信息
            if (invoiceBillDetails != null && !invoiceBillDetails.isEmpty()) {
                for (InvoiceBillDetail detail : invoiceBillDetails) {
                    if (detail.getGoodsName() != null) {
                        descBuilder.append("商品名称=").append(detail.getGoodsName());
                    }
                    if (detail.getPrice() != null) {
                        descBuilder.append(", 商品金额=").append(detail.getPrice());
                    }
                    descBuilder.append("; ");
                }
            }
            log.setOperationDesc(descBuilder.toString());
            log.setCreateTime(new java.util.Date());
            invoiceManageLogService.insertInvoiceManageLog(log);
        } catch (Exception e) {
            logger.error("记录应付账单申请开票日志失败: {}", e.getMessage());
        }
    }
    /**
@@ -475,3 +744,5 @@
    }
}