import { qaWeek } from './qaWeeks' 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' | 'week' month?: string week?: 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 DepartmentPersonStatistic { key: string name: string department_ids: string[] visits: number last_asked_at: string | null } export interface DepartmentStatisticsSnapshot { people: DepartmentPersonStatistic[] rows: DepartmentStatistic[] total_visits: number unmapped_visits: number total_people: number organization: QAOrganizationVersion regions: RegionDefinition[] period: 'all' | 'month' | 'week' month: string week: 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 => v !== null && typeof v === 'object' && !Array.isArray(v) ? (v as Record) : 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 ( !['all', 'month', 'week'].includes(query.period) || d.period !== query.period || (d.week === undefined ? '' : text(d.week)) !== (query.week ?? '') || 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() if (query.period === 'week') { if (!query.week || !/^\d{4}-W\d{2}$/.test(query.week) || query.month) return bad() let range try { range = qaWeek(Number(query.week.slice(0, 4)), Number(query.week.slice(6))) } catch { return bad() } if ( start === null || Date.parse(start) !== Date.parse(range.start + ':00+08:00') || Date.parse(end) > Date.parse(range.end + ':00+08:00') ) 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() } if (!Array.isArray(d.people) || d.people.length !== total_people || d.people.length > 100000) return bad() const personKeys = new Set() const people: DepartmentPersonStatistic[] = d.people.map((value) => { const p = obj(value), key = text(p.key), name = text(p.name), visits = count(p.visits) const last = p.last_asked_at === null ? null : instant(p.last_asked_at) if ( Object.keys(p).some((k) => !['key', 'name', 'department_ids', 'visits', 'last_asked_at'].includes(k)) || !/^person-[a-f0-9]{64}$/.test(key) || personKeys.has(key) || name.length > 1000 || name.includes('\0') || !Array.isArray(p.department_ids) || p.department_ids.length > 1000 || p.department_ids.some((id) => typeof id !== 'string' || !byID.has(id)) || new Set(p.department_ids).size !== p.department_ids.length || visits > total_visits || (visits === 0) !== (last === null) || (last !== null && (Date.parse(last) >= Date.parse(end) || (start !== null && Date.parse(last) < Date.parse(start)))) ) return bad() personKeys.add(key) return { key, name, department_ids: p.department_ids as string[], visits, last_asked_at: last } }) // Expanded people are an explanation of the existing branch totals, never an extra sum. const branches = new Map(rows.map((r) => [r.id, { total: 0, visitors: 0, visits: 0, last: null as string | null }])) let mapped = 0, allVisits = 0 for (const person of people) { allVisits += person.visits if (person.department_ids.length) mapped += person.visits const seen = new Set() for (let id of person.department_ids) while (id && !seen.has(id)) { seen.add(id) id = byID.get(id)!.parent_id } for (const id of seen) { const b = branches.get(id)! b.total++ b.visits += person.visits if (person.visits) b.visitors++ if (person.last_asked_at && (!b.last || Date.parse(person.last_asked_at) > Date.parse(b.last))) b.last = person.last_asked_at } } if (allVisits > total_visits || mapped !== total_visits - unmapped_visits) return bad() for (const row of rows) { const b = branches.get(row.id)! if ( b.total !== row.total_people || b.visitors !== row.visitors || b.visits !== row.visits || (b.last === null ? row.last_asked_at !== null : row.last_asked_at === null || Date.parse(b.last) !== Date.parse(row.last_asked_at)) ) return bad() } return { state: 'ready', cache_key, cache_hit: v.cache_hit, retry_after: 0, snapshot: { people, rows, total_people, total_visits, unmapped_visits, organization, regions, period: query.period, month: query.month ?? '', week: query.week ?? '', start, end, generated_at: generated, expires_at: expires, }, } } export async function fetchDepartmentStatistics( query: DepartmentStatisticsQuery, signal?: AbortSignal ): Promise { 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).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 }