Files
knowledge-governance/web/src/QAOperations.tsx
T
姚章浩 4b3aaff321 feat(qa-ops): 完成复检留档与人工复核闭环
治理侧保存输入观测版本、自动复检及人工复核历史,输入变化失效、版本冲突和幂等重放不覆盖人工记录。批量质量数量使用完整筛选元数据,未采集原文不伪造快照,延迟旧扫描不回退新输入。

验证:全仓 make verify 退出码0,Go656及前端253通过;五包竞态、源/组织/质量隔离PG、真实只读源和隔离网页读回复核通过。默认91个可选集成跳过不计通过。未接AI模型,不写DobotAI源库,未推送、未合并、未部署。
2026-10-17 22:37:26 +08:00

557 lines
22 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
import { useEffect, useRef, useState } from 'react'
import type { FormEvent } from 'react'
import { useOptionalAuth } from './auth'
import { fetchQARecord, fetchQARecords, fetchQAStatus, mergeQAPages, qaCellValue, qaColumns } from './qaOps'
import type { QAQuery, QARecord, QARecordPage, QAStatus } from './qaOps'
import './qaOps.css'
import { QARegions } from './QARegions'
import { QAUsage } from './QAUsage'
import { QAMonthly } from './QAMonthly'
import { QAQualityEditor, QAQualityCounts } from './QAQuality'
import { qualityLabels } from './qaQuality'
import { usageLabels } from './qaUsage'
interface ViewProps {
onQualitySaved?: (record: QARecord) => void
onReloadDetail?: () => void
page: QARecordPage | null
status: QAStatus | null
loading: boolean
error: string | null
detail: QARecord | null
detailLoading: boolean
detailError: string | null
onSelect: (id: string) => void
onCloseDetail: () => void
onLoadMore: () => void
onRetry: () => void
}
const stateLabels = { disabled: '未配置', unavailable: '连接不可用', blocked: '接入被阻断', connected: '已连接' }
const warningLabels: Record<string, string> = {
database_temp_enabled: '数据库仍允许临时对象:未视为完全只读验收通过',
database_transport_unencrypted: '数据库连接未启用 TLS:上线前须完成传输安全审核',
}
const stamp = (value: string) => new Date(value).toLocaleString('zh-CN', { hour12: false })
const statusLabels: Record<string, string> = {
succeeded: '成功',
failed: '失败',
running: '处理中',
cancelled: '已取消',
}
const sourceCoverageLabels: Record<string, string> = { covered: '已覆盖', uncovered: '未覆盖' }
export function QAOperationsView(props: ViewProps) {
const page = props.page
const columns = qaColumns.filter(({ key }) => page?.columns.includes(key))
const detail = props.detail
const showDrawer = Boolean(detail || props.detailLoading || props.detailError)
return (
<section className="qa-ops-results" aria-label="问答记录">
<div className="qa-ops-result-bar">
<span>
{props.loading ? '正在读取…' : page ? `共 ${page.total} 条 · 已显示 ${page.items.length} 条` : '尚未读取问答'}
</span>
<span className="qa-ops-source">
DobotAI 2.0 / 钉钉 · 独立只读连接{props.status ? ` · ${stateLabels[props.status.state]}` : ''}
</span>
</div>
{page?.organization ? (
<p className="qa-ops-muted qa-ops-organization">
{page.organization.state === 'ready'
? `缺失组织信息按当前通讯录补全(${stamp(page.organization.synced_at!)}),不代表提问时归属。目录:${page.organization.directory_id};区域版本:${page.organization.revision_id || '未保存'}`
: '尚无完整通讯录,仅展示源端已有组织快照,不根据姓名推断。'}
</p>
) : null}
{props.status?.warnings.map((warning) => (
<p className="qa-ops-warning" key={warning}>
{warningLabels[warning] ?? '数据源有待审核的安全告警'}
</p>
))}
{props.error ? (
<div className="error-banner" role="alert">
{props.error}{' '}
<button type="button" onClick={props.onRetry} disabled={props.loading}>
重试读取
</button>
</div>
) : null}
{page && page.items.length > 0 ? (
<div className="qa-ops-table-scroll" aria-label="问答表格滚动区" tabIndex={0}>
<table className="qa-ops-table">
<thead>
<tr>
{columns.map(({ key, label }) => (
<th key={key}>{label}</th>
))}
<th>操作</th>
</tr>
</thead>
<tbody>
{page.items.map((item) => (
<tr key={item.id}>
{columns.map(({ key }) => (
<td
key={key}
className={
key === 'answer' || key === 'question' || key === 'question_chinese' || key === 'department'
? 'qa-ops-text-cell'
: ''
}
>
<span
className={
key === 'coverage' &&
(item.quality?.effective.coverage ?? item.coverage.verdict) === 'uncovered'
? 'qa-ops-uncovered'
: ''
}
>
{qaCellValue(item, key) ?? '—'}
</span>
</td>
))}
<td>
<button
type="button"
onClick={() => props.onSelect(item.id)}
aria-label={`查看问答 ${item.id} 的详情`}
>
详情
</button>
{item.quality ? (
<small className="qa-quality-state">{qualityLabels[item.quality.state]}</small>
) : null}
</td>
</tr>
))}
</tbody>
</table>
</div>
) : page && !props.loading && !props.error ? (
<p className="qa-ops-empty">没有符合条件的问答,请调整时间范围或关键词。</p>
) : null}
{page ? (
<footer className="qa-ops-page-bar">
<span>本次读取:{stamp(page.as_of)} · 空列按整个筛选结果隐藏</span>
{page.has_more ? (
<button type="button" onClick={props.onLoadMore} disabled={props.loading}>
{props.loading ? '读取中…' : '加载更多'}
</button>
) : page.items.length > 0 ? (
<span>已显示全部</span>
) : null}
</footer>
) : null}
{showDrawer ? (
<>
<button
className="qa-ops-backdrop"
type="button"
onClick={props.onCloseDetail}
aria-label="关闭问答详情遮罩"
/>
<aside
className="qa-ops-drawer"
role="dialog"
aria-modal="true"
aria-label="问答详情"
onKeyDown={(event) => {
if (event.key === 'Escape') props.onCloseDetail()
if (event.key === 'Tab') {
const buttons = Array.from(
event.currentTarget.querySelectorAll<HTMLElement>(
'button:not([disabled]), a[href], input:not([disabled]), select:not([disabled]), textarea:not([disabled]), summary, [tabindex="0"]'
)
)
const first = buttons[0],
last = buttons[buttons.length - 1]
if (event.shiftKey && document.activeElement === first) {
event.preventDefault()
last?.focus()
}
if (!event.shiftKey && document.activeElement === last) {
event.preventDefault()
first?.focus()
}
}
}}
>
<header>
<h3>问答详情</h3>
<button type="button" autoFocus onClick={props.onCloseDetail}>
关闭详情
</button>
</header>
{props.detailLoading ? <p role="status">正在读取完整问答…</p> : null}
{props.detailError ? (
<p className="error-banner" role="alert">
{props.detailError}
</p>
) : null}
{detail ? (
<div className="qa-ops-detail-content">
<dl className="qa-ops-detail-meta">
<dt>提问时间</dt>
<dd>
{stamp(detail.asked_at)}
{detail.time_source === 'turn.created_at' ? '(问答时间回退,入站消息缺失)' : ''}
</dd>
<dt>提问人</dt>
<dd>{detail.asker || '未关联'}</dd>
<dt>部门</dt>
<dd>
{detail.department || '未匹配'}
{detail.organization?.department_origin === 'current_directory' ? '(当前通讯录补全)' : ''}
</dd>
<dt>区域</dt>
<dd>
{detail.region || '未配置/待核对'}
{detail.organization?.region_origin === 'current_directory' ? '(当前配置补全)' : ''}
</dd>
{detail.organization ? (
<>
<dt>当前组织关联</dt>
<dd>
{detail.organization.state === 'matched'
? '已关联'
: (usageLabels[detail.organization.state] ?? detail.organization.state)}
</dd>
<dt>当前通讯录部门/区域</dt>
<dd>
{detail.organization.departments.join(';') || '未匹配'} /{' '}
{detail.organization.region || '未配置或待核对'}
</dd>
<dt>组织版本</dt>
<dd>
{detail.organization.version.directory_id || '无完整目录'} /{' '}
{detail.organization.version.revision_id || '未保存区域配置'}
</dd>
<dt>源端组织快照</dt>
<dd>
{detail.organization.source_department || '空'} / {detail.organization.source_region || '空'}
</dd>
</>
) : null}
<dt>问答状态</dt>
<dd>{statusLabels[detail.status] ?? detail.status}</dd>
<dt>流程触发人员信息</dt>
<dd>{detail.trigger_person || '未记录'}</dd>
</dl>
<h4>原始问题</h4>
<div className="qa-ops-full-text">{detail.question || '无文本问题'}</div>
<h4>AI答案</h4>
<div className="qa-ops-full-text">{detail.answer || '尚无答案;不默认判覆盖或正确'}</div>
<h4>治理侧覆盖复检</h4>
<p>
{detail.coverage.verdict === 'uncovered'
? '未覆盖:答案包含“暂无已发布”,引用不能抵消这一结果。'
: '待评估:未命中“暂无已发布”不代表已覆盖。'}
</p>
<p className="qa-ops-muted">规则:{detail.coverage.rule_version}</p>
<h4>源端覆盖(仅对照)</h4>
<p>
{sourceCoverageLabels[detail.source_coverage.verdict] ?? '未记录'} ·{' '}
{detail.source_coverage.evaluator_version || '无版本'}
</p>
<p className="qa-ops-muted">{detail.source_coverage.reason_code || '未记录判定原因'}</p>
{detail.quality ? (
<QAQualityEditor
key={detail.id}
recordId={detail.id}
quality={detail.quality}
onSaved={props.onQualitySaved ?? (() => {})}
onReload={props.onReloadDetail ?? (() => {})}
/>
) : (
<p className="qa-ops-muted">质量留档/人工复核未配置。</p>
)}
<h4>用户反馈</h4>
<p>
提问人:
{detail.feedback.asker_value === 'up'
? '点赞'
: detail.feedback.asker_value === 'down'
? '点踩'
: '无反馈'}
;全部反馈:赞 {detail.feedback.up} / 踩 {detail.feedback.down}
</p>
<h4>引用知识</h4>
<pre>{JSON.stringify(detail.references, null, 2)}</pre>
<details>
<summary>问题媒体记录</summary>
<pre>{JSON.stringify(detail.media, null, 2)}</pre>
</details>
</div>
) : null}
</aside>
</>
) : null}
</section>
)
}
function localInput(value: Date): string {
return new Date(value.getTime() - value.getTimezoneOffset() * 60_000).toISOString().slice(0, 16)
}
function initialDraft() {
const end = new Date()
return { start: localInput(new Date(end.getTime() - 7 * 24 * 3600_000)), end: localInput(end), keyword: '' }
}
export function QAOperations() {
const [view, setView] = useState<'records' | 'regions' | 'usage'>('records')
const [usageMode, setUsageMode] = useState<'regions' | 'monthly'>('regions')
const auth = useOptionalAuth()
const canRead = auth?.identity?.role === 'admin'
const [draft, setDraft] = useState(initialDraft)
const [query, setQuery] = useState<QAQuery | null>(null)
const [page, setPage] = useState<QARecordPage | null>(null)
const [status, setStatus] = useState<QAStatus | null>(null)
const [error, setError] = useState<string | null>(null)
const [loading, setLoading] = useState(false)
const [revision, setRevision] = useState(0)
const [qualityRevision, setQualityRevision] = useState(0)
const [detail, setDetail] = useState<QARecord | null>(null)
const [detailLoading, setDetailLoading] = useState(false)
const [detailError, setDetailError] = useState<string | null>(null)
const generation = useRef(0)
const detailRequest = useRef<AbortController | null>(null)
const moreRequest = useRef<AbortController | null>(null)
const returnFocus = useRef<HTMLElement | null>(null)
useEffect(() => {
if (!canRead || query) return
setQuery({
start: new Date(draft.start).toISOString(),
end: new Date(draft.end).toISOString(),
keyword: draft.keyword,
cursor: '',
})
}, [canRead, draft, query])
useEffect(() => {
if (!query || !canRead) return
if (view !== 'records') {
setLoading(false)
moreRequest.current?.abort()
detailRequest.current?.abort()
setDetail(null)
return
}
const controller = new AbortController()
generation.current += 1
moreRequest.current?.abort()
detailRequest.current?.abort()
setLoading(true)
setError(null)
setPage(null)
setDetail(null)
setDetailError(null)
setDetailLoading(false)
void fetchQAStatus(controller.signal)
.then(setStatus)
.catch(() => {
if (!controller.signal.aborted) setStatus(null)
})
void fetchQARecords(query, controller.signal)
.then((result) => {
if (!controller.signal.aborted) setPage(result)
})
.catch((reason: unknown) => {
if (!controller.signal.aborted) setError(reason instanceof Error ? reason.message : '问答读取失败')
})
.finally(() => {
if (!controller.signal.aborted) setLoading(false)
})
return () => controller.abort()
}, [query, canRead, revision, view])
useEffect(
() => () => {
detailRequest.current?.abort()
moreRequest.current?.abort()
},
[]
)
const submit = (event: FormEvent) => {
event.preventDefault()
try {
const start = new Date(draft.start),
end = new Date(draft.end)
if (!(start < end)) throw new Error('开始时间必须早于结束时间')
setQuery({ start: start.toISOString(), end: end.toISOString(), keyword: draft.keyword, cursor: '' })
} catch (reason) {
setError(reason instanceof Error ? reason.message : '时间格式无效')
}
}
const select = async (id: string) => {
detailRequest.current?.abort()
returnFocus.current = document.activeElement as HTMLElement | null
const controller = new AbortController()
detailRequest.current = controller
setDetail(null)
setDetailError(null)
setDetailLoading(true)
try {
const result = await fetchQARecord(id, controller.signal)
if (!controller.signal.aborted) setDetail(result)
} catch (reason) {
if (!controller.signal.aborted) setDetailError(reason instanceof Error ? reason.message : '详情读取失败')
} finally {
if (!controller.signal.aborted) setDetailLoading(false)
}
}
const close = () => {
detailRequest.current?.abort()
setDetail(null)
setDetailError(null)
setDetailLoading(false)
returnFocus.current?.focus()
}
const loadMore = async () => {
if (!query || !page?.has_more || loading) return
const currentGeneration = generation.current
const controller = new AbortController()
moreRequest.current = controller
setLoading(true)
setError(null)
try {
const result = await fetchQARecords({ ...query, cursor: page.next_cursor }, controller.signal)
if (!controller.signal.aborted && currentGeneration === generation.current) {
setPage(mergeQAPages(page, result))
}
} catch (reason) {
if (!controller.signal.aborted && currentGeneration === generation.current)
setError(reason instanceof Error ? reason.message : '翻页失败')
} finally {
if (!controller.signal.aborted && currentGeneration === generation.current) setLoading(false)
}
}
return (
<section className="qa-ops" aria-label="问答运营">
<header className="qa-ops-header">
<h2>
问答运营 <span>/ {view === 'regions' ? '区域归属' : view === 'usage' ? '使用统计' : '问答记录'}</span>
</h2>
<p>真实问答只读查询;原始记录、源端判断与治理复检分开保留。</p>
</header>
{!canRead ? (
<p className="error-banner" role="alert">
尚未配置员工问答可见范围,当前仅管理员可访问。
</p>
) : (
<>
<nav className="qa-region-tabs" aria-label="问答运营视图">
<button type="button" aria-pressed={view === 'records'} onClick={() => setView('records')}>
问答记录
</button>
<button type="button" aria-pressed={view === 'usage'} onClick={() => setView('usage')}>
使用统计
</button>
<button type="button" aria-pressed={view === 'regions'} onClick={() => setView('regions')}>
区域使用
</button>
</nav>
{view === 'usage' ? (
<nav className="qa-region-tabs" aria-label="使用统计视图">
<button type="button" aria-pressed={usageMode === 'regions'} onClick={() => setUsageMode('regions')}>
区域汇总
</button>
<button type="button" aria-pressed={usageMode === 'monthly'} onClick={() => setUsageMode('monthly')}>
个人月明细
</button>
</nav>
) : null}
{view === 'usage' && usageMode === 'monthly' ? (
<QAMonthly />
) : view === 'regions' ? (
<QARegions />
) : (
<>
<form className="qa-ops-query" onSubmit={submit}>
<label>
开始时间
<input
type="datetime-local"
required
value={draft.start}
onChange={(event) => setDraft({ ...draft, start: event.target.value })}
/>
</label>
<label>
结束时间(不含)
<input
type="datetime-local"
required
value={draft.end}
onChange={(event) => setDraft({ ...draft, end: event.target.value })}
/>
</label>
<label className="qa-ops-keyword">
关键词
<input
type="search"
maxLength={200}
placeholder="检索原始问题"
value={draft.keyword}
onChange={(event) => setDraft({ ...draft, keyword: event.target.value })}
/>
</label>
<button type="submit" disabled={loading}>
查询
</button>
</form>
<p className="qa-ops-slice-note">
部门/区域保留源快照,缺失时按当前通讯录补全;使用统计不是绩效结论。外语翻译与AI评估仍暂缓,空值不默认填“否”。
</p>
{view === 'records' ? <QAQualityCounts query={query} revision={qualityRevision} /> : null}
{view === 'usage' ? (
<QAUsage query={query} />
) : (
<QAOperationsView
page={page}
status={status}
error={error}
loading={loading}
detail={detail}
detailLoading={detailLoading}
detailError={detailError}
onReloadDetail={() => {
if (detail) void select(detail.id)
}}
onQualitySaved={(fresh) => {
if (fresh.id !== detail?.id) return
setDetail(fresh)
setPage((old) => {
if (!old) return old
const all = new Set(old.columns)
const f = fresh.quality?.effective
if (f) {
if (f.coverage) all.add('coverage')
if (f.correctness) all.add('is_correct')
for (const key of ['product_category', 'problem_type', 'root_cause'] as const)
if (f[key]) all.add(key)
}
return {
...old,
items: old.items.map((item) => (item.id === fresh.id ? fresh : item)),
columns: qaColumns.filter((c) => all.has(c.key)).map((c) => c.key),
}
})
setQualityRevision((v) => v + 1)
}}
onSelect={(id) => void select(id)}
onCloseDetail={close}
onLoadMore={() => void loadMore()}
onRetry={() => setRevision((value) => value + 1)}
/>
)}
</>
)}
</>
)}
</section>
)
}