feat(qaops): 增加个人自然月用量与零记录人员明细

This commit is contained in:
姚章浩
2026-10-17 19:59:33 +08:00
parent 56b8cabed9
commit 9556db1ef0
18 changed files with 1248 additions and 10 deletions
+37
View File
@@ -0,0 +1,37 @@
import { renderToStaticMarkup } from 'react-dom/server'
import { describe, it, expect } from 'vitest'
import { QAMonthlyView } from './QAMonthly'
import { monthlyFixture } from './qaMonthly.fixture'
import { parseQAMonthly } from './qaMonthly'
describe('personal monthly view', () => {
it('shows a partial month as progress, escapes source names and does not imply eligibility', () => {
const html = renderToStaticMarkup(
<QAMonthlyView
data={parseQAMonthly(monthlyFixture)}
loading={false}
error=""
onRetry={() => {}}
onPage={() => {}}
/>
)
for (const text of ['本源零记录', '当月进度', '姓名未同步', '不是考核名单', '当前通讯录', '未关联'])
expect(html).toContain(text)
expect(html).not.toContain('<script>')
expect(html).not.toContain('达标率')
expect(html).not.toContain('绩效合格')
})
it('does not display stale rows or fake zeros on errors', () => {
const html = renderToStaticMarkup(
<QAMonthlyView
data={parseQAMonthly(monthlyFixture)}
loading={false}
error="统计不可用"
onRetry={() => {}}
onPage={() => {}}
/>
)
expect(html).toContain('统计不可用')
expect(html).not.toContain('<table')
expect(html).not.toContain('共 0')
})
})
+252
View File
@@ -0,0 +1,252 @@
import { useEffect, useState } from 'react'
import type { FormEvent } from 'react'
import { beijingMonth, fetchQAMonthly } from './qaMonthly'
import type { MonthlyPeople, MonthlyQuery } from './qaMonthly'
import { usageLabels } from './qaUsage'
const stamp = (v: string) => new Date(v).toLocaleString('zh-CN', { timeZone: 'Asia/Shanghai', hour12: false })
interface ViewProps {
data: MonthlyPeople | null
loading: boolean
error: string
onRetry: () => void
onPage: (page: number) => void
}
export function QAMonthlyView({ data, loading, error, onRetry, onPage }: ViewProps) {
return (
<section className="qa-ops-results qa-monthly-results" aria-label="个人月度使用明细">
{loading ? (
<p className="qa-ops-muted" role="status">
正在读取个人月明细…
</p>
) : null}
{error ? (
<div className="error-banner" role="alert">
{error}{' '}
<button type="button" onClick={onRetry} disabled={loading}>
重新查询
</button>
</div>
) : null}
{data && !loading && !error ? (
<>
<div className="qa-ops-result-bar">
<strong>
{data.month} · {data.partial ? '当月进度 / 截止时点' : '完整自然月时间范围'}
</strong>
<span>仅 DobotAI 2.0 · 北京时间</span>
</div>
<p className="qa-ops-muted">
全名册:{data.roster_people} 人 · 已关联提问 {data.used_people} 人 · 本源零记录 {data.zero_people}{' '}
人。名册来自当前通讯录,不是在职证明,也不是考核名单。
</p>
<p className="qa-ops-muted">
本月范围内 {data.questions} 条问答,已关联 {data.linked_questions} 条,未关联 {data.unresolved_questions}{' '}
条。0 仅表示本源未关联到提问,不等于实际未使用;成功/失败不是答案正确性结论。
</p>
{data.missing_names > 0 ? (
<p className="qa-ops-warning">
{data.missing_names} 人姓名未同步,请重新同步通讯录;不根据姓名猜身份,不用原始标识代替姓名。
</p>
) : null}
<details className="qa-ops-organization">
<summary>统计范围与组织版本</summary>
<p>
范围:{stamp(data.start)} 至 {stamp(data.end)}(不含结束)。当前通讯录同步于{' '}
{stamp(data.organization.synced_at!)}
;不代表提问时部门或正式绩效分母。自然月时间范围完整不代表已归档全部历史。目录:
{data.organization.directory_id};区域:{data.organization.revision_id || '未保存'}。
</p>
</details>
<div className="qa-ops-result-bar">
<span>
符合人员筛选 {data.total} 人 · 第 {data.page} 页
</span>
<span>上方全名册指标不随人员筛选变化</span>
</div>
{data.rows.length ? (
<div className="qa-ops-table-scroll" aria-label="个人月明细表格滚动区" tabIndex={0}>
<table className="qa-ops-table qa-monthly-table">
<thead>
<tr>
{['姓名', '当前部门完整路径', '区域 / 待核对状态', '问答次数', '成功', '失败', '其他'].map((v) => (
<th key={v}>{v}</th>
))}
</tr>
</thead>
<tbody>
{data.rows.map((row) => (
<tr key={row.key}>
<td>{row.name || '姓名未同步'}</td>
<td>{row.departments.join(';') || '无部门记录'}</td>
<td>{usageLabels[row.region || row.state]}</td>
<td>{row.questions}</td>
<td>{row.succeeded}</td>
<td>{row.failed}</td>
<td>{row.other}</td>
</tr>
))}
</tbody>
</table>
</div>
) : (
<p className="qa-ops-empty">没有符合人员筛选的记录,请调整条件;这不是通讯录为空。</p>
)}
<footer className="qa-ops-page-bar">
<span>本次读取:{stamp(data.as_of)}</span>
<div>
{data.page > 1 ? (
<button type="button" onClick={() => onPage(data.page - 1)}>
上一页
</button>
) : null}
{data.has_more ? (
<button type="button" onClick={() => onPage(data.page + 1)}>
下一页
</button>
) : null}
</div>
</footer>
</>
) : null}
</section>
)
}
export function QAMonthly() {
const [draft, setDraft] = useState(() => ({
month: beijingMonth(),
cutoff: '',
region: '',
department_id: '',
activity: 'all',
search: '',
}))
const [request, setRequest] = useState<MonthlyQuery>({ month: draft.month })
const [data, setData] = useState<MonthlyPeople | null>(null),
[options, setOptions] = useState<MonthlyPeople['department_options']>([]),
[loading, setLoading] = useState(false),
[error, setError] = useState('')
useEffect(() => {
const controller = new AbortController()
setLoading(true)
setData(null)
setError('')
fetchQAMonthly(request, controller.signal)
.then((next) => {
if (!controller.signal.aborted) {
setData(next)
setOptions(next.department_options)
}
})
.catch((reason) => {
if (!controller.signal.aborted) setError(reason instanceof Error ? reason.message : '个人月明细读取失败')
})
.finally(() => {
if (!controller.signal.aborted) setLoading(false)
})
return () => controller.abort()
}, [request])
const change = (key: keyof typeof draft, value: string) => {
setDraft({ ...draft, [key]: value })
setData(null)
setError('')
}
const query = () => {
try {
setRequest({
...draft,
cutoff: draft.cutoff ? new Date(draft.cutoff + '+08:00').toISOString() : undefined,
page: 1,
})
} catch {
setData(null)
setError('截止时间无效,请按北京时间填写')
}
}
const submit = (event: FormEvent) => {
event.preventDefault()
query()
}
const page = (n: number) => {
if (data)
setRequest({
...request,
cutoff: data.end,
page: n,
directory_id: data.organization.directory_id,
revision_id: data.organization.revision_id,
})
}
return (
<>
<form className="qa-ops-query qa-monthly-query" onSubmit={submit} aria-label="个人月明细筛选">
<label>
自然月(北京时间)
<input
type="month"
required
value={draft.month}
disabled={loading}
onChange={(e) => change('month', e.target.value)}
/>
</label>
<label>
截止时间(可留空)
<input
type="datetime-local"
value={draft.cutoff}
disabled={loading}
onChange={(e) => change('cutoff', e.target.value)}
/>
</label>
<label>
区域 / 状态
<select value={draft.region} disabled={loading} onChange={(e) => change('region', e.target.value)}>
<option value="">全部区域 / 状态</option>
{['国内工业', 'APAC', 'EMEA', 'America', 'unassigned', 'cross_region'].map((key) => (
<option key={key} value={key}>
{usageLabels[key]}
</option>
))}
</select>
</label>
<label>
部门(含子部门)
<select
value={draft.department_id}
disabled={loading}
onChange={(e) => change('department_id', e.target.value)}
>
<option value="">全部部门</option>
{options.map((d) => (
<option value={d.id} key={d.id}>
{d.path}
</option>
))}
</select>
</label>
<label>
使用记录
<select value={draft.activity} disabled={loading} onChange={(e) => change('activity', e.target.value)}>
<option value="all">全部人员</option>
<option value="used">已关联提问</option>
<option value="zero">本源零记录</option>
</select>
</label>
<label>
姓名 / 部门路径
<input
type="search"
maxLength={100}
value={draft.search}
disabled={loading}
onChange={(e) => change('search', e.target.value)}
/>
</label>
<button type="submit" disabled={loading}>
查询个人月明细
</button>
</form>
<QAMonthlyView data={data} loading={loading} error={error} onRetry={query} onPage={page} />
</>
)
}
+15 -1
View File
@@ -6,6 +6,7 @@ import type { QAQuery, QARecord, QARecordPage, QAStatus } from './qaOps'
import './qaOps.css'
import { QARegions } from './QARegions'
import { QAUsage } from './QAUsage'
import { QAMonthly } from './QAMonthly'
import { usageLabels } from './qaUsage'
interface ViewProps {
@@ -276,6 +277,7 @@ function initialDraft() {
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)
@@ -427,7 +429,19 @@ export function QAOperations() {
区域使用
</button>
</nav>
{view === 'regions' ? (
{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 />
) : (
<>
+54
View File
@@ -0,0 +1,54 @@
export const monthlyFixture = {
organization: {
state: 'ready',
directory_id: 'd',
directory_source: 'weekly_report_live',
synced_at: '2026-10-17T07:59:50Z',
revision_id: 'r',
basis: 'current_directory',
},
source: '2.0',
timezone: 'Asia/Shanghai',
month: '2026-10',
start: '2026-10-01T00:00:00+08:00',
end: '2026-10-17T16:00:00+08:00',
month_end: '2026-11-01T00:00:00+08:00',
as_of: '2026-10-17T08:00:01Z',
partial: true,
questions: 3,
linked_questions: 2,
unresolved_questions: 1,
roster_people: 2,
used_people: 1,
zero_people: 1,
missing_names: 1,
total: 2,
page: 1,
limit: 30,
has_more: false,
department_options: [{ id: 'root', path: '示例部门' }],
rows: [
{
key: 'person-a',
name: '<script>示例姓名</script>',
departments: ['示例部门'],
region: 'APAC',
state: 'matched',
questions: 2,
succeeded: 1,
failed: 1,
other: 0,
},
{
key: 'person-b',
name: '',
departments: ['示例部门'],
region: '',
state: 'unassigned',
questions: 0,
succeeded: 0,
failed: 0,
other: 0,
},
],
}
+37
View File
@@ -0,0 +1,37 @@
import { describe, it, expect, vi } from 'vitest'
import { parseQAMonthly, fetchQAMonthly, beijingMonth } from './qaMonthly'
import { monthlyFixture } from './qaMonthly.fixture'
describe('personal natural-month contracts', () => {
it('sends personnel filters only in a same-origin no-store read body', async () => {
const fake = vi.fn().mockResolvedValue(new Response(JSON.stringify({ data: monthlyFixture }), { status: 200 }))
vi.stubGlobal('fetch', fake)
try {
await fetchQAMonthly({ month: '2026-10', search: '示例敏感筛选' })
expect(fake.mock.calls[0][0]).toBe('/api/v1/qa-ops/usage/people')
expect(fake.mock.calls[0][1]).toMatchObject({ method: 'POST', credentials: 'same-origin', cache: 'no-store' })
expect(JSON.parse(fake.mock.calls[0][1].body).search).toBe('示例敏感筛选')
} finally {
vi.unstubAllGlobals()
}
})
it('selects the month in Beijing rather than the browser timezone', () => {
expect(beijingMonth(new Date('2026-09-30T16:00:00Z'))).toBe('2026-10')
})
it('keeps named and missing-name zero-use members with a separate unresolved bucket', () => {
expect(parseQAMonthly(monthlyFixture)).toMatchObject({ zero_people: 1, missing_names: 1, unresolved_questions: 1 })
})
it('rejects nonconserving totals, fabricated pagination and inconsistent month boundaries', () => {
for (const invalid of [
{ ...monthlyFixture, zero_people: 0 },
{ ...monthlyFixture, linked_questions: 3 },
{ ...monthlyFixture, rows: [monthlyFixture.rows[0]] },
{ ...monthlyFixture, partial: false },
{ ...monthlyFixture, source: '1.0' },
{ ...monthlyFixture, month: '2026-1' },
{ ...monthlyFixture, month_end: '2026-11-02T00:00:00+08:00' },
{ ...monthlyFixture, rows: [monthlyFixture.rows[0], monthlyFixture.rows[0]] },
])
expect(() => parseQAMonthly(invalid)).toThrow()
})
})
+200
View File
@@ -0,0 +1,200 @@
import { parseQAOrganizationVersion } from './qaOps'
import type { QAOrganizationVersion } from './qaOps'
import { getPayload } from './qaOps'
export interface MonthlyQuery {
month: string
cutoff?: string
region?: string
department_id?: string
activity?: string
search?: string
page?: number
limit?: number
directory_id?: string
revision_id?: string
}
export interface MonthlyPerson {
key: string
name: string
departments: string[]
region: string
state: 'matched' | 'unassigned' | 'cross_region'
questions: number
succeeded: number
failed: number
other: number
}
export interface MonthlyPeople {
organization: QAOrganizationVersion
source: '2.0'
timezone: 'Asia/Shanghai'
month: string
start: string
end: string
month_end: string
as_of: string
partial: boolean
questions: number
linked_questions: number
unresolved_questions: number
roster_people: number
used_people: number
zero_people: number
missing_names: number
total: number
page: number
limit: number
has_more: boolean
rows: MonthlyPerson[]
department_options: { id: string; path: string }[]
}
const fail = (): never => {
throw new Error('个人月明细返回格式异常,未展示可能失真的统计')
}
const obj = (v: unknown): Record<string, unknown> =>
v && typeof v === 'object' && !Array.isArray(v) ? (v as Record<string, unknown>) : fail()
const text = (v: unknown): string => (typeof v === 'string' ? v : fail())
const count = (v: unknown): number => (typeof v === 'number' && Number.isSafeInteger(v) && v >= 0 ? v : fail())
const flag = (v: unknown): boolean => (typeof v === 'boolean' ? v : fail())
const instant = (v: unknown): string => {
const t = text(v)
return Number.isFinite(Date.parse(t)) ? t : fail()
}
const regions = ['国内工业', 'APAC', 'EMEA', 'America']
export function parseQAMonthly(value: unknown): MonthlyPeople {
const v = obj(value),
organization = parseQAOrganizationVersion(v.organization)
if (organization.state !== 'ready' || v.source !== '2.0' || v.timezone !== 'Asia/Shanghai') fail()
const month = text(v.month)
if (!/^(?!0000)\d{4}-(0[1-9]|1[0-2])$/.test(month)) fail()
const start = instant(v.start),
end = instant(v.end),
month_end = instant(v.month_end),
as_of = instant(v.as_of),
partial = flag(v.partial)
const expectedEnd = new Date(`${month}-01T00:00:00Z`)
expectedEnd.setUTCMonth(expectedEnd.getUTCMonth() + 1)
if (
Date.parse(start) !== Date.parse(`${month}-01T00:00:00+08:00`) ||
Date.parse(month_end) !== expectedEnd.getTime() - 8 * 60 * 60 * 1000 ||
Date.parse(end) <= Date.parse(start) ||
Date.parse(end) > Date.parse(month_end) ||
partial !== Date.parse(end) < Date.parse(month_end)
)
fail()
const questions = count(v.questions),
linked_questions = count(v.linked_questions),
unresolved_questions = count(v.unresolved_questions),
roster_people = count(v.roster_people),
used_people = count(v.used_people),
zero_people = count(v.zero_people),
missing_names = count(v.missing_names),
total = count(v.total),
page = count(v.page),
limit = count(v.limit),
has_more = flag(v.has_more)
if (
questions !== linked_questions + unresolved_questions ||
roster_people !== used_people + zero_people ||
missing_names > roster_people ||
total > roster_people ||
page < 1 ||
page > 100000 ||
limit < 1 ||
limit > 100
)
fail()
if (!Array.isArray(v.rows) || !Array.isArray(v.department_options)) return fail()
const keys = new Set<string>()
const rows = v.rows.map((raw: unknown) => {
const r = obj(raw),
key = text(r.key),
name = text(r.name),
region = text(r.region),
state = text(r.state)
if (
!key ||
keys.has(key) ||
name.length > 1000 ||
!['matched', 'unassigned', 'cross_region'].includes(state) ||
(state === 'matched' && !regions.includes(region)) ||
(state !== 'matched' && region !== '')
)
fail()
keys.add(key)
if (!Array.isArray(r.departments)) return fail()
const q = count(r.questions),
s = count(r.succeeded),
f = count(r.failed),
o = count(r.other)
if (s + f + o !== q) fail()
return {
key,
name,
region,
state: state as MonthlyPerson['state'],
departments: r.departments.map(text),
questions: q,
succeeded: s,
failed: f,
other: o,
}
})
const offset = (page - 1) * limit
if (
rows.length !== Math.max(0, Math.min(limit, total - offset)) ||
has_more !== offset + rows.length < total ||
rows.reduce((n, r) => n + r.questions, 0) > linked_questions
)
fail()
const ids = new Set<string>()
const department_options = v.department_options.map((raw: unknown) => {
const d = obj(raw),
id = text(d.id),
path = text(d.path)
if (!id || !path || ids.has(id)) fail()
ids.add(id)
return { id, path }
})
return {
organization,
source: '2.0',
timezone: 'Asia/Shanghai',
month,
start,
end,
month_end,
as_of,
partial,
questions,
linked_questions,
unresolved_questions,
roster_people,
used_people,
zero_people,
missing_names,
total,
page,
limit,
has_more,
rows,
department_options,
}
}
export async function fetchQAMonthly(q: MonthlyQuery, signal?: AbortSignal): Promise<MonthlyPeople> {
return parseQAMonthly(
await getPayload('/api/v1/qa-ops/usage/people', signal, {
method: 'POST',
headers: { 'Content-Type': 'application/json', 'X-Governance-Action': 'qa-usage-read' },
body: JSON.stringify(q),
})
)
}
export function beijingMonth(now = new Date()): string {
const parts = new Intl.DateTimeFormat('en-CA', {
timeZone: 'Asia/Shanghai',
year: 'numeric',
month: '2-digit',
}).formatToParts(now)
return `${parts.find((p) => p.type === 'year')!.value}-${parts.find((p) => p.type === 'month')!.value}`
}
+48
View File
@@ -7,6 +7,54 @@
height: calc(100dvh - 44px);
overflow: hidden;
}
.qa-ops-query.qa-monthly-query {
display: grid;
grid-template-columns: repeat(3, minmax(0, 1fr));
}
.qa-monthly-query label {
min-width: 0;
}
.qa-monthly-query select,
.qa-monthly-query input {
width: 100%;
min-width: 0;
}
.qa-monthly-query select {
min-height: 36px;
padding: 7px;
color: var(--ink-strong);
background: var(--bg-panel);
border: 1px solid var(--border-strong);
border-radius: var(--r-sm);
}
.qa-monthly-results > .qa-ops-muted {
margin: 6px 14px;
font-size: 12px;
line-height: 1.5;
}
.qa-ops-table.qa-monthly-table {
min-width: 800px;
table-layout: fixed;
}
.qa-monthly-table th:nth-child(1) {
width: 15%;
}
.qa-monthly-table th:nth-child(2) {
width: 30%;
}
.qa-monthly-table th:nth-child(3) {
width: 23%;
}
.qa-monthly-table td:nth-child(1),
.qa-monthly-table td:nth-child(2) {
white-space: normal;
overflow-wrap: anywhere;
}
@media (max-width: 760px) {
.qa-ops-query.qa-monthly-query {
grid-template-columns: minmax(0, 1fr);
}
}
.qa-ops-header h2 {
margin: 0 0 5px;
font-size: 21px;
+6 -2
View File
@@ -231,8 +231,12 @@ export function parseQARecordPage(value: unknown): QARecordPage {
}
}
export async function getPayload(path: string, signal?: AbortSignal): Promise<unknown> {
const response = await fetch(path, { credentials: 'same-origin', cache: 'no-store', signal })
export async function getPayload(
path: string,
signal?: AbortSignal,
request: Pick<RequestInit, 'method' | 'headers' | 'body'> = {}
): Promise<unknown> {
const response = await fetch(path, { ...request, credentials: 'same-origin', cache: 'no-store', signal })
const raw: unknown = await response.json().catch(() => null)
if (!response.ok) {
const payload = raw && typeof raw === 'object' ? (raw as Record<string, unknown>) : null