yxh
8 天以前 edbfa6b1a3a45e79cb17b06f3798535c3b1ba395
修改了增值税城建税
已修改18个文件
851 ■■■■■ 文件已修改
ruoyi-admin/src/main/java/com/ruoyi/web/controller/project/ServiceFundController.java 41 ●●●●● 补丁 | 查看 | 原始文档 | blame | 历史
ruoyi-admin/src/main/java/com/ruoyi/web/controller/project/ServiceFunddetailController.java 37 ●●●●● 补丁 | 查看 | 原始文档 | blame | 历史
ruoyi-admin/src/main/java/com/ruoyi/web/controller/project/ServiceReimbursementdetailController.java 6 ●●●●● 补丁 | 查看 | 原始文档 | blame | 历史
ruoyi-common/src/main/java/com/ruoyi/common/tax/TaxtUtils.java 18 ●●●●● 补丁 | 查看 | 原始文档 | blame | 历史
ruoyi-common/src/main/java/com/ruoyi/common/utils/poi/ExcelUtil.java 15 ●●●●● 补丁 | 查看 | 原始文档 | blame | 历史
ruoyi-project/src/main/java/com/ruoyi/project/common/AttachmentNameValidator.java 78 ●●●●● 补丁 | 查看 | 原始文档 | blame | 历史
ruoyi-project/src/main/java/com/ruoyi/project/domain/VExpertfeeDonor.java 19 ●●●●● 补丁 | 查看 | 原始文档 | blame | 历史
ruoyi-project/src/main/java/com/ruoyi/project/domain/VExpertfeeExpert.java 25 ●●●●● 补丁 | 查看 | 原始文档 | blame | 历史
ruoyi-project/src/main/java/com/ruoyi/project/domain/vo/TaxMoneyByItemEO.java 5 ●●●●● 补丁 | 查看 | 原始文档 | blame | 历史
ruoyi-project/src/main/java/com/ruoyi/project/domain/vo/TaxMoneySumEO.java 10 ●●●●● 补丁 | 查看 | 原始文档 | blame | 历史
ruoyi-project/src/main/java/com/ruoyi/project/mapper/ServiceFundMapper.java 17 ●●●●● 补丁 | 查看 | 原始文档 | blame | 历史
ruoyi-project/src/main/java/com/ruoyi/project/service/impl/ServiceDonorpaymentServiceImpl.java 3 ●●●●● 补丁 | 查看 | 原始文档 | blame | 历史
ruoyi-project/src/main/java/com/ruoyi/project/service/impl/ServiceFundServiceImpl.java 301 ●●●●● 补丁 | 查看 | 原始文档 | blame | 历史
ruoyi-project/src/main/java/com/ruoyi/project/service/impl/ServiceFunddetailServiceImpl.java 208 ●●●●● 补丁 | 查看 | 原始文档 | blame | 历史
ruoyi-project/src/main/java/com/ruoyi/project/service/impl/ServiceFundtaxServiceImpl.java 13 ●●●●● 补丁 | 查看 | 原始文档 | blame | 历史
ruoyi-project/src/main/resources/mapper/project/ServiceFundMapper.xml 47 ●●●●● 补丁 | 查看 | 原始文档 | blame | 历史
ruoyi-project/src/main/resources/mapper/project/ServiceFunddetailMapper.xml 5 ●●●●● 补丁 | 查看 | 原始文档 | blame | 历史
ruoyi-project/src/main/resources/mapper/project/VExpertfeeDonorMapper.xml 3 ●●●●● 补丁 | 查看 | 原始文档 | blame | 历史
ruoyi-admin/src/main/java/com/ruoyi/web/controller/project/ServiceFundController.java
@@ -9,6 +9,7 @@
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.core.domain.entity.SysRole;
import com.ruoyi.common.core.domain.model.LoginUser;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.enums.BusinessType;
@@ -146,13 +147,49 @@
    @GetMapping("/list")
    public TableDataInfo list(ServiceFund serviceFund) {
        startPage();
        //List<ServiceFund> list = serviceFundService.queryList(serviceFund);
        SysUser user = SecurityUtils.getLoginUser().getUser();
        serviceFund.setUsername(user.getNickName());
        // 2026-11-10:按角色划分可见范围(原实现一律只查"申请人=本人",管理员/组长看不到别人的单据)
        applyFundDataScope(serviceFund, user);
        List<ServiceFund> list = serviceFundService.selectServiceFundList(serviceFund);
        return getDataTable(list);
    }
    /**
     * 报销单列表数据范围:
     * 超管(user_id=1 或 role_id=1)→ 全部;
     * 业务组长(role_id=13)→ 本组(DeptmentNo = 登录人所属部门);
     * 其他(专职人员等)→ 本人(UserName = 登录人昵称)。
     */
    private void applyFundDataScope(ServiceFund serviceFund, SysUser user) {
        if (user == null) {
            return;
        }
        if (Long.valueOf(1L).equals(user.getUserId()) || hasRole(user, 1L)) {
            // 超管:不加任何过滤,看全部
            return;
        }
        if (hasRole(user, 13L) && user.getDeptId() != null) {
            // 业务组长:看本组
            serviceFund.setDeptmentno(String.valueOf(user.getDeptId()));
            return;
        }
        // 默认:只看本人
        serviceFund.setUsername(user.getNickName());
    }
    /** 判断登录人是否拥有指定角色 */
    private boolean hasRole(SysUser user, Long roleId) {
        if (user == null || user.getRoles() == null) {
            return false;
        }
        for (SysRole role : user.getRoles()) {
            if (role != null && roleId.equals(role.getRoleId())) {
                return true;
            }
        }
        return false;
    }
    @GetMapping("/listnew")
    public TableDataInfo listnew(FundVO fundVO) {
        startPage();
ruoyi-admin/src/main/java/com/ruoyi/web/controller/project/ServiceFunddetailController.java
@@ -10,6 +10,7 @@
import com.ruoyi.common.exception.base.BaseException;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.project.domain.FunddetailReqVo;
import com.ruoyi.project.domain.ServiceFund;
import com.ruoyi.project.domain.ServiceFunddetail;
import com.ruoyi.project.domain.SpStatBonus;
import com.ruoyi.project.domain.SpStatBonusDept;
@@ -17,6 +18,7 @@
import com.ruoyi.project.domain.vo.TaxMoneyByItemEO;
import com.ruoyi.project.domain.vo.TaxMoneySumEO;
import com.ruoyi.project.domain.vo.TaxMoneyVO;
import com.ruoyi.project.service.IServiceFundService;
import com.ruoyi.project.service.IServiceFunddetailService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
@@ -43,6 +45,34 @@
public class ServiceFunddetailController extends BaseController {
    @Autowired
    private IServiceFunddetailService serviceFunddetailService;
    @Autowired
    private IServiceFundService serviceFundService;
    /**
     * 2026-11-17:该明细所属报销单是否要求附件名含中文。
     * 口径:专家劳务费(applytype=1)、伦理专家费(2) 不要求;医学成本(3)、办公费用(4) 等其他类型必须含中文。
     * 报销类型取父单 service_fund.ApplyType(明细行自身的 applytype 是费用项目类型,不能用于此判断)。
     *
     * @return {@code true}=必须含中文
     */
    private boolean requireChineseName(ServiceFunddetail detail) {
        if (detail == null || detail.getFundid() == null) {
            return false;
        }
        try {
            ServiceFund fund = serviceFundService.getById(detail.getFundid());
            if (fund == null || fund.getApplytype() == null) {
                return false;
            }
            String type = String.valueOf(fund.getApplytype()).trim();
            return !("1".equals(type) || "2".equals(type));
        } catch (Exception e) {
            // 取不到报销类型时不额外拦截,避免因读取异常把正常保存卡死
            log.warn("附件名中文校验获取报销类型失败,跳过中文校验:{}", e.getMessage());
            return false;
        }
    }
    /**
@@ -93,7 +123,8 @@
        // 2026-10-15:附件文件名规范二次校验(与前端 opo-web/src/utils/fileNameCheck.js 同口径,
        // 目的是防止绕过前端直接调接口保存不合规附件名)。新增场景没有历史附件,用严格模式。
        String nameError = com.ruoyi.project.common.AttachmentNameValidator
                .checkJsonList(serviceFunddetail.getInvoicefiles(), serviceFunddetail.getAnnexfiles());
                .checkJsonList(requireChineseName(serviceFunddetail),
                        serviceFunddetail.getInvoicefiles(), serviceFunddetail.getAnnexfiles());
        if (nameError != null) {
            return AjaxResult.error("附件文件名不符合要求,无法保存:" + nameError);
        }
@@ -124,8 +155,8 @@
            }
        }
        String nameError = com.ruoyi.project.common.AttachmentNameValidator
                .checkJsonListForUpdate(existingNames, serviceFunddetail.getInvoicefiles(),
                        serviceFunddetail.getAnnexfiles());
                .checkJsonListForUpdate(existingNames, requireChineseName(serviceFunddetail),
                        serviceFunddetail.getInvoicefiles(), serviceFunddetail.getAnnexfiles());
        if (nameError != null) {
            return AjaxResult.error("附件文件名不符合要求,无法保存:" + nameError);
        }
ruoyi-admin/src/main/java/com/ruoyi/web/controller/project/ServiceReimbursementdetailController.java
@@ -113,7 +113,7 @@
                ? serviceReimbursementdetailVO.getAnnexfiles()
                : JSON.toJSONString(serviceReimbursementdetailVO.getAnnexfilesList());
        String nameError = com.ruoyi.project.common.AttachmentNameValidator
                .checkJsonList(invoiceJson, annexJson);
                .checkJsonList(true, invoiceJson, annexJson);
        if (nameError != null) {
            return AjaxResult.error("附件文件名不符合要求,无法保存:" + nameError);
        }
@@ -151,7 +151,7 @@
                }
            }
            String nameError = com.ruoyi.project.common.AttachmentNameValidator.checkJsonListForUpdate(
                    existingNames, serviceReimbursementdetail.getInvoicefiles(),
                    existingNames, true, serviceReimbursementdetail.getInvoicefiles(),
                    serviceReimbursementdetail.getAnnexfiles());
            if (nameError != null) {
                return AjaxResult.error("附件文件名不符合要求,无法保存:" + nameError);
@@ -192,7 +192,7 @@
                ? serviceReimbursementdetailVO.getAnnexfiles()
                : JSON.toJSONString(serviceReimbursementdetailVO.getAnnexfilesList());
        String nameError = com.ruoyi.project.common.AttachmentNameValidator
                .checkJsonListForUpdate(existingNames, invoiceJson, annexJson);
                .checkJsonListForUpdate(existingNames, true, invoiceJson, annexJson);
        if (nameError != null) {
            return AjaxResult.error("附件文件名不符合要求,无法保存:" + nameError);
        }
ruoyi-common/src/main/java/com/ruoyi/common/tax/TaxtUtils.java
@@ -57,8 +57,8 @@
            taxMoney = multiply.multiply(BigDecimal.valueOf(0.4)).subtract(BigDecimal.valueOf(7000));
        }
        DecimalFormat decimalFormat = new DecimalFormat("#0.00");
        //进一法
        decimalFormat.setRoundingMode(RoundingMode.CEILING);
        // 算税统一四舍五入到分(2026-11-17 由“进一法”调整为四舍五入)
        decimalFormat.setRoundingMode(RoundingMode.HALF_UP);
        String format = decimalFormat.format(taxMoney);
        log.info("税金为:{}", format);
        return format;
@@ -69,7 +69,7 @@
     * <p>
     * 注意:除数必须用字符串/常量构造的精确值。原先写成 {@code new BigDecimal(0.84)} 等,
     * 会把 double 的二进制误差带进除法(如 8313.06 / 0.84 变成 9896.500000…001),
     * 再叠加向上取整就多出 1 分钱,导致“税后反算税前”无法还原(8300.00 类金额反解出 10000.03)。
     * 再叠加取整就多出 1 分钱,导致“税后反算税前”无法还原(8300.00 类金额反解出 10000.03)。
     *
     * @param money
     * @return
@@ -82,27 +82,27 @@
        }
//第一个参数是除数,第二个参数代表保留几位小数,第三个代表的是使用的模式
        if (money.doubleValue() > 800 && money.doubleValue() <= 3360) {
            taxMoney = money.subtract(new BigDecimal(160)).divide(new BigDecimal("0.8"), 2, BigDecimal.ROUND_CEILING);
            taxMoney = money.subtract(new BigDecimal(160)).divide(new BigDecimal("0.8"), 2, BigDecimal.ROUND_HALF_UP);
        }
        if (money.doubleValue() > 3360 && money.doubleValue() <= 21000) {
            taxMoney = money.divide(new BigDecimal("0.84"), 2, BigDecimal.ROUND_CEILING);
            taxMoney = money.divide(new BigDecimal("0.84"), 2, BigDecimal.ROUND_HALF_UP);
        }
        if (money.doubleValue() > 21000 && money.doubleValue() <= 49500) {
            money = money.subtract(new BigDecimal(2000));
            taxMoney = money.divide(new BigDecimal("0.76"), 2, BigDecimal.ROUND_CEILING);
            taxMoney = money.divide(new BigDecimal("0.76"), 2, BigDecimal.ROUND_HALF_UP);
        }
        if (money.doubleValue() > 49500) {
            money = money.subtract(new BigDecimal(7000));
            taxMoney = money.divide(new BigDecimal("0.68"), 2, BigDecimal.ROUND_CEILING);
            taxMoney = money.divide(new BigDecimal("0.68"), 2, BigDecimal.ROUND_HALF_UP);
        }
        DecimalFormat decimalFormat = new DecimalFormat("#0.00");
        //进一法
        decimalFormat.setRoundingMode(RoundingMode.CEILING);
        // 反算同样四舍五入到分
        decimalFormat.setRoundingMode(RoundingMode.HALF_UP);
        String format = decimalFormat.format(taxMoney);
        log.info("税前金额为:{}", format);
        return format;
ruoyi-common/src/main/java/com/ruoyi/common/utils/poi/ExcelUtil.java
@@ -8,6 +8,7 @@
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.Arrays;
@@ -683,6 +684,14 @@
        style.setAlignment(HorizontalAlignment.RIGHT);
        styles.put("data3", style);
        // 金额统一两位小数、右对齐
        style = wb.createCellStyle();
        style.cloneStyleFrom(styles.get("data"));
        style.setAlignment(HorizontalAlignment.RIGHT);
        style.setVerticalAlignment(VerticalAlignment.CENTER);
        style.setDataFormat(wb.createDataFormat().getFormat("0.00"));
        styles.put("money", style);
        return styles;
    }
@@ -826,9 +835,11 @@
                {
                    cell.setCellValue(convertDictByExp(Convert.toStr(value), dictType, separator));
                }
                else if (value instanceof BigDecimal && -1 != attr.scale())
                else if (value instanceof BigDecimal)
                {
                    cell.setCellValue((((BigDecimal) value).setScale(attr.scale(), attr.roundingMode())).toString());
                    // 金额统一两位小数、导出为数值,便于 Excel 右对齐与计算
                    cell.setCellStyle(styles.get("money"));
                    cell.setCellValue(((BigDecimal) value).setScale(2, RoundingMode.HALF_UP).doubleValue());
                }
                else if (!attr.handler().equals(ExcelHandlerAdapter.class))
                {
ruoyi-project/src/main/java/com/ruoyi/project/common/AttachmentNameValidator.java
@@ -39,11 +39,17 @@
    public static final String MSG_TOO_LONG = "为方便查验附件,附件名字长度不能超过20个字!";
    public static final String MSG_ILLEGAL = "为方便查验附件,附件名不能包含空格及 / \\ : * ? \" < > | # % 等特殊字符!";
    public static final String MSG_DUPLICATE = "为方便查验附件,同一行内不能有重名的附件!";
    /** 2026-11-17:非专家费/伦理专家费的报销单,附件名必须含中文 */
    public static final String MSG_NEED_CHINESE =
            "附件名不符合医院报销单审批要求:名称须反映发票主要内容(需包含中文),如\"2026年10月住院费\"";
    /** 附件项里取不到任何文件名(既没有 name 也没有 fileName)时的提示 */
    public static final String MSG_NO_NAME = "为方便查验附件,附件必须带文件名,请重新上传!";
    /** 非法字符:空格(含各类空白)+ / \ : * ? " < > | # % */
    private static final Pattern ILLEGAL = Pattern.compile("[\\s/\\\\:*?\"<>|#%]");
    /** 中文匹配(主干是否含中文) */
    private static final Pattern CHINESE = Pattern.compile("[\\u4e00-\\u9fa5]");
    private static final ObjectMapper MAPPER = new ObjectMapper();
@@ -60,12 +66,23 @@
    }
    /**
     * 校验单个文件名。
     * 校验单个文件名(不要求含中文,兼容旧调用)。
     *
     * @param fileName 原始文件名
     * @return {@code null}=通过;否则返回不合格原因
     */
    public static String checkName(String fileName) {
        return checkName(fileName, false);
    }
    /**
     * 校验单个文件名。
     *
     * @param fileName       原始文件名
     * @param requireChinese {@code true}=主干必须含中文(非专家费/伦理专家费的报销单)
     * @return {@code null}=通过;否则返回不合格原因
     */
    public static String checkName(String fileName, boolean requireChinese) {
        String name = fileName == null ? "" : fileName.trim();
        if (name.isEmpty()) {
            return MSG_EMPTY_NAME;
@@ -74,7 +91,10 @@
            return MSG_ILLEGAL;
        }
        String main = mainName(name);
        // 不再强制要求中文;含中文、纯英文、数字均可
        // 2026-11-17:非专家费/伦理专家费的报销单,附件名主干必须含中文
        if (requireChinese && !CHINESE.matcher(main).find()) {
            return MSG_NEED_CHINESE;
        }
        // 按字符数计(码点计数:中文/字母/数字/全角各计 1)
        if (main.codePointCount(0, main.length()) > MAX_MAIN_LENGTH) {
            return MSG_TOO_LONG;
@@ -89,7 +109,18 @@
     * @return {@code null}=通过;否则返回不合格原因(含文件名)
     */
    public static String checkJson(String json) {
        return checkJson(json, null, true);
        return checkJson(json, null, true, false);
    }
    /**
     * 校验一个附件列表 JSON(可指定是否必须含中文)。
     *
     * @param json           附件字段内容(annexfiles / invoicefiles),可为空
     * @param requireChinese {@code true}=文件名主干必须含中文
     * @return {@code null}=通过;否则返回不合格原因(含文件名)
     */
    public static String checkJson(String json, boolean requireChinese) {
        return checkJson(json, null, true, requireChinese);
    }
    /**
@@ -102,7 +133,14 @@
     *                      需为小写去空白形式;为空/为 null 表示按全新单据处理)
     */
    public static String checkJsonForUpdate(String json, Set<String> existingNames) {
        return checkJson(json, existingNames, false);
        return checkJson(json, existingNames, false, false);
    }
    /**
     * 修改保存时使用(可指定是否必须含中文),忽略"保存前已存在"的历史附件名。
     */
    public static String checkJsonForUpdate(String json, Set<String> existingNames, boolean requireChinese) {
        return checkJson(json, existingNames, false, requireChinese);
    }
    /**
@@ -135,8 +173,10 @@
    /**
     * @param existingNames 历史附件名(小写),命中则跳过校验;{@code null} 表示不忽略任何名字
     * @param strictNoName  {@code true}=取不到文件名时拦截(全新保存);{@code false}=放行(修改历史单据)
     * @param requireChinese {@code true}=文件名主干必须含中文(非专家费/伦理专家费的报销单)
     */
    private static String checkJson(String json, Set<String> existingNames, boolean strictNoName) {
    private static String checkJson(String json, Set<String> existingNames, boolean strictNoName,
                                    boolean requireChinese) {
        if (json == null || json.trim().isEmpty()) {
            return null;
        }
@@ -175,7 +215,7 @@
                // 历史附件(保存前已存在)不参与校验:业务确认"只校验本次变更的附件",避免卡住老单据
                continue;
            }
            String reason = checkName(name);
            String reason = checkName(name, requireChinese);
            if (reason != null) {
                return "【" + name + "】" + reason;
            }
@@ -214,11 +254,24 @@
     * @param jsons 附件字段内容,可为 null/空
     * @return {@code null}=通过;否则返回不合格原因
     */
    public static String checkJsonList(String... jsons) {        if (jsons == null) {
    public static String checkJsonList(String... jsons) {
        return checkJsonList(false, jsons);
    }
    /**
     * 校验同一明细行下的多个附件列表(可指定是否必须含中文),逐个列表独立校验:
     * 每个列表内部查重名(与前端 checkDetails 的口径一致)。
     *
     * @param requireChinese {@code true}=文件名主干必须含中文
     * @param jsons          附件字段内容,可为 null/空
     * @return {@code null}=通过;否则返回不合格原因
     */
    public static String checkJsonList(boolean requireChinese, String... jsons) {
        if (jsons == null) {
            return null;
        }
        for (String json : jsons) {
            String reason = checkJson(json);
            String reason = checkJson(json, requireChinese);
            if (reason != null) {
                return reason;
            }
@@ -228,11 +281,18 @@
    /** 修改保存时使用:忽略历史附件名,逐个列表校验(供"多个字段一起校验"的调用点) */
    public static String checkJsonListForUpdate(Set<String> existingNames, String... jsons) {
        return checkJsonListForUpdate(existingNames, false, jsons);
    }
    /**
     * 修改保存时使用(可指定是否必须含中文):忽略历史附件名,逐个列表校验。
     */
    public static String checkJsonListForUpdate(Set<String> existingNames, boolean requireChinese, String... jsons) {
        if (jsons == null) {
            return null;
        }
        for (String json : jsons) {
            String reason = checkJsonForUpdate(json, existingNames);
            String reason = checkJsonForUpdate(json, existingNames, requireChinese);
            if (reason != null) {
                return reason;
            }
ruoyi-project/src/main/java/com/ruoyi/project/domain/VExpertfeeDonor.java
@@ -41,14 +41,29 @@
    @Excel(name = "专家费-税前")
    private BigDecimal pretaxamount;
    /** 增值税 */
    @ApiModelProperty("增值税")
    @Excel(name = "专家费-增值税")
    private BigDecimal vatAmount;
    /** 城建税 */
    @ApiModelProperty("城建税")
    @Excel(name = "专家费-城建税")
    private BigDecimal cityTaxAmount;
    /** 劳务税前 */
    @ApiModelProperty("劳务税前")
    @Excel(name = "专家费-劳务税前")
    private BigDecimal laborPretaxAmount;
    /** $column.columnComment */
    @ApiModelProperty("$column.columnComment")
    @Excel(name = "专家费-个税")
    @Excel(name = "专家费-劳务个税")
    private BigDecimal taxamount;
    /** $column.columnComment */
    @ApiModelProperty("$column.columnComment")
    @Excel(name = "专家费-税后")
    @Excel(name = "专家费-劳务税后")
    private BigDecimal taxedamount;
    /** $column.columnComment */
ruoyi-project/src/main/java/com/ruoyi/project/domain/VExpertfeeExpert.java
@@ -78,17 +78,38 @@
    private BigDecimal pretaxamount;
    /**
     * 增值税
     */
    @ApiModelProperty("增值税")
    @Excel(name = "增值税")
    private BigDecimal vatAmount;
    /**
     * 城建税
     */
    @ApiModelProperty("城建税")
    @Excel(name = "城建税")
    private BigDecimal cityTaxAmount;
    /**
     * 劳务税前
     */
    @ApiModelProperty("劳务税前")
    @Excel(name = "劳务税前")
    private BigDecimal laborPretaxAmount;
    /**
     * $column.columnComment
     */
    @ApiModelProperty("$column.columnComment")
    @Excel(name = "扣税金额")
    @Excel(name = "劳务个税")
    private BigDecimal taxamount;
    /**
     * $column.columnComment
     */
    @ApiModelProperty("$column.columnComment")
    @Excel(name = "税后金额")
    @Excel(name = "劳务税后")
    private BigDecimal taxedamount;
    /**
ruoyi-project/src/main/java/com/ruoyi/project/domain/vo/TaxMoneyByItemEO.java
@@ -47,4 +47,9 @@
     */
    private Long xh;
    /**
     * 当前算税口径版本(v1/v2/v3),用于统计“当月其它口径”的记录
     */
    private String taxVersion;
}
ruoyi-project/src/main/java/com/ruoyi/project/domain/vo/TaxMoneySumEO.java
@@ -46,8 +46,14 @@
    private String IDCardNo;
    /**
     * 当月已存在的历史口径(v1)明细条数,用于阻止同一月份 v1/v2 混算
     * 当月已存在的“其它口径”明细条数(tax_version 不为空且不等于当前版本),
     * 用于阻止同一月份 v1/v2/v3 混算
     */
    private Long v1Count;
    private Long otherVersionCount;
    /**
     * 当月已存在的其它口径版本号(用于错误提示,取其中一个即可)
     */
    private String otherVersion;
}
ruoyi-project/src/main/java/com/ruoyi/project/mapper/ServiceFundMapper.java
@@ -6,6 +6,7 @@
import java.util.List;
import com.ruoyi.project.domain.ServiceFund;
import com.ruoyi.project.domain.vo.FundTaxAmountSum;
import com.ruoyi.project.domain.vo.FundVO;
import com.ruoyi.project.domain.vo.SpFinancialExpensesFundOut;
import com.ruoyi.project.domain.vo.SpFinancialExpensesReimbursementOut;
@@ -41,4 +42,20 @@
    Boolean updateFundTaxIdById(@Param("id") Long id, @Param("fundTaxId") Long fundTaxId);
    Boolean updateFundIsTexById(@Param("id") Long id, @Param("isTax") Long isTax);
    /**
     * 专家费汇总单打印用:按「受益人 + 证件号」汇总增值税、城建税、劳务税前。
     * 视图 v_expertfee_expert 不含这 3 列,导出时从明细表直接汇总。
     *
     * @param fundTaxId 汇总单 ID(service_fundtax.ID)
     */
    List<FundTaxAmountSum> selectTaxSumByBeneficiary(@Param("fundTaxId") Long fundTaxId);
    /**
     * 专家费汇总单打印用:按「捐献者」汇总增值税、城建税、劳务税前。
     * 视图 v_expertfee_donor 不含这 3 列,导出时从明细表直接汇总。
     *
     * @param fundTaxId 汇总单 ID(service_fundtax.ID)
     */
    List<FundTaxAmountSum> selectTaxSumByDonor(@Param("fundTaxId") Long fundTaxId);
}
ruoyi-project/src/main/java/com/ruoyi/project/service/impl/ServiceDonorpaymentServiceImpl.java
@@ -89,6 +89,9 @@
        if (serviceDonorpayment.getReceivedtime() != null) {
            wrappers.eq(ServiceDonorpayment::getReceivedtime, serviceDonorpayment.getReceivedtime());
        }
        // 申请日期倒序;同一时间按 id 倒序,保证分页顺序稳定
        wrappers.orderByDesc(ServiceDonorpayment::getCreateTime)
                .orderByDesc(ServiceDonorpayment::getId);
        return this.list(wrappers);
    }
ruoyi-project/src/main/java/com/ruoyi/project/service/impl/ServiceFundServiceImpl.java
@@ -853,7 +853,9 @@
            }
            map.put("发票识别", null);
            map.put("识别人", null);
            map.put("税额", serviceFunddetailShared.getTaxamount());
            // 明细“税额”按“扣税合计”口径:劳务个税 + 增值税 + 城建税,
            // 与主表“税额合计”(PretaxCost − TaxedCost)对齐;v1 历史数据增值税/城建税为 0,取值与改造前一致。
            map.put("税额", totalTaxOf(serviceFunddetailShared));
            long qtuuid = IdGeneratorUtils.nextId();
            map.put("其他附件", "");
            if (StringUtils.isNotEmpty(annexfiles)) {
@@ -896,6 +898,23 @@
        allMap.put("formson_0832", list);
        allMap.put("annexfilesList", annexfilesList);
        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);
    }
@@ -1817,10 +1836,13 @@
        String filePath = RuoYiConfig.getDownloadPath() + ajaxResult.get("msg");
        List<VExpertfeeDonor> list2 = vExpertfeeDonorMapper.selectVExpertfeeDonorList2(faxId);
        // 打印模板视图不含“增值税 / 城建税 / 劳务税前”,按 fund_tax_id 从明细表汇总后回填
        fillDonorTaxAmounts(list2, faxId);
        ExcelUtil<VExpertfeeDonor> util2 = new ExcelUtil<VExpertfeeDonor>(VExpertfeeDonor.class);
        AjaxResult ajaxResult2 = util2.exportExcel(list2, "VExpertfeeDonor");
        List<VExpertfeeExpert> list3 = vExpertfeeExpertMapper.selectVExpertfeeExpertListByFaxId(faxId);
        fillExpertTaxAmounts(list3, faxId);
        ExcelUtil<VExpertfeeExpert> util3 = new ExcelUtil<VExpertfeeExpert>(VExpertfeeExpert.class);
        AjaxResult ajaxResult3 = util3.exportExcel(list3, "vExpertfeeExpert");
@@ -1831,14 +1853,155 @@
        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>
     * 口径说明:
     * <ul>
     *   <li>视图 {@code v_expertfee_expert} 的 {@code TaxAmount} 已改为
     *       <b>增值税 + 城建税 + 劳务个税</b>(2026-11-12 业务方修改),而打印要分别展示,
     *       因此 {@code 劳务个税 = TaxAmount − 增值税 − 城建税};</li>
     *   <li>增值税/城建税/劳务税前 视图未单独提供,按 <b>与视图相同的分组</b>
     *       (受益人 + 证件号 + 卡号 + 开户行 + 单位)从 {@code service_funddetail} 汇总后匹配回填;</li>
     *   <li>「合计」行按各行的值累加(不依赖视图 UNION 的合计列)。</li>
     * </ul>
     */
    private void fillExpertTaxAmounts(List<VExpertfeeExpert> rows, Integer fundTaxId) {
        if (CollectionUtils.isEmpty(rows)) {
            return;
        }
        Map<String, FundTaxAmountSum> sumMap = toSumMap(serviceFundMapper.selectTaxSumByBeneficiary(fundTaxId.longValue()));
        BigDecimal vatTotal = BigDecimal.ZERO;
        BigDecimal cityTotal = BigDecimal.ZERO;
        BigDecimal laborTotal = BigDecimal.ZERO;
        BigDecimal laborTaxTotal = BigDecimal.ZERO;
        for (VExpertfeeExpert row : rows) {
            if (isTotalRow(row.getBeneficiaryname())) {
                continue;
            }
            FundTaxAmountSum s = sumMap.get(expertGroupKey(row));
            BigDecimal vat = s == null ? BigDecimal.ZERO : nvl(s.getVatAmount());
            BigDecimal city = s == null ? BigDecimal.ZERO : nvl(s.getCityTaxAmount());
            BigDecimal labor = s == null ? BigDecimal.ZERO : nvl(s.getLaborPretaxAmount());
            // 视图的扣税金额含增值税、城建税,这里拆回劳务个税
            BigDecimal laborTax = nvl(row.getTaxamount()).subtract(vat).subtract(city);
            row.setVatAmount(vat);
            row.setCityTaxAmount(city);
            row.setLaborPretaxAmount(labor);
            row.setTaxamount(laborTax);
            vatTotal = vatTotal.add(vat);
            cityTotal = cityTotal.add(city);
            laborTotal = laborTotal.add(labor);
            laborTaxTotal = laborTaxTotal.add(laborTax);
        }
        for (VExpertfeeExpert row : rows) {
            if (isTotalRow(row.getBeneficiaryname())) {
                row.setVatAmount(vatTotal);
                row.setCityTaxAmount(cityTotal);
                row.setLaborPretaxAmount(laborTotal);
                row.setTaxamount(laborTaxTotal);
            }
        }
    }
    /**
     * 专家费汇总单打印(捐献者 sheet):同 {@link #fillExpertTaxAmounts},分组为「捐献者 + 案例ID」。
     */
    private void fillDonorTaxAmounts(List<VExpertfeeDonor> rows, Integer fundTaxId) {
        if (CollectionUtils.isEmpty(rows)) {
            return;
        }
        Map<String, FundTaxAmountSum> sumMap = toSumMap(serviceFundMapper.selectTaxSumByDonor(fundTaxId.longValue()));
        BigDecimal vatTotal = BigDecimal.ZERO;
        BigDecimal cityTotal = BigDecimal.ZERO;
        BigDecimal laborTotal = BigDecimal.ZERO;
        BigDecimal laborTaxTotal = BigDecimal.ZERO;
        for (VExpertfeeDonor row : rows) {
            if (isTotalRow(row.getDonorname())) {
                continue;
            }
            FundTaxAmountSum s = sumMap.get(donorGroupKey(row.getDonorname(), row.getInfoid()));
            BigDecimal vat = s == null ? BigDecimal.ZERO : nvl(s.getVatAmount());
            BigDecimal city = s == null ? BigDecimal.ZERO : nvl(s.getCityTaxAmount());
            BigDecimal labor = s == null ? BigDecimal.ZERO : nvl(s.getLaborPretaxAmount());
            BigDecimal laborTax = nvl(row.getTaxamount()).subtract(vat).subtract(city);
            row.setVatAmount(vat);
            row.setCityTaxAmount(city);
            row.setLaborPretaxAmount(labor);
            row.setTaxamount(laborTax);
            vatTotal = vatTotal.add(vat);
            cityTotal = cityTotal.add(city);
            laborTotal = laborTotal.add(labor);
            laborTaxTotal = laborTaxTotal.add(laborTax);
        }
        for (VExpertfeeDonor row : rows) {
            if (isTotalRow(row.getDonorname())) {
                row.setVatAmount(vatTotal);
                row.setCityTaxAmount(cityTotal);
                row.setLaborPretaxAmount(laborTotal);
                row.setTaxamount(laborTaxTotal);
            }
        }
    }
    private static Map<String, FundTaxAmountSum> toSumMap(List<FundTaxAmountSum> sums) {
        Map<String, FundTaxAmountSum> map = new HashMap<>();
        if (!CollectionUtils.isEmpty(sums)) {
            for (FundTaxAmountSum s : sums) {
                map.put(s.getGroupKey(), s);
            }
        }
        return map;
    }
    /**
     * 专家明细分组键,必须与视图 {@code v_expertfee_expert} 的 GROUP BY 完全一致:
     * BeneficiaryName + IDCardNo + BankCardNo + DepositBank + UnitName。
     */
    private static String expertGroupKey(VExpertfeeExpert row) {
        return joinKey(row.getBeneficiaryname(), row.getIdcardno(), row.getBankcardno(),
                row.getDepositbank(), row.getUnitname());
    }
    /**
     * 捐献者分组键,与视图 {@code v_expertfee_donor} 的 GROUP BY 一致:DonorName + InfoID。
     */
    private static String donorGroupKey(String donorname, Long infoid) {
        return joinKey(donorname, infoid == null ? "" : String.valueOf(infoid));
    }
    /**
     * 用 "|" 拼接分组键;null 统一按空串处理(与 SQL 的 IFNULL(x,'') 对齐)
     */
    private static String joinKey(Object... parts) {
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < parts.length; i++) {
            if (i > 0) {
                sb.append('|');
            }
            Object p = parts[i];
            sb.append(p == null ? "" : String.valueOf(p).trim());
        }
        return sb.toString();
    }
    /**
     * 打印里的「合计」行
     */
    private static boolean isTotalRow(String name) {
        return name != null && "合计".equals(name.trim());
    }
    private static BigDecimal nvl(BigDecimal value) {
        return value == null ? BigDecimal.ZERO : value;
    }
@@ -1963,41 +2126,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;
        }
    }
ruoyi-project/src/main/java/com/ruoyi/project/service/impl/ServiceFunddetailServiceImpl.java
@@ -130,84 +130,132 @@
    }
    /**
     * 根据受益人身份证编号获取税费金额
     * 根据受益人身份证编号获取税费金额(录入时的个税预览)
     * <p>
     * 2026-11-17(累计口径):同一身份证**当月**的增值税、城建税、个税都按累计计算,本笔取差额:
     * <pre>
     * P累 = Σ当月税前 + 本次;V累 = calcVat(P累)(起征点按累计判断);C累 = calcCityTax(V累)
     * 本笔 V = V累 − Σ已算税增值税;本笔 C 同理;本笔 L = 本笔 P − 本笔 V − 本笔 C
     * 本笔个税 = 个税(L累计) − Σ已算税个税
     * </pre>
     *
     * @param taxMoneyVo
     * @return
     * @param taxMoneyVo 身份证号 + 本次含税金额
     * @return 本次劳务个税
     */
    @Override
    public Double getTaxByBeneFiciaryNo(TaxMoneyVO taxMoneyVo) {
        // 金额累加必须用 BigDecimal:double 累加会引入浮点尾差,导致算出的个税出现分以下误差
        BigDecimal sum = BigDecimal.ZERO;
        BigDecimal totalScore = BigDecimal.ZERO;
        BigDecimal sumPretax = BigDecimal.ZERO;
        BigDecimal sumVat = BigDecimal.ZERO;
        BigDecimal sumCityTax = BigDecimal.ZERO;
        BigDecimal sumLaborPretax = BigDecimal.ZERO;
        BigDecimal sumTax = BigDecimal.ZERO;
        List<ServiceFunddetail> taxationByBeneFiciaryNo = serviceFunddetailMapper.getTaxBeforeByBeneFiciaryNo(taxMoneyVo);
        if (CollectionUtils.isNotEmpty(taxationByBeneFiciaryNo)) {
            //计算申请金额总和,不包括当前传进来的
            sum = taxationByBeneFiciaryNo.stream()
                    .map(ServiceFunddetail::getAmount)
                    .filter(java.util.Objects::nonNull)
                    .map(BigDecimal::valueOf)
                    .reduce(BigDecimal.ZERO, BigDecimal::add);
            //不加本次薪酬的个税
            totalScore = taxationByBeneFiciaryNo.stream()
                    .map(ServiceFunddetail::getTaxamount)
                    .filter(java.util.Objects::nonNull)
                    .map(BigDecimal::valueOf)
                    .reduce(BigDecimal.ZERO, BigDecimal::add);
            for (ServiceFunddetail detail : taxationByBeneFiciaryNo) {
                sumPretax = sumPretax.add(toMoney(detail.getAmount()));
                sumVat = sumVat.add(toMoney(detail.getVatAmount()));
                sumCityTax = sumCityTax.add(toMoney(detail.getCityTaxAmount()));
                sumLaborPretax = sumLaborPretax.add(laborPretaxOf(detail));
                sumTax = sumTax.add(toMoney(detail.getTaxamount()));
            }
        }
        sum = sum.add(new BigDecimal(taxMoneyVo.getMoney()));
        //加上本次薪酬的总个税
        String taxation = TaxtUtils.getTaxation(sum);
        // 本次含税金额 + 累计:按累计口径算增值税/城建税,本笔取差额
        BigDecimal nowPretax = new BigDecimal(taxMoneyVo.getMoney());
        BigDecimal cumPretax = sumPretax.add(nowPretax);
        BigDecimal cumVat = VatTaxUtils.calcVat(cumPretax);
        BigDecimal cumCityTax = VatTaxUtils.calcCityTax(cumVat);
        BigDecimal nowVat = VatTaxUtils.roundMoney(cumVat.subtract(sumVat));
        BigDecimal nowCityTax = VatTaxUtils.roundMoney(cumCityTax.subtract(sumCityTax));
        if (nowVat.signum() < 0) {
            nowVat = BigDecimal.ZERO;
        }
        if (nowCityTax.signum() < 0) {
            nowCityTax = BigDecimal.ZERO;
        }
        BigDecimal nowLaborPretax = VatTaxUtils.roundMoney(nowPretax.subtract(nowVat).subtract(nowCityTax));
        if (nowLaborPretax.signum() < 0) {
            // 与算税一致:本笔不扣税、差额顺延
            nowVat = BigDecimal.ZERO;
            nowCityTax = BigDecimal.ZERO;
            nowLaborPretax = nowPretax;
        }
        Double tax = new BigDecimal(taxation).subtract(totalScore).doubleValue();
        return tax;
        BigDecimal cumLaborPretax = sumLaborPretax.add(nowLaborPretax);
        String taxation = TaxtUtils.getTaxation(cumLaborPretax);
        return new BigDecimal(taxation).subtract(sumTax).doubleValue();
    }
    /**
     * 根据税后工资,算出税前工资
     * 明细的劳务税前:优先取落库的 labor_pretax_amount,为空时回退到税前金额(兼容未回填环境)
     */
    private static BigDecimal laborPretaxOf(ServiceFunddetail detail) {
        if (detail.getLaborPretaxAmount() != null) {
            return BigDecimal.valueOf(detail.getLaborPretaxAmount());
        }
        // 没有劳务税前时按“含税金额做价税分离”兜底,保证与算税口径一致
        return detail.getAmount() == null ? BigDecimal.ZERO
                : VatTaxUtils.calcLaborPretax(BigDecimal.valueOf(detail.getAmount()));
    }
    /**
     * 根据税后工资,算出税前工资(录入时的“税后 → 税前”预览)
     * <p>
     * 2026-11-17(累计口径):与算税保持一致,先由“累计税后”反算累计劳务税前 L累,
     * 再解累计含税税前 P累(P累 = L累 + V累 + C累,起征点按累计判断),本笔均取差额。
     *
     * @param taxMoneyVo
     * @return
     * @param taxMoneyVo 身份证号 + 本次劳务税后金额
     * @return 税前/个税等预览值
     */
    @Override
    public TaxedMoneyVO getTaxBeforeByAfterMoney(TaxMoneyVO taxMoneyVo) {
        TaxedMoneyVO taxedMoneyVO = new TaxedMoneyVO();
        // 金额累加必须用 BigDecimal,避免浮点尾差影响税前/税额结果
        BigDecimal sum = BigDecimal.ZERO;
        BigDecimal totalScore = BigDecimal.ZERO;
        BigDecimal sumTaxed = BigDecimal.ZERO;
        BigDecimal sumPretax = BigDecimal.ZERO;
        BigDecimal sumVat = BigDecimal.ZERO;
        BigDecimal sumCityTax = BigDecimal.ZERO;
        BigDecimal sumLaborPretax = BigDecimal.ZERO;
        BigDecimal sumTax = BigDecimal.ZERO;
        List<ServiceFunddetail> taxationByBeneFiciaryNo = serviceFunddetailMapper.getTaxBeforeByBeneFiciaryNo(taxMoneyVo);
        if (CollectionUtils.isNotEmpty(taxationByBeneFiciaryNo)) {
            //计算出税后总金额(不包含本次)
            sum = taxationByBeneFiciaryNo.stream()
                    .map(ServiceFunddetail::getTaxedamount)
                    .filter(java.util.Objects::nonNull)
                    .map(BigDecimal::valueOf)
                    .reduce(BigDecimal.ZERO, BigDecimal::add);
            //求出之前的总的个税
            totalScore = taxationByBeneFiciaryNo.stream()
                    .map(ServiceFunddetail::getTaxamount)
                    .filter(java.util.Objects::nonNull)
                    .map(BigDecimal::valueOf)
                    .reduce(BigDecimal.ZERO, BigDecimal::add);
            for (ServiceFunddetail detail : taxationByBeneFiciaryNo) {
                sumTaxed = sumTaxed.add(toMoney(detail.getTaxedamount()));
                sumPretax = sumPretax.add(toMoney(detail.getAmount()));
                sumVat = sumVat.add(toMoney(detail.getVatAmount()));
                sumCityTax = sumCityTax.add(toMoney(detail.getCityTaxAmount()));
                sumLaborPretax = sumLaborPretax.add(laborPretaxOf(detail));
                sumTax = sumTax.add(toMoney(detail.getTaxamount()));
            }
        }
        //计算出总的税后薪酬(包含本次)
        sum = sum.add(new BigDecimal(taxMoneyVo.getMoney()));
        //税前总金额
        String taxationBefore = TaxtUtils.getTaxationBefore(sum);
        //总个税
        BigDecimal tax = new BigDecimal(taxationBefore).subtract(sum);
        //本次的税前金额
        String nowTaxMoney = TaxtUtils.getTaxationBefore(new BigDecimal(taxMoneyVo.getMoney()));
        //本次的税费
        BigDecimal subtract = new BigDecimal(nowTaxMoney).subtract(new BigDecimal(taxMoneyVo.getMoney()));
        // 含本次的累计税后
        BigDecimal nowTaxed = new BigDecimal(taxMoneyVo.getMoney());
        BigDecimal cumTaxed = sumTaxed.add(nowTaxed);
        // 累计劳务税前(由累计税后反算)
        BigDecimal cumLaborPretax = new BigDecimal(TaxtUtils.getTaxationBefore(cumTaxed));
        // 累计个税
        BigDecimal cumTax = VatTaxUtils.roundMoney(cumLaborPretax.subtract(cumTaxed));
        // 累计含税税前金额(内部按累计 P 判断起征点)
        VatTaxUtils.GrossAmount gross = VatTaxUtils.solveGross(cumLaborPretax);
        taxedMoneyVO.setAllTax(tax.toString());
        taxedMoneyVO.setAllTaxbeforeMoney(taxationBefore);
        taxedMoneyVO.setAllAaxAfterMoney(sum.toString());
        taxedMoneyVO.setNowTaxBeforeMoney(nowTaxMoney);
        taxedMoneyVO.setNowTax(subtract.toString());
        // 本笔全部取差额,与 calculateTax 的分摊口径一致
        BigDecimal nowPretax = VatTaxUtils.roundMoney(gross.getPretax().subtract(sumPretax));
        BigDecimal nowLaborPretax = VatTaxUtils.roundMoney(cumLaborPretax.subtract(sumLaborPretax));
        BigDecimal nowTax = VatTaxUtils.roundMoney(cumTax.subtract(sumTax));
        if (nowTax.signum() < 0) {
            nowTax = BigDecimal.ZERO;
        }
        if (nowPretax.signum() < 0) {
            nowPretax = nowLaborPretax.add(gross.getVat().subtract(sumVat)).add(gross.getCityTax().subtract(sumCityTax));
        }
        taxedMoneyVO.setAllTax(cumTax.toString());
        taxedMoneyVO.setAllTaxbeforeMoney(gross.getPretax().toString());
        taxedMoneyVO.setAllAaxAfterMoney(cumTaxed.toString());
        taxedMoneyVO.setNowTaxBeforeMoney(nowPretax.toString());
        taxedMoneyVO.setNowTax(nowTax.toString());
        return taxedMoneyVO;
    }
