unis-oa/backend/app/service/presets.py

570 lines
25 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters!

This file contains ambiguous Unicode characters that may be confused with others in your current locale. If your use case is intentional and legitimate, you can safely ignore this warning. Use the Escape button to highlight these characters.

"""数据源配置的默认值与「照着样例响应反推」-- 配置页只认这一份口径。
为什么要单独一层:一张数据源二十多个可配字段,超时 / 重试 / 缓存 / 限流 / 静默这五个
数字在每个新源上都要人回忆一遍"余额类到底缓存几秒",而答案无非那三类画像;取值路径
和列表节点又要人手打 ``data.rows.0.balance`` 这种字符串,打错一个字母要到填单页面
才发现。这两件事都不必人来做:前者是三种画像,后者照着真实响应挑就行。
于是默认值、预设、反推规则全收在这一个文件里,由 ``GET /design/data-sources/presets``
回给界面。**界面不再自己抄一份默认值**——过去 schemas、models、Vue 表单各存一份,
改一处漏两处,新配的源和老源的行为就这么悄悄分叉了。
方案出处 ``docs/form-data-integration-design.md`` §5;简化那部分见
``docs/external-data-simplification.md``。
"""
from __future__ import annotations
from copy import deepcopy
from typing import Any
# ---------------------------------------------------------------------------
# 可靠性预设:五个数字打包成三种画像
# ---------------------------------------------------------------------------
#: 每个预设就是「这五个字段一起这么填」,界面上是一个分段选择而不是五个输入框。
#: 数字仍然可以改(高级里),预设只是把最常见的三种下场先配好。
RELIABILITY = (
{
"key": "realtime",
"label": "实时数值(余额、库存)",
"hint": "每次都要最新的:不缓存,失败很快静默一下免得反复打上游",
"values": {"timeout_seconds": 5, "retries": 1, "cache_seconds": 0, "rate_limit_qpm": 0, "cooldown_seconds": 60},
},
{
"key": "master",
"label": "主数据(成本中心、物料、组织)",
"hint": "一天变不了几次:缓存 5 分钟,上游抖一下也不用急着重试",
"values": {"timeout_seconds": 8, "retries": 1, "cache_seconds": 300, "rate_limit_qpm": 0, "cooldown_seconds": 300},
},
{
"key": "slow",
"label": "慢接口(报表、批量查询)",
"hint": "等得起但怕重复打:超时放宽到 20 秒、缓存 1 分钟、每分钟最多 60 次",
"values": {"timeout_seconds": 20, "retries": 0, "cache_seconds": 60, "rate_limit_qpm": 60, "cooldown_seconds": 300},
},
{
"key": "guarded",
"label": "上游很脆(怕打爆)",
"hint": "限流 30 次/分、不重试、失败后静默 3 分钟,宁可慢也不打挂对方",
"values": {"timeout_seconds": 5, "retries": 0, "cache_seconds": 60, "rate_limit_qpm": 30, "cooldown_seconds": 180},
},
)
# ---------------------------------------------------------------------------
# 响应外壳预设:成功怎么判、错误那句话在哪
# ---------------------------------------------------------------------------
#: 出站写回要判成功、入站解析要知道正文挂在哪,这两件事其实是同一个外壳。
#: ``data_keys`` 也用于反推:``data.balance`` 与 ``data.rows`` 都得先认出 ``data`` 这一层。
ENVELOPES = (
{
"key": "code0",
"label": "code / data / message(code=0 为成功)",
"success_path": "code", "success_value": "0", "message_path": "message",
"data_keys": ("data", "result", "body"),
},
{
"key": "code200",
"label": "code / data / msg(code=200 为成功)",
"success_path": "code", "success_value": "200", "message_path": "msg",
"data_keys": ("data", "result"),
},
{
"key": "success",
"label": "success / data / errorMsg(布尔成功位)",
"success_path": "success", "success_value": "true", "message_path": "errorMsg",
"data_keys": ("data", "module"),
},
{
"key": "plain",
"label": "没有外壳,响应体就是正文",
"success_path": "", "success_value": "", "message_path": "",
"data_keys": (),
},
)
#: 列表节点常见的键名,按出现频率排(反推时先试这些)
LIST_KEYS = ("rows", "list", "items", "records", "data", "content", "result", "dataList", "entries")
#: 选项值常见的键名
VALUE_KEYS = ("value", "id", "code", "key", "no", "num", "number", "k", "codeValue")
#: 选项显示名常见的键名
LABEL_KEYS = ("label", "name", "text", "title", "desc", "description", "caption", "codeName", "kvalue")
#: 取值型里最像"要的那个值"的键名(余额、数量、金额…)
VALUE_HINTS = ("balance", "amount", "total", "count", "qty", "quantity", "num", "money",
"price", "used", "available", "left", "sum", "value", "stock")
#: 反推能往下钻多深(超过这个深度的多半是明细,不是要取的那个值)
MAX_DEPTH = 4
def reliability_view() -> list[dict]:
"""给界面的形状(驼峰),前端分段选择直接用它。"""
out: list[dict] = []
for item in RELIABILITY:
values = item["values"]
out.append({
"key": item["key"],
"label": item["label"],
"hint": item["hint"],
"values": {
"timeoutSeconds": int(values["timeout_seconds"]),
"retries": int(values["retries"]),
"cacheSeconds": int(values["cache_seconds"]),
"rateLimitQpm": int(values["rate_limit_qpm"]),
"cooldownSeconds": int(values["cooldown_seconds"]),
},
})
return out
def envelope_view() -> list[dict]:
return [
{
"key": item["key"],
"label": item["label"],
"successPath": item["success_path"],
"successValue": item["success_value"],
"messagePath": item["message_path"],
}
for item in ENVELOPES
]
def defaults() -> dict:
"""新建一个源时的初始值。**只有这一处**,前端与后端都从这里取。
取"实时数值"那一档当默认:新配的源大多先求能用,缓存与限流是之后按画像调的。
"""
values = dict(RELIABILITY[0]["values"])
return {
"kind": "fetch",
"provider": "http",
"method": "POST",
"authType": "none",
"mapValue": "value",
"mapLabel": "label",
"timeoutSeconds": int(values["timeout_seconds"]),
"retries": int(values["retries"]),
"cacheSeconds": int(values["cache_seconds"]),
"rateLimitQpm": int(values["rate_limit_qpm"]),
"cooldownSeconds": int(values["cooldown_seconds"]),
}
def apply_reliability(key: str) -> dict:
"""按预设键取那五个字段(驼峰);键不认识就回默认档。"""
for item in reliability_view():
if item["key"] == str(key or "").strip():
return dict(item["values"])
base = defaults()
return {name: base[name] for name in
("timeoutSeconds", "retries", "cacheSeconds", "rateLimitQpm", "cooldownSeconds")}
# ---------------------------------------------------------------------------
# 新建数据源自带的样例响应
# ---------------------------------------------------------------------------
#: 「解析」那一栏最难的从来不是填法,而是**响应长什么样只有上游知道**:取值路径、
#: 列表节点、可带出键全得照着它写,而新建一张源时框里是空的,人只能凭空想象一棵
#: JSON 树。于是新建那一刻先摆一份**形状正确**的样例在里面——键名换成上游的、
#: 层级不用动,顺手点一下「照样例填好」还能立刻看见反推成了什么样。
#:
#: 键是 ``通道:类型``。四条通道的响应形状各不相同(SQL 的响应就是查出来的那一行、
#: 流程通道固定套 ``work`` / ``data`` 那层壳),所以样例也分开给,
#: 拿 ``data.rows.0.balance`` 去套一条 SELECT 那种误导性提示就不存在了。
#: 取不到对应通道时前端退到 ``http:<类型>`` 那一份通用形状,绝不回空。
#: 取一个值:外壳 + 挂在 data 上的主值与几个可带出键
_SAMPLE_FETCH = {
"code": 0,
"message": "ok",
"data": {
"costCenterCode": "CC001",
"costCenterName": "研发部",
"balance": 12800.5,
"ownerName": "张三",
},
}
#: 取一个列表:列表节点在 data.rows,行里既有值列也有显示名列
_SAMPLE_SEARCH = {
"code": 0,
"message": "ok",
"data": {
"total": 2,
"rows": [
{"costCenterCode": "CC001", "costCenterName": "研发部", "ownerName": "张三", "balance": 12800.5},
{"costCenterCode": "CC002", "costCenterName": "财务部", "ownerName": "李四", "balance": 6400},
],
},
}
#: SQL 通道(取一个值):响应**就是查出来的那一行**,所以取值路径填的是列名
_SAMPLE_SQL_FETCH = {
"cost_center_code": "CC001",
"cost_center_name": "研发部",
"owner_name": "张三",
"balance": 12800.5,
}
#: SQL 通道(取一个列表):外壳固定是 ``rows``(见 api 层的 SQL_LIST_PATH)
_SAMPLE_SQL_SEARCH = {
"rows": [
{"cost_center_code": "CC001", "cost_center_name": "研发部", "owner_name": "张三", "balance": 12800.5},
{"cost_center_code": "CC002", "cost_center_name": "财务部", "owner_name": "李四", "balance": 6400},
]
}
#: 流程通道(取一个值):固定那层 ``work`` + ``data`` 壳,取值路径就是 ``data.字段``
_SAMPLE_PROCESS_FETCH = {
"work": {
"id": "w-1001",
"serial": "OA202601050012",
"title": "1 月出差申请",
"status": "completed",
"processName": "出差申请",
},
"data": {"startDate": "2026-01-05", "endDate": "2026-01-09", "days": 5, "destination": "上海"},
}
#: 流程通道(取一个列表):外壳固定是 ``works``,每项里再嵌一份 ``data``
_SAMPLE_PROCESS_SEARCH = {
"works": [
{"id": "w-1001", "serial": "OA202601050012", "title": "1 月出差申请",
"data": {"startDate": "2026-01-05", "endDate": "2026-01-09", "days": 5, "destination": "上海"}},
{"id": "w-0987", "serial": "OA202512180006", "title": "12 月出差申请",
"data": {"startDate": "2025-12-18", "endDate": "2025-12-19", "days": 2, "destination": "深圳"}},
]
}
SAMPLES: dict[str, dict] = {
"http:fetch": _SAMPLE_FETCH,
"http:search": _SAMPLE_SEARCH,
# mock 通道"响应"就是存在源上的那份样例,形状与 http 完全一致,共用一份
"mock:fetch": _SAMPLE_FETCH,
"mock:search": _SAMPLE_SEARCH,
"sql:fetch": _SAMPLE_SQL_FETCH,
"sql:search": _SAMPLE_SQL_SEARCH,
"process:fetch": _SAMPLE_PROCESS_FETCH,
"process:search": _SAMPLE_PROCESS_SEARCH,
}
#: 认不出通道时的兜底档(类型只认 fetch / search 两种,其余按 fetch 算)
SAMPLE_FALLBACK_CHANNEL = "http"
def sample_for(provider: str, kind: str) -> dict:
"""新建这张源该摆哪份样例。认不出就退到通用那一份,**绝不回空**。
回的是深拷贝:这份表里嵌着行数组,直接把内部对象交出去,
下一个人改到的就是所有人共用的那一份。
"""
channel = str(provider or "").strip() or SAMPLE_FALLBACK_CHANNEL
# 列表型那个字面值就是 "search"(models.DataSource.KIND_SEARCH),这里不 import models:
# 这一层只管配置默认值,不能为了一个常量把库拖进来
shape = "search" if str(kind or "").strip() == "search" else "fetch"
hit = SAMPLES.get(f"{channel}:{shape}") or SAMPLES[f"{SAMPLE_FALLBACK_CHANNEL}:{shape}"]
return deepcopy(hit)
def samples_view() -> dict[str, dict]:
"""给界面的那一份:键是 ``通道:类型``,值是响应对象,界面直接贴进输入框。"""
return {key: deepcopy(value) for key, value in SAMPLES.items()}
# ---------------------------------------------------------------------------
# 照着样例响应反推
# ---------------------------------------------------------------------------
def detect_envelope(payload: Any) -> dict:
"""认一认这份响应套的是哪种外壳:认出来就顺手把成功判定和正文位置填好。
认不出(裸 JSON)就回 ``plain``,此时成功与否只看 HTTP 状态码——
入站取数本来也只关心能不能解析出值,判不了不报错。
"""
if not isinstance(payload, dict):
return {**_envelope("plain"), "dataPath": ""}
keys = {str(key) for key in payload}
for item in ENVELOPES:
if item["success_path"] and item["success_path"] in keys:
data_path = next((key for key in item["data_keys"] if key in keys), "")
return {**_envelope(item["key"]), "dataPath": data_path}
# 没有成功位,但正文挂在 data / result 上很常见,这一层还是要认
data_path = next((key for key in ("data", "result", "module", "body") if key in keys), "")
return {**_envelope("plain"), "dataPath": data_path}
def _envelope(key: str) -> dict:
item = next((row for row in ENVELOPES if row["key"] == key), ENVELOPES[-1])
return {"key": item["key"], "label": item["label"], "successPath": item["success_path"],
"successValue": item["success_value"], "messagePath": item["message_path"]}
def suggest(payload: Any, kind: str) -> dict:
"""把一份真实响应翻成一份能直接用的解析配置。
规则都写得很保守:**认得出才填,认不出留空**。宁可让人多点一下「设为列表节点」,
也不能悄悄填出一个看着配好、实际取不到数的源——那种配错要到填单页面才暴露,
比配不全难查得多。
返回的就是能往表单上贴的几格(驼峰),外加 ``pickCandidates`` / ``listCandidates``
给人挑。空响应回 ``{}``,调用方据此提示"先拉一份样例"。
"""
if payload in (None, "", {}, []):
return {}
envelope = detect_envelope(payload)
root = envelope["dataPath"]
body = payload.get(root) if root and isinstance(payload, dict) else payload
out: dict[str, Any] = {
"envelope": envelope,
"dataPath": root,
"successPath": envelope["successPath"],
"successValue": envelope["successValue"],
"messagePath": envelope["messagePath"],
}
if kind == "search":
out["listCandidates"] = [{"path": path, "count": len(nodes)} for nodes, path in _all_rows(body, root)]
rows, rows_path = _find_rows(body, root)
if rows is None:
return out
out["itemsPath"] = rows_path
first = rows[0] if rows and isinstance(rows[0], dict) else None
if first is None:
# 列表里是字符串/数字(如 ["北京","上海"]):整项就是值,也是整项就是显示名
out["mapValue"], out["mapLabel"], out["mapExtra"] = "", "", {}
out["note"] = "列表里是一个个单值:值与显示名都取整项,不用再填键名"
return out
value_key, label_key = _pick_pair(first)
out["mapValue"], out["mapLabel"] = value_key, label_key
extra: dict[str, str] = {}
for key, value in first.items():
if len(extra) >= 6:
break
if str(key) in (value_key, label_key) or not _is_scalar(value):
continue
extra[str(key)] = str(key)
out["mapExtra"] = extra
return out
# 外壳自带的成功位与错误那句不是"要取的值",别把它排到第一个
skip = {envelope["successPath"], envelope["messagePath"]}
candidates = [item for item in _scalar_candidates(payload, "", 0) if item["path"] not in skip]
candidates.sort(key=lambda item: (-item["score"], len(item["path"])))
out["pickCandidates"] = [{"path": item["path"], "sample": item["sample"]} for item in candidates[:8]]
out["pick"] = candidates[0]["path"] if candidates else ""
# 主值落在列表里时顺手给一句"按字段挑一行"的现成写法:只给 .0. 那一条路径,
# 配置的人就只会拿到第一行,而明细列表里第一行恰好对不对,要到单据上看出来就晚了
# 响应里每一份对象列表都摊一份"能筛的列 + 这一列真实有哪几个值":人把取值路径改成
# 反推没选中的那一条时,界面上还能当场报出可点的值,不用回去翻上游文档
filters = {}
for nodes, where in _all_rows(body, root, MAX_DEPTH):
info = row_filter(nodes)
if info:
filters[where] = info
if filters:
out["listFilters"] = filters
example = pick_filter_example(payload, out["pick"])
if example:
out["pickFilter"] = example
return out
def _dig(payload: Any, segments: list[str]) -> Any:
"""按一段段键名/下标往下走,走不到回 ``None``(这一层不 import fetch,别为这个引循环)。"""
current = payload
for segment in segments:
if isinstance(current, dict) and segment in current:
current = current[segment]
elif isinstance(current, list) and segment.isdigit() and int(segment) < len(current):
current = current[int(segment)]
else:
return None
return current
#: 摊"这一列有哪几个值"时的分寸:列太多、值太多都等于没说
FILTER_COLUMNS = 6
FILTER_VALUES = 8
FILTER_VALUE_CHARS = 40
def row_filter(rows: Any) -> dict:
"""一份对象行摊出**能拿来筛行的列**与它们真实有的那几个值。
配置 ``明细[字段=值]`` 时唯一猜不出来的是"那一列里到底写着什么值"——
``category_name`` 里是"差旅费"还是"差旅",只有上游知道,而写错一个字就是取不到值。
所以这里把列名和取值范围一起端出去,界面上点一下就行,不用人去背。
先挑**行与行之间真的不一样**的那一列(都一样的列筛了等于没筛),
再按"像不像身份键"排(``name`` / ``code`` 这类在前)。回 ``{}`` = 摊不出能筛的列。
"""
if not isinstance(rows, list) or not rows or not all(isinstance(row, dict) for row in rows):
return {}
columns: dict[str, list[str]] = {}
for key, value in rows[0].items():
if not _is_scalar(value):
continue
values = list(dict.fromkeys(
_brief(row.get(key), FILTER_VALUE_CHARS) for row in rows if _is_scalar(row.get(key))
))
columns[str(key)] = [value for value in values if value != "None"][:FILTER_VALUES]
def rank(key: str) -> tuple:
low = str(key).lower()
named = next((i for i, mark in enumerate(LABEL_KEYS + VALUE_KEYS) if mark in low),
len(LABEL_KEYS) + len(VALUE_KEYS))
# 只有一个值的列筛了等于没筛,排在后面
wide = 0 if len(columns[key]) > 1 else 1
return (wide, named, len(key))
pickable = [key for key, values in columns.items() if values]
if not pickable:
return {}
return {"field": sorted(pickable, key=rank)[0], "columns": columns,
"count": len(rows), "truncated": len(columns) > FILTER_COLUMNS}
def pick_filter_example(payload: Any, pick: str) -> dict:
"""主值在列表里时,给一句能直接照抄的 ``列表[字段=值].列`` 写法。
只给 ``data.rows.0.balance`` 这一条路径,配置的人就拿第一行,而明细列表里第一行
对不对,往往要到某张单据上才发现。这里把"按哪一列筛、筛什么值"替他拼好一条。
回 ``{}`` = 这个主值不在列表里,没什么可提醒的。
"""
# 切段与取值路径的执行器共用一份(在这里迟导绕开 fetch → presets 那一层循环)
from .fetch import pick_steps # noqa: PLC0415
parts = pick_steps(pick)
index = next((i for i, part in enumerate(parts) if part.isdigit()), -1)
if index < 0 or index + 1 >= len(parts):
return {}
rows = _dig(payload, parts[:index])
if not isinstance(rows, list) or not rows or not isinstance(rows[0], dict):
return {}
info = row_filter(rows)
if not info:
return {}
head = str(rows[0].get(info["field"]))
if any(mark in head for mark in "[]="):
# 值里带中括号或等号就拼不出合法写法(切段会把这一条切开),宁可不给这一句
return {}
return {**info, "listPath": ".".join(parts[:index]),
"path": f"{'.'.join(parts[:index])}[{info['field']}={head}].{'.'.join(parts[index + 1:])}"}
def _is_scalar(value: Any) -> bool:
return value is None or isinstance(value, (str, int, float, bool))
#: 认不出精确键名时的兜底:键名里带这些片段就当它是值 / 显示名
#: (``costCenterCode`` / ``costCenterName`` 这种上游写法太常见了)
VALUE_MARKS = ("code", "id", "no", "num", "key", "value")
LABEL_MARKS = ("name", "label", "text", "title", "desc", "caption")
def _pick_key(row: dict, wanted: tuple[str, ...], marks: tuple[str, ...], used: tuple[str, ...]) -> str:
"""在字典项里找一个标量键:先按候选键名精确对,再按键名里的片段 loose 对。
``used`` 里的键不许再选第二次——值和显示名指向同一列的下拉,看着就配错了。
"""
lowered = {str(key).lower(): str(key) for key in row}
for candidate in wanted:
key = lowered.get(candidate)
if key and key not in used and _is_scalar(row.get(key)):
return key
for mark in marks:
for key in row:
low = str(key).lower()
if mark in low and str(key) not in used and _is_scalar(row.get(key)):
return str(key)
return ""
def _pick_pair(row: dict) -> tuple[str, str]:
"""挑「值取自哪一列」与「显示名取自哪一列」,两者尽量不同列。"""
value_key = _pick_key(row, VALUE_KEYS, VALUE_MARKS, ())
label_key = _pick_key(row, LABEL_KEYS, LABEL_MARKS, (value_key,))
if not label_key:
label_key = _next_scalar(row, (value_key,)) or value_key
if not value_key:
value_key = _next_scalar(row, (label_key,)) if label_key else _next_scalar(row, ())
value_key = value_key or label_key
return value_key, label_key
def _next_scalar(row: dict, used: tuple[str, ...]) -> str:
for key, value in row.items():
if str(key) not in used and _is_scalar(value):
return str(key)
return ""
def _find_rows(body: Any, prefix: str, depth: int = 3) -> tuple[list | None, str]:
"""在正文里找列表节点:优先对象数组,实在没有再退回纯标量数组。
先对象数组是因为字典项要的是「值 + 显示名」,一串 ``["北京","上海"]`` 只能整项当值,
是备选而不是首选。
"""
found = _all_rows(body, prefix, depth)
for nodes, path in found:
if nodes and isinstance(nodes[0], dict):
return nodes, path
return found[0] if found else (None, "")
def _all_rows(body: Any, prefix: str, depth: int = 3) -> list[tuple[list, str]]:
"""深度优先列出所有对象数组,常见的键名排在前面。"""
out: list[tuple[list, str]] = []
seen: set[str] = set()
def walk(node: Any, path: str, left: int) -> None:
if left < 0 or len(out) > 20 or path in seen:
return
if isinstance(node, list):
# 空 path = 响应体本身就是列表,解析规则里留空就是"整个响应",是合法配法
if node and (all(isinstance(item, dict) for item in node) or all(_is_scalar(item) for item in node)):
seen.add(path)
out.append((node, path))
for item in node[:1]:
walk(item, f"{path}.0" if path else "0", left - 1)
return
if not isinstance(node, dict):
return
keys = sorted(node, key=lambda key: (LIST_KEYS.index(str(key)) if str(key) in LIST_KEYS else len(LIST_KEYS), str(key)))
for key in keys:
child = f"{path}.{key}" if path else str(key)
walk(node[key], child, left - 1)
walk(body, prefix, depth)
return out
def _scalar_candidates(payload: Any, prefix: str, depth: int) -> list[dict]:
"""把响应里的标量叶子摊出来并按"像不像要取的那个值"打分。
打分只看键名与深度:余额、金额、数量这类名字排前面,越浅越靠前。
这不是什么聪明的推断,但它把「八个叶子里挑一个」变成了「第一个大概率就是」。
"""
out: list[dict] = []
if depth > MAX_DEPTH:
return out
if isinstance(payload, dict):
for key, value in payload.items():
path = f"{prefix}.{key}" if prefix else str(key)
if _is_scalar(value):
out.append({"path": path, "sample": _brief(value), "score": _score(str(key), depth)})
else:
out.extend(_scalar_candidates(value, path, depth + 1))
elif isinstance(payload, list):
for item in payload[:1]:
out.extend(_scalar_candidates(item, f"{prefix}.0" if prefix else "0", depth + 1))
return out
def _score(key: str, depth: int) -> int:
lowered = str(key).lower()
hit = next((index for index, hint in enumerate(VALUE_HINTS) if hint in lowered), None)
return (60 - hit * 4 if hit is not None else 10) - depth
def _brief(value: Any, limit: int = 60) -> str:
text = " ".join(str("" if value is None else value).split())
return text if len(text) <= limit else text[:limit] + "…"