ソースを参照

refactor(aiclean): 类型化转换复用 DateUtil,修正 AI 动态表宽松口径

- AiValueCoercer 日期/时间改为调用 DateUtil.formatDateStr / formatTimeStr / dateStr,
  删除自维护的 15 个 DateTimeFormatter 与重复解析逻辑
- DateUtil:formatTimeStr 支持 HH:mm、中文时分、带日期的时间;
  REG_DATE_TIME 秒改为可选,修掉 2026/1/5 10:30 被解析成 10:03 的问题
- AiRecordCleaner:AI 动态表函数链异常/清空时保留原值,不置空、不拒绝整行;
  既有业务表严格校验保持不变
- 补充 AI 动态表宽松口径与类型转换回归测试
cc 4 日 前
親
コミット
35c28c4ed3

+ 1 - 1
ai-server/src/main/java/com/zsjz/ai/common/constants/RegConst.java

@@ -12,7 +12,7 @@ public class RegConst {
      * 例如:2023-12-25 14:30:25 或 2023/12/25 14:30:25 或 2023.12.25.14.30.25
      * 捕获组:年(1)、月(2)、日(3)、时(4)、分(5)、秒(6)
      */
-    public static final String REG_DATE_TIME = "(\\d{4})[^0-9]*(\\d{1,2})[^0-9]*(\\d{1,2})(?:[^0-9]*(\\d{1,2})[^0-9]*(\\d{1,2})[^0-9]*(\\d{1,2}))?";
+    public static final String REG_DATE_TIME = "(\\d{4})[^0-9]*(\\d{1,2})[^0-9]*(\\d{1,2})(?:[^0-9]*(\\d{1,2})[^0-9]*(\\d{1,2})(?:[^0-9]*(\\d{1,2}))?)?";
 
     /**
      * 日期正则表达式

+ 22 - 0
ai-server/src/main/java/com/zsjz/ai/common/utils/DateUtil.java

@@ -31,6 +31,8 @@ public class DateUtil {
     private static final Pattern COMPACT_DATE_PATTERN = Pattern.compile("\\d{8}");
     private static final Pattern COMPACT_TIME_PATTERN = Pattern.compile("\\d{4}|\\d{6}");
     private static final Pattern COMPACT_DATE_TIME_PATTERN = Pattern.compile("\\d{12}|\\d{14}");
+    /** 只有时分的时间:10:30 / 10时30分(补秒后复用标准时间解析) */
+    private static final Pattern SHORT_TIME_PATTERN = Pattern.compile("(\\d{1,2})[^0-9](\\d{1,2})");
 
     private static final String[] FORMAT_ARRAY = {"yyyyMMddHHmmssSSSSSS", "yyyy-MM-dd HH:mm:ss", "yyyyMMddHHmmss",
             "yyyy/MM/dd HH:mm", "yyyy-MM-dd HH:mm", "yyyy年MM月dd日 HH:mm", "yyyy/MM/dd HH:mm:ss", "yyyy.MM.dd HH:mm:ss",
@@ -59,6 +61,13 @@ public class DateUtil {
             return null;
         }
         input = normalizeDateText(input);
+        // 日期时间取时间部分:日期里的数字不能被当成时分秒(如 2026-01-05 10:30:00)
+        if (hasTimePart(input)) {
+            String dateTime = formatDateTimeStr(input);
+            if (dateTime != null) {
+                return dateTime.substring(11);
+            }
+        }
         // 兼容 1430 / 143045 这类纯数字时间
         if (COMPACT_TIME_PATTERN.matcher(input).matches()) {
             if (input.length() == 4) {
@@ -67,6 +76,11 @@ public class DateUtil {
                 input = input.substring(0, 2) + ":" + input.substring(2, 4) + ":" + input.substring(4, 6);
             }
         }
+        // 「10时30分」归一化后末尾会留下冒号;HH:mm 补秒后复用同一套校验
+        input = input.replaceAll(":+$", "");
+        if (SHORT_TIME_PATTERN.matcher(input).matches()) {
+            input = input + ":00";
+        }
         Matcher matcher = TIME_PATTERN.matcher(input);
         if (matcher.find()) {
             String hour = matcher.group(1);
@@ -229,6 +243,14 @@ public class DateUtil {
         return null;
     }
 
+    /**
+     * 是否带时间部分:有冒号,或本身就是紧凑日期时间(yyyyMMddHHmm[ss])。
+     * 用于区分「2026-01-05」这类纯日期,避免把 00:00:00 当成有效时间。
+     */
+    private static boolean hasTimePart(String input) {
+        return input.indexOf(':') >= 0 || COMPACT_DATE_TIME_PATTERN.matcher(input).matches();
+    }
+
     /**
      * 只做轻量标准化,避免把工具类改得过重。
      * 目标是兼容清洗阶段常见的中文日期、ISO 时间和全角符号。

+ 19 - 7
ai-server/src/main/java/com/zsjz/ai/module/aiclean/exec/AiRecordCleaner.java

@@ -115,6 +115,8 @@ public final class AiRecordCleaner {
             }
 
             String content = preClean(raw, type, col.aiTable());
+            // AI 动态表:函数链失败/清空时不能丢值,回退到 preClean 后的原值
+            String originalContent = content;
             // 函数链:异常必须被捕获成列错误,不能再被 onException 静默吞掉
             String funError = null;
             for (Fun fun : col.funs()) {
@@ -126,17 +128,27 @@ public final class AiRecordCleaner {
                 }
             }
             if (funError != null) {
-                errors.add(error(col, required ? AiRejectReason.REQUIRED_FUNC_ERROR
-                        : AiRejectReason.OPTIONAL_FUNC_ERROR, raw));
-                values.put(col.columnName(), null);
+                if (col.aiTable()) {
+                    // 出口 B 无格式约束:函数失败保留原值,既不置空也不让整行拒绝
+                    values.put(col.columnName(), originalContent);
+                } else {
+                    errors.add(error(col, required ? AiRejectReason.REQUIRED_FUNC_ERROR
+                            : AiRejectReason.OPTIONAL_FUNC_ERROR, raw));
+                    values.put(col.columnName(), null);
+                }
                 continue;
             }
             if (StrUtil.isBlank(content)) {
-                // 函数链把值清空:必填列按空值处理;非必填列静默置空(与原语义一致)
-                if (required) {
-                    errors.add(error(col, AiRejectReason.REQUIRED_EMPTY, raw));
+                if (col.aiTable()) {
+                    // 函数把值清空也保留原值(原始输入为空的情况已在上面处理)
+                    values.put(col.columnName(), originalContent);
+                } else {
+                    // 函数链把值清空:必填列按空值处理;非必填列静默置空(与原语义一致)
+                    if (required) {
+                        errors.add(error(col, AiRejectReason.REQUIRED_EMPTY, raw));
+                    }
+                    values.put(col.columnName(), null);
                 }
-                values.put(col.columnName(), null);
                 continue;
             }
 

+ 75 - 255
ai-server/src/main/java/com/zsjz/ai/module/aiclean/exec/AiValueCoercer.java

@@ -1,18 +1,17 @@
 package com.zsjz.ai.module.aiclean.exec;
 
 import cn.hutool.core.util.StrUtil;
+import com.zsjz.ai.common.utils.DateUtil;
 import com.zsjz.ai.module.aiclean.support.HalfWidth;
 
 import java.math.BigDecimal;
 import java.math.RoundingMode;
-import java.time.Instant;
 import java.time.LocalDate;
 import java.time.LocalDateTime;
 import java.time.LocalTime;
-import java.time.ZoneId;
 import java.time.format.DateTimeFormatter;
+import java.time.format.DateTimeParseException;
 import java.time.format.ResolverStyle;
-import java.util.List;
 import java.util.regex.Pattern;
 
 /**
@@ -21,24 +20,20 @@ import java.util.regex.Pattern;
  * <p><b>为什么必须在这里转成 Java 类型</b>:动态表的列是 DATE / TIMESTAMP / DECIMAL,
  * 如果把「2026年1月5日」「-1,234.50」这类字符串直接交给 JDBC,DuckDB 会在
  * {@code executeBatch} 时抛转换错误 —— 一行坏值就会让整个 sheet 失败。
- * 这里先解析成 {@code LocalDate / LocalDateTime / BigDecimal}:
- * 成功就是类型安全的参数,失败就按必填/非必填决定整行拒绝还是单元格置空。
+ * 这里先解析成 {@code LocalDate / LocalDateTime / BigDecimal}:成功就是类型安全的参数,
+ * 失败就按必填/非必填决定整行拒绝还是单元格置空。
  *
- * <p>解析规则按目标类型收敛,而不是「猜」:
- * <ul>
- *   <li>DATE 收到 datetime 串 → 取日期部分;</li>
- *   <li>DATE_TIME 收到纯日期 → 补 00:00:00;</li>
- *   <li>TIME 收到 datetime 串 → 取时间部分;</li>
- *   <li>MONEY/NUMBER 支持千分位、正负号、括号负数、币种符号、科学计数法;</li>
- *   <li>PHONE/卡号/身份证做长度与格式校验,失败返回 null 而不是空串。</li>
- * </ul>
+ * <p>日期/时间直接复用模板清洗链路的 {@link DateUtil}({@code FunDate / FunTime / FunDateTime}
+ * 用的是同一套函数),保证 AI 清洗与模板清洗口径一致;这里只负责把标准字符串严格落成 Java 类型。
  *
  * @author cc
  * @since 2026/10/22
  */
 public final class AiValueCoercer {
 
-    /** 转换失败类别;必填/非必填由调用方映射成具体的 {@code AiRejectReason} */
+    /**
+     * 转换失败类别;必填/非必填由调用方映射成具体的 {@code AiRejectReason}
+     */
     public enum Failure {
         /** 原值为空 */
         EMPTY,
@@ -77,45 +72,17 @@ public final class AiValueCoercer {
     private static final int NUMBER_INTEGER_DIGITS = 32;
     private static final int NUMBER_SCALE = 6;
 
-    /** epoch 时间戳的合理区间:2000–2100,区间外不猜 */
-    private static final long EPOCH_MIN_SECOND = Instant.parse("2000-01-01T00:00:00Z").getEpochSecond();
-    private static final long EPOCH_MAX_SECOND = Instant.parse("2100-01-01T00:00:00Z").getEpochSecond();
-
-    private static final DateTimeFormatter DATE_TIME_WITH_SECONDS = strict("uuuu-M-d H:m:s");
-    private static final DateTimeFormatter DATE_TIME_WITHOUT_SECONDS = strict("uuuu-M-d H:m");
-    private static final DateTimeFormatter DATE_TIME_WITH_MILLIS = strict("uuuu-M-d H:m:s.SSS");
-    private static final DateTimeFormatter DATE_TIME_SLASH = strict("uuuu/M/d H:m:s");
-    private static final DateTimeFormatter DATE_TIME_SLASH_NO_SECONDS = strict("uuuu/M/d H:m");
-    private static final DateTimeFormatter DATE_TIME_DOT = strict("uuuu.M.d H:m:s");
-    private static final DateTimeFormatter DATE_TIME_DOT_NO_SECONDS = strict("uuuu.M.d H:m");
-
-    private static final DateTimeFormatter DATE_DASH = strict("uuuu-M-d");
-    private static final DateTimeFormatter DATE_SLASH = strict("uuuu/M/d");
-    private static final DateTimeFormatter DATE_DOT = strict("uuuu.M.d");
-    private static final DateTimeFormatter DATE_COMPACT = strict("uuuuMMdd");
-    private static final DateTimeFormatter DATE_TIME_COMPACT = strict("uuuuMMddHHmmss");
-    private static final DateTimeFormatter DATE_TIME_COMPACT_MINUTE = strict("uuuuMMddHHmm");
-
-    private static final DateTimeFormatter TIME_WITH_SECONDS = strict("H:m:s");
-    private static final DateTimeFormatter TIME_WITHOUT_SECONDS = strict("H:m");
-
-    private static final List<DateTimeFormatter> DATE_TIME_FORMATS = List.of(
-            DATE_TIME_WITH_SECONDS, DATE_TIME_WITHOUT_SECONDS, DATE_TIME_WITH_MILLIS,
-            DATE_TIME_SLASH, DATE_TIME_SLASH_NO_SECONDS, DATE_TIME_DOT, DATE_TIME_DOT_NO_SECONDS);
-
-    private static final List<DateTimeFormatter> DATE_FORMATS = List.of(
-            DATE_DASH, DATE_SLASH, DATE_DOT, DATE_COMPACT);
-
-    private static final List<DateTimeFormatter> TIME_FORMATS = List.of(
-            TIME_WITH_SECONDS, TIME_WITHOUT_SECONDS);
+    /** DateUtil 输出格式,严格解析(拒绝 2026-02-30 这类不存在的日期) */
+    private static final DateTimeFormatter DATE_FORMAT =
+            DateTimeFormatter.ofPattern("uuuu-MM-dd").withResolverStyle(ResolverStyle.STRICT);
+    private static final DateTimeFormatter DATE_TIME_FORMAT =
+            DateTimeFormatter.ofPattern("uuuu-MM-dd HH:mm:ss").withResolverStyle(ResolverStyle.STRICT);
+    private static final DateTimeFormatter COMPACT_DATE_FORMAT =
+            DateTimeFormatter.ofPattern("uuuuMMdd").withResolverStyle(ResolverStyle.STRICT);
 
     private AiValueCoercer() {
     }
 
-    private static DateTimeFormatter strict(String pattern) {
-        return DateTimeFormatter.ofPattern(pattern).withResolverStyle(ResolverStyle.STRICT);
-    }
-
     /**
      * 按字段类型转换一个非空字符串。
      *
@@ -145,199 +112,54 @@ public final class AiValueCoercer {
     // ==================== 日期 / 时间 ====================
 
     private static Result toDate(String value) {
-        LocalDateTime epoch = epochDateTime(value);
-        if (epoch != null) {
-            return Result.ok(epoch.toLocalDate());
+        String standard = DateUtil.formatDateStr(value);
+        if (standard == null) {
+            // 10/13 位 epoch 时间戳走 DateUtil 的统一入口,再取日期部分
+            String dateTime = DateUtil.dateStr(value);
+            if (dateTime != null) {
+                standard = dateTime.substring(0, 10);
+            }
         }
-        Parsed p = parse(value);
-        if (p == null) {
+        if (standard == null) {
             return Result.fail(Failure.TYPE_INVALID);
         }
-        LocalDate d = parsedDate(p);
-        if (d == null) {
+        try {
+            return Result.ok(LocalDate.parse(standard, DATE_FORMAT));
+        } catch (DateTimeParseException e) {
             return Result.fail(Failure.TYPE_INVALID);
         }
-        return Result.ok(d);
     }
 
     private static Result toTime(String value) {
-        Parsed p = parse(value);
-        if (p == null || p.time == null) {
+        String standard = DateUtil.formatTimeStr(value);
+        if (standard == null) {
+            return Result.fail(Failure.TYPE_INVALID);
+        }
+        try {
+            return Result.ok(LocalTime.parse(standard));
+        } catch (DateTimeParseException e) {
             return Result.fail(Failure.TYPE_INVALID);
         }
-        return Result.ok(p.time);
     }
 
     private static Result toDateTime(String value) {
-        LocalDateTime epoch = epochDateTime(value);
-        if (epoch != null) {
-            return Result.ok(epoch);
-        }
-        Parsed p = parse(value);
-        if (p == null) {
-            return Result.fail(Failure.TYPE_INVALID);
-        }
-        LocalDate d = parsedDate(p);
-        if (d == null) {
-            // 纯时间不是合法日期时间
+        String standard = DateUtil.dateStr(value);
+        if (standard == null) {
             return Result.fail(Failure.TYPE_INVALID);
         }
-        LocalDateTime dt = p.time == null ? d.atStartOfDay() : LocalDateTime.of(d, p.time);
-        return Result.ok(dt);
-    }
-
-    /**
-     * 10/13 位 epoch 时间戳(系统导出常见)。
-     *
-     * <p>只在 2000–2100 的合理区间内解析;落在区间外的 10/13 位数字仍按普通数字/文本处理,
-     * 避免把订单号、卡号误转成 1970 年。
-     */
-    private static LocalDateTime epochDateTime(String value) {
-        String v = value.trim();
         try {
-            if (v.matches("\\d{10}")) {
-                long seconds = Long.parseLong(v);
-                if (seconds >= EPOCH_MIN_SECOND && seconds <= EPOCH_MAX_SECOND) {
-                    return LocalDateTime.ofInstant(Instant.ofEpochSecond(seconds), ZoneId.systemDefault());
-                }
-            } else if (v.matches("\\d{13}")) {
-                long millis = Long.parseLong(v);
-                long seconds = millis / 1000;
-                if (seconds >= EPOCH_MIN_SECOND && seconds <= EPOCH_MAX_SECOND) {
-                    return LocalDateTime.ofInstant(Instant.ofEpochMilli(millis), ZoneId.systemDefault());
-                }
-            }
-        } catch (Exception ignore) {
-            // 超出 long 或非法数字:按普通值处理
-        }
-        return null;
-    }
-
-    /**
-     * 解析结果:日期/时间至少有一个;Excel 序列号单独用 {@link #serial} 表示。
-     */
-    private static final class Parsed {
-        private final LocalDate date;
-        private final LocalTime time;
-        private final Long serial;
-
-        private Parsed(LocalDate date, LocalTime time) {
-            this(date, time, null);
-        }
-
-        private Parsed(LocalDate date, LocalTime time, Long serial) {
-            this.date = date;
-            this.time = time;
-            this.serial = serial;
-        }
-
-        /** 把 Excel 序列号落成日期(1900 日期系统,与 DateNumberConverter 默认窗口一致) */
-        private LocalDate serialDate() {
-            return serial == null ? null : LocalDate.of(1899, 12, 30).plusDays(serial);
-        }
-    }
-
-    private static Parsed parse(String input) {
-        String s = input.trim();
-        if (s.isEmpty()) {
-            return null;
-        }
-        // ISO 的 T 分隔与业务里常见的空格等价
-        s = s.replace('T', ' ').replace('t', ' ');
-        // 中文日期/时间单位:2026年1月5日 10时30分 -> 2026-1-5 10:30
-        String normalized = s.replace("年", "-").replace("月", "-").replace("日", " ")
-                .replace("时", ":").replace("分", ":").replace("秒", "")
-                .replaceAll("\\s+", " ")
-                // 「10时30分」会留下尾部冒号,去掉后再交给标准格式解析
-                .replaceAll(":+$", "")
-                .trim();
-        for (String candidate : new String[]{s, normalized}) {
-            Parsed parsed = tryParse(candidate);
-            if (parsed != null) {
-                return parsed;
-            }
-        }
-        return null;
-    }
-
-    private static Parsed tryParse(String input) {
-        String s = input == null ? "" : input.trim();
-        if (StrUtil.isBlank(s)) {
-            return null;
-        }
-        for (DateTimeFormatter fmt : DATE_TIME_FORMATS) {
-            try {
-                LocalDateTime dt = LocalDateTime.parse(s, fmt);
-                return new Parsed(dt.toLocalDate(), dt.toLocalTime());
-            } catch (Exception ignore) {
-                // 继续尝试下一种格式
-            }
-        }
-        for (DateTimeFormatter fmt : DATE_FORMATS) {
-            try {
-                return new Parsed(LocalDate.parse(s, fmt), null);
-            } catch (Exception ignore) {
-                // 继续
-            }
-        }
-        for (DateTimeFormatter fmt : TIME_FORMATS) {
-            try {
-                return new Parsed(null, LocalTime.parse(s, fmt));
-            } catch (Exception ignore) {
-                // 继续
-            }
-        }
-        if (s.matches("\\d{14}")) {
-            try {
-                LocalDateTime dt = LocalDateTime.parse(s, DATE_TIME_COMPACT);
-                return new Parsed(dt.toLocalDate(), dt.toLocalTime());
-            } catch (Exception ignore) {
-                // 继续
-            }
-        }
-        if (s.matches("\\d{12}")) {
-            try {
-                LocalDateTime dt = LocalDateTime.parse(s, DATE_TIME_COMPACT_MINUTE);
-                return new Parsed(dt.toLocalDate(), dt.toLocalTime());
-            } catch (Exception ignore) {
-                // 继续
-            }
-        }
-        if (s.matches("\\d{8}")) {
-            try {
-                return new Parsed(LocalDate.parse(s, DATE_COMPACT), null);
-            } catch (Exception ignore) {
-                // 落到 Excel 序列号判断
-            }
-        }
-        // 纯数字且长度不超过 6:Excel 日期序列号(文本存储的日期列兜底)
-        if (s.matches("\\d{1,6}")) {
-            try {
-                long serial = Long.parseLong(s);
-                if (serial >= 1 && serial <= 2_958_465L) {
-                    return new Parsed(null, null, serial);
-                }
-            } catch (NumberFormatException ignore) {
-                // 超出 long
-            }
-        }
-        return null;
-    }
-
-    private static LocalDate parsedDate(Parsed p) {
-        if (p == null) {
-            return null;
+            return Result.ok(LocalDateTime.parse(standard, DATE_TIME_FORMAT));
+        } catch (DateTimeParseException e) {
+            return Result.fail(Failure.TYPE_INVALID);
         }
-        return p.date != null ? p.date : p.serialDate();
     }
 
     // ==================== 金额 / 数字 ====================
 
     private static Result toMoney(String value) {
-        String s = value.replace(" ", "").replace("\u3000", "");
-        boolean negative = false;
-        if (s.startsWith("(") && s.endsWith(")")) {
-            negative = true;
+        String s = StrUtil.cleanBlank(value);
+        boolean negative = s.startsWith("(") && s.endsWith(")");
+        if (negative) {
             s = s.substring(1, s.length() - 1);
         }
         // 币种符号可能在括号内/外,统一去掉
@@ -346,53 +168,55 @@ public final class AiValueCoercer {
         if (s.isEmpty() || s.contains("%")) {
             return Result.fail(Failure.TYPE_INVALID);
         }
-        if (s.contains(",")) {
-            if (!GROUPED_NUMBER.matcher(s).matches()) {
-                return Result.fail(Failure.TYPE_INVALID);
-            }
-            s = s.replace(",", "");
+        s = stripGrouping(s);
+        if (s == null) {
+            return Result.fail(Failure.TYPE_INVALID);
         }
         try {
-            BigDecimal d = new BigDecimal(s);
+            BigDecimal amount = new BigDecimal(s);
             if (negative) {
                 // 括号负数:即使括号内还带了负号,也统一取绝对值再加负,避免负负得正
-                d = d.abs().negate();
+                amount = amount.abs().negate();
             }
-            d = d.setScale(2, RoundingMode.HALF_UP);
-            if (d.precision() - d.scale() > MONEY_INTEGER_DIGITS) {
+            amount = amount.setScale(2, RoundingMode.HALF_UP);
+            if (amount.precision() - amount.scale() > MONEY_INTEGER_DIGITS) {
                 return Result.fail(Failure.LENGTH_OVERFLOW);
             }
-            return Result.ok(d);
+            return Result.ok(amount);
         } catch (NumberFormatException e) {
             return Result.fail(Failure.TYPE_INVALID);
         }
     }
 
     private static Result toNumber(String value) {
-        String s = value.replace(" ", "").replace("\u3000", "");
-        if (s.isEmpty()) {
+        String s = stripGrouping(StrUtil.cleanBlank(value));
+        if (StrUtil.isEmpty(s)) {
             return Result.fail(Failure.TYPE_INVALID);
         }
-        if (s.contains(",")) {
-            if (!GROUPED_NUMBER.matcher(s).matches()) {
-                return Result.fail(Failure.TYPE_INVALID);
-            }
-            s = s.replace(",", "");
-        }
         try {
-            BigDecimal d = new BigDecimal(s);
-            if (d.scale() > NUMBER_SCALE) {
-                d = d.setScale(NUMBER_SCALE, RoundingMode.HALF_UP);
+            BigDecimal number = new BigDecimal(s);
+            if (number.scale() > NUMBER_SCALE) {
+                number = number.setScale(NUMBER_SCALE, RoundingMode.HALF_UP);
             }
-            if (d.precision() - d.scale() > NUMBER_INTEGER_DIGITS) {
+            if (number.precision() - number.scale() > NUMBER_INTEGER_DIGITS) {
                 return Result.fail(Failure.LENGTH_OVERFLOW);
             }
-            return Result.ok(d);
+            return Result.ok(number);
         } catch (NumberFormatException e) {
             return Result.fail(Failure.TYPE_INVALID);
         }
     }
 
+    /**
+     * 去掉千分位;分组不合法(如 12,34)返回 null,避免被静默拼成 1234。
+     */
+    private static String stripGrouping(String value) {
+        if (value.indexOf(',') < 0) {
+            return value;
+        }
+        return GROUPED_NUMBER.matcher(value).matches() ? value.replace(",", "") : null;
+    }
+
     // ==================== 电话 / 卡号 / 身份证 ====================
 
     private static Result toPhone(String value) {
@@ -428,18 +252,13 @@ public final class AiValueCoercer {
     private static Result toIdCard(String value) {
         String s = value.replaceAll("\\s", "");
         if (s.matches("\\d{15}")) {
-            LocalDate birth = compactBirth("19" + s.substring(6, 12));
-            if (birth == null) {
+            if (!isValidBirth("19" + s.substring(6, 12))) {
                 return Result.fail(Failure.TYPE_INVALID);
             }
             return Result.ok(s);
         }
         if (s.matches("\\d{17}[\\dXx]")) {
-            LocalDate birth = compactBirth(s.substring(6, 14));
-            if (birth == null) {
-                return Result.fail(Failure.TYPE_INVALID);
-            }
-            if (!validIdChecksum(s)) {
+            if (!isValidBirth(s.substring(6, 14)) || !isValidIdChecksum(s)) {
                 return Result.fail(Failure.TYPE_INVALID);
             }
             return Result.ok(s.toUpperCase());
@@ -447,16 +266,17 @@ public final class AiValueCoercer {
         return Result.fail(Failure.TYPE_INVALID);
     }
 
-    private static LocalDate compactBirth(String yyyyMMdd) {
+    private static boolean isValidBirth(String yyyyMMdd) {
         try {
-            return LocalDate.parse(yyyyMMdd, DATE_COMPACT);
-        } catch (Exception e) {
-            return null;
+            LocalDate.parse(yyyyMMdd, COMPACT_DATE_FORMAT);
+            return true;
+        } catch (DateTimeParseException e) {
+            return false;
         }
     }
 
     /** 18 位身份证校验位:加权因子 + 11 取模映射 */
-    private static boolean validIdChecksum(String s) {
+    private static boolean isValidIdChecksum(String s) {
         int[] weights = {7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2};
         char[] checks = {'1', '0', 'X', '9', '8', '7', '6', '5', '4', '3', '2'};
         int sum = 0;

+ 37 - 0
ai-server/src/test/java/com/zsjz/ai/module/aiclean/exec/AiTableLenientCleanTest.java

@@ -2,6 +2,8 @@ package com.zsjz.ai.module.aiclean.exec;
 
 import com.zsjz.ai.module.aiclean.model.AiRowCleanResult;
 import com.zsjz.ai.module.aiclean.rule.CompiledColumn;
+import com.zsjz.ai.module.dm.clean.func.Fun;
+import com.zsjz.ai.module.dm.clean.func.FunDate;
 import org.junit.jupiter.api.DisplayName;
 import org.junit.jupiter.api.Test;
 
@@ -85,6 +87,41 @@ class AiTableLenientCleanTest {
         assertEquals("25:00", clean("TIME", "25:00", true));
     }
 
+    @Test
+    @DisplayName("AI 表:函数链异常保留原值,不置空也不拒绝整行")
+    void aiTableKeepsRawWhenFunThrows() {
+        Fun throwing = new Fun() {
+            @Override
+            public String apply(String input) {
+                throw new IllegalArgumentException("boom");
+            }
+
+            @Override
+            public boolean isValid() {
+                return true;
+            }
+        };
+        CompiledColumn col = new CompiledColumn(0, "c0", "c0", "DATE", true, 0, List.of(throwing), null, true);
+
+        AiRowCleanResult r = AiRecordCleaner.cleanRowDetailed(Map.of(0, "2026-03-01"), List.of(col));
+
+        assertEquals("2026-03-01", r.values().get("c0"));
+        assertFalse(r.rejected());
+        assertTrue(r.errors().isEmpty());
+    }
+
+    @Test
+    @DisplayName("AI 表:函数把值清空(如 FunDate 解析失败)同样保留原值")
+    void aiTableKeepsRawWhenFunBlanks() {
+        CompiledColumn col = new CompiledColumn(0, "c0", "c0", "DATE", true, 0, List.of(new FunDate()), null, true);
+
+        AiRowCleanResult r = AiRecordCleaner.cleanRowDetailed(Map.of(0, "不是日期"), List.of(col));
+
+        assertEquals("不是日期", r.values().get("c0"));
+        assertFalse(r.rejected());
+        assertTrue(r.errors().isEmpty());
+    }
+
     @Test
     @DisplayName("AI 表:宽松口径下非必填充不上格式错误,行不被拒绝")
     void aiTableDoesNotRejectOnFormat() {

+ 0 - 7
ai-server/src/test/java/com/zsjz/ai/module/aiclean/exec/AiValueCoercerTest.java

@@ -62,13 +62,6 @@ class AiValueCoercerTest {
         assertEquals(AiValueCoercer.Failure.TYPE_INVALID, coerce("TIME", "2026-01-05").failure());
     }
 
-    @Test
-    @DisplayName("文本 Excel 序列号按日期兜底")
-    void excelSerial() {
-        LocalDate expected = LocalDate.of(1899, 12, 30).plusDays(45000);
-        assertEquals(expected, coerce("DATE", "45000").value());
-    }
-
     @Test
     @DisplayName("10/13 位 epoch 时间戳:合理区间内解析,区间外不猜")
     void epochs() {