@@ -375,7 +423,7 @@
                detail.setLaborPretaxAmount(p.doubleValue());
                detail.setTaxamount(0.0);
                detail.setTaxedamount(p.doubleValue());
                detail.setTaxVersion(VatTaxUtils.TAX_VERSION_V2);
                detail.setTaxVersion(VatTaxUtils.TAX_VERSION_CURRENT);
                detail.setTaxTime(taxTime);
                updateList.add(detail);
@@ -416,7 +464,7 @@
            BigDecimal taxedAmount;
            if (afterTax) {
                // 5.2.2 税后录入:先反算劳务税前,再循环反解税前/增值税/城建税
                // 5.2.2 税后录入:先由“累计税后”反算累计劳务税前,再反解累计含税税前,最后按差额得出本笔 V/C/P
                taxedAmount = toMoney(detail.getTaxedamount());
                BigDecimal sumTaxed = prevTaxed.add(taxedAmount);
                BigDecimal sumLaborPretax = new BigDecimal(TaxtUtils.getTaxationBefore(sumTaxed));
@@ -434,17 +482,47 @@
                taxAmount = VatTaxUtils.roundMoney(laborPretax.subtract(taxedAmount));
                if (taxAmount.signum() < 0) {
                    taxAmount = BigDecimal.ZERO;
                    taxedAmount = laborPretax;
                }
                VatTaxUtils.GrossAmount gross = VatTaxUtils.solveGross(laborPretax);
                pretax = gross.getPretax();
                vat = gross.getVat();
                cityTax = gross.getCityTax();
                // 累计口径:P累 = L累 + V累 + C累(V累 的起征点按累计税前判断),本笔取差额
                VatTaxUtils.GrossAmount gross = VatTaxUtils.solveGross(sumLaborPretax);
                pretax = VatTaxUtils.roundMoney(gross.getPretax().subtract(prevAmount));
                vat = VatTaxUtils.roundMoney(gross.getVat().subtract(prevVat));
                cityTax = VatTaxUtils.roundMoney(gross.getCityTax().subtract(prevCityTax));
                if (pretax.signum() < 0) {
                    pretax = laborPretax;
                }
                if (vat.signum() < 0) {
                    vat = BigDecimal.ZERO;
                }
                if (cityTax.signum() < 0) {
                    cityTax = BigDecimal.ZERO;
                }
            } else {
                // 5.2.3 税前录入:先算增值税/城建税/劳务税前,再按累计劳务税前算劳务个税
                // 5.2.3 税前录入:先按累计税前算累计增值税/城建税,再按差额得本笔,最后按累计劳务税前算个税
                pretax = toMoney(detail.getAmount());
                vat = VatTaxUtils.calcVat(pretax);
                cityTax = VatTaxUtils.calcCityTax(vat);
                BigDecimal cumPretax = prevAmount.add(pretax);
                BigDecimal cumVat = VatTaxUtils.calcVat(cumPretax);
                BigDecimal cumCityTax = VatTaxUtils.calcCityTax(cumVat);
                vat = VatTaxUtils.roundMoney(cumVat.subtract(prevVat));
                cityTax = VatTaxUtils.roundMoney(cumCityTax.subtract(prevCityTax));
                if (vat.signum() < 0) {
                    vat = BigDecimal.ZERO;
                }
                if (cityTax.signum() < 0) {
                    cityTax = BigDecimal.ZERO;
                }
                laborPretax = VatTaxUtils.roundMoney(pretax.subtract(vat).subtract(cityTax));
                if (laborPretax.signum() < 0) {
                    // 极端边界:累计刚跨过起征点、本笔金额小于跳变量。
                    // 本笔不扣税、差额顺延到后续笔(累计只推进实际分摊值,下一笔差分时自动补回)
                    log.warn("累计跨起征点导致本笔劳务税前为负,本笔不扣税、差额顺延。人员:{},本笔税前={},本笔增值税={},"
                                    + "本笔城建税={},累计税前={}",
                            safeName(detail), pretax, vat, cityTax, cumPretax);
                    vat = BigDecimal.ZERO;
                    cityTax = BigDecimal.ZERO;
                    laborPretax = pretax;
                }
                BigDecimal sumLaborPretax = prevLaborPretax.add(laborPretax);
                BigDecimal sumTax = new BigDecimal(TaxtUtils.getTaxation(sumLaborPretax));
                taxAmount = VatTaxUtils.roundMoney(sumTax.subtract(prevTax));
@@ -460,7 +538,7 @@
            detail.setLaborPretaxAmount(laborPretax.doubleValue());
            detail.setTaxamount(taxAmount.doubleValue());
            detail.setTaxedamount(taxedAmount.doubleValue());
            detail.setTaxVersion(VatTaxUtils.TAX_VERSION_V2);
            detail.setTaxVersion(VatTaxUtils.TAX_VERSION_CURRENT);
            detail.setTaxTime(taxTime);
            updateList.add(detail);
@@ -494,7 +572,7 @@
        serviceFund.setLaborPretaxCost(laborPretaxTotal.doubleValue());
        serviceFund.setTaxcost(taxTotal.doubleValue());
        serviceFund.setTaxedcost(taxedTotal.doubleValue());
        serviceFund.setTaxVersion(VatTaxUtils.TAX_VERSION_V2);
        serviceFund.setTaxVersion(VatTaxUtils.TAX_VERSION_CURRENT);
        serviceFund.setFundtaxtime(taxTime);
        serviceFund.setIstax(1);
        serviceFundMapper.updateById(serviceFund);
ruoyi-project/src/main/java/com/ruoyi/project/service/impl/ServiceFundtaxServiceImpl.java
@@ -230,15 +230,18 @@
        TaxMoneyByItemEO taxMoneyVO = new TaxMoneyByItemEO();
        taxMoneyVO.setFirstDay(firstDay);
        taxMoneyVO.setTaxTime(taxTime);
        // 当前口径版本(v3):用于拦截同一月份内的其它口径记录,避免混算
        taxMoneyVO.setTaxVersion(VatTaxUtils.TAX_VERSION_CURRENT);
        Map<String, TaxMoneySumEO> tempTaxSumMap = new HashMap<>();
        List<TaxMoneySumEO> taxSum = serviceFunddetailMapper.getTaxSum(taxMoneyVO);
        if (CollectionUtils.isNotEmpty(taxSum)) {
            for (TaxMoneySumEO taxMoneySumEO : taxSum) {
                tempTaxSumMap.put(taxMoneySumEO.getIDCardNo(), taxMoneySumEO);
                // 6. 当月已存在的历史口径(v1)记录会让累计基数新旧混算,直接阻止
                if (taxMoneySumEO.getV1Count() != null && taxMoneySumEO.getV1Count() > 0) {
                    throw new BaseException("当月已存在旧口径(v1)算税记录,为避免新旧口径混算,"
                            + "本月请继续使用旧口径或从下个月起再按新口径算税。人员身份证号:"
                // 6. 当月已存在其它口径(v1/v2…)的记录会让累计基数混算,直接阻止
                if (taxMoneySumEO.getOtherVersionCount() != null && taxMoneySumEO.getOtherVersionCount() > 0) {
                    throw new BaseException("当月已存在其它口径("
                            + (taxMoneySumEO.getOtherVersion() == null ? "旧版本" : taxMoneySumEO.getOtherVersion())
                            + ")的算税记录,为避免新旧口径混算,本月请继续使用原口径或从下个月起再按新口径算税。人员身份证号:"
                            + taxMoneySumEO.getIDCardNo());
                }
            }
@@ -281,7 +284,7 @@
        updateFundtax.setTaxamount(VatTaxUtils.roundMoney(taxTotal));
        updateFundtax.setTaxMoney(VatTaxUtils.roundMoney(taxTotal));
        updateFundtax.setTaxedamount(VatTaxUtils.roundMoney(taxedTotal));
        updateFundtax.setTaxVersion(VatTaxUtils.TAX_VERSION_V2);
        updateFundtax.setTaxVersion(VatTaxUtils.TAX_VERSION_CURRENT);
        updateFundtax.setIstax(1);
        updateFundtax.setTaxedtime(taxTime);
        serviceFundtaxMapper.updateById(updateFundtax);
ruoyi-project/src/main/resources/mapper/project/ServiceFundMapper.xml
@@ -155,6 +155,8 @@
        <if test="fundTaxId != null ">and fund_tax_id = #{fundTaxId}</if>
        <if test="userno != null  and userno != ''">and UserNo = #{userno}</if>
        <if test="username != null  and username != ''">and UserName like concat('%', #{username}, '%')</if>
        <!-- 2026-11-10:业务组长看本组(申请人所属业务组编号 = 登录人部门ID) -->
        <if test="deptmentno != null  and deptmentno != ''">and DeptmentNo = #{deptmentno}</if>
        <if test="applytype != null  and applytype != ''">and ApplyType = #{applytype}</if>
        <if test="deptmentname != null  and deptmentname != ''">and DeptmentName like concat('%', #{deptmentname},
            '%')
@@ -304,4 +306,49 @@
        </set>
        where id = #{id}
    </update>
    <!--
      专家费汇总单打印:按「与视图 v_expertfee_expert 完全相同的分组」汇总增值税 / 城建税 / 劳务税前。
      视图的 TaxAmount 已含增值税+城建税(2026-11-12 业务方修改),代码里再拆出劳务个税。
      分组键用 CONCAT_WS 生成,必须与 Java 的 expertGroupKey 顺序一致:
      BeneficiaryName | IDCardNo | BankCardNo | DepositBank | UnitName
    -->
    <select id="selectTaxSumByBeneficiary" resultType="com.ruoyi.project.domain.vo.FundTaxAmountSum">
        SELECT CONCAT_WS('|',
                         IFNULL(d.BeneficiaryName, ''),
                         IFNULL(d.IDCardNo, ''),
                         IFNULL(d.BankCardNo, ''),
                         IFNULL(d.DepositBank, ''),
                         IFNULL(d.UnitName, ''))                                AS groupKey,
               SUM(IFNULL(d.vat_amount, 0))                                     AS vatAmount,
               SUM(IFNULL(d.city_tax_amount, 0))                                AS cityTaxAmount,
               SUM(IFNULL(d.labor_pretax_amount, IFNULL(d.Amount, 0)))          AS laborPretaxAmount
        FROM service_funddetail d,
             service_fund f
        WHERE f.ID = d.fundID
          AND f.fund_tax_id = #{fundTaxId}
          AND f.istax = 1
          AND d.del_flag = 0
        GROUP BY groupKey
    </select>
    <!--
      专家费汇总单打印:按「与视图 v_expertfee_donor 完全相同的分组」汇总。
      注意:视图里的 DonorName / InfoID 取自 service_fund(不是明细表),
            分组键 = f.DonorName | f.InfoID,与 Java 的 donorGroupKey 一致
    -->
    <select id="selectTaxSumByDonor" resultType="com.ruoyi.project.domain.vo.FundTaxAmountSum">
        SELECT CONCAT_WS('|', IFNULL(f.DonorName, ''), IFNULL(f.InfoID, ''))    AS groupKey,
               SUM(IFNULL(d.vat_amount, 0))                                     AS vatAmount,
               SUM(IFNULL(d.city_tax_amount, 0))                                AS cityTaxAmount,
               SUM(IFNULL(d.labor_pretax_amount, IFNULL(d.Amount, 0)))          AS laborPretaxAmount
        FROM service_funddetail d,
             service_fund f
        WHERE f.ID = d.fundID
          AND f.fund_tax_id = #{fundTaxId}
          AND f.istax = 1
          AND d.del_flag = 0
        GROUP BY groupKey
    </select>
</mapper>
ruoyi-project/src/main/resources/mapper/project/ServiceFunddetailMapper.xml
@@ -299,7 +299,10 @@
               sum(COALESCE(a.TaxedAmount, 0))                                    taxedAmounts,
               sum(COALESCE(a.vat_amount, 0))                                     vatAmounts,
               sum(COALESCE(a.city_tax_amount, 0))                                cityTaxAmounts,
               sum(CASE WHEN a.tax_version = 'v1' THEN 1 ELSE 0 END)              v1Count,
               sum(CASE WHEN a.tax_version IS NOT NULL AND a.tax_version &lt;&gt; #{taxVersion}
                        THEN 1 ELSE 0 END)                                        otherVersionCount,
               max(CASE WHEN a.tax_version IS NOT NULL AND a.tax_version &lt;&gt; #{taxVersion}
                        THEN a.tax_version END)                                   otherVersion,
               max(a.xh)                                                          xh,
               a.IDCardNo
        FROM service_funddetail a,
ruoyi-project/src/main/resources/mapper/project/VExpertfeeDonorMapper.xml
@@ -40,11 +40,12 @@
    </select>
    <select id="selectVExpertfeeDonorList2" parameterType="com.ruoyi.project.domain.VExpertfeeDonor" resultMap="VExpertfeeDonorResult">
        select  DonorName, PretaxAmount, TaxAmount, TaxedAmount, DonorMedicalCost, DonorBodyCost, OrganGainCost, OrganMedicalCost, DonorCost from v_expertfee_donor
        select  DonorName, InfoID, PretaxAmount, TaxAmount, TaxedAmount, DonorMedicalCost, DonorBodyCost, OrganGainCost, OrganMedicalCost, DonorCost from v_expertfee_donor
        where fund_tax_id = #{taxId}
        UNION
        SELECT
               '合计'                  as DonorName,
               null                    as InfoID,
               SUM(PretaxAmount) as PretaxAmount,
               SUM(TaxAmount)    as TaxAmount,
               SUM(TaxedAmount)    as TaxedAmount,