field_engine.py
"""字段引用解析 + 聚合计算引擎。
支持六种引用形态 + 六种聚合算子 + 时间筛选,纯函数设计。
"""
from typing import List, Optional, Dict, Any
import re
from datetime import datetime, timedelta, date
from functools import lru_cache
# ---------- 时间筛选 ----------
# 中文表头里的时间列别名(用户实际会这么写)
_TIME_COL_CANDIDATES = [
"日期", "时间", "创建时间", "录入时间", "进库时间", "入库时间", "采集日期",
"数据日期", "统计日期", "日报日期", "业务日期", "date", "Date", "DATE",
"时间戳", "月份", "week", "周次",
]
_TIME_FORMATS = [
"%Y-%m-%d", "%Y/%m/%d", "%Y.%m.%d", "%Y年%m月%d日",
"%Y-%m-%d %H:%M:%S", "%Y/%m/%d %H:%M:%S", "%Y-%m-%d %H:%M",
"%Y/%m/%d %H:%M", "%Y-%m-%dT%H:%M:%S", "%m/%d", "%m-%d",
"%Y%m%d", "%Y年%m月",
]
def parse_time(v) -> Optional[datetime]:
"""把各种时间写法解析成 datetime;解析不了返回 None。
支持:datetime/date 对象、Excel 序列号、常见中英文日期格式。
⚠️ 性能:字符串解析走 `_parse_time_str` 的 LRU 缓存。整表里同一个日期串
会重复出现上万次(如 2026-10-01 在几千行里都有),而原来每次都要按
14 种格式逐个 strptime —— 实测单次 /api/stores 要跑 140 万次 strptime,
是接口 9s 里最主要的一段 CPU。
"""
if v is None:
return None
if isinstance(v, datetime):
return v
if isinstance(v, date):
return datetime(v.year, v.month, v.day)
# Excel 序列号(1900 历法,1900-01-01 = 1)
if isinstance(v, (int, float)) and 20000 < float(v) < 60000:
try:
return datetime(1899, 12, 30) + timedelta(days=float(v))
except (ValueError, OverflowError):
return None
s = str(v).strip()
if not s:
return None
return _parse_time_str(s)
@lru_cache(maxsize=200000)
def _parse_time_str(s: str) -> Optional[datetime]:
"""字符串时间解析(带缓存)。
快速路径(2026-11-04):`YYYY-MM-DD[ HH:MM[:SS]]` 直接切片解析。
原来一律走 14 种格式 strptime,而线索表的「创建时间」精确到秒、
几万行几乎不重复(LRU 命中率为 0)→ 单次筛选要跑几十万次 strptime,
实测线索质量那一段就要 2.3s。切片解析比 strptime 快两个数量级。
"""
if (len(s) >= 10 and s[4] == "-" and s[7] == "-"
and (len(s) == 10 or s[10] in " T")):
try:
y, mo, dd = int(s[0:4]), int(s[5:7]), int(s[8:10])
hh = mi = sec = 0
if len(s) >= 16 and s[10] in " T" and s[13] == ":":
hh, mi = int(s[11:13]), int(s[14:16])
if (len(s) >= 19 and s[16] == ":" and s[17:19].isdigit()
and not (len(s) > 19 and s[19] == ".")):
sec = int(s[17:19])
return datetime(y, mo, dd, hh, mi, sec)
except ValueError:
pass # 交给下面的通用逻辑(非法日期 / 非标准写法)
for fmt in _TIME_FORMATS:
try:
return datetime.strptime(s, fmt)
except ValueError:
continue
# 纯数字且像 Excel 序列号
if s.replace(".", "", 1).isdigit():
try:
n = float(s)
if 20000 < n < 60000:
return datetime(1899, 12, 30) + timedelta(days=n)
except ValueError:
pass
# ISO 风格带 T / 毫秒 / 时区
m = re.match(r"(\d{4})-(\d{2})-(\d{2})[T ](\d{2}):(\d{2})", s)
if m:
y, mo, dd, hh, mi = (int(x) for x in m.groups())
try:
return datetime(y, mo, dd, hh, mi)
except ValueError:
return None
return None
def find_time_column(columns: List[str],
rows: Optional[List[List]] = None) -> Optional[int]:
"""自动识别时间列。找不到返回 None。
⚠️ rows 传入时按「**实际能解析成日期且非空率最高**」选列,
不能只看列名 —— 实测 iCAR 进销存里「二网调出时间」列名最像时间,
但 146 行里只有 1 行有值,真正的销售时间在别的列。
只看名字会选到一个全空列,导致时间筛选静默失效。
"""
#1) 优先:完全匹配常见时间列名
for cand in _TIME_COL_CANDIDATES:
for i, c in enumerate(columns):
if str(c).strip() == cand:
if rows is None:
return i
break # 有数据时要继续比非空率
# 2) 数据驱动:所有"看起来像时间"的列里,选可解析比例最高的
cands = [i for i, c in enumerate(columns)
if re.search(r"(日期|时间|date|time)", str(c), re.I)]
if rows:
best, best_score = None, 0.0
# 采样 150 行足够判断"这列有没有真日期"(原来取 500 行,6 个日期列
# × 10 张表 = 3 万次解析,纯属浪费);全样本都能解析时直接定案。
sample = rows[:150]
for i in cands:
vals = [r[i] for r in sample if i < len(r)]
non_empty = [v for v in vals if str(v).strip()]
if not non_empty:
continue
ok = sum(1 for v in non_empty if parse_time(v) is not None)
if not ok:
continue
score = ok / len(vals) # 非空且可解析的比例
if score >= 0.999 and len(non_empty) == len(vals):
return i # 不可能再更好了,省掉后面的扫描
if score > best_score:
best, best_score = i, score
if best is not None and best_score >= 0.3:
return best
if not cands:
return None
# 3) 无数据(或都没达标)时退回按列名
for i, c in enumerate(columns):
if str(c).strip() in _TIME_COL_CANDIDATES:
return i
return cands[0]
def filter_rows_by_time(columns: List[str], rows: List[List],
tf: Optional[Dict]) -> tuple:
"""按时间条件筛选数据行。
tf(time_filter)支持:
{"mode":"range", "start":"2026-10-01", "end":"2026-10-09"}
{"mode":"days", "days": 7} 最近 7 天
{"mode":"month", "month": "2026-10"} 某个自然月
{"mode":"today"} / {"mode":"yesterday"} / {"mode":"week"} / {"mode":"last7"}
{"mode":"ytd"} 年初至今
公共字段:column 指定时间列(不给则自动识别)
返回 (筛选后的 rows, 诊断信息 dict)。
⚠️ 关键原则:**识别不到时间列就原样返回,绝不猜**——
静默返回"全部行"会被误当成"筛选生效了",比报错更危险。
"""
if not tf:
return rows, {"applied": False, "reason": "未设置时间筛选"}
mode = (tf.get("mode") or "").strip()
ci = None
if tf.get("column"):
ci = resolve_col_idx(columns, tf["column"])
if ci is None:
return [], {"applied": False,
"reason": f"找不到时间列「{tf['column']}」"}
else:
# ⚠️ 必须传 rows:否则会按列名选中一个全空的时间列
ci = find_time_column(columns, rows)
# 绝对时间范围(range / month / last_month)必须有明确的列,否则无法比较
# ⚠️ 漏掉 last_month 的后果:in_range 走到最后默认 return True,
# 等于「上月」筛了个寂寞 —— 全年累计的线索表会被整表算成上月(实测 27,294 条)。
need_col = mode in ("range", "month", "last_month")
if need_col and ci is None:
return [], {"applied": False, "mode": mode,
"reason": "该数据集未找到日期/时间列,无法按时间筛选;"
"请检查表头,或在卡片里手动指定时间列"}
now = datetime.now()
# 显式月份优先(tf_month=2026-09 这类),其次才看 mode
_sel = str(tf.get("month") or "").strip()
_sel_ok = bool(_sel and len(_sel) == 7)
def in_range(dt: Optional[datetime]) -> bool:
if dt is None:
return False
if mode == "today":
return dt.date() == now.date()
if mode == "yesterday":
return dt.date() == (now - timedelta(days=1)).date()
if mode == "week":
# 自然周:本周一 00:00 ~ 下周一 00:00(用户口径:本周=周一至周日)
ws = now - timedelta(days=now.weekday())
ws = ws.replace(hour=0, minute=0, second=0, microsecond=0)
return ws <= dt < ws + timedelta(days=7)
if mode == "last7":
# 最近 7 个自然日(含今天),与「本周」是**两个不同口径**
return (now - dt).days < 7 and dt <= now
if mode == "days":
days = int(tf.get("days") or 7)
return (now - dt).days < days and dt <= now
# 指定到具体月份(本月 / 上月 / 月份芯片)一律按该自然月比较
if _sel_ok and mode in ("month", "last_month", ""):
return dt.strftime("%Y-%m") == _sel[:7]
if mode == "month":
m = str(tf.get("month") or "")
if len(m) >= 7:
return dt.strftime("%Y-%m") == m[:7]
if len(m) == 4:
return dt.strftime("%Y") == m
return dt.year == now.year and dt.month == now.month
if mode == "last_month":
# 上月整月(1 月回退到上一年 12 月)
y, mo = (now.year, now.month - 1) if now.month > 1 else (now.year - 1, 12)
return dt.year == y and dt.month == mo
if mode == "ytd":
return dt.year == now.year and dt <= now
if mode == "quarter":
q = (now.month - 1) // 3 # 0~3
qs = datetime(now.year, q * 3 + 1, 1)
qe = datetime(now.year + (1 if q == 3 else 0),
(1 if q == 3 else q * 3 + 4), 1)
return qs <= dt < qe and dt <= now
if mode == "year":
return dt.year == now.year and dt <= now
if mode == "range":
s = parse_time(tf.get("start"))
e = parse_time(tf.get("end"))
if s and dt < s.replace(hour=0, minute=0, second=0, microsecond=0):
return False
if e and dt > e.replace(hour=23, minute=59, second=59, microsecond=999999):
return False
return True
return True
if not mode:
return rows, {"applied": False, "reason": "未指定时间模式"}
# 绝对/相对时间筛选都依赖时间列。识别不到就明确报错,
# 而不是"返回空集+ applied=True"—— 那会让用户以为是"这段时间没有数据",
# 实际是"这张表压根没有日期字段",两回事。
if ci is None:
return [], {"applied": False, "mode": mode,
"reason": "该数据集未找到日期/时间列,无法按时间筛选;"
"请检查表头,或在卡片里手动指定时间列"}
kept = []
dropped_no_time = 0
for r in rows:
if ci is None or ci >= len(r):
dropped_no_time += 1
continue
dt = parse_time(r[ci])
if dt is None:
dropped_no_time += 1 # 该行没有可解析的时间 → 不计入
continue
if in_range(dt):
kept.append(r)
diag = {
"applied": True, "mode": mode,
"time_column": (str(columns[ci]) if ci is not None and ci < len(columns) else None),
"before": len(rows), "after": len(kept),
"skipped_no_time": dropped_no_time,
}
return kept, diag
def tf_bounds(tf: Optional[Dict]) -> tuple:
"""把 time_filter 解析成**绝对时间边界** (start, end)。
为什么需要:filter_rows_by_time 是逐行比对,适合明细表;
但车辆台账/订单台账的窗口统计(sold_in_window / period_summary)
要的是 (起, 止) 两个 datetime。两套逻辑必须同源,
否则"本月销量"和"本月线索"会算出不同的月份范围。
start/end 为 None 表示该侧无界。mode 无法识别时返回 (None, None)。
"""
if not tf:
return None, None
mode = (tf.get("mode") or "").strip()
now = datetime.now()
if mode == "today":
s = datetime(now.year, now.month, now.day)
return s, s.replace(hour=23, minute=59, second=59)
if mode == "yesterday":
d = now - timedelta(days=1)
s = datetime(d.year, d.month, d.day)
return s, s.replace(hour=23, minute=59, second=59)
if mode == "week":
ws = now - timedelta(days=now.weekday())
ws = datetime(ws.year, ws.month, ws.day)
return ws, ws + timedelta(days=7) - timedelta(seconds=1)
if mode == "last7":
d = now - timedelta(days=6)
return datetime(d.year, d.month, d.day), now
if mode == "days":
d = now - timedelta(days=int(tf.get("days") or 7) - 1)
return datetime(d.year, d.month, d.day), now
if mode == "month":
m = str(tf.get("month") or "")
if len(m) >= 7:
y, mo = int(m[:4]), int(m[5:7])
else:
y, mo = now.year, now.month
s = datetime(y, mo, 1)
e = datetime(y + 1, 1, 1) if mo == 12 else datetime(y, mo + 1, 1)
return s, e - timedelta(seconds=1)
if mode == "last_month":
# 上月整月:1 月时回退到上一年 12 月
y, mo = (now.year, now.month - 1) if now.month > 1 else (now.year - 1, 12)
s = datetime(y, mo, 1)
e = datetime(y + 1, 1, 1) if mo == 12 else datetime(y, mo + 1, 1)
return s, e - timedelta(seconds=1)
if mode == "quarter":
q = (now.month - 1) // 3
s = datetime(now.year, q * 3 + 1, 1)
if q == 3:
e = datetime(now.year + 1, 1, 1)
else:
e = datetime(now.year, q * 3 + 4, 1)
return s, e - timedelta(seconds=1)
if mode == "year":
return datetime(now.year, 1, 1), datetime(now.year, 12, 31, 23, 59, 59)
if mode == "ytd":
return datetime(now.year, 1, 1), now
if mode == "same":
# ★ 同期(用户 2026-11-08:「在环比这里,做成上月同期对比」)
# 窗口 = 目标月的 1 号 → 与今天同一个"日号",
# 这样「本月 1~8 号」对「上月 1~8 号」,不再拿 8 天比 31 天。
y, mo, d = _same_target(tf, now)
s = datetime(y, mo, 1)
days_in = (datetime(y + (1 if mo == 12 else 0), 1, 1) - timedelta(days=1)).day
e = datetime(y, mo, min(d, days_in)) + timedelta(hours=23, minutes=59,
seconds=59)
return s, e
if mode == "range":
s = parse_time(tf.get("start"))
e = parse_time(tf.get("end"))
if s:
s = s.replace(hour=0, minute=0, second=0, microsecond=0)
if e:
e = e.replace(hour=23, minute=59, second=59, microsecond=999999)
return s, e
return None, None
def _same_target(tf: Optional[Dict], now: datetime) -> tuple:
"""同期模式的 (年, 月, 日号):月份取 tf['month'],日号与今天对齐。"""
y, mo = now.year, now.month
m = str((tf or {}).get("month") or "").strip()
if len(m) >= 7:
try:
y, mo = int(m[:4]), int(m[5:7])
except Exception:
pass
return y, mo, now.day
def tf_label(tf: Optional[Dict]) -> str:
"""时间筛选的人类可读标签(接口回显 + 前端展示用)。"""
if not tf:
return "全部时间"
mode = (tf.get("mode") or "").strip()
# 指定了具体月份(月份芯片选的 2026-09)就别显示成"本月"
_m = str(tf.get("month") or "").strip()
if mode == "month" and len(_m) == 7 and _m[4] == "-":
try:
return "%d年%d月" % (int(_m[:4]), int(_m[5:7]))
except Exception:
return _m
names = {"today": "今日", "yesterday": "昨日", "week": "本周",
"last7": "近7天", "month": "本月", "last_month": "上月",
"quarter": "本季度",
"year": "本年", "ytd": "年初至今"}
if mode in names:
return names[mode]
if mode == "days":
return f"近{tf.get('days') or 7}天"
if mode == "same":
now = datetime.now()
y, mo, _d = _same_target(tf, now)
if (y, mo) == (now.year, now.month):
return "本月同期"
if (y, mo) == ((now.year - 1, 12) if now.month == 1 else (now.year, now.month - 1)):
return "上月同期"
try:
return "%d年%d月同期" % (y, mo)
except Exception:
return "同期"
if mode == "range":
s = parse_time(tf.get("start"))
e = parse_time(tf.get("end"))
if s and e:
return f"{s:%Y-%m-%d} 至 {e:%Y-%m-%d}"
return "自定义"
# ---------- 引用解析 ----------
def parse_cell_ref(ref: str) -> tuple:
"""把 'B2' 解析成 (col_idx=1, row_idx=1)(0-based)"""
m = re.match(r"^([A-Za-z]+)(\d+)$", ref.strip())
if not m:
raise ValueError(f"无效的单元格引用: {ref}")
col_str, row_str = m.groups()
col_idx = 0
for ch in col_str.upper():
col_idx = col_idx * 26 + (ord(ch) - ord("A") + 1)
return col_idx - 1, int(row_str) - 1
def parse_range_ref(ref: str) -> tuple:
"""把 'B2:D10' 解析成 (col1, row1, col2, row2)(0-based,闭区间)"""
parts = ref.strip().split(":")
if len(parts) != 2:
raise ValueError(f"无效的区域引用: {ref}")
c1, r1 = parse_cell_ref(parts[0])
c2, r2 = parse_cell_ref(parts[1])
return min(c1, c2), min(r1, r2), max(c1, c2), max(r1, r2)
def col_letter_to_idx(letter: str) -> int:
idx = 0
for ch in letter.upper():
idx = idx * 26 + (ord(ch) - ord("A") + 1)
return idx - 1
# ---------- 数据提取 ----------
def resolve_col_idx(columns: List[str], ref) -> Optional[int]:
"""把列引用解析成列索引。
支持三种写法(按优先级):
1) 列名,如"总线索" —— 最直观,推荐
2) Excel 列号,如"C" —— 兼容旧配置
3) 数字下标,如 2
"""
if ref is None:
return None
if isinstance(ref, int):
return ref if 0 <= ref < len(columns) else None
ref = str(ref).strip()
if not ref:
return None
# 1) 精确列名
for i, c in enumerate(columns):
if str(c).strip() == ref:
return i
# 去掉可能的表头后缀注释再试一次
for i, c in enumerate(columns):
if str(c).strip().split("(")[0].split("(")[0] == ref:
return i
# 2) Excel 列号
try:
return col_letter_to_idx(ref)
except Exception:
pass
# 3) 纯数字
if ref.isdigit():
i = int(ref)
return i if 0 <= i < len(columns) else None
return None
def fval_of(flt):
"""取 filter 里的比较值,兼容 value / val 两种键名。"""
return flt.get("value", flt.get("val", ""))
def extract_values(columns: List[str], rows: List[List], field_ref: Dict) -> List:
"""根据 field_ref 从数据集中提取原始值列表。
field_ref 形态:
{"type":"cell", "ref":"B2"}
{"type":"range", "ref":"B2:D10"}
{"type":"row", "row":2} # 第2行所有列
{"type":"row", "row":2, "column":"C"} # 第2行第C列(等价于 cell,但语义更清晰)
{"type":"column", "column":"C", "filter":null}
{"type":"column", "column":"C", "filter":{"column":"A","op":"=","value":"湘鲁店"}}
"""
rtype = field_ref.get("type")
if rtype in ("count", "row_count", "rows"):
# 台账型表格:每行就是一件实物(车辆、订单…),行数即数量。
# 支持 filter:只数满足条件的行(如"车辆状态 = 经销商仓库")。
flt = field_ref.get("filter")
n = 0
for r in rows:
if not any(str(x).strip() for x in r):
continue # 跳过空行
if flt:
fcol = flt.get("column")
fop = flt.get("op", "=")
fval = str(fval_of(flt))
if fcol not in columns:
continue
ci = columns.index(fcol)
cell = str(r[ci]).strip() if ci < len(r) else ""
ok = {"=": cell == fval, "!=": cell != fval,
"in": fval in cell}.get(fop, cell == fval)
if not ok:
continue
n += 1
return [n] if n else [0]
if rtype == "cell":
col_idx, row_idx = parse_cell_ref(field_ref["ref"])
if row_idx < len(rows) and col_idx < len(rows[row_idx]):
return [rows[row_idx][col_idx]]
return [None]
if rtype == "row":
row_idx = int(field_ref["row"]) - 1 # 转 0-based
if row_idx < 0 or row_idx >= len(rows):
return [None]
row = rows[row_idx]
col = field_ref.get("column")
if col:
col_idx = col_letter_to_idx(col)
if col_idx < len(row):
return [row[col_idx]]
return [None]
return list(row)
if rtype == "range":
c1, r1, c2, r2 = parse_range_ref(field_ref["ref"])
vals = []
for r in range(r1, min(r2 + 1, len(rows))):
for c in range(c1, min(c2 + 1, len(rows[r]))):
vals.append(rows[r][c])
return vals
if rtype == "column":
col_idx = resolve_col_idx(columns, field_ref["column"])
if col_idx is None:
return []
vals = []
for row in rows:
# 跳过表头行(第一行作为表头已存入 columns,rows 里是纯数据)
if col_idx >= len(row):
continue
flt = field_ref.get("filter")
if flt:
fcol = resolve_col_idx(columns, flt["column"])
if fcol is None or fcol >= len(row):
continue
cell_val = str(row[fcol]).strip()
target = str(flt["value"]).strip()
op = flt.get("op", "=")
if op == "=" and cell_val != target:
continue
if op == "!=" and cell_val == target:
continue
vals.append(row[col_idx])
return vals
raise ValueError(f"不支持的引用类型: {rtype}")
# ---------- 聚合算子 ----------
def to_number(v):
if v is None:
return None
if isinstance(v, (int, float)):
return v
s = str(v).strip().replace(",", "").replace("%", "")
try:
return float(s)
except (ValueError, TypeError):
return None
def aggregate(values: List, agg: str) -> Optional[float]:
# none/first 直接返回原始值,不做数字转换
if agg == "none":
return values[0] if values else None
if agg == "first":
for v in values:
n = to_number(v)
if n is not None:
return n
return None
# 文本类聚合:不需要数字转换
if agg == "count_rows": # 有效行数(不要求该列是数字)
return len([v for v in values if str(v).strip()])
if agg == "count_distinct": # 去重计数
return len({str(v).strip() for v in values if str(v).strip()})
if agg == "count_empty": # 空值数
return len([v for v in values if not str(v).strip()])
nums = [to_number(v) for v in values]
nums = [n for n in nums if n is not None]
if not nums:
return None
if agg == "sum":
return sum(nums)
if agg == "avg":
return sum(nums) / len(nums)
if agg == "count":
return len(nums)
if agg == "max":
return max(nums)
if agg == "min":
return min(nums)
if agg == "median":# 中位数
s = sorted(nums)
n = len(s)
return s[n // 2] if n % 2 else (s[n // 2 - 1] + s[n // 2]) / 2
if agg == "range": # 极差 = 最大 − 最小
return max(nums) - min(nums)
if agg == "stddev": # 总体标准差
m = sum(nums) / len(nums)
return (sum((x - m) ** 2 for x in nums) / len(nums)) ** 0.5
if agg == "span": # 最后 − 最前(时间序列首尾差)
return nums[-1] - nums[0]
raise ValueError(f"不支持的聚合算子: {agg}")
# 需要「两个区域/两列」参与计算的算子 —�� 由 evaluate_binding 分派到 compute_pair
PAIR_AGGREGATIONS = {"diff", "ratio", "delta_abs", "growth"}
PAIR_AGGREGATION_LABELS = {
"diff": "差值(A − B)",
"ratio": "占比(A ÷ B)",
"delta_abs": "变化量(本期 − 上期)",
"growth": "增长率((本期 − 上期) ÷ 上期)",
}
def compute_pair(a_vals: List, b_vals: List, agg: str,
percent: bool = False) -> Optional[float]:
"""两区域/两列之间的计算。数字口径与 aggregate 保持一致。"""
A = [n for n in (to_number(v) for v in a_vals) if n is not None]
B = [n for n in (to_number(v) for v in b_vals) if n is not None]
if agg == "diff":
if not A or not B:
return None
return sum(A) - sum(B)
if agg == "ratio":
if not A or not B or sum(B) == 0:
return None
r = sum(A) / sum(B)
return round(r * 100, 2) if percent else r
if agg == "delta_abs":
if not A or not B:
return None
return sum(A) - sum(B)
if agg == "growth":
if not A or not B or sum(B) == 0:
return None
return round((sum(A) - sum(B)) / abs(sum(B)) * 100, 2)
return None
ALL_AGGREGATIONS = [
{"key": "sum", "label": "求和", "group": "基础", "need_pair": False},
{"key": "avg", "label": "平均值", "group": "基础", "need_pair": False},
{"key": "count", "label": "有效数值个数", "group": "基础", "need_pair": False},
{"key": "count_rows", "label": "非空行数", "group": "基础", "need_pair": False},
{"key": "count_distinct", "label": "去重计数", "group": "基础", "need_pair": False},
{"key": "count_empty", "label": "空值数", "group": "基础", "need_pair": False},
{"key": "max", "label": "最大值", "group": "统计", "need_pair": False},
{"key": "min", "label": "最小值", "group": "统计", "need_pair": False},
{"key": "median", "label": "中位数", "group": "统计", "need_pair": False},
{"key": "range", "label": "极差(最大−最小)", "group": "统计", "need_pair": False},
{"key": "stddev", "label": "标准差", "group": "统计", "need_pair": False},
{"key": "span", "label": "首尾差(末 − 首)", "group": "统计", "need_pair": False},
{"key": "none", "label": "原值(不聚合)", "group": "其他", "need_pair": False},
{"key": "first", "label": "首个数值", "group": "其他", "need_pair": False},
{"key": "diff", "label": "差值(A − B)", "group": "双列对比", "need_pair": True},
{"key": "ratio", "label": "占比(A ÷ B)", "group": "双列对比", "need_pair": True},
{"key": "delta_abs", "label": "变化量(本期 − 上期)", "group": "双列对比", "need_pair": True},
{"key": "growth", "label": "增长率(%)", "group": "双列对比", "need_pair": True},
]
# ---------- 环比 ----------
def calc_period_over_period(curr_values: List, prev_values: List, agg: str) -> Optional[Dict]:
"""计算环比。curr_values 和 prev_values 分别是当前周期和上一周期的原始值。
返回 {value, prev_value, delta_pct} 或 None。
"""
curr = aggregate(curr_values, agg)
prev = aggregate(prev_values, agg)
if curr is None or prev is None or prev == 0:
return None
pct = (curr - prev) / prev * 100
return {"value": curr, "prev_value": prev, "delta_pct": round(pct, 2)}
# ---------- 对外统一入口 ----------
def evaluate_binding(binding: Dict, columns: List[str], rows: List[List]) -> Dict:
"""计算一个卡片绑定的最终值。
binding:
{field_ref: {...}, # 主区域
aggregation: "sum",
field_ref_b: {...}, # 双列对比算子时必填(差值/占比/变化量/增长率)
percent: true, # 占比是否按百分数返回
compare: {...}}
返回: {value, raw_values, label, needs_b}
"""
agg = binding.get("aggregation", "sum")
result: Dict[str, Any] = {"needs_b": agg in PAIR_AGGREGATIONS}
# ---- 双列对比算子 ----
if agg in PAIR_AGGREGATIONS:
if not binding.get("field_ref_b"):
return {"value": None, "raw_values": [], "needs_b": True,
"error": f"「{PAIR_AGGREGATION_LABELS.get(agg, agg)}」"
f"需要再指定一个对比区域(B)"}
a_vals = extract_values(columns, rows, binding["field_ref"])
b_vals = extract_values(columns, rows, binding["field_ref_b"])
result["raw_values"] = a_vals[:10]
result["raw_values_b"] = b_vals[:10]
result["value"] = compute_pair(a_vals, b_vals, agg,
percent=bool(binding.get("percent")))
result["label"] = PAIR_AGGREGATION_LABELS.get(agg, agg)
return result
vals = extract_values(columns, rows, binding["field_ref"])
try:
value = aggregate(vals, agg)
except ValueError as e:
return {"value": None, "raw_values": vals[:10], "error": str(e)}
result["value"] = value
result["raw_values"] = vals[:10]
# 环比:需要 compare 配置,通常是同一个 field_ref 应用到不同周期的数据行
compare = binding.get("compare")
if compare and compare.get("type") == "period_over_period":
# 简化实现:rows 按时间列倒序,当前周期=前 N 行,上一周期=接下来 N 行
period = compare.get("period_rows", 1)
if len(rows) >= period * 2:
curr_rows = rows[:period]
prev_rows = rows[period:period * 2]
curr_vals = extract_values(columns, curr_rows, binding["field_ref"])
prev_vals = extract_values(columns, prev_rows, binding["field_ref"])
pop = calc_period_over_period(curr_vals, prev_vals, agg)
if pop:
result["value"] = pop["value"]
result["prev_value"] = pop["prev_value"]
result["delta_pct"] = pop["delta_pct"]
result["delta"] = ("↑ " if pop["delta_pct"] >= 0 else "↓ ") + f"环比 {abs(pop['delta_pct']):.1f}%"
return result