import { useEffect, useMemo, useState } from 'react' import type { ReactNode } from 'react' import { X } from 'lucide-react' import clsx from 'clsx' import { api } from '../api/client' import { useStudio } from '../store/studio' import { modelOptions, providerOfModel, useCatalog } from '../store/catalog' import { useRadioGroup } from '../components/ui' import { DUAL_CHECK_TEXT } from '../lib/terms' import type { VerifySettings } from '../types' import type { FieldRenderProps, NodeSummaryContext } from './nodeDefs' /* * 双盲复算节点的检查器控件(nodeDefs 里 dual_check 各字段的 render)和节点卡片的摘要。 * * 口径卡、要复算的指标、口径说明都得看画布上别的节点:从 studio store 读,不往检查器的 props 里加字段。 * 每个控件只写自己那个键(FieldRenderProps.onChange);写回 undefined 就是「留空 = 跟随默认」,配置里不留空值。 * 后端认的键和缺省见 types.ts 的 DualCheckConfig */ const T = DUAL_CHECK_TEXT type CanvasNode = NodeSummaryContext['nodes'][number] type CanvasEdge = NodeSummaryContext['edges'][number] const isRecord = (v: unknown): v is Record => !!v && typeof v === 'object' && !Array.isArray(v) const ids = (v: unknown): string[] => (Array.isArray(v) ? v.filter((x): x is string => typeof x === 'string' && !!x) : []) /** 某个节点的全部上游(沿连线往回走),不含它自己 */ function upstreamOf(id: string, edges: readonly CanvasEdge[]): Set { const parents = new Map() for (const e of edges) parents.set(e.target, [...(parents.get(e.target) ?? []), e.source]) const seen = new Set() const stack = [...(parents.get(id) ?? [])] while (stack.length) { const cur = stack.pop()! if (seen.has(cur) || cur === id) continue seen.add(cur) stack.push(...(parents.get(cur) ?? [])) } return seen } /** 画布上的口径卡:本节点上游的在前(复算只能复算它们),其余的另列 */ function cardsOf(id: string, nodes: readonly CanvasNode[], edges: readonly CanvasEdge[]) { const up = upstreamOf(id, edges) const cards = nodes.filter((n) => n.data.nodeType === 'metrics') return { upstream: cards.filter((n) => up.has(n.id)), other: cards.filter((n) => !up.has(n.id)) } } /** * 实际复算哪张卡:写了 card 就是它(不在画布上时 node 为 null);没写取上游的口径卡,上游只有一张时就是它, * 好几张时说不准,node 为 null、由调用方照实说 */ function targetOf(config: Record, id: string, nodes: readonly CanvasNode[], edges: readonly CanvasEdge[]) { const { upstream } = cardsOf(id, nodes, edges) const card = typeof config.card === 'string' && config.card ? config.card : '' if (card) return { node: nodes.find((n) => n.id === card && n.data.nodeType === 'metrics') ?? null, card, upstream } return { node: upstream.length === 1 ? upstream[0] : null, card: '', upstream } } /** 一张口径卡在摘要里的名字:节点名,没起名的用口径名,再没有用 id */ const cardName = (n: CanvasNode): string => String(n.data.label || n.data.config?.caliber || n.id) /** 口径卡里定义的指标;引用别的工作流发布的口径(caliber_from)时指标运行时才知道,返回 null */ function metricsOf(n: CanvasNode): { id: string; name: string }[] | null { const cfg = n.data.config ?? {} if (isRecord(cfg.caliber_from)) return null return (Array.isArray(cfg.metrics) ? cfg.metrics : []) .filter((m: any) => isRecord(m) && typeof m.id === 'string' && m.id) .map((m: any) => ({ id: String(m.id), name: typeof m.name === 'string' ? m.name : '' })) } /** * 节点卡片的摘要:复算哪张口径卡、几个指标(NodeDef.summary)。NodeCard 在 studio store 的选择器里调它, * 每条事件都会跑一遍:只做几次数组查找,返回字符串 */ export function dualCheckSummary({ id, config, nodes, edges }: NodeSummaryContext): string { const S = T.summary const { node, card, upstream } = targetOf(config, id, nodes, edges) const picked = ids(config.metrics) let text: string if (node) { const all = metricsOf(node) text = S.card(cardName(node), picked.length ? picked.length : null, all ? all.length : null) } else if (card) { text = S.card(card, picked.length ? picked.length : null, null) } else { text = upstream.length > 1 ? S.many(upstream.length) : S.noCard } return config.enabled === false ? `${text} · ${S.off}` : text } // ---------------------------------------------------------------- 设置里的默认值 /** * 设置里核查一组的值:相对误差、启用的「跟随设置」要写出眼下是多少。整个会话取一次(同检查器的运行默认值), * 取不到就不写,不挡编辑 */ let verifyPending: Promise | null = null let verifyValue: VerifySettings | null | undefined function useVerifyDefaults(): VerifySettings | null { const [value, setValue] = useState(verifyValue ?? null) useEffect(() => { if (verifyValue !== undefined) return verifyPending ??= api.settings.get().then( (s) => (verifyValue = isRecord(s?.verify) ? s.verify as VerifySettings : null), () => { verifyPending = null; return null }, // 这次没取到,下次打开再试 ) let alive = true void verifyPending.then((v) => { if (alive) setValue(v) }) return () => { alive = false } }, []) return verifyValue ?? value } /** 字段下面的一行提醒(所选口径卡不在上游之类),提醒色 */ function Warn({ children, attr }: { children: ReactNode; attr: string }) { return (
{children}
) } // ---------------------------------------------------------------- 各字段 /** 要复算的口径卡:下拉选画布上的口径卡,上游的一组、其余的一组;留空取上游的口径卡 */ function CardField({ id, nodeId, value, invalid, describedBy, onChange }: FieldRenderProps) { const nodes = useStudio((s) => s.nodes) const edges = useStudio((s) => s.edges) const { upstream, other } = useMemo(() => cardsOf(nodeId, nodes, edges), [nodeId, nodes, edges]) const current = typeof value === 'string' ? value : '' const known = [...upstream, ...other].some((n) => n.id === current) const option = (n: CanvasNode) => ( ) return ( <> {current && known && !upstream.some((n) => n.id === current) && {T.cardNotUpstream}} {current && !known && {T.cardMissing(current)}} ) } /** * 复算的指标:所选口径卡的指标逐个勾。没写(全部勾着)是缺省——复算输入来自查询的全部指标;全部勾回来时写回 * undefined,配置里不留一份和缺省等价的清单。最后一个不让取消:一个都不勾和缺省分不清 */ function MetricsField({ id, nodeId, value, config, describedBy, onChange }: FieldRenderProps) { const nodes = useStudio((s) => s.nodes) const edges = useStudio((s) => s.edges) const target = useMemo(() => targetOf(config, nodeId, nodes, edges), [config, nodeId, nodes, edges]) const picked = ids(value) const metrics = target.node ? metricsOf(target.node) : undefined if (!target.node || metrics === undefined) { return (
{target.upstream.length > 1 && !target.card ? T.summary.many(target.upstream.length) : T.metricsNoCard}
) } if (metrics === null || !metrics.length) { return (
{metrics === null ? T.metricsPinned : T.metricsNone}
{picked.length > 0 && ( )}
) } const known = new Set(metrics.map((m) => m.id)) const valid = picked.filter((p) => known.has(p)) const stale = picked.filter((p) => !known.has(p)) const all = !picked.length const checked = new Set(all ? metrics.map((m) => m.id) : valid) const write = (next: Set) => { const ordered = metrics.map((m) => m.id).filter((m) => next.has(m)) onChange(ordered.length === metrics.length ? undefined : ordered) } return (
{metrics.map((m) => { const on = checked.has(m.id) const last = on && checked.size === 1 return ( ) })}
{all ? T.metricsDefault : T.metricsPicked(checked.size, metrics.length)}
{stale.length > 0 && ( {T.metricsStale(stale)} )}
) } /** * 口径说明:要复算的每个指标一段,给盲算模型看的业务定义(它看不到原流程的 SQL)。存成 {指标 id: 说明}, * 清空的那一项去掉,全清空写回 undefined。已经写了、指标却不在复算范围里的照样列出来,好让人看见并删掉 */ function DefinitionsField({ id, nodeId, value, config, describedBy, onChange }: FieldRenderProps) { const nodes = useStudio((s) => s.nodes) const edges = useStudio((s) => s.edges) const target = useMemo(() => targetOf(config, nodeId, nodes, edges), [config, nodeId, nodes, edges]) const defs: Record = isRecord(value) ? Object.fromEntries(Object.entries(value).filter(([, v]) => typeof v === 'string')) as Record : {} const metrics = target.node ? metricsOf(target.node) : undefined const picked = ids(config.metrics) const rows = metrics ? (picked.length ? metrics.filter((m) => picked.includes(m.id)) : metrics) : [] const gone = Object.keys(defs).filter((k) => !rows.some((r) => r.id === k)) const set = (metric: string, text: string | null) => { const next = { ...defs } if (text != null && text.trim()) next[metric] = text else delete next[metric] onChange(Object.keys(next).length ? next : undefined) } if (!rows.length && !gone.length) { return (
{metrics === null ? T.definitionsPinned : T.definitionsNone}
) } return (
{rows.map((m) => (