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 search?: string region?: string onSelect?: (ids: string[]) => void onCollapse?: (id: string) => void } export { departmentTime } from './qaPeopleAnalysis' export function defaultStatisticsCollapsed(data: DepartmentStatisticsSnapshot): Set { 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 (
{department ? '人员' : '未关联部门人员'} {person.name || '未命名人员'} {paths.length > 1 ? (
兼属 {paths.length} 部门
    {paths.map((path) => (
  • {path}
  • ))}
) : null}
— — — {person.visits.toLocaleString('zh-CN')} {person.last_asked_at === null ? '—' : departmentTime(person.last_asked_at)} ) } 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() 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 (
{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 ( {!collapsed.has(d.id) ? members.map((person) => ( )) : null} ) })} {!p.region && !p.search ? p.data.people .filter((person) => !person.department_ids.length) .map((person) => ( )) : null}
部门 / 人员 总人数 访问人数 访问比例 访问次数 最近提问时间
{ if (node) node.indeterminate = partial }} onChange={(e) => p.onSelect?.(selectDepartmentBranch(p.data.rows, selected, d.id, e.target.checked)) } /> {hasChildren || members.length ? ( ) : ( )} {d.name} {label ? {label} : null}
{d.total_people.toLocaleString('zh-CN')} {d.visitors.toLocaleString('zh-CN')} {d.ratio === null ? '—' : `${d.ratio.toFixed(1)}%`} {d.visits.toLocaleString('zh-CN')} {d.last_asked_at === null ? '—' : departmentTime(d.last_asked_at)}
{!rows.length ?

没有匹配的部门

: null}
) } 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 (
已勾选 {selectedCount} 个部门
) } 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(null), [error, setError] = useState(''), [busy, setBusy] = useState(true), [cached, setCached] = useState(false) const [selected, setSelected] = useState([]), [collapsed, setCollapsed] = useState>(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(null), query = useMemo( () => period === 'all' ? { period: 'all' } : period === 'month' ? { period: 'month', month } : { period: 'week', week }, [period, month, week] ) useEffect(() => { const controller = new AbortController() let timer: ReturnType 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 (

区域统计

{period === 'month' ? ( ) : null} {period === 'week' ? ( ) : null} {analysisMode === 'departments' ? ( <> void bind(id)} /> ) : null}
{catalogDirty ?

区域设置有未保存修改,请先保存或放弃后再绑定部门。

: null} {bindingError ? (

{bindingError}

) : null} {bindingNotice ?

{bindingNotice}

: null}
{busy ? data ? '后台重新聚合中,暂保留上次结果…' : '正在后台聚合部门统计…' : data ? `${cached ? '60秒缓存结果' : '统计已更新'} · 统计截至 ${departmentTime(data.end)} · 通讯录 ${data.organization.synced_at ? departmentTime(data.organization.synced_at) : '未同步'}` : ''}
{error ? (
{error} {data ? ';当前为上一次结果,未替换成零数据' : ''}{' '}
) : null} {data ? ( <> {analysisMode === 'departments' ? ( setCollapsed((old) => { const next = new Set(old) if (next.has(id)) next.delete(id) else next.add(id) return next }) } /> ) : ( )} {analysisMode === 'departments' ? (

部门汇总含全部子部门并按稳定身份去重;展开仅列本部门直属人员,兼属人数为当前通讯录直接关联的不同部门总数,不包含自动继承的上级。个人访问次数跨兼属部门展示同一数值,不重复累计到部门汇总;收起及区域筛选不改变统计。访问为已入总表的提问事件。

) : null} {data.unmapped_visits > 0 ? (

另有 {data.unmapped_visits.toLocaleString('zh-CN')} 次提问未能归入当前通讯录部门,未虚构归属。

) : null} ) : !busy && !error ? (

尚无统计结果,请重新读取。

) : null}
) }