feat(qaops): 接入问答组织补全与区域使用统计

This commit is contained in:
姚章浩
2026-10-17 19:02:13 +08:00
parent cc4906b6a9
commit 56b8cabed9
23 changed files with 1182 additions and 71 deletions
+79 -30
View File
@@ -1,10 +1,12 @@
import { useEffect, useRef, useState } from 'react'
import type { FormEvent } from 'react'
import { useOptionalAuth } from './auth'
import { fetchQARecord, fetchQARecords, fetchQAStatus, qaCellValue, qaColumns } from './qaOps'
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 { usageLabels } from './qaUsage'
interface ViewProps {
page: QARecordPage | null
@@ -48,6 +50,13 @@ export function QAOperationsView(props: ViewProps) {
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] ?? '数据源有待审核的安全告警'}
@@ -79,7 +88,9 @@ export function QAOperationsView(props: ViewProps) {
<td
key={key}
className={
key === 'answer' || key === 'question' || key === 'question_chinese' ? 'qa-ops-text-cell' : ''
key === 'answer' || key === 'question' || key === 'question_chinese' || key === 'department'
? 'qa-ops-text-cell'
: ''
}
>
<span
@@ -174,6 +185,40 @@ export function QAOperationsView(props: ViewProps) {
</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>
@@ -230,7 +275,7 @@ function initialDraft() {
}
export function QAOperations() {
const [view, setView] = useState<'records' | 'regions'>('records')
const [view, setView] = useState<'records' | 'regions' | 'usage'>('records')
const auth = useOptionalAuth()
const canRead = auth?.identity?.role === 'admin'
const [draft, setDraft] = useState(initialDraft)
@@ -260,6 +305,13 @@ export function QAOperations() {
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()
@@ -286,7 +338,7 @@ export function QAOperations() {
if (!controller.signal.aborted) setLoading(false)
})
return () => controller.abort()
}, [query, canRead, revision])
}, [query, canRead, revision, view])
useEffect(
() => () => {
@@ -341,17 +393,7 @@ export function QAOperations() {
try {
const result = await fetchQARecords({ ...query, cursor: page.next_cursor }, controller.signal)
if (!controller.signal.aborted && currentGeneration === generation.current) {
setPage((current) =>
current
? {
...result,
items: [
...current.items,
...result.items.filter((item) => !current.items.some(({ id }) => id === item.id)),
],
}
: result
)
setPage(mergeQAPages(page, result))
}
} catch (reason) {
if (!controller.signal.aborted && currentGeneration === generation.current)
@@ -364,7 +406,7 @@ export function QAOperations() {
<section className="qa-ops" aria-label="问答运营">
<header className="qa-ops-header">
<h2>
问答运营 <span>/ {view === 'regions' ? '区域归属' : '问答记录'}</span>
问答运营 <span>/ {view === 'regions' ? '区域归属' : view === 'usage' ? '使用统计' : '问答记录'}</span>
</h2>
<p>真实问答只读查询;原始记录、源端判断与治理复检分开保留。</p>
</header>
@@ -378,6 +420,9 @@ export function QAOperations() {
<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>
@@ -420,21 +465,25 @@ export function QAOperations() {
</button>
</form>
<p className="qa-ops-slice-note">
当前切片:问答查询与覆盖复检。外语翻译、AI评估及人员映射尚未接入;空值不默认填“否”。
部门/区域保留源快照,缺失时按当前通讯录补全;使用统计不是绩效结论。外语翻译与AI评估仍暂缓,空值不默认填“否”。
</p>
<QAOperationsView
page={page}
status={status}
error={error}
loading={loading}
detail={detail}
detailLoading={detailLoading}
detailError={detailError}
onSelect={(id) => void select(id)}
onCloseDetail={close}
onLoadMore={() => void loadMore()}
onRetry={() => setRevision((value) => value + 1)}
/>
{view === 'usage' ? (
<QAUsage query={query} />
) : (
<QAOperationsView
page={page}
status={status}
error={error}
loading={loading}
detail={detail}
detailLoading={detailLoading}
detailError={detailError}
onSelect={(id) => void select(id)}
onCloseDetail={close}
onLoadMore={() => void loadMore()}
onRetry={() => setRevision((value) => value + 1)}
/>
)}
</>
)}
</>
+36
View File
@@ -0,0 +1,36 @@
import { renderToStaticMarkup } from 'react-dom/server'
import { describe, expect, it } from 'vitest'
import { QAUsageView } from './QAUsage'
import { parseQAUsage } from './qaUsage'
const usage = parseQAUsage({
organization: {
state: 'ready',
directory_id: 'd',
directory_source: 'weekly_report_live',
synced_at: '2026-10-17T07:59:50Z',
revision_id: 'r',
basis: 'current_directory',
},
as_of: '2026-10-17T08:00:00Z',
start: '2026-10-14T00:00:00Z',
end: '2026-10-15T00:00:00Z',
keyword: '',
questions: 2,
identified_users: 0,
rows: [{ key: 'unmatched', questions: 2, succeeded: 1, failed: 1, other: 0, users: null, roster_people: null }],
})
describe('usage statistics evidence', () => {
it('shows a current-roster basis and unknown counts without performance claims', () => {
const html = renderToStaticMarkup(<QAUsageView data={usage} loading={false} error="" onRetry={() => {}} />)
expect(html).toContain('按当前通讯录回看')
expect(html).toContain('名册未匹配')
expect(html).toContain('不可确定')
expect(html).not.toContain('达标率')
expect(html).not.toContain('绩效合格')
})
it('keeps unavailable data an error, not a zero-result report', () => {
const html = renderToStaticMarkup(<QAUsageView data={null} loading={false} error="上游不可用" onRetry={() => {}} />)
expect(html).toContain('上游不可用')
expect(html).not.toContain('共 0 条')
})
})
+105
View File
@@ -0,0 +1,105 @@
import { useEffect, useState } from 'react'
import type { QAQuery } from './qaOps'
import { fetchQAUsage, usageLabels } from './qaUsage'
import type { QAUsage as Usage } from './qaUsage'
interface Props {
data: Usage | null
loading: boolean
error: string
onRetry: () => void
}
const stamp = (v: string) => new Date(v).toLocaleString('zh-CN', { hour12: false })
export function QAUsageView({ data, loading, error, onRetry }: Props) {
return (
<section className="qa-ops-results" aria-label="使用统计">
<p className="qa-ops-slice-note">
按当前通讯录回看历史问答,不代表提问时的组织归属。成功/失败是源端运行状态,不等于答案正确;不输出绩效结论。
</p>
{loading ? <p role="status">正在读取完整筛选范围的使用统计…</p> : null}
{error ? (
<p className="error-banner" role="alert">
{error}{' '}
<button type="button" onClick={onRetry} disabled={loading}>
重试统计
</button>
</p>
) : null}
{data && !error ? (
<>
<div className="qa-ops-result-bar">
<span>
共 {data.questions} 条问答 · 已关联提问人数 {data.identified_users}
</span>
<span>统计截止读取时间:{stamp(data.as_of)}</span>
</div>
<p className="qa-ops-muted qa-ops-organization">
范围:{stamp(data.start)} 至 {stamp(data.end)}(不含结束时刻)
{data.keyword ? ` · 原问题包含:${data.keyword}` : ''}
</p>
<p className="qa-ops-muted qa-ops-organization">
{data.organization.state === 'ready'
? `通讯录同步:${stamp(data.organization.synced_at!)} · 目录 ${data.organization.directory_id} · 区域配置 ${data.organization.revision_id || '尚未保存'}`
: '尚无完整通讯录,当前不能确定部门区域或去重人数。'}
</p>
<div className="qa-ops-table-scroll" tabIndex={0} aria-label="使用统计表格滚动区">
<table className="qa-ops-table qa-usage-table">
<thead>
<tr>
<th>区域/待核对状态</th>
<th>问答条数</th>
<th>成功</th>
<th>失败</th>
<th>其他状态</th>
<th>已关联提问人数</th>
<th>通讯录归属人数</th>
</tr>
</thead>
<tbody>
{data.rows.map((row) => (
<tr key={row.key}>
<td>{usageLabels[row.key]}</td>
<td>{row.questions}</td>
<td>{row.succeeded}</td>
<td>{row.failed}</td>
<td>{row.other}</td>
<td>{row.users ?? '不可确定'}</td>
<td>{row.roster_people ?? '不适用'}</td>
</tr>
))}
</tbody>
</table>
</div>
<p className="qa-ops-muted qa-ops-organization">
按问答唯一 ID 计次;同一名册人员的多部门、多个身份记录只计 1
人。未匹配或身份冲突不编造人数;通讯录人数不是在职或考核人数。
</p>
</>
) : null}
</section>
)
}
export function QAUsage({ query }: { query: QAQuery | null }) {
const [data, setData] = useState<Usage | null>(null),
[loading, setLoading] = useState(false),
[error, setError] = useState(''),
[revision, setRevision] = useState(0)
useEffect(() => {
if (!query) return
const c = new AbortController()
setLoading(true)
setData(null)
setError('')
void fetchQAUsage(query, c.signal)
.then((value) => {
if (!c.signal.aborted) setData(value)
})
.catch((e: unknown) => {
if (!c.signal.aborted) setError(e instanceof Error ? e.message : '统计读取失败')
})
.finally(() => {
if (!c.signal.aborted) setLoading(false)
})
return () => c.abort()
}, [query, revision])
return <QAUsageView data={data} loading={loading} error={error} onRetry={() => setRevision((v) => v + 1)} />
}
+50
View File
@@ -0,0 +1,50 @@
import { describe, expect, it } from 'vitest'
import { parseQAOrganizationVersion, mergeQAPages, parseQARecordPage } from './qaOps'
import { parseQAUsage } from './qaUsage'
const version = {
state: 'ready',
directory_id: 'd',
directory_source: 'weekly_report_live',
synced_at: '2026-10-17T07:59:50Z',
revision_id: 'r',
basis: 'current_directory',
}
const row = { key: 'APAC', questions: 5, succeeded: 3, failed: 1, other: 1, users: 1, roster_people: 4 }
const usage = {
organization: version,
as_of: '2026-10-17T08:00:00Z',
start: '2026-10-14T00:00:00Z',
end: '2026-10-15T00:00:00Z',
keyword: '',
questions: 5,
identified_users: 1,
rows: [row],
}
describe('organization evidence and usage contracts', () => {
it('keeps a valid current-roster version and rejects contradictory metadata', () => {
expect(parseQAOrganizationVersion(version).directory_id).toBe('d')
expect(() => parseQAOrganizationVersion({ ...version, directory_id: '' })).toThrow()
})
it('does not append pages across directory or regional revisions', () => {
const page = parseQARecordPage({
items: [],
columns: [],
total: 0,
has_more: false,
next_cursor: '',
as_of: usage.as_of,
organization: version,
})
expect(() =>
mergeQAPages(page, { ...page, organization: { ...page.organization!, revision_id: 'changed' } })
).toThrow(/配置已变化/)
expect(mergeQAPages(page, page).total).toBe(0)
})
it('validates event conservation and unknown participant counts instead of inventing zeros', () => {
expect(parseQAUsage(usage).identified_users).toBe(1)
expect(parseQAUsage({ ...usage, rows: [{ ...row, users: null, roster_people: null }] }).rows[0].users).toBeNull()
expect(() => parseQAUsage({ ...usage, questions: 6 })).toThrow()
expect(() => parseQAUsage({ ...usage, rows: [{ ...row, other: 0 }] })).toThrow()
expect(() => parseQAUsage({ ...usage, rows: [{ ...row, questions: -1 }] })).toThrow()
})
})
+6
View File
@@ -66,6 +66,12 @@
outline: 2px solid var(--c-run);
outline-offset: 2px;
}
.qa-ops-organization {
margin: 8px 14px;
overflow-wrap: anywhere;
font-size: 12px;
line-height: 1.5;
}
.qa-ops-results {
display: flex;
flex-direction: column;
+93 -2
View File
@@ -17,7 +17,59 @@ export const qaColumns = [
] as const
export type QAColumn = (typeof qaColumns)[number]['key']
export interface QAOrganizationVersion {
state: 'ready' | 'empty'
directory_id: string
directory_source: string
synced_at: string | null
revision_id: string
basis: 'current_directory'
}
export interface QARecordOrganization {
version: QAOrganizationVersion
state: string
departments: string[]
region: string
source_department: string
source_region: string
department_origin: string
region_origin: string
}
export function parseQAOrganizationVersion(value: unknown): QAOrganizationVersion {
const v = object(value)
if (!['ready', 'empty'].includes(text(v.state)) || v.basis !== 'current_directory') return invalid()
const result = {
state: v.state as QAOrganizationVersion['state'],
directory_id: text(v.directory_id),
directory_source: text(v.directory_source),
synced_at: v.synced_at === null ? null : instant(v.synced_at),
revision_id: text(v.revision_id),
basis: 'current_directory' as const,
}
if (
result.state === 'ready' &&
(!result.directory_id ||
!result.synced_at ||
!['weekly_report_live', 'weekly_report_snapshot'].includes(result.directory_source))
)
return invalid()
if (result.state === 'empty' && (result.directory_id || result.revision_id || result.synced_at !== null))
return invalid()
return result
}
export function mergeQAPages(current: QARecordPage, next: QARecordPage): QARecordPage {
if (
current.organization?.directory_id !== next.organization?.directory_id ||
current.organization?.revision_id !== next.organization?.revision_id
)
throw new Error('通讯录或区域配置已变化,请重新查询,不能混合不同版本的分页结果')
return {
...next,
items: [...current.items, ...next.items.filter((item) => !current.items.some((old) => old.id === item.id))],
}
}
export interface QARecord {
organization?: QARecordOrganization
id: string
status: string
question: string
@@ -41,6 +93,7 @@ export interface QARecord {
language?: string
}
export interface QARecordPage {
organization?: QAOrganizationVersion
items: QARecord[]
columns: QAColumn[]
total: number
@@ -121,6 +174,36 @@ export function parseQARecord(value: unknown): QARecord {
if (typeof row.is_correct !== 'boolean' && row.is_correct !== null) return invalid()
item.is_correct = row.is_correct
}
if (row.organization !== undefined) {
const o = object(row.organization)
if (
!Array.isArray(o.departments) ||
![
'matched',
'unassigned',
'cross_region',
'unmatched',
'identity_conflict',
'no_identity',
'directory_missing',
].includes(text(o.state))
)
return invalid()
const origin = (v: unknown) => {
const s = text(v)
return ['source_snapshot', 'current_directory', 'unavailable'].includes(s) ? s : invalid()
}
item.organization = {
version: parseQAOrganizationVersion(o.version),
state: text(o.state),
departments: o.departments.map(text),
region: text(o.region),
source_department: text(o.source_department),
source_region: text(o.source_region),
department_origin: origin(o.department_origin),
region_origin: origin(o.region_origin),
}
}
return item
}
@@ -137,10 +220,18 @@ export function parseQARecordPage(value: unknown): QARecordPage {
return invalid()
if (new Set(items.map(({ id }) => id)).size !== items.length || new Set(columns).size !== columns.length)
return invalid()
return { items, columns, total, has_more: page.has_more, next_cursor: nextCursor, as_of: instant(page.as_of) }
return {
items,
columns,
total,
has_more: page.has_more,
next_cursor: nextCursor,
as_of: instant(page.as_of),
...(page.organization === undefined ? {} : { organization: parseQAOrganizationVersion(page.organization) }),
}
}
async function getPayload(path: string, signal?: AbortSignal): Promise<unknown> {
export async function getPayload(path: string, signal?: AbortSignal): Promise<unknown> {
const response = await fetch(path, { credentials: 'same-origin', cache: 'no-store', signal })
const raw: unknown = await response.json().catch(() => null)
if (!response.ok) {
+85
View File
@@ -0,0 +1,85 @@
import type { QAOrganizationVersion, QAQuery } from './qaOps'
import { getPayload, parseQAOrganizationVersion } from './qaOps'
export interface QAUsageRow {
key: string
questions: number
succeeded: number
failed: number
other: number
users: number | null
roster_people: number | null
}
export interface QAUsage {
organization: QAOrganizationVersion
as_of: string
start: string
end: string
keyword: string
questions: number
identified_users: number
rows: QAUsageRow[]
}
const bad = (): never => {
throw new Error('使用统计响应无效,请检查完整性及接口契约')
}
const obj = (v: unknown): Record<string, unknown> =>
v && typeof v === 'object' && !Array.isArray(v) ? (v as Record<string, unknown>) : bad()
const text = (v: unknown) => (typeof v === 'string' ? v : bad())
const count = (v: unknown) => (typeof v === 'number' && Number.isSafeInteger(v) && v >= 0 ? v : bad())
const stamp = (v: unknown) => {
const s = text(v)
return !Number.isNaN(Date.parse(s)) ? s : bad()
}
export const usageLabels: Record<string, string> = {
国内工业: '国内工业',
APAC: 'APAC',
EMEA: 'EMEA',
America: 'America',
unassigned: '未配置区域',
cross_region: '跨区域待核对',
unmatched: '名册未匹配',
identity_conflict: '身份冲突',
no_identity: '身份信息缺失',
directory_missing: '尚无完整通讯录',
}
export function parseQAUsage(value: unknown): QAUsage {
const v = obj(value)
if (!Array.isArray(v.rows)) return bad()
const rows = v.rows.map((raw) => {
const r = obj(raw)
const key = text(r.key)
if (!Object.hasOwn(usageLabels, key)) return bad()
const row = {
key,
questions: count(r.questions),
succeeded: count(r.succeeded),
failed: count(r.failed),
other: count(r.other),
users: r.users === null ? null : count(r.users),
roster_people: r.roster_people === null ? null : count(r.roster_people),
}
if (row.questions !== row.succeeded + row.failed + row.other) return bad()
return row
})
const result = {
organization: parseQAOrganizationVersion(v.organization),
as_of: stamp(v.as_of),
start: stamp(v.start),
end: stamp(v.end),
keyword: text(v.keyword),
questions: count(v.questions),
identified_users: count(v.identified_users),
rows,
}
if (
result.questions !== rows.reduce((n, r) => n + r.questions, 0) ||
new Set(rows.map((r) => r.key)).size !== rows.length ||
!(new Date(result.start) < new Date(result.end))
)
return bad()
return result
}
export async function fetchQAUsage(query: QAQuery, signal?: AbortSignal): Promise<QAUsage> {
const params = new URLSearchParams({ start: query.start, end: query.end, keyword: query.keyword })
return parseQAUsage(await getPayload(`/api/v1/qa-ops/usage?${params}`, signal))
}