Files
knowledge-governance/web/src/QADepartmentStatistics.tsx
T
姚章浩 f533c63fef
build / build (push) Successful in 1m13s
fix(qaops): 移除部门名称后的直属人数小字
只移除本部门直属人数标签及无用样式,保留总人数独立列、部门展开、直属人员、兼属及统计值。

验证:标签不再出现的回归先红后绿,11项相关测试及类型检查通过。完整门禁、候选与上线验收待执行。
2026-10-24 13:58:02 +08:00

562 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 { Fragment, useEffect, useMemo, useRef, useState } from 'react'
import type {
DepartmentStatisticsSnapshot,
DepartmentStatisticsQuery,
DepartmentPersonStatistic,
} from './qaDepartmentStatistics'
import { fetchDepartmentStatistics } from './qaDepartmentStatistics'
import { departmentTree, selectDepartmentBranch, subtreeIDs } from './qaRegionSelection'
import { currentQAWeekValue } from './qaWeeks'
import { bindOrganizationDepartments } from './qaOrg'
import type { RegionDefinition } from './qaOrg'
import { QARegions } from './QARegions'
import { PeopleAnalysisView } from './QAPeopleAnalysis'
import { departmentTime } from './qaPeopleAnalysis'
import './qaDepartmentStatistics.css'
import { QAPeriodInput } from './QAPeriodInput'
export interface DepartmentStatisticsViewProps {
data: DepartmentStatisticsSnapshot
selected?: string[]
collapsed?: ReadonlySet<string>
search?: string
region?: string
onSelect?: (ids: string[]) => void
onCollapse?: (id: string) => void
}
export { departmentTime } from './qaPeopleAnalysis'
export function defaultStatisticsCollapsed(data: DepartmentStatisticsSnapshot): Set<string> {
const direct = new Set(data.people.flatMap((p) => p.department_ids))
return new Set(
departmentTree(data.rows, new Set())
.filter((r) => r.depth >= 1 && (r.hasChildren || direct.has(r.department.id)))
.map((r) => r.department.id)
)
}
function DepartmentPersonRow({
person,
department,
depth,
data,
}: {
person: DepartmentPersonStatistic
department: string
depth: number
data: DepartmentStatisticsSnapshot
}) {
const nodes = new Map(data.rows.map((d) => [d.id, d]))
const paths = person.department_ids
.map((id) => {
const names: string[] = []
while (id) {
const d = nodes.get(id)!
names.unshift(d.name)
id = d.parent_id
}
return names.join('/')
})
.sort((a, b) => a.localeCompare(b, 'zh-CN'))
return (
<tr
className="qa-department-person-row"
data-person-key={person.key}
data-parent-department={department}
data-visits={person.visits}
data-membership-count={person.department_ids.length}
>
<td>
<div className="qa-department-person" style={{ paddingInlineStart: depth * 20 + 44 }}>
<span className="qa-person-kind">{department ? '人员' : '未关联部门人员'}</span>
<span className="qa-person-name">{person.name || '未命名人员'}</span>
{paths.length > 1 ? (
<details className="qa-person-memberships">
<summary title={paths.join(';')} aria-label={`兼属 ${paths.length} 部门:${paths.join(';')}`}>
兼属 {paths.length} 部门
</summary>
<ul>
{paths.map((path) => (
<li key={path}>{path}</li>
))}
</ul>
</details>
) : null}
</div>
</td>
<td aria-label="人员行不单独计算部门总人数">—</td>
<td aria-label="人员行不单独计算访问人数">—</td>
<td aria-label="人员行不单独计算部门访问比例">—</td>
<td>{person.visits.toLocaleString('zh-CN')}</td>
<td>{person.last_asked_at === null ? '—' : departmentTime(person.last_asked_at)}</td>
</tr>
)
}
export function DepartmentStatisticsView(p: DepartmentStatisticsViewProps) {
const selected = p.selected ?? [],
collapsed = p.collapsed ?? defaultStatisticsCollapsed(p.data),
rows = departmentTree(p.data.rows, collapsed, p.search ?? '', p.region ?? '')
const direct = new Map<string, DepartmentPersonStatistic[]>()
for (const person of p.data.people)
for (const id of person.department_ids) {
const list = direct.get(id) ?? []
list.push(person)
direct.set(id, list)
}
for (const list of direct.values())
list.sort((a, b) => a.name.localeCompare(b.name, 'zh-CN') || a.key.localeCompare(b.key))
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 />
<col className="qa-department-time-column" />
</colgroup>
<thead>
<tr>
<th>部门 / 人员</th>
<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,
members = direct.get(d.id) ?? []
return (
<Fragment key={d.id}>
<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 || members.length ? (
<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>{d.total_people.toLocaleString('zh-CN')}</td>
<td>{d.visitors.toLocaleString('zh-CN')}</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>
{!collapsed.has(d.id)
? members.map((person) => (
<DepartmentPersonRow
key={person.key}
person={person}
department={d.id}
depth={depth}
data={p.data}
/>
))
: null}
</Fragment>
)
})}
{!p.region && !p.search
? p.data.people
.filter((person) => !person.department_ids.length)
.map((person) => (
<DepartmentPersonRow key={person.key} person={person} department="" depth={0} data={p.data} />
))
: null}
</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 DepartmentRegionBinding({
regions,
selectedCount,
disabled,
onBind,
}: {
regions: RegionDefinition[]
selectedCount: number
disabled: boolean
onBind: (id: string) => void
}) {
const [target, setTarget] = useState('')
useEffect(() => {
if (target && !regions.some((r) => r.id === target)) setTarget('')
}, [regions, target])
return (
<div className="qa-department-binding" aria-label="就地绑定部门区域">
<span>已勾选 {selectedCount} 个部门</span>
<select
aria-label="绑定目标区域"
value={target}
disabled={disabled || !selectedCount}
onChange={(e) => setTarget(e.target.value)}
>
<option value="">选择绑定区域</option>
{regions.map((r) => (
<option key={r.id} value={r.id}>
{r.name}
</option>
))}
</select>
<button
type="button"
disabled={disabled || !selectedCount || !regions.some((r) => r.id === target)}
onClick={() => onBind(target)}
>
绑定选中部门
</button>
</div>
)
}
const currentWeekValue = currentQAWeekValue
export function QARegionalStatistics({ onSaved }: { onSaved?: () => void } = {}) {
const [analysisMode, setAnalysisMode] = useState<'departments' | 'regions' | 'people'>('departments')
const [period, setPeriod] = useState<'all' | 'month' | 'week'>('all'),
[month, setMonth] = useState(currentMonth),
[week, setWeek] = useState(currentWeekValue),
[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(''),
[binding, setBinding] = useState(false),
[bindingError, setBindingError] = useState(''),
[bindingNotice, setBindingNotice] = useState(''),
[catalogDirty, setCatalogDirty] = useState(false)
const key = useRef(''),
condition = useRef(''),
collapsedDirectory = useRef(''),
bindingRequest = useRef<AbortController | null>(null),
query = useMemo<DepartmentStatisticsQuery>(
() =>
period === 'all'
? { period: 'all' }
: period === 'month'
? { period: 'month', month }
: { period: 'week', week },
[period, month, week]
)
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)))
if (collapsedDirectory.current !== fresh.organization.directory_id) {
setCollapsed(defaultStatisticsCollapsed(fresh))
collapsedDirectory.current = fresh.organization.directory_id
} else 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])
const invalidateOrganization = () => {
setData(null)
key.current = ''
setReload((v) => v + 1)
onSaved?.()
}
useEffect(() => () => bindingRequest.current?.abort(), [])
const bind = async (regionID: string) => {
if (!data || busy || binding || catalogDirty) return
const controller = new AbortController()
bindingRequest.current = controller
setBinding(true)
setBindingError('')
setBindingNotice('')
try {
await bindOrganizationDepartments(
{ directory_id: data.organization.directory_id, revision_id: data.organization.revision_id },
selected,
regionID,
controller.signal
)
if (controller.signal.aborted) return
setBindingNotice(
`已绑定 ${selected.length} 个部门至 ${data.regions.find((r) => r.id === regionID)?.name ?? '所选区域'},已独立读回保存结果`
)
setSelected([])
invalidateOrganization()
} catch (e) {
if (!controller.signal.aborted)
setBindingError(e instanceof Error ? e.message : '绑定失败,未将未确认结果标为成功')
} finally {
if (!controller.signal.aborted) setBinding(false)
}
}
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)}>
区域设置
</button>
</div>
</header>
<nav className="qa-analysis-switcher" aria-label="分析维度">
{(
[
['departments', '按部门'],
['regions', '按区域'],
['people', '按人'],
] as const
).map(([mode, label]) => (
<button key={mode} type="button" aria-pressed={analysisMode === mode} onClick={() => setAnalysisMode(mode)}>
{label}
</button>
))}
</nav>
<aside
className="qa-region-settings-panel"
hidden={!settings}
role="dialog"
aria-modal="false"
aria-label="区域设置面板"
>
<header>
<h3>区域设置</h3>
<button type="button" onClick={() => setSettings(false)}>
关闭设置
</button>
</header>
<div className="qa-region-settings-content">
<QARegions open={settings} onSaved={() => invalidateOrganization()} onDirtyChange={setCatalogDirty} />
</div>
</aside>
<div>
<div className="qa-department-filters">
<label>
统计范围
<select
aria-label="部门统计范围"
value={period}
onChange={(e) => setPeriod(e.target.value as 'all' | 'month' | 'week')}
>
<option value="all">按累计统计</option>
<option value="month">按自然月统计</option>
<option value="week">按自然周统计</option>
</select>
</label>
{period === 'month' ? (
<QAPeriodInput
kind="month"
label="统计月份"
ariaLabel="部门统计月份"
value={month}
max={currentMonth()}
onChange={setMonth}
/>
) : null}
{period === 'week' ? (
<QAPeriodInput
kind="week"
label="统计周次(北京时间周一至周日)"
ariaLabel="部门统计周次"
value={week}
max={currentWeekValue()}
onChange={setWeek}
/>
) : null}
{analysisMode === 'departments' ? (
<>
<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>
<DepartmentRegionBinding
regions={data?.regions ?? []}
selectedCount={selected.length}
disabled={busy || binding || settings || catalogDirty}
onBind={(id) => void bind(id)}
/>
<button type="button" disabled={!selected.length} onClick={() => setSelected([])}>
取消勾选
</button>
</>
) : null}
</div>
{catalogDirty ? <p className="qa-ops-muted">区域设置有未保存修改,请先保存或放弃后再绑定部门。</p> : null}
{bindingError ? (
<p role="alert" className="error-banner">
{bindingError}
</p>
) : null}
{bindingNotice ? <p role="status">{bindingNotice}</p> : null}
<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 ? (
<>
{analysisMode === 'departments' ? (
<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
})
}
/>
) : (
<PeopleAnalysisView
key={[
analysisMode,
data.period,
data.month,
data.week,
data.organization.directory_id,
data.organization.revision_id,
].join(':')}
data={data}
mode={analysisMode}
/>
)}
{analysisMode === 'departments' ? (
<p className="qa-department-note">
部门汇总含全部子部门并按稳定身份去重;展开仅列本部门直属人员,兼属人数为当前通讯录直接关联的不同部门总数,不包含自动继承的上级。个人访问次数跨兼属部门展示同一数值,不重复累计到部门汇总;收起及区域筛选不改变统计。访问为已入总表的提问事件。
</p>
) : null}
{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>
)
}