feat(qaops): 增加部门树区域统计与父子联选
build / build (push) Successful in 1m5s

区域配置入口改为区域统计,五列表按当前通讯录整支人员去重;调岗依当前归属、零分母未知、最近真实提问时间和父行收起不重算。仅读治理正式总表,后台单并发/请求合并/60秒缓存,目录与配置版本隔离,客户端失败不伪零。

保留区域自定义目录与预览/双版本锁保存,父部门勾选联选全后代,取消子支清除祖先整支选择,避免隐式覆盖未选子级;允许删除无引用区域,已有引用不静默孤立。统计页与设置共享选择,统计支持累计与北京时间自然月;不新增迁移,不改DobotAI生产、代理、原问答、历史趋势或已有AI任务。

验证已执行:完整make verify退出0,705 Go/340前端通过、120项声明的可选集成跳过且必需0跳过;镜像全量隔离PG race退出0;新增去重/调岗/空分母、后台缓存/并发、HTTP授权/严格请求、真PG目录与配置失效、树选择/收起、五列与删除保护均先红后绿。旧导航测试按新名称更新后全量通过。上线前治理库备份与真实恢复72表/29张QA内容哈希一致,匹配独立主密钥受限备份。

当前尚待精确SHA CI、同镜像真实数据浏览器与正式读回,不把源码验证称为已上线。公司真实区域映射不在本轮擅改;只在隔离库验证保存。
This commit is contained in:
姚章浩
2026-10-19 19:01:36 +08:00
parent a9870beade
commit 4a2b2b7d84
25 changed files with 1642 additions and 20 deletions
+25
View File
@@ -0,0 +1,25 @@
import { it, expect } from 'vitest'
import { renderToStaticMarkup } from 'react-dom/server'
import { DepartmentStatisticsView } from './QADepartmentStatistics'
import { parseDepartmentStatistics } from './qaDepartmentStatistics'
import { departmentStatisticsFixture } from './qaDepartmentStatistics.fixture'
it('renders exactly five requested columns, a denominator and no fabricated zero ratio', () => {
const data = parseDepartmentStatistics(departmentStatisticsFixture, { period: 'all' }).snapshot!
const html = renderToStaticMarkup(<DepartmentStatisticsView data={data} />)
const headers = [...html.matchAll(/<th[^>]*>([^<]+)<\/th>/g)].map((m) => m[1])
expect(headers).toEqual(['部门', '访问人数', '访问比例', '访问次数', '最近提问时间'])
expect(html).toContain('总人数')
expect(html).toContain('66.7%')
expect(html).toContain('50.0%')
expect(html).not.toContain('覆盖服务')
expect(html).toContain('data-ratio="unknown"')
expect(html).not.toContain('NaN')
})
it('keeps parent values unchanged when child departments are collapsed', () => {
const data = parseDepartmentStatistics(departmentStatisticsFixture, { period: 'all' }).snapshot!
const html = renderToStaticMarkup(<DepartmentStatisticsView data={data} collapsed={new Set(['root'])} />)
expect(html).toContain('data-department-id="root"')
expect(html).not.toContain('data-department-id="child"')
expect(html).toContain('66.7%')
expect(html).toContain('总人数')
})
+307
View File
@@ -0,0 +1,307 @@
import { useEffect, useMemo, useRef, useState } from 'react'
import type { DepartmentStatisticsSnapshot } from './qaDepartmentStatistics'
import { fetchDepartmentStatistics } from './qaDepartmentStatistics'
import { departmentTree, selectDepartmentBranch, subtreeIDs } from './qaRegionSelection'
import { QARegions } from './QARegions'
import './qaDepartmentStatistics.css'
export interface DepartmentStatisticsViewProps {
data: DepartmentStatisticsSnapshot
selected?: string[]
collapsed?: ReadonlySet<string>
search?: string
region?: string
onSelect?: (ids: string[]) => void
onCollapse?: (id: string) => void
}
export const departmentTime = (value: string) =>
new Date(value).toLocaleString('zh-CN', {
timeZone: 'Asia/Shanghai',
year: 'numeric',
month: '2-digit',
day: '2-digit',
hour: '2-digit',
minute: '2-digit',
hour12: false,
})
export function DepartmentStatisticsView(p: DepartmentStatisticsViewProps) {
const selected = p.selected ?? [],
collapsed = p.collapsed ?? new Set<string>(),
rows = departmentTree(p.data.rows, collapsed, p.search ?? '', p.region ?? '')
return (
<section className="qa-department-list" aria-label="部门访问统计" data-generated-at={p.data.generated_at}>
<div className="qa-department-table-scroll" tabIndex={0} aria-label="部门统计表格滚动区">
<table className="qa-department-table">
<colgroup>
<col className="qa-department-name-column" />
<col />
<col />
<col />
<col className="qa-department-time-column" />
</colgroup>
<thead>
<tr>
<th>部门</th>
<th>访问人数</th>
<th>访问比例</th>
<th title="已入总表的唯一提问事件,包含失败请求;不包含未采集的网页浏览">访问次数</th>
<th>最近提问时间</th>
</tr>
</thead>
<tbody>
{rows.map(({ department: d, depth, hasChildren }) => {
const branch = subtreeIDs(p.data.rows, [d.id]),
checked = branch.every((id) => selected.includes(id)),
partial = !checked && branch.some((id) => selected.includes(id)),
label = p.data.regions.find((r) => r.id === d.region)?.name
return (
<tr
key={d.id}
data-department-id={d.id}
data-visitors={d.visitors}
data-total-people={d.total_people}
data-visits={d.visits}
data-latest={d.last_asked_at ?? ''}
>
<td>
<div className="qa-department-name" style={{ paddingInlineStart: depth * 20 }}>
<input
type="checkbox"
aria-label={`选择部门 ${d.name}及子部门`}
checked={checked}
ref={(node) => {
if (node) node.indeterminate = partial
}}
onChange={(e) =>
p.onSelect?.(selectDepartmentBranch(p.data.rows, selected, d.id, e.target.checked))
}
/>
{hasChildren ? (
<button
type="button"
className="qa-department-expand"
aria-label={`${collapsed.has(d.id) ? '展开' : '收起'}部门 ${d.name}`}
aria-expanded={!collapsed.has(d.id)}
onClick={() => p.onCollapse?.(d.id)}
>
{collapsed.has(d.id) ? '›' : '⌄'}
</button>
) : (
<span className="qa-department-expand-space" />
)}
<span className="qa-department-label">
{d.name}
{label ? <small className="qa-department-region">{label}</small> : null}
</span>
</div>
</td>
<td>
<span>{d.visitors.toLocaleString('zh-CN')}</span>
<small className="qa-department-roster">总人数 {d.total_people.toLocaleString('zh-CN')}</small>
</td>
<td className="qa-department-ratio" data-ratio={d.ratio === null ? 'unknown' : d.ratio}>
{d.ratio === null ? '—' : `${d.ratio.toFixed(1)}%`}
</td>
<td>{d.visits.toLocaleString('zh-CN')}</td>
<td>{d.last_asked_at === null ? '—' : departmentTime(d.last_asked_at)}</td>
</tr>
)
})}
</tbody>
</table>
{!rows.length ? <p className="qa-ops-empty">没有匹配的部门</p> : null}
</div>
</section>
)
}
const currentMonth = () => {
const parts = new Intl.DateTimeFormat('zh-CN', {
timeZone: 'Asia/Shanghai',
year: 'numeric',
month: '2-digit',
}).formatToParts(new Date())
return `${parts.find((p) => p.type === 'year')!.value}-${parts.find((p) => p.type === 'month')!.value}`
}
export function QARegionalStatistics() {
const [period, setPeriod] = useState<'all' | 'month'>('all'),
[month, setMonth] = useState(currentMonth),
[reload, setReload] = useState(0),
[settings, setSettings] = useState(false)
const [data, setData] = useState<DepartmentStatisticsSnapshot | null>(null),
[error, setError] = useState(''),
[busy, setBusy] = useState(true),
[cached, setCached] = useState(false)
const [selected, setSelected] = useState<string[]>([]),
[collapsed, setCollapsed] = useState<Set<string>>(new Set()),
[search, setSearch] = useState(''),
[region, setRegion] = useState('')
const key = useRef(''),
condition = useRef(''),
query = useMemo(
() => (period === 'all' ? { period: 'all' as const } : { period: 'month' as const, month }),
[period, month]
)
useEffect(() => {
const controller = new AbortController()
let timer: ReturnType<typeof setTimeout>
const signature = JSON.stringify(query)
if (condition.current !== signature) {
setData(null)
key.current = ''
condition.current = signature
}
const poll = async () => {
setBusy(true)
setError('')
try {
const result = await fetchDepartmentStatistics(query, controller.signal)
if (controller.signal.aborted) return
if (key.current !== result.cache_key) {
setData(null)
key.current = result.cache_key
}
if (result.state === 'ready' && result.snapshot) {
const fresh = result.snapshot
setData(fresh)
setCached(result.cache_hit)
setBusy(false)
const ids = new Set(fresh.rows.map((d) => d.id))
setSelected((old) => old.filter((id) => ids.has(id)))
setCollapsed((old) => new Set([...old].filter((id) => ids.has(id))))
setRegion((old) => (fresh.regions.some((r) => r.id === old) ? old : ''))
timer = setTimeout(() => void poll(), Math.max(1000, Date.parse(fresh.expires_at) - Date.now() + 100))
} else timer = setTimeout(() => void poll(), result.retry_after * 1000)
} catch (e) {
if (!controller.signal.aborted) {
setError(e instanceof Error ? e.message : '区域统计读取失败')
setBusy(false)
}
}
}
void poll()
return () => {
controller.abort()
clearTimeout(timer)
}
}, [query, reload])
return (
<section className="qa-regional-statistics" aria-label="区域统计">
<header className="qa-department-toolbar">
<h3>区域统计</h3>
<div className="qa-department-actions">
<button type="button" disabled={busy} onClick={() => setReload((v) => v + 1)}>
重新读取统计
</button>
<button type="button" aria-expanded={settings} onClick={() => setSettings((v) => !v)}>
{settings ? '返回部门统计' : '区域设置'}
</button>
</div>
</header>
<div hidden={!settings} className="qa-department-editor">
<QARegions selection={selected} onSelectionChange={setSelected} onSaved={() => setReload((v) => v + 1)} />
</div>
<div hidden={settings}>
<div className="qa-department-filters">
<label>
统计范围
<select
aria-label="部门统计范围"
value={period}
onChange={(e) => setPeriod(e.target.value as 'all' | 'month')}
>
<option value="all">累计提问访问</option>
<option value="month">按自然月</option>
</select>
</label>
{period === 'month' ? (
<label>
统计月份
<input
aria-label="部门统计月份"
type="month"
min="2000-01"
max={currentMonth()}
value={month}
onChange={(e) => setMonth(e.target.value)}
/>
</label>
) : null}
<label>
部门
<input
type="search"
aria-label="搜索统计部门"
value={search}
onChange={(e) => setSearch(e.target.value)}
placeholder="搜索部门或完整路径"
/>
</label>
<label>
区域
<select aria-label="筛选统计区域" value={region} onChange={(e) => setRegion(e.target.value)}>
<option value="">全部区域</option>
{data?.regions.map((r) => (
<option key={r.id} value={r.id}>
{r.name}
</option>
))}
</select>
</label>
<button type="button" disabled={!selected.length} onClick={() => setSettings(true)}>
设置选中部门的区域{selected.length ? `(${selected.length})` : ''}
</button>
<button type="button" disabled={!selected.length} onClick={() => setSelected([])}>
取消勾选
</button>
</div>
<div className="qa-department-meta" role="status" aria-live="polite">
{busy
? data
? '后台重新聚合中,暂保留上次结果…'
: '正在后台聚合部门统计…'
: data
? `${cached ? '60秒缓存结果' : '统计已更新'} · 统计截至 ${departmentTime(data.end)} · 通讯录 ${data.organization.synced_at ? departmentTime(data.organization.synced_at) : '未同步'}`
: ''}
</div>
{error ? (
<div className="error-banner" role="alert">
{error}
{data ? ';当前为上一次结果,未替换成零数据' : ''}{' '}
<button type="button" onClick={() => setReload((v) => v + 1)}>
重试
</button>
</div>
) : null}
{data ? (
<>
<DepartmentStatisticsView
data={data}
selected={selected}
collapsed={collapsed}
search={search}
region={region}
onSelect={setSelected}
onCollapse={(id) =>
setCollapsed((old) => {
const next = new Set(old)
if (next.has(id)) next.delete(id)
else next.add(id)
return next
})
}
/>
<p className="qa-department-note">
每行含本部门及全部子部门,按当前通讯录人员去重;收起不改变统计。访问为已入总表的提问事件,区域筛选只改变可见部门。
</p>
{data.unmapped_visits > 0 ? (
<p className="qa-department-note">
另有 {data.unmapped_visits.toLocaleString('zh-CN')} 次提问未能归入当前通讯录部门,未虚构归属。
</p>
) : null}
</>
) : !busy && !error ? (
<p className="qa-ops-empty">尚无统计结果,请重新读取。</p>
) : null}
</div>
</section>
)
}
+1 -1
View File
@@ -117,7 +117,7 @@ describe('QA operations workbench', () => {
it('uses the four requested destinations in their fixed order', () => {
const html = renderToStaticMarkup(<QAOperationsTabs view="records" onChange={vi.fn()} />)
const labels = ['问题流水', '问题统计看板', '区域配置', '周报生成']
const labels = ['问题流水', '问题统计看板', '区域统计', '周报生成']
for (const label of labels) expect(html).toContain(label)
for (let i = 1; i < labels.length; i++) expect(html.indexOf(labels[i - 1])).toBeLessThan(html.indexOf(labels[i]))
expect(html).not.toContain('部门/区域保留源快照')
+3 -3
View File
@@ -4,7 +4,7 @@ import { useOptionalAuth } from './auth'
import { fetchQARecord, fetchAllQARecords, fetchQAStatus, qaCellValue, qaColumns } from './qaOps'
import type { QAQuery, QARecord, QARecordPage, QAStatus } from './qaOps'
import './qaOps.css'
import { QARegions } from './QARegions'
import { QARegionalStatistics } from './QADepartmentStatistics'
import { QADashboard } from './QADashboard'
import { QAWeekly } from './QAWeekly'
import { QAQualityEditor } from './QAQuality'
@@ -26,7 +26,7 @@ export function QAOperationsTabs({ view, onChange }: { view: QAOpsView; onChange
[
['records', '问题流水'],
['dashboard', '问题统计看板'],
['regions', '区域配置'],
['regions', '区域统计'],
['weekly', '周报生成'],
] as const
).map(([id, label]) => (
@@ -603,7 +603,7 @@ export function QAOperations() {
</>
) : null}
{view === 'regions' ? (
<QARegions />
<QARegionalStatistics />
) : view === 'weekly' ? (
<QAWeekly query={query} />
) : view === 'dashboard' ? (
+10
View File
@@ -51,6 +51,16 @@ const props = {
onRemoveMissing: vi.fn(),
}
describe('region mapping workbench', () => {
it('allows removing unused region definitions but protects regions referenced by department rules', () => {
const regions = [
{ id: 'APAC', name: 'Assigned' },
{ id: 'spare', name: 'Spare' },
]
const html = renderToStaticMarkup(<RegionMappingView {...props} regions={regions} />)
expect(html).toContain('删除区域 Spare')
expect(html).toMatch(/aria-label="删除区域 Assigned"[^>]*disabled=""/)
})
it('separates multiselect from bulk application and renders hierarchy and editable region names', () => {
const custom = {
...state,
+32 -11
View File
@@ -9,7 +9,7 @@ import {
} from './qaOrg'
import type { Organization, RegionRule, RegionDefinition } from './qaOrg'
import './qaRegions.css'
import { applyBulkRegionRules, departmentLevels } from './qaRegionSelection'
import { applyBulkRegionRules, departmentLevels, selectDepartmentBranch } from './qaRegionSelection'
import { completedSyncAction, directorySyncActive, fetchDirectorySync, startDirectorySync } from './qaOrgSync'
import type { DirectorySyncStatus } from './qaOrgSync'
import { newOperationID } from './operationKey'
@@ -57,8 +57,7 @@ export function RegionMappingView(p: Props) {
)
const maximum = rows.reduce((n, r) => Math.max(n, r.levels.length), 0)
const label = (id: string, catalog = regions) => catalog.find((r) => r.id === id)?.name ?? id
const choose = (id: string, checked: boolean) =>
p.onSelect?.(checked ? [...new Set([...selected, id])] : selected.filter((x) => x !== id))
const choose = (id: string, checked: boolean) => p.onSelect?.(selectDepartmentBranch(all, selected, id, checked))
const add = () => {
if (!newName.trim()) return
const next = [...regions, { id: 'region-' + newOperationID(), name: newName.trim() }]
@@ -155,6 +154,19 @@ export function RegionMappingView(p: Props) {
p.onCatalog?.(regions.map((x) => (x.id === r.id ? { ...x, name: e.target.value } : x)))
}
/>
<button
type="button"
aria-label={`删除区域 ${r.name}`}
disabled={p.busy || p.rules.some((rule) => rule.region === r.id)}
title={
p.rules.some((rule) => rule.region === r.id)
? '此区域仍有部门配置,请先移除对应配置'
: '从草稿移除此区域,保存后生效'
}
onClick={() => p.onCatalog?.(regions.filter((item) => item.id !== r.id))}
>
删除区域
</button>
</label>
))}
</div>
@@ -226,12 +238,10 @@ export function RegionMappingView(p: Props) {
disabled={p.busy || !departments.length}
checked={departments.length > 0 && departments.every((r) => selected.includes(r.department.id))}
onChange={(e) => {
const visible = new Set(departments.map((r) => r.department.id))
p.onSelect?.(
e.target.checked
? [...new Set([...selected, ...visible])]
: selected.filter((id) => !visible.has(id))
)
let next = [...selected]
for (const row of departments)
next = selectDepartmentBranch(all, next, row.department.id, e.target.checked)
p.onSelect?.(next)
}}
/>
全选当前列表
@@ -351,7 +361,11 @@ export function RegionMappingView(p: Props) {
function signature(rules: RegionRule[], regions: RegionDefinition[]) {
return JSON.stringify({ rules: [...rules].sort((a, b) => a.department_id.localeCompare(b.department_id)), regions })
}
export function QARegions() {
export function QARegions({
selection,
onSelectionChange,
onSaved,
}: { selection?: string[]; onSelectionChange?: (ids: string[]) => void; onSaved?: () => void } = {}) {
const [syncStatus, setSyncStatus] = useState<DirectorySyncStatus | null>(null),
[syncError, setSyncError] = useState(''),
[syncSubmitting, setSyncSubmitting] = useState(false)
@@ -364,7 +378,12 @@ export function QARegions() {
[preview, setPreview] = useState<Organization | null>(null),
[rules, setRules] = useState<RegionRule[]>([])
const [regions, setRegions] = useState<RegionDefinition[]>([]),
[selected, setSelected] = useState<string[]>([])
[localSelected, setLocalSelected] = useState<string[]>([])
const selected = selection ?? localSelected,
setSelected = (ids: string[]) => {
setLocalSelected(ids)
onSelectionChange?.(ids)
}
const [region, setRegion] = useState<string>(''),
[search, setSearch] = useState(''),
[busy, setBusy] = useState(false),
@@ -496,6 +515,7 @@ export function QARegions() {
accept(readback)
if (readback.revision_id !== value.revision_id) throw new Error('保存后配置再次变化,已读取最新版本,请核对')
setNotice('区域归属已保存并重新读取')
onSaved?.()
} else setPreview(value)
}
} catch (e) {
@@ -513,6 +533,7 @@ export function QARegions() {
selectedIDs={selected}
onCatalog={(next) => {
setRegions(next)
setRegion((old) => (next.some((r) => r.id === old) ? old : (next[0]?.id ?? '')))
setPreview(null)
setNotice('')
setError('')
+174
View File
@@ -0,0 +1,174 @@
.qa-regional-statistics {
min-width: 0;
color: #334155;
}
.qa-department-toolbar {
display: flex;
align-items: center;
justify-content: space-between;
gap: 12px;
margin: 0 0 14px;
}
.qa-department-toolbar h3 {
margin: 0;
font-size: 18px;
}
.qa-department-actions,
.qa-department-filters {
display: flex;
align-items: end;
flex-wrap: wrap;
gap: 10px;
}
.qa-department-filters {
padding: 10px 0;
}
.qa-department-filters label {
display: flex;
flex-direction: column;
gap: 4px;
font-size: 12px;
color: #64748b;
}
.qa-department-filters input,
.qa-department-filters select {
min-height: 34px;
max-width: 240px;
}
.qa-department-meta,
.qa-department-note {
font-size: 12px;
color: #718096;
margin: 8px 0;
line-height: 1.6;
}
.qa-department-table-scroll {
max-height: calc(100vh - 340px);
min-height: 280px;
overflow: auto;
border: 1px solid #e5ebf2;
border-radius: 5px;
min-width: 0;
max-width: 100%;
background: #fff;
}
.qa-department-table {
width: 100%;
min-width: 900px;
border-collapse: collapse;
table-layout: fixed;
font-size: 14px;
}
.qa-department-name-column {
width: 43%;
}
.qa-department-time-column {
width: 20%;
}
.qa-department-table th,
.qa-department-table td {
padding: 13px 12px;
border-right: 1px solid #e8edf4;
border-bottom: 1px solid #e8edf4;
text-align: center;
vertical-align: middle;
white-space: nowrap;
font-variant-numeric: tabular-nums;
}
.qa-department-table th {
position: sticky;
top: 0;
z-index: 2;
background: #f8fafc;
font-weight: 600;
color: #60748c;
}
.qa-department-table td:first-child,
.qa-department-table th:first-child {
text-align: left;
}
.qa-department-table tbody tr:hover {
background: #f7faff;
}
.qa-department-name {
display: flex;
align-items: center;
gap: 7px;
min-width: 0;
}
.qa-department-name input[type='checkbox'] {
flex: none;
width: 15px;
height: 15px;
margin: 0;
}
.qa-department-expand,
.qa-department-expand-space {
display: inline-flex;
flex: none;
align-items: center;
justify-content: center;
width: 20px;
min-width: 20px;
height: 24px;
}
.qa-department-expand {
padding: 0;
border: 0;
background: transparent;
color: #536c88;
font-size: 20px;
cursor: pointer;
}
.qa-department-expand:focus-visible {
outline: 2px solid #3b82f6;
outline-offset: 2px;
}
.qa-department-label {
min-width: 0;
white-space: normal;
overflow-wrap: anywhere;
line-height: 1.5;
}
.qa-department-region,
.qa-department-roster {
display: block;
font-size: 11px;
line-height: 1.5;
color: #8190a4;
margin-top: 2px;
}
.qa-department-ratio {
font-weight: 650;
}
.qa-department-ratio[data-ratio='unknown'] {
font-weight: 400;
color: #8190a4;
}
.qa-department-editor {
min-width: 0;
}
@media (max-width: 680px) {
.qa-department-toolbar {
align-items: flex-start;
}
.qa-department-actions {
justify-content: flex-end;
}
.qa-department-actions button {
font-size: 12px;
padding: 6px 8px;
}
.qa-department-table-scroll {
max-height: 65vh;
}
.qa-department-filters input {
max-width: 180px;
}
.qa-department-filters {
gap: 8px;
}
.qa-department-filters label {
max-width: 100%;
}
}
+62
View File
@@ -0,0 +1,62 @@
export const departmentStatisticsFixture = {
state: 'ready',
cache_key: 'a'.repeat(64),
cache_hit: true,
retry_after: 0,
snapshot: {
period: 'all',
month: '',
start: '2026-04-01T00:00:00+08:00',
end: '2026-10-19T12:00:00+08:00',
generated_at: '2026-10-19T12:00:01+08:00',
expires_at: '2026-10-19T12:01:01+08:00',
total_people: 3,
total_visits: 6,
unmapped_visits: 1,
organization: {
state: 'ready',
directory_id: 'fixture-directory',
directory_source: 'weekly_report_snapshot',
synced_at: '2026-10-18T00:00:00+08:00',
revision_id: 'fixture-revision',
basis: 'current_directory',
region_names: ['Education'],
},
regions: [{ id: 'edu', name: 'Education' }],
rows: [
{
id: 'root',
parent_id: '',
name: 'Fixture Root',
region: '',
visitors: 2,
total_people: 3,
ratio: (100 * 2) / 3,
visits: 5,
last_asked_at: '2026-10-18T06:00:00+08:00',
},
{
id: 'child',
parent_id: 'root',
name: 'Fixture Child',
region: 'edu',
visitors: 1,
total_people: 2,
ratio: 50,
visits: 2,
last_asked_at: '2026-10-17T06:00:00+08:00',
},
{
id: 'empty',
parent_id: 'root',
name: 'Empty',
region: '',
visitors: 0,
total_people: 0,
ratio: null,
visits: 0,
last_asked_at: null,
},
],
},
}
+23
View File
@@ -0,0 +1,23 @@
import { it, expect } from 'vitest'
import { parseDepartmentStatistics } from './qaDepartmentStatistics'
import { departmentStatisticsFixture as fixture } from './qaDepartmentStatistics.fixture'
it('preserves source roster denominators, null zero-denominator ratio and exact cache identity', () => {
const data = parseDepartmentStatistics(fixture, { period: 'all' })
expect(data.snapshot?.rows[0].visitors).toBe(2)
expect(data.snapshot?.rows[0].total_people).toBe(3)
expect(data.snapshot?.rows[2].ratio).toBeNull()
expect(data.cache_key).toBe(fixture.cache_key)
})
it('rejects fake zeros, invalid hierarchy, inconsistent ratios and wrong conditions', () => {
for (const rows of [
fixture.snapshot.rows.map((r) => (r.id === 'empty' ? { ...r, ratio: 0 } : r)),
fixture.snapshot.rows.map((r) => (r.id === 'child' ? { ...r, parent_id: 'missing' } : r)),
fixture.snapshot.rows.map((r) => (r.id === 'child' ? { ...r, visitors: 3 } : r)),
fixture.snapshot.rows.map((r) => (r.id === 'child' ? { ...r, ratio: 70 } : r)),
fixture.snapshot.rows.map((r) => (r.id === 'child' ? { ...r, last_asked_at: '2027-01-01T00:00:00Z' } : r)),
])
expect(() =>
parseDepartmentStatistics({ ...fixture, snapshot: { ...fixture.snapshot, rows } }, { period: 'all' })
).toThrow()
expect(() => parseDepartmentStatistics(fixture, { period: 'month', month: '2026-10' })).toThrow()
})
+191
View File
@@ -0,0 +1,191 @@
import type { QAOrganizationVersion } from './qaOps'
import { parseQAOrganizationVersion } from './qaOps'
import { parseRegionDefinitions } from './qaOrg'
import { departmentTree } from './qaRegionSelection'
import type { RegionDefinition } from './qaOrg'
export interface DepartmentStatisticsQuery {
period: 'all' | 'month'
month?: string
}
export interface DepartmentStatistic {
id: string
parent_id: string
name: string
region: string
visitors: number
total_people: number
ratio: number | null
visits: number
last_asked_at: string | null
}
export interface DepartmentStatisticsSnapshot {
rows: DepartmentStatistic[]
total_visits: number
unmapped_visits: number
total_people: number
organization: QAOrganizationVersion
regions: RegionDefinition[]
period: 'all' | 'month'
month: string
start: string | null
end: string
generated_at: string
expires_at: string
}
export interface DepartmentStatisticsResult {
state: 'pending' | 'ready'
cache_key: string
cache_hit: boolean
retry_after: number
snapshot: DepartmentStatisticsSnapshot | null
}
const bad = (): never => {
throw Error('区域统计响应无效,请重试或联系管理员')
}
const obj = (v: unknown): Record<string, unknown> =>
v !== null && 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 instant = (v: unknown) => (typeof v === 'string' && Number.isFinite(Date.parse(v)) ? v : bad())
export function parseDepartmentStatistics(raw: unknown, query: DepartmentStatisticsQuery): DepartmentStatisticsResult {
const v = obj(raw),
cache_key = text(v.cache_key)
if (
!/^[a-f0-9]{64}$/.test(cache_key) ||
typeof v.cache_hit !== 'boolean' ||
!['pending', 'ready'].includes(String(v.state))
)
return bad()
if (v.state === 'pending') {
if (v.snapshot !== null || v.retry_after !== 1) return bad()
return { state: 'pending', cache_key, cache_hit: false, retry_after: 1, snapshot: null }
}
if (v.retry_after !== 0) return bad()
const d = obj(v.snapshot),
organization = parseQAOrganizationVersion(d.organization)
if (!organization || organization.state !== 'ready' || !organization.directory_id || !organization.synced_at)
return bad()
const regions = parseRegionDefinitions(d.regions),
regionIDs = new Set(regions.map((r) => r.id))
if (
d.period !== query.period ||
d.month !== (query.month ?? '') ||
!Array.isArray(d.rows) ||
!d.rows.length ||
d.rows.length > 20000
)
return bad()
const end = instant(d.end),
generated = instant(d.generated_at),
expires = instant(d.expires_at),
start = d.start === null ? null : instant(d.start)
if (
Date.parse(expires) - Date.parse(generated) !== 60000 ||
Date.parse(end) > Date.parse(generated) ||
(start !== null && Date.parse(start) >= Date.parse(end))
)
return bad()
const total_people = count(d.total_people),
total_visits = count(d.total_visits),
unmapped_visits = count(d.unmapped_visits)
if (unmapped_visits > total_visits) return bad()
const rows: DepartmentStatistic[] = d.rows.map((raw) => {
const r = obj(raw),
id = text(r.id),
parent_id = text(r.parent_id),
name = text(r.name),
region = text(r.region),
visitors = count(r.visitors),
total = count(r.total_people),
visits = count(r.visits),
last = r.last_asked_at === null ? null : instant(r.last_asked_at)
if (
!id ||
!name ||
(region !== '' && !regionIDs.has(region)) ||
visitors > total ||
total > total_people ||
visits < visitors ||
visits > total_visits - unmapped_visits ||
(visits === 0) !== (visitors === 0) ||
(visits === 0) !== (last === null) ||
(last !== null &&
(Date.parse(last) >= Date.parse(end) || (start !== null && Date.parse(last) < Date.parse(start))))
)
return bad()
if (
total === 0
? r.ratio !== null
: typeof r.ratio !== 'number' ||
!Number.isFinite(r.ratio) ||
Math.abs(r.ratio - (100 * visitors) / total) > 1e-8
)
return bad()
return {
id,
parent_id,
name,
region,
visitors,
total_people: total,
ratio: r.ratio as number | null,
visits,
last_asked_at: last,
}
})
departmentTree(rows, new Set())
const byID = new Map(rows.map((r) => [r.id, r]))
for (const row of rows) {
const parent = byID.get(row.parent_id)
if (
parent &&
(parent.total_people < row.total_people ||
parent.visitors < row.visitors ||
parent.visits < row.visits ||
(row.last_asked_at !== null &&
(parent.last_asked_at === null || Date.parse(parent.last_asked_at) < Date.parse(row.last_asked_at))))
)
return bad()
}
return {
state: 'ready',
cache_key,
cache_hit: v.cache_hit,
retry_after: 0,
snapshot: {
rows,
total_people,
total_visits,
unmapped_visits,
organization,
regions,
period: query.period,
month: query.month ?? '',
start,
end,
generated_at: generated,
expires_at: expires,
},
}
}
export async function fetchDepartmentStatistics(
query: DepartmentStatisticsQuery,
signal?: AbortSignal
): Promise<DepartmentStatisticsResult> {
const response = await fetch('/api/v1/qa-ops/departments/statistics', {
method: 'POST',
credentials: 'same-origin',
cache: 'no-store',
signal,
headers: { 'Content-Type': 'application/json', 'X-Governance-Action': 'qa-department-statistics' },
body: JSON.stringify(query),
})
const raw: unknown = await response.json().catch(() => null)
if (!response.ok) {
const error = raw && typeof raw === 'object' ? (raw as Record<string, unknown>).error : undefined
throw Error(typeof error === 'string' ? error : `区域统计读取失败(HTTP ${response.status})`)
}
const data = parseDepartmentStatistics(obj(raw).data, query)
if ((response.status === 202) !== (data.state === 'pending')) return bad()
return data
}
+26
View File
@@ -0,0 +1,26 @@
import { it, expect } from 'vitest'
import { subtreeIDs, selectDepartmentBranch, departmentTree } from './qaRegionSelection'
const nodes = [
{ id: 'root', parent_id: '', name: 'Root' },
{ id: 'child', parent_id: 'root', name: 'Child' },
{ id: 'leaf', parent_id: 'child', name: 'Leaf' },
{ id: 'other', parent_id: 'root', name: 'Other' },
]
it('selects a full branch and removes partial ancestors when a descendant is unchecked', () => {
expect(new Set(subtreeIDs(nodes, ['child']))).toEqual(new Set(['child', 'leaf']))
const selected = selectDepartmentBranch(nodes, [], 'root', true)
expect(new Set(selected)).toEqual(new Set(nodes.map((d) => d.id)))
expect(new Set(selectDepartmentBranch(nodes, selected, 'leaf', false))).toEqual(new Set(['other']))
expect(selected).toHaveLength(4)
})
it('collapses hierarchy without dropping source rows or changing statistics', () => {
const before = JSON.stringify(nodes)
expect(departmentTree(nodes, new Set(['child'])).map((r) => r.department.id)).toEqual(['root', 'child', 'other'])
expect(departmentTree(nodes, new Set(['root']), 'Leaf').map((r) => r.department.id)).toEqual([
'root',
'child',
'leaf',
])
expect(JSON.stringify(nodes)).toBe(before)
expect(() => departmentTree([{ id: 'bad', parent_id: 'bad', name: 'Cycle' }], new Set())).toThrow()
})
+88
View File
@@ -1,4 +1,92 @@
import type { DepartmentRegion, RegionRule } from './qaOrg'
export type DepartmentNode = { id: string; parent_id: string; name: string }
export function subtreeIDs(nodes: DepartmentNode[], ids: string[]): string[] {
const children = new Map<string, string[]>(),
known = new Set(nodes.map((n) => n.id))
for (const node of nodes) {
const list = children.get(node.parent_id) ?? []
list.push(node.id)
children.set(node.parent_id, list)
}
const seen = new Set<string>(),
queue = [...ids]
while (queue.length) {
const id = queue.pop()!
if (!known.has(id)) throw Error('部门不在当前通讯录')
if (seen.has(id)) continue
seen.add(id)
queue.push(...(children.get(id) ?? []))
}
return [...seen]
}
export function selectDepartmentBranch(
nodes: DepartmentNode[],
selected: string[],
id: string,
checked: boolean
): string[] {
const ids = subtreeIDs(nodes, [id]),
next = new Set(selected)
if (checked) ids.forEach((x) => next.add(x))
else {
ids.forEach((x) => next.delete(x))
const parents = new Map(nodes.map((n) => [n.id, n.parent_id]))
const seen = new Set<string>()
let parent = parents.get(id)
while (parent && !seen.has(parent)) {
seen.add(parent)
next.delete(parent)
parent = parents.get(parent)
}
}
return [...next]
}
export function departmentTree<T extends DepartmentNode>(
nodes: T[],
collapsed: ReadonlySet<string>,
search = '',
region = ''
): Array<{ department: T; depth: number; hasChildren: boolean }> {
const known = new Map(nodes.map((n) => [n.id, n])),
children = new Map<string, T[]>()
if (known.size !== nodes.length) throw Error('通讯录部门重复')
for (const node of nodes) {
if (node.parent_id && !known.has(node.parent_id)) throw Error('通讯录缺少父部门')
const list = children.get(node.parent_id) ?? []
list.push(node)
children.set(node.parent_id, list)
}
for (const list of children.values())
list.sort((a, b) => a.name.localeCompare(b.name, 'zh-CN') || a.id.localeCompare(b.id))
const all: Array<{ department: T; depth: number; hasChildren: boolean; parents: string[]; path: string }> = [],
seen = new Set<string>()
const walk = (parent: string, parents: string[], names: string[]) => {
for (const node of children.get(parent) ?? []) {
if (seen.has(node.id) || parents.length > 100) throw Error('通讯录部门层级无效')
seen.add(node.id)
all.push({
department: node,
depth: parents.length,
hasChildren: !!children.get(node.id)?.length,
parents,
path: [...names, node.name].join('/'),
})
walk(node.id, [...parents, node.id], [...names, node.name])
}
}
walk('', [], [])
if (all.length !== nodes.length) throw Error('通讯录部门存在循环')
if (search || region) {
const matches = all.filter(
(r) =>
(!search || r.path.toLowerCase().includes(search.toLowerCase())) &&
(!region || (r.department as DepartmentNode & { region?: string }).region === region)
)
const visible = new Set(matches.flatMap((r) => [r.department.id, ...r.parents]))
return all.filter((r) => visible.has(r.department.id))
}
return all.filter((r) => !r.parents.some((id) => collapsed.has(id)))
}
export function applyBulkRegionRules(rules: RegionRule[], ids: string[], region: string): RegionRule[] {
const selected = new Set(ids)
if (!selected.size) return [...rules]