yxh
8 天以前 5a6781cad342b0b7e8d5c62048582b9479540a35
ruoyi-project/src/main/java/com/ruoyi/project/service/impl/ServiceFundServiceImpl.java
@@ -15,17 +15,23 @@
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.core.domain.model.LoginUser;
import com.ruoyi.common.enums.ApplyTypeEnum;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.exception.base.BaseException;
import com.ruoyi.common.tax.VatTaxUtils;
import com.ruoyi.common.utils.HttpClientKit;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.bean.DtoConversionUtils;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.project.common.FundNotifyMessageBuilder;
import com.ruoyi.project.common.IdGeneratorUtils;
import com.ruoyi.project.domain.*;
import com.ruoyi.project.domain.vo.*;
import com.ruoyi.project.mapper.*;
import com.ruoyi.project.service.*;
import com.ruoyi.system.mapper.SysUserMapper;
import com.ruoyi.system.mapper.SysUserRoleMapper;
import com.ruoyi.system.service.ISysConfigService;
import com.ruoyi.system.service.ISysUserService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.ObjectUtils;
@@ -59,6 +65,10 @@
public class ServiceFundServiceImpl extends ServiceImpl<ServiceFundMapper, ServiceFund> implements IServiceFundService {
    @Autowired
    ServiceFundMapper serviceFundMapper;
    /** 专家劳务费 9 条费用控制规则校验(同一案例累计) */
    @Autowired
    private ExpertFeeValidateService expertFeeValidateService;
    @Autowired
    private DingTalkService dingTalkService;
@@ -135,6 +145,35 @@
    @Value("${spring.profiles.active}")
    private String active;
    @Autowired
    private ISysConfigService sysConfigService;
    /**
     * 审批单是否上传医院协友(致远)系统:0=不上传(测试环境),1=上传(正式环境)。
     *
     * <p>2026-10-09 新增:原来用 {@code spring.profiles.active == druid} 判断是否推送,
     * 测试环境与正式环境无法通过参数区分。改为系统参数控制。
     */
    private static final String CFG_UPLOAD_OA = "sys.approval.upload.oa";
    /** 参数缺省值:上传(保持正式环境原有行为) */
    private static final boolean DEFAULT_UPLOAD_OA = true;
    /** 审批单是否需要上传医院协友(致远)系统 */
    private boolean isUploadOaEnabled() {
        String value = null;
        try {
            value = sysConfigService.selectConfigByKey(CFG_UPLOAD_OA);
        } catch (Exception e) {
            log.warn("读取参数 {} 失败,按默认值 {} 处理", CFG_UPLOAD_OA, DEFAULT_UPLOAD_OA, e);
        }
        if (value == null || value.trim().isEmpty()) {
            return DEFAULT_UPLOAD_OA;
        }
        String v = value.trim();
        return "1".equals(v) || "true".equalsIgnoreCase(v) || "y".equalsIgnoreCase(v) || "on".equalsIgnoreCase(v);
    }
    /**
     * 致远系统流程退回
     *
@@ -197,6 +236,12 @@
        String phone = null;
        String applytype = null;
        Long flowlevel = null;
        //钉钉通知用的单据信息
        Double amount = null;
        String donorName = null;
        String billNo = null;
        String travelers = null;
        String reason = null;
        if (serviceProcessVO.getApplytype().equals("0")) {
            ServiceReimbursement serviceReimbursement = new ServiceReimbursement();
            serviceReimbursement.setId(StringUtils.isNotEmpty(serviceProcessVO.getBackCode()) ? Long.valueOf(serviceProcessVO.getBackCode()) : null);
@@ -211,6 +256,11 @@
            phone = serviceReimbursementList.get(0).getPhone();
            flowlevel = serviceReimbursementList.get(0).getFlowlevel();
            applytype = "0";
            amount = serviceReimbursementList.get(0).getAmountrequested();
            billNo = FundNotifyMessageBuilder.billNo(serviceReimbursementList.get(0).getBh(),
                    serviceReimbursementList.get(0).getId());
            travelers = serviceReimbursementList.get(0).getTravelers();
            reason = serviceReimbursementList.get(0).getReason();
        } else {
            ServiceFund serviceFund = new ServiceFund();
            serviceFund.setId(StringUtils.isNotEmpty(serviceProcessVO.getBackCode()) ? Long.valueOf(serviceProcessVO.getBackCode()) : null);
@@ -224,6 +274,10 @@
            phone = serviceFunds.get(0).getPhone();
            flowlevel = serviceFunds.get(0).getFlowlevel();
            applytype = serviceFunds.get(0).getApplytype();
            amount = serviceFunds.get(0).getPretaxcost();
            donorName = serviceFunds.get(0).getDonorname();
            billNo = FundNotifyMessageBuilder.billNo(serviceFunds.get(0).getBh(),
                    serviceFunds.get(0).getId());
        }
//        //将操作保存到fundflow表中
@@ -246,7 +300,16 @@
        SysUser sysUser = sysUserService.selectUserByUserName(userNo);
        sendMeg(serviceProcessVO, phone);
        //钉钉通知内容:单据信息(类型/报销人/金额/案例/编号)+ 审批人/审批时间/意见
        List<ConcurrentHashMap<String, Object>> notifyRows = FundNotifyMessageBuilder.newRows();
        FundNotifyMessageBuilder.addBillInfo(notifyRows, applytype, userName, amount, donorName, billNo);
        FundNotifyMessageBuilder.addTravelInfo(notifyRows, travelers, reason);
        FundNotifyMessageBuilder.addAuditResult(notifyRows, serviceProcessVO.getCheckusername(),
                serviceProcessVO.getCheckTime(),
                FundNotifyMessageBuilder.opinion(serviceProcessVO.getFlowconclusion(),
                        serviceProcessVO.getFlowcontent()));
        sendMeg(serviceProcessVO, phone, notifyRows);
        //发送信息保存
        ServiceSystemmessage serviceSystemmessage = new ServiceSystemmessage();
        serviceSystemmessage.setFundtype(1);
@@ -258,7 +321,7 @@
        serviceSystemmessage.setUpdateBy(sysUser.getNickName());
        serviceSystemmessage.setIsread(0);
        serviceSystemmessage.setMessagetype(1);
        serviceSystemmessage.setMessagetitle("财务系统信息");
        serviceSystemmessage.setMessagetitle("OPO系统审批");
        serviceSystemmessage.setMessagecontent(serviceProcessVO.getFlowcontent());
        iServiceSystemmessageService.save(serviceSystemmessage);
@@ -372,6 +435,7 @@
    }
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Map<String, String> checkFund(CheckFundVO checkFundVO, LoginUser loginUser) {
        ServiceFund serviceFund = getById(checkFundVO.getFundid());
        Map<String, String> map = new HashMap<>();
@@ -379,6 +443,19 @@
        if (serviceFund == null) {
            map.put(HttpStatus.NO_CONTENT + "", "费用编号不正确");
            return map;
        }
        // 专家劳务费:审核“通过”前校验 9 条费用控制规则(同一案例累计);不通过则不阻断
        if (checkFundVO.getFlowconclusion() != null && checkFundVO.getFlowconclusion() == 1) {
            ExpertFeeCheckResult expertFeeResult = expertFeeValidateService.validateBeforeCheck(checkFundVO.getFundid());
            if (expertFeeResult.hasError()) {
                map.put(HttpStatus.ERROR + "", expertFeeResult.errorMessage());
                return map;
            }
            if (expertFeeResult.hasWarning()) {
                // 规则 5、6 仅提示,不阻断审核
                log.warn("专家劳务费审核校验提示:fundId={},{}", checkFundVO.getFundid(), expertFeeResult.warningMessage());
            }
        }
        Integer TotalLevel = 0;
@@ -407,6 +484,11 @@
        Integer RecordStatus = serviceFund.getRecordstatus();
        Integer FlowLevel = serviceFund.getFlowlevel().intValue();
        Integer OriginalFlowLevel = FlowLevel;
        //审批结论必填:原实现直接 == 1 拆箱,接口被直调传 null 会 NPE 500
        if (checkFundVO.getFlowconclusion() == null) {
            map.put(HttpStatus.ERROR + "", "审批结论不能为空");
            return map;
        }
        if (checkFundVO.getFlowconclusion() == 1) {
            CheckFlag = 1;
            if (TotalLevel == 0) {
@@ -435,8 +517,9 @@
                if (newSwitch == 1) {
                    aBoolean1 = sendData(serviceFund);
                    if (!aBoolean1) {
                        map.put("500", "发送失败");
                        return map;
                        // 推送医院协友系统失败:整个审批不生效(事务回滚),允许下次重新审批
                        log.error("费用审批单上传医院协友系统失败,审批不生效,fundId={},请重新审批", serviceFund.getId());
                        throw new ServiceException("医院协友系统接收失败,本次审批未生效,请稍后重新审批");
                    }
                }
                //保存审批流程表
@@ -477,22 +560,25 @@
                    FlowLevel = 0;
                }
            }
            SysUser sysUser = sysUserService.selectUserByUserName(serviceFund.getUserno());
            ArrayList<ConcurrentHashMap<String, Object>> contentList = new ArrayList<>();
            ConcurrentHashMap cmap = new ConcurrentHashMap();
            cmap.put("审批人:", loginUser.getUser().getUserName());
            cmap.put("审批时间:", new Date());
            cmap.put("意见:", "不通过");
            if (StringUtils.isNotBlank(checkFundVO.getFlowcontent())) cmap.put("意见:", checkFundVO.getFlowcontent());
            contentList.add(cmap);
        }
        SysUser sysUser = sysUserService.selectUserByUserName(serviceFund.getUserno());
        //审批未通过:单据信息 + 审批人/审批时间/意见(意见 = "审批未通过。" + 驳回意见)
        List<ConcurrentHashMap<String, Object>> contentList = FundNotifyMessageBuilder.newRows();
        FundNotifyMessageBuilder.addBillInfo(contentList, serviceFund.getApplytype(),
                serviceFund.getUsername(), serviceFund.getPretaxcost(), serviceFund.getDonorname(),
                FundNotifyMessageBuilder.billNo(serviceFund.getBh(), serviceFund.getId()));
        FundNotifyMessageBuilder.addAuditResult(contentList, loginUser.getUser().getNickName(), new Date(),
                FundNotifyMessageBuilder.opinion(checkFundVO.getFlowconclusion()+"",
                        checkFundVO.getFlowcontent()));
        try {
            DingTalkReqVo dingTalkReqVo = new DingTalkReqVo();
            dingTalkReqVo.setTitle("财务系统驳回信息");
            dingTalkReqVo.setTitle(FundNotifyMessageBuilder.TITLE);
            dingTalkReqVo.setNumber(sysUser.getPhonenumber());
            dingTalkReqVo.setContents(contentList);
            dingTalkService.sendNotification(dingTalkReqVo);
        } catch (Exception e) {
            log.error("费用---审批未通过钉钉通知失败,fundId={}", serviceFund.getId(), e);
        }
        serviceFund.setRecordstatus(RecordStatus);
        serviceFund.setFlowlevel(FlowLevel.longValue());
        //  serviceFund.setBackflowlevel(serviceFund.getFlowlevel());
@@ -516,18 +602,33 @@
        Boolean aBoolean = serviceFundflowService.saveData(serviceFundflow);
        log.info("sserviceFund保存的的值是-------- :{}", aBoolean);
        //053审批通过之后,就需要把“办公室主任”的名字填上
        if (checkFundVO.getFlowconclusion() == 1 && user.getUserName().equals("053")) {
            serviceFund.setOfficedirector(user.getNickName());
        //办公室审批通过之后,就需要把“办公室主任”的名字填上
        SysUser sysUsers = null;
        if (StringUtils.isNotEmpty(user.getUserName())) {
            sysUsers = sysUserMapper.selectUserByUserName(user.getUserName());
            log.info("费用sysUsers返回的值为:{}", sysUsers);
        }
        // 2026-10-09:推送条件由"当前审核人有 officedirector 角色"改为"本次审批后到达最后一级"。
        // 原写法在"最后一级审核人没有该角色"时永远不会推送,而"非最后一级的 officedirector"会提前推送。
        boolean uploadAtLastLevel = checkFundVO.getFlowconclusion() == 1
                && TotalLevel != null && TotalLevel != 0 && TotalLevel == OriginalFlowLevel + 1;
        if (uploadAtLastLevel) {
            // 仍只在该角色审批时记录办公室主任,保持字段语义不变
            if (sysUsers != null && sysUsers.getRoles() != null
                    && sysUsers.getRoles().stream().anyMatch(role -> "officedirector".equals(role.getRoleKey()))) {
                serviceFund.setOfficedirector(user.getNickName());
            }
            serviceFund.setUploadStates(1);
            //数据发送
            Boolean aBoolean1 = null;
            if (newSwitch == 1) {
                log.info("费用newSwitch返回的值为:{}", newSwitch);
                //搞一个开关,别影响老流程
                aBoolean1 = sendData(serviceFund);
                if (!aBoolean1) {
                    map.put("500", "发送失败");
                    return map;
                    // 推送医院协友系统失败:整个审批不生效(事务回滚),允许下次重新审批
                    log.error("费用审批单上传医院协友系统失败,审批不生效,fundId={},请重新审批", serviceFund.getId());
                    throw new ServiceException("医院协友系统接收失败,本次审批未生效,请稍后重新审批");
                }
            }
        }
@@ -591,9 +692,36 @@
    }
    /**
     * 审批单上传医院协友(致远)系统。
     *
     * <p>2026-10-09:外层包一层兜底,保证**任何异常都不会向外抛**(原来 strRes 为 null 时
     * 会在 parseObject 后取 code 触发 NPE,把整个审批请求打成 500)。
     * 返回 false 表示推送失败,调用方按"审批不生效、允许下次重新审批"处理。
     */
    public Boolean sendData(ServiceFund serviceFund) {
        // fund和funddetail的数据获取
        addFundSharedInfo(serviceFund.getId());
        if (!isUploadOaEnabled()) {
            // 上传开关关闭(如测试环境):跳过上传并视为成功,绝不能因此阻断审批
            log.info("审批单上传医院协友系统已关闭(sys.approval.upload.oa != 1),跳过上传并视为成功,fundId={}",
                    serviceFund == null ? null : serviceFund.getId());
            return true;
        }
        try {
            return doSendData(serviceFund);
        } catch (Throwable t) {
            log.error("费用审批单上传医院协友系统异常,审批不生效,fundId={}",
                    serviceFund == null ? null : serviceFund.getId(), t);
            return false;
        }
    }
    private Boolean doSendData(ServiceFund serviceFund) {
        // 2026-10-09:接住 addFundSharedInfo 的失败信号(附件上传失败时它会回滚分享表并返回 false)
        Boolean sharedOk = addFundSharedInfo(serviceFund.getId());
        if (sharedOk == null || !sharedOk) {
            log.error("费用报销单上传失败:分享表/附件环节失败,审批不生效,fundId={}", serviceFund.getId());
            return false;
        }
        List<ServiceFundShared> fundShareInfos = serviceFundSharedMapper.getFundShareInfoById(serviceFund.getId());
        if (CollectionUtils.isEmpty(fundShareInfos)) return false;
@@ -632,7 +760,7 @@
        map.put("data", data);
        String strRes = null;
        if (!active.equals("druid")) {
        if (isUploadOaEnabled()) {
            //如果是本地环境,就不调这个了
            String token = getToken();
            JSONObject json1 = JSONObject.parseObject(token);
@@ -672,16 +800,33 @@
            }
        }
        log.error("------------------strRes的值为:{}", strRes);
        JSONObject jsonObject = JSONObject.parseObject(strRes);
        if (strRes == null || strRes.trim().isEmpty()) {
            // 医院协友系统无返回(超时/异常/未配置):推送失败,由调用方回滚整个审批
            log.error("费用审批单上传医院协友系统失败:接口无返回内容,fundId={}", serviceFund.getId());
            return false;
        }
        JSONObject jsonObject = null;
        try {
            jsonObject = JSONObject.parseObject(strRes);
        } catch (Exception e) {
            log.error("费用审批单上传医院协友系统失败:返回内容无法解析,fundId={},strRes={}",
                    serviceFund.getId(), strRes, e);
            return false;
        }
        if (jsonObject == null) {
            log.error("费用审批单上传医院协友系统失败:返回内容为空,fundId={},strRes={}",
                    serviceFund.getId(), strRes);
            return false;
        }
        String code = jsonObject.getString("code");
        if (!code.equals("0")) {
        if (code == null || !"0".equals(code)) {
            log.error("费用审批单上传医院协友系统失败:code={},fundId={},strRes={}",
                    code, serviceFund.getId(), strRes);
            return false;
        }
        return true;
    }
    private static final AtomicLong COUNTER = new AtomicLong(System.currentTimeMillis());
    private Map<String, List<Map<String, Object>>> formson_0832(List<ServiceFunddetailShared> serviceFunddetailSharedList) {
        Map<String, List<Map<String, Object>>> allMap = new HashMap<>();
@@ -689,6 +834,10 @@
        List<Map<String, Object>> list = new ArrayList<>();
        List<Map<String, Object>> annexfilesList = new ArrayList<>();
        for (ServiceFunddetailShared serviceFunddetailShared : serviceFunddetailSharedList) {
            //附件处理
            String annexfiles = serviceFunddetailShared.getAnnexfiles();
            String invoicefiles = serviceFunddetailShared.getInvoicefiles();
            Map<String, Object> map = new HashMap<>();
            map.put("序号1", serviceFunddetailShared.getOrderno());
            map.put("费用项目", serviceFunddetailShared.getItemname());
@@ -696,15 +845,23 @@
            map.put("开户银行", serviceFunddetailShared.getDepositbank());
            map.put("卡号", serviceFunddetailShared.getBankcardno());
            map.put("收益人家属或专家", serviceFunddetailShared.getBeneficiaryname());
            map.put("税后金额", serviceFunddetailShared.getTaxamount());
            map.put("税后金额", serviceFunddetailShared.getTaxedamount());
            map.put("作废最终金额", null);
            Long fpuuid = COUNTER.incrementAndGet();
            map.put("发票附件", fpuuid);
            Long fpuuid = IdGeneratorUtils.nextId();
            map.put("发票附件", "");
            if (StringUtils.isNotEmpty(invoicefiles)) {
                map.put("发票附件", fpuuid);
            }
            map.put("发票识别", null);
            map.put("识别人", null);
            map.put("税额", null);
            long qtuuid = COUNTER.incrementAndGet();
            map.put("其他附件", qtuuid);
            // 明细“税额”按“扣税合计”口径:劳务个税 + 增值税 + 城建税,
            // 与主表“税额合计”(PretaxCost − TaxedCost)对齐;v1 历史数据增值税/城建税为 0,取值与改造前一致。
            map.put("税额", totalTaxOf(serviceFunddetailShared));
            long qtuuid = IdGeneratorUtils.nextId();
            map.put("其他附件", "");
            if (StringUtils.isNotEmpty(annexfiles)) {
                map.put("其他附件", qtuuid);
            }
            map.put("项目编码", serviceFunddetailShared.getItemcode());
            map.put("预算项目", null);
            map.put("贷方科目", null);
@@ -714,9 +871,6 @@
            map.put("费用说明", null);
            list.add(map);
            //附件处理
            String annexfiles = serviceFunddetailShared.getAnnexfiles();
            String invoicefiles = serviceFunddetailShared.getInvoicefiles();
            int i = 0;
            if (StringUtils.isNotEmpty(annexfiles)) {
@@ -747,6 +901,23 @@
        return allMap;
    }
    /**
     * 明细上传协友的“税额” = 劳务个税 + 增值税 + 城建税(扣税合计口径)。
     * <p>
     * 背景:2026-11 新增增值税、城建税后,主表“税额合计”取 `PretaxCost − TaxedCost`,
     * 天然包含这两项;若明细仍只发劳务个税,致远里“税额合计 ≠ 明细税额之和”(差增值税+城建税)。
     * v1 历史数据的增值税/城建税均为 0,取值与改造前完全一致。
     */
    private static BigDecimal totalTaxOf(ServiceFunddetailShared detail) {
        if (detail == null) {
            return BigDecimal.ZERO.setScale(2, BigDecimal.ROUND_HALF_UP);
        }
        BigDecimal tax = detail.getTaxamount() == null ? BigDecimal.ZERO : BigDecimal.valueOf(detail.getTaxamount());
        BigDecimal vat = detail.getVatAmount() == null ? BigDecimal.ZERO : BigDecimal.valueOf(detail.getVatAmount());
        BigDecimal city = detail.getCityTaxAmount() == null ? BigDecimal.ZERO : BigDecimal.valueOf(detail.getCityTaxAmount());
        return tax.add(vat).add(city).setScale(2, BigDecimal.ROUND_HALF_UP);
    }
    private Map<String, Object> getformmain_0831(ServiceFund serviceFund) {
        ServiceFundflow serviceFundflow = new ServiceFundflow();
@@ -766,22 +937,23 @@
        formmain_0831.put("财务审批", null);
        formmain_0831.put("财务部负责人审批", getLastApprovalInfo(serviceFundflows, serviceFund.getFinancedirector()));
//        formmain_0831.put("办公室主任审批", "办公室主任审批", "审批人:周育成 & 审批时间:" + new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()) + " & 审批结果:通过");
//        formmain_0831.put("办公室主任审批", "办公室主任审批", "审批人:吴志强 & 审批时间:" + new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()) + " & 审批结果:通过");
        if (serviceFund.getBackflowlevel() == 3)
            formmain_0831.put("办公室主任审批", "审批人:周育成 & 审批时间:" + new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()) + " & 审批结果:通过");
        else formmain_0831.put("办公室主任审批", getLastApprovalInfo(serviceFundflows, "周育成"));
            formmain_0831.put("办公室主任审批", "审批人:吴志强 & 审批时间:" + new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()) + " & 审批结果:通过");
        else formmain_0831.put("办公室主任审批", getLastApprovalInfo(serviceFundflows, "吴志强"));
        formmain_0831.put("业务副院长审批", serviceFund.getBusvicepresident());
        formmain_0831.put("财务副院长审批", serviceFund.getFinvicepresident());
        formmain_0831.put("中心负责人审批", serviceFund.getOpochecker());
        formmain_0831.put("支付方式", serviceFund.getZffs());
        formmain_0831.put("组长", getLastApprovalInfo(serviceFundflows, serviceFund.getManagername()));
        String lastApprovalInfo = getLastApprovalInfo(serviceFundflows, serviceFund.getManagername());
        formmain_0831.put("组长", lastApprovalInfo.contains("吴志强") ? null : lastApprovalInfo);
        formmain_0831.put("审批人员", StringUtils.isEmpty(getLastApprovalInfo(serviceFundflows, serviceFund.getFinancechecher())) ? "陈慕华" : getLastApprovalInfo(serviceFundflows, serviceFund.getFinancechecher()));
        formmain_0831.put("支付日期", serviceFund.getRiqi());
        formmain_0831.put("识别人-作废", null);
        formmain_0831.put("财务审批签字", serviceFund.getFinancedirector());
        formmain_0831.put("财务部负责人签字", serviceFund.getFinancedirector());
        formmain_0831.put("表达类型", null);
        formmain_0831.put("表达类型", StringUtils.isEmpty(serviceFund.getApplytype()) ? null : ApplyTypeEnum.getDescByCode(serviceFund.getApplytype()));
        formmain_0831.put("税前金额合计", serviceFund.getPretaxcost());
        formmain_0831.put("税额合计", serviceFund.getPretaxcost() - serviceFund.getTaxedcost());
        formmain_0831.put("表单编号1", null);
@@ -867,13 +1039,12 @@
            serviceFunddetailShareds.get(i).setId(null);
            //数据发送给财务
            try {
                if (!active.equals("druid")) uploadOAFileAndUpdateDb(serviceFunddetailShareds.get(i));
                if (isUploadOaEnabled()) uploadOAFileAndUpdateDb(serviceFunddetailShareds.get(i));
            } catch (Exception e) {
                e.printStackTrace();
                log.error("Exception中入参的ID为:{},异常信息为 : {}", id, e.getMessage());
                log.error("费用附件上传医院协友系统失败:单据id={}(本次报销单上传整体失败,审批不生效)", id, e);
                if (id != null) {
                    Boolean aBoolean = sharedService.delfundsharedInfoById(null, id);
                    log.error("fund2分享表里的数据是否删除成功:{}", aBoolean);
                    log.error("已回滚分享表数据:{}", aBoolean);
                }
                return false;
            }
@@ -1403,8 +1574,23 @@
    }
    @Override
    public ExpertFeeCheckResult validateExpertFee(ServiceFundVO serviceFundVO) {
        return expertFeeValidateService.validateBeforeSave(serviceFundVO);
    }
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Long addOrUpdateNew(ServiceFundVO serviceFundVO) {
        // 专家劳务费:保存前校验 9 条费用控制规则(同一案例累计)
        ExpertFeeCheckResult expertFeeResult = expertFeeValidateService.validateBeforeSave(serviceFundVO);
        if (expertFeeResult.hasError()) {
            throw new BaseException(expertFeeResult.errorMessage());
        }
        if (expertFeeResult.hasWarning()) {
            // 规则 5、6 仅提示,不阻断保存;前端单独取用提示文案
            log.warn("专家劳务费保存校验提示:{}", expertFeeResult.warningMessage());
        }
        Long id = null;
        //将数据保存到fund表
        serviceFundVO.setUploadStates(0);
@@ -1417,6 +1603,28 @@
            // 保存详情数据
            for (ServiceFunddetailVO serviceFunddetailVO : serviceFunddetails) {
                // 2026-10-15:附件文件名规范二次校验(与前端 fileNameCheck 同口径;只校验本次变更的附件,历史附件放行)
                java.util.Set<String> existingNames = new java.util.HashSet<>();
                if (serviceFunddetailVO.getId() != null) {
                    ServiceFunddetail oldDetail = serviceFunddetailMapper.selectById(serviceFunddetailVO.getId());
                    if (oldDetail != null) {
                        existingNames.addAll(com.ruoyi.project.common.AttachmentNameValidator
                                .collectNames(oldDetail.getInvoicefiles()));
                        existingNames.addAll(com.ruoyi.project.common.AttachmentNameValidator
                                .collectNames(oldDetail.getAnnexfiles()));
                    }
                }
                String invoiceJson = CollectionUtils.isEmpty(serviceFunddetailVO.getInvoicefilesList())
                        ? serviceFunddetailVO.getInvoicefiles()
                        : JSON.toJSONString(serviceFunddetailVO.getInvoicefilesList());
                String annexJson = CollectionUtils.isEmpty(serviceFunddetailVO.getAnnexfilesList())
                        ? serviceFunddetailVO.getAnnexfiles()
                        : JSON.toJSONString(serviceFunddetailVO.getAnnexfilesList());
                String nameError = com.ruoyi.project.common.AttachmentNameValidator
                        .checkJsonListForUpdate(existingNames, invoiceJson, annexJson);
                if (nameError != null) {
                    throw new BaseException("附件文件名不符合要求,无法保存:" + nameError);
                }
                //去掉身份证的首尾空格
                if (StringUtils.isNotEmpty(serviceFunddetailVO.getIdcardno())) {
                    serviceFunddetailVO.setIdcardno(serviceFunddetailVO.getIdcardno().trim());
@@ -1466,10 +1674,9 @@
            return null;
        }
        //总税前
        Double pretaxcosts = 0.00;
        //总税后
        Double taxedcosts = 0.00;
        //总税前、总税后(金额累加用 BigDecimal,避免浮点尾差)
        BigDecimal pretaxcosts = BigDecimal.ZERO;
        BigDecimal taxedcosts = BigDecimal.ZERO;
        for (ServiceFunddetailVO serviceFunddetailVO : serviceFunddetails) {
            serviceFunddetailVO.setFundid(id);
@@ -1478,13 +1685,18 @@
            if (!performance.isEmpty()) {
                Double amount = performance.get("amount");
                Double taxedamount = performance.get("taxedamount");
                pretaxcosts = pretaxcosts + amount;
                taxedcosts = taxedcosts + taxedamount;
                if (amount != null) {
                    pretaxcosts = pretaxcosts.add(BigDecimal.valueOf(amount));
                }
                if (taxedamount != null) {
                    taxedcosts = taxedcosts.add(BigDecimal.valueOf(taxedamount));
                }
            }
            serviceFundVO.setPretaxcost(pretaxcosts);
            serviceFundVO.setTaxedcost(taxedcosts);
            updateById(serviceFundVO);
        }
        // 合计在循环结束后统一回写,原来写在循环内会每行都 UPDATE 一次,且中间值被反复覆盖
        serviceFundVO.setPretaxcost(pretaxcosts.doubleValue());
        serviceFundVO.setTaxedcost(taxedcosts.doubleValue());
        updateById(serviceFundVO);
        Map map = new HashMap();
        map.put("fundId", id);
        return map;
@@ -1513,10 +1725,23 @@
            //通过受益人名称,将税前、税后的值相加
            Map<String, Double> sumAmount = serviceFunddetails.stream().collect(Collectors.groupingBy(ServiceFunddetail::getBeneficiaryname, Collectors.summingDouble(ServiceFunddetail::getAmount)));
            Map<String, Double> sumTaxdAmount = serviceFunddetails.stream().collect(Collectors.groupingBy(ServiceFunddetail::getBeneficiaryname, Collectors.summingDouble(ServiceFunddetail::getTaxedamount)));
            // 新增口径:增值税、城建税、劳务税前、劳务个税按受益人合计
            Map<String, Double> sumVat = serviceFunddetails.stream().collect(Collectors.groupingBy(ServiceFunddetail::getBeneficiaryname,
                    Collectors.summingDouble(d -> d.getVatAmount() == null ? 0.0 : d.getVatAmount())));
            Map<String, Double> sumCityTax = serviceFunddetails.stream().collect(Collectors.groupingBy(ServiceFunddetail::getBeneficiaryname,
                    Collectors.summingDouble(d -> d.getCityTaxAmount() == null ? 0.0 : d.getCityTaxAmount())));
            Map<String, Double> sumLaborPretax = serviceFunddetails.stream().collect(Collectors.groupingBy(ServiceFunddetail::getBeneficiaryname,
                    Collectors.summingDouble(d -> d.getLaborPretaxAmount() == null ? 0.0 : d.getLaborPretaxAmount())));
            Map<String, Double> sumTax = serviceFunddetails.stream().collect(Collectors.groupingBy(ServiceFunddetail::getBeneficiaryname,
                    Collectors.summingDouble(d -> d.getTaxamount() == null ? 0.0 : d.getTaxamount())));
            for (String key : sumAmount.keySet()) {
                ServiceFunddetailExcel serviceFunddetailExcel = new ServiceFunddetailExcel();
                serviceFunddetailExcel.setAmount(sumAmount.getOrDefault(key, 0.0));
                serviceFunddetailExcel.setVatAmount(sumVat.getOrDefault(key, 0.0));
                serviceFunddetailExcel.setCityTaxAmount(sumCityTax.getOrDefault(key, 0.0));
                serviceFunddetailExcel.setLaborPretaxAmount(sumLaborPretax.getOrDefault(key, 0.0));
                serviceFunddetailExcel.setTaxamount(sumTax.getOrDefault(key, 0.0));
                serviceFunddetailExcel.setTaxedamount(sumTaxdAmount.getOrDefault(key, 0.0));
                for (ServiceFunddetail serviceFunddetail2 : serviceFunddetails) {
                    if (serviceFunddetail2.getBeneficiaryname().equals(key)) {
@@ -1612,10 +1837,13 @@
        String filePath = RuoYiConfig.getDownloadPath() + ajaxResult.get("msg");
        List<VExpertfeeDonor> list2 = vExpertfeeDonorMapper.selectVExpertfeeDonorList2(faxId);
        // 打印模板视图不含“增值税 / 城建税 / 劳务税前”,按 fund_tax_id 从明细表汇总后回填
        fillDonorTaxAmounts(list2);
        ExcelUtil<VExpertfeeDonor> util2 = new ExcelUtil<VExpertfeeDonor>(VExpertfeeDonor.class);
        AjaxResult ajaxResult2 = util2.exportExcel(list2, "VExpertfeeDonor");
        List<VExpertfeeExpert> list3 = vExpertfeeExpertMapper.selectVExpertfeeExpertListByFaxId(faxId);
        fillExpertTaxAmounts(list3);
        ExcelUtil<VExpertfeeExpert> util3 = new ExcelUtil<VExpertfeeExpert>(VExpertfeeExpert.class);
        AjaxResult ajaxResult3 = util3.exportExcel(list3, "vExpertfeeExpert");
@@ -1626,14 +1854,99 @@
        String name = "专家费汇总单" + new SimpleDateFormat("yyyyMMddHHmmss").format(new Date()) + ".xlsx";
        // mergeExcel 内部会写文件、校验结果,并在 finally 里清理 3 个临时 sheet 文件
        mergeExcel(list1, RuoYiConfig.getDownloadPath() + name);
        for (String path : list1) {
            new File(RuoYiConfig.getDownloadPath() + path).delete();
        }
        Map<String, Object> map = new HashMap<>();
        map.put("downloadUrl", "/profile/download/" + name);
        map.put("downloadName", name);
        return map;
    }
    /**
     * 专家费汇总单打印(专家明细 sheet):增值税、城建税直接取视图列,劳务税前按差额计算。
     * <p>
     * 2026-11-18:视图 {@code v_expertfee_expert} 已独立提供 {@code vat_amount}、{@code city_tax_amount},
     * 且 {@code TaxAmount} 恢复为<b>纯劳务个税</b>,因此:
     * <ul>
     *   <li>增值税 / 城建税 / 劳务税后 直接用视图值,不再从明细表二次汇总;</li>
     *   <li>劳务税前 = 税前金额 − 增值税 − 城建税;</li>
     *   <li>「合计」行按各行累加。</li>
     * </ul>
     */
    private void fillExpertTaxAmounts(List<VExpertfeeExpert> rows) {
        if (CollectionUtils.isEmpty(rows)) {
            return;
        }
        BigDecimal vatTotal = BigDecimal.ZERO;
        BigDecimal cityTotal = BigDecimal.ZERO;
        BigDecimal laborTotal = BigDecimal.ZERO;
        for (VExpertfeeExpert row : rows) {
            if (isTotalRow(row.getBeneficiaryname())) {
                continue;
            }
            BigDecimal vat = nvl(row.getVatAmount());
            BigDecimal city = nvl(row.getCityTaxAmount());
            BigDecimal labor = VatTaxUtils.roundMoney(
                    nvl(row.getPretaxamount()).subtract(vat).subtract(city));
            row.setVatAmount(vat);
            row.setCityTaxAmount(city);
            row.setLaborPretaxAmount(labor);
            vatTotal = vatTotal.add(vat);
            cityTotal = cityTotal.add(city);
            laborTotal = laborTotal.add(labor);
        }
        for (VExpertfeeExpert row : rows) {
            if (isTotalRow(row.getBeneficiaryname())) {
                row.setVatAmount(vatTotal);
                row.setCityTaxAmount(cityTotal);
                row.setLaborPretaxAmount(laborTotal);
            }
        }
    }
    /**
     * 专家费汇总单打印(捐献者 sheet):口径同 {@link #fillExpertTaxAmounts},合计行按「捐献者」行的值累加。
     */
    private void fillDonorTaxAmounts(List<VExpertfeeDonor> rows) {
        if (CollectionUtils.isEmpty(rows)) {
            return;
        }
        BigDecimal vatTotal = BigDecimal.ZERO;
        BigDecimal cityTotal = BigDecimal.ZERO;
        BigDecimal laborTotal = BigDecimal.ZERO;
        for (VExpertfeeDonor row : rows) {
            if (isTotalRow(row.getDonorname())) {
                continue;
            }
            BigDecimal vat = nvl(row.getVatAmount());
            BigDecimal city = nvl(row.getCityTaxAmount());
            BigDecimal labor = VatTaxUtils.roundMoney(
                    nvl(row.getPretaxamount()).subtract(vat).subtract(city));
            row.setVatAmount(vat);
            row.setCityTaxAmount(city);
            row.setLaborPretaxAmount(labor);
            vatTotal = vatTotal.add(vat);
            cityTotal = cityTotal.add(city);
            laborTotal = laborTotal.add(labor);
        }
        for (VExpertfeeDonor row : rows) {
            if (isTotalRow(row.getDonorname())) {
                row.setVatAmount(vatTotal);
                row.setCityTaxAmount(cityTotal);
                row.setLaborPretaxAmount(laborTotal);
            }
        }
    }
    /**
     * 打印里的「合计」行
     */
    private static boolean isTotalRow(String name) {
        return name != null && "合计".equals(name.trim());
    }
    private static BigDecimal nvl(BigDecimal value) {
        return value == null ? BigDecimal.ZERO : value;
    }
@@ -1699,10 +2012,18 @@
                log.info("filePath的修改:{}", filePath);
                String url = rbDetailFile.getUrl();
                //file用的是绝对位置
                String substring = url.substring(url.indexOf("/profile/upload") + "/profile/upload".length());
                // 2026-10-09:附件地址解析加固,避免 url 异常/文件缺失时抛 NPE 导致看不到失败原因
                int profileIdx = url == null ? -1 : url.indexOf("/profile/upload");
                if (profileIdx < 0) {
                    throw new ServiceException("附件地址格式不正确(缺少 /profile/upload),无法上传协友:" + url);
                }
                String substring = url.substring(profileIdx + "/profile/upload".length());
//            String strFile = rbDetailFile.getUrl().replace(filePath, "/profile/upload");
                System.out.println("fund服务的filePath + substring: " + filePath + substring);
                File filetest = new File(filePath + substring);
                if (!filetest.exists()) {
                    throw new ServiceException("附件文件在服务器上不存在,无法上传协友:" + filetest.getAbsolutePath());
                }
                String struploadResult = HttpClientKit.sendPostWithFile(filetest, strFUrl);
                log.info("第三方传回的数据: {}", struploadResult);
@@ -1750,41 +2071,115 @@
        return id;
    }
    /**
     * 把 3 个 sheet 的临时导出文件合并成一个「专家费汇总单」。
     * <p>
     * 修复点(2026-11-12):
     * <ol>
     *   <li>原实现用 {@code cell.getStringCellValue()} 复制单元格,遇到数字单元格会抛
     *       {@code IllegalStateException: Cannot get a STRING value from a NUMERIC cell},
     *       而外层 catch 把异常吞掉 → 接口仍返回下载地址,但合并文件没生成,前端下载 404;</li>
     *   <li>原实现没有关闭输入/输出流,Windows 上临时文件被锁定,删不掉(残留 *_vExpertfee*.xlsx);</li>
     *   <li>失败时不再静默,抛业务异常让前端看到真实原因。</li>
     * </ol>
     */
    public void mergeExcel(List<String> files, String outputFile) {
        try {
            Workbook resultWorkbook = new XSSFWorkbook();
        File outFile = new File(outputFile);
        try (Workbook resultWorkbook = new XSSFWorkbook()) {
            // 表头与数据两种样式,避免每个单元格都新建样式(原实现每格一个样式,文件会变大)
            CellStyle headerStyle = createMergeCellStyle(resultWorkbook, true);
            CellStyle bodyStyle = createMergeCellStyle(resultWorkbook, false);
            for (String file : files) {
                InputStream is1 = new FileInputStream(RuoYiConfig.getDownloadPath() + file);
                Workbook workbook1 = new XSSFWorkbook(is1);
                Sheet sheet1 = workbook1.getSheetAt(0);
                // 复制第一个文件的Sheet
                Sheet newSheet1 = resultWorkbook.createSheet(file.substring(0, file.indexOf(".")));
                for (Row row : sheet1) {
                    Row newRow = newSheet1.createRow(row.getRowNum());
                    int columns = row.getLastCellNum();
                    for (int i = 0; i < columns; i++) {
                        newSheet1.setColumnWidth(i, 5000);
                        Cell cell = row.getCell(i);
                        Cell newCell = newRow.createCell(cell.getColumnIndex());
                        newCell.setCellValue(cell.getStringCellValue());
                        // 创建单元格样式
                        CellStyle style = resultWorkbook.createCellStyle();
                        style.setAlignment(HorizontalAlignment.CENTER); // 水平居中
                        style.setVerticalAlignment(VerticalAlignment.CENTER); // 垂直居中
                        if (row.getRowNum() == 0) {
                            // 设置第一行背景色
                            style.setFillForegroundColor(IndexedColors.GREY_50_PERCENT.getIndex());
                            style.setFillPattern(FillPatternType.SOLID_FOREGROUND);
                File srcFile = new File(RuoYiConfig.getDownloadPath() + file);
                try (InputStream is1 = new FileInputStream(srcFile);
                     Workbook workbook1 = new XSSFWorkbook(is1)) {
                    Sheet sheet1 = workbook1.getSheetAt(0);
                    String sheetName = file.contains(".") ? file.substring(0, file.indexOf(".")) : file;
                    Sheet newSheet = resultWorkbook.createSheet(sheetName);
                    for (Row row : sheet1) {
                        Row newRow = newSheet.createRow(row.getRowNum());
                        short columns = row.getLastCellNum();
                        for (int i = 0; i < columns; i++) {
                            newSheet.setColumnWidth(i, 5000);
                            Cell newCell = newRow.createCell(i);
                            copyCellValue(row.getCell(i), newCell);
                            newCell.setCellStyle(row.getRowNum() == 0 ? headerStyle : bodyStyle);
                        }
                        newCell.setCellStyle(style);
                    }
                }
            }
            FileOutputStream out = new FileOutputStream(outputFile);
            resultWorkbook.write(out);
            // 先写临时文件再改名,避免下载到写了一半的文件
            File tmpFile = new File(outputFile + ".tmp");
            try (FileOutputStream out = new FileOutputStream(tmpFile)) {
                resultWorkbook.write(out);
            }
            if (!tmpFile.renameTo(outFile) && !tmpFile.equals(outFile)) {
                // rename 失败(目标被占用等)时退化为直接写目标文件
                try (FileOutputStream out = new FileOutputStream(outFile)) {
                    resultWorkbook.write(out);
                }
                tmpFile.delete();
            }
        } catch (Exception e) {
            e.printStackTrace();
            log.error("生成专家费汇总单失败,outputFile={}", outputFile, e);
            throw new ServiceException("生成专家费汇总单失败:" + e.getMessage());
        } finally {
            // 合并完成后清理临时 sheet 文件(失败时也尝试清理,避免残留)
            for (String file : files) {
                File tmp = new File(RuoYiConfig.getDownloadPath() + file);
                if (tmp.exists() && !tmp.delete()) {
                    log.warn("临时导出文件未能删除:{}", tmp.getAbsolutePath());
                }
            }
        }
        if (!outFile.exists() || outFile.length() == 0) {
            throw new ServiceException("生成专家费汇总单失败:文件未生成");
        }
    }
    /**
     * 合并用的单元格样式(表头灰底、正文白底),统一居中
     */
    private static CellStyle createMergeCellStyle(Workbook workbook, boolean header) {
        CellStyle style = workbook.createCellStyle();
        style.setAlignment(HorizontalAlignment.CENTER);
        style.setVerticalAlignment(VerticalAlignment.CENTER);
        if (header) {
            style.setFillForegroundColor(IndexedColors.GREY_50_PERCENT.getIndex());
            style.setFillPattern(FillPatternType.SOLID_FOREGROUND);
        }
        return style;
    }
    /**
     * 按单元格实际类型复制值:数字按数字、日期按日期、公式按公式,空单元格保持为空。
     * 原实现只支持字符串单元格,遇到金额(数字)就抛异常。
     */
    private static void copyCellValue(Cell source, Cell target) {
        if (source == null) {
            target.setBlank();
            return;
        }
        switch (source.getCellType()) {
            case STRING:
                target.setCellValue(source.getStringCellValue());
                break;
            case NUMERIC:
                if (DateUtil.isCellDateFormatted(source)) {
                    target.setCellValue(source.getDateCellValue());
                } else {
                    target.setCellValue(source.getNumericCellValue());
                }
                break;
            case BOOLEAN:
                target.setCellValue(source.getBooleanCellValue());
                break;
            case FORMULA:
                target.setCellFormula(source.getCellFormula());
                break;
            default:
                target.setBlank();
                break;
        }
    }
@@ -1801,7 +2196,8 @@
    }
    public void sendMeg(ServiceProcessVO serviceProcessVO, String phone) {
    public void sendMeg(ServiceProcessVO serviceProcessVO, String phone,
                        List<ConcurrentHashMap<String, Object>> contentList) {
        //记录操作记录
        ServiceFundflow serviceFundflow = new ServiceFundflow();
@@ -1819,18 +2215,15 @@
        serviceFundflow.setApplytype(serviceProcessVO.getApplytype());
        serviceFundflow.setFundid(StringUtils.isNotEmpty(serviceProcessVO.getBackCode()) ? Long.valueOf(serviceProcessVO.getBackCode()) : null);
        fundflowService.save(serviceFundflow);
        ArrayList<ConcurrentHashMap<String, Object>> contentList = new ArrayList<>();
        ConcurrentHashMap map = new ConcurrentHashMap();
        map.put("审批人:", serviceProcessVO.getCheckusername());
        map.put("审批时间:", serviceProcessVO.getCheckTime());
        map.put("意见:", serviceProcessVO.getFlowcontent());
        contentList.add(map);
        DingTalkReqVo dingTalkReqVo = new DingTalkReqVo();
        dingTalkReqVo.setTitle("财务系统信息");
        dingTalkReqVo.setNumber(phone);
        dingTalkReqVo.setContents(contentList);
        log.info("钉钉发送消息:{}", dingTalkReqVo);
        dingTalkService.sendNotification(dingTalkReqVo);
        try {
            DingTalkReqVo dingTalkReqVo = new DingTalkReqVo();
            dingTalkReqVo.setTitle(FundNotifyMessageBuilder.TITLE);
            dingTalkReqVo.setNumber(phone);
            dingTalkReqVo.setContents(contentList);
            log.info("钉钉发送消息:{}", dingTalkReqVo);
            dingTalkService.sendNotification(dingTalkReqVo);
        } catch (Exception e) {
            log.error("报销审批钉钉消息发送失败,不影响主流程", e);
        }
    }
}