feat(qa-ops): 支持自定义区域与分级部门批量归属
build / build (push) Successful in 1m8s

This commit is contained in:
姚章浩
2026-10-18 21:50:29 +08:00
parent 8835a473dd
commit 76671e0784
33 changed files with 865 additions and 100 deletions
+5 -3
View File
@@ -73,7 +73,7 @@ export function QAMonthlyView({ data, loading, error, onRetry, onPage }: ViewPro
<tr key={row.key}>
<td>{row.name || '姓名未同步'}</td>
<td>{row.departments.join(';') || '无部门记录'}</td>
<td>{usageLabels[row.region || row.state]}</td>
<td>{usageLabels[row.region || row.state] ?? (row.region || row.state)}</td>
<td>{row.questions}</td>
<td>{row.succeeded}</td>
<td>{row.failed}</td>
@@ -117,6 +117,7 @@ export function QAMonthly() {
const [request, setRequest] = useState<MonthlyQuery>({ month: draft.month })
const [data, setData] = useState<MonthlyPeople | null>(null),
[options, setOptions] = useState<MonthlyPeople['department_options']>([]),
[regionOptions, setRegionOptions] = useState<string[]>([]),
[loading, setLoading] = useState(false),
[error, setError] = useState('')
useEffect(() => {
@@ -129,6 +130,7 @@ export function QAMonthly() {
if (!controller.signal.aborted) {
setData(next)
setOptions(next.department_options)
setRegionOptions(next.organization.region_names ?? [])
}
})
.catch((reason) => {
@@ -196,9 +198,9 @@ export function QAMonthly() {
区域 / 状态
<select value={draft.region} disabled={loading} onChange={(e) => change('region', e.target.value)}>
<option value="">全部区域 / 状态</option>
{['国内工业', 'APAC', 'EMEA', 'America', 'unassigned', 'cross_region'].map((key) => (
{[...regionOptions, 'unassigned', 'cross_region'].map((key) => (
<option key={key} value={key}>
{usageLabels[key]}
{usageLabels[key] ?? key}
</option>
))}
</select>
+25 -1
View File
@@ -51,6 +51,30 @@ const props = {
onRemoveMissing: vi.fn(),
}
describe('region mapping workbench', () => {
it('separates multiselect from bulk application and renders hierarchy and editable region names', () => {
const custom = {
...state,
regions: [{ id: 'APAC', name: '国外工业Amercia' }],
view: { ...state.view, regions: { APAC: 1 } },
}
const html = renderToStaticMarkup(<RegionMappingView {...props} state={custom} />)
for (const label of [
'区域设置',
'添加区域',
'一级部门',
'二级部门',
'三级部门',
'四级及更深',
'批量归属',
'全选当前列表',
'取消本次勾选',
'国外工业Amercia',
])
expect(html).toContain(label)
expect(html).toMatch(/disabled=""[^>]*>批量归属/)
expect(html).not.toContain('将 示例公司/')
})
it('shows real synchronization stages without inventing progress and protects dirty drafts', () => {
const syncStatus = {
configured: true,
@@ -80,7 +104,7 @@ describe('region mapping workbench', () => {
const bodyRule = css.match(/\.qa-region-table td\s*\{([^}]+)\}/)?.[1] ?? ''
expect(bodyRule).toMatch(/white-space:\s*normal/)
expect(bodyRule).toMatch(/overflow-wrap:\s*anywhere/)
const statusRule = css.match(/\.qa-region-table td:nth-child\(4\)\s*\{([^}]+)\}/)?.[1] ?? ''
const statusRule = css.match(/\.qa-region-table td\.qa-region-basis\s*\{([^}]+)\}/)?.[1] ?? ''
expect(statusRule).toMatch(/white-space:\s*nowrap/)
})
it('shows a dated historical roster, conflicts and no invented performance verdict', () => {
+216 -39
View File
@@ -1,11 +1,24 @@
import { useEffect, useRef, useState } from 'react'
import { changeRegionRule, fetchOrganization, previewOrganization, regionNames, saveOrganization } from './qaOrg'
import type { Organization, RegionRule } from './qaOrg'
import {
changeRegionRule,
fetchOrganization,
previewOrganization,
organizationRegions,
parseRegionDefinitions,
saveOrganization,
} from './qaOrg'
import type { Organization, RegionRule, RegionDefinition } from './qaOrg'
import './qaRegions.css'
import { applyBulkRegionRules, departmentLevels } from './qaRegionSelection'
import { completedSyncAction, directorySyncActive, fetchDirectorySync, startDirectorySync } from './qaOrgSync'
import type { DirectorySyncStatus } from './qaOrgSync'
import { newOperationID } from './operationKey'
interface Props {
regions?: RegionDefinition[]
selectedIDs?: string[]
onCatalog?: (regions: RegionDefinition[]) => void
onSelect?: (ids: string[]) => void
onApply?: () => void
syncStatus?: DirectorySyncStatus | null
syncError?: string
syncSubmitting?: boolean
@@ -28,10 +41,35 @@ interface Props {
onReload: () => void
}
export function RegionMappingView(p: Props) {
const display = p.preview ?? p.state
const available = p.state?.state === 'ready'
const departments =
display?.view.departments.filter((d) => d.path.toLowerCase().includes(p.search.toLowerCase())) ?? []
const [newName, setNewName] = useState(''),
[level, setLevel] = useState(''),
[catalogError, setCatalogError] = useState('')
const display = p.preview ?? p.state,
available = p.state?.state === 'ready'
const regions = p.regions ?? organizationRegions(p.state),
selected = p.selectedIDs ?? []
const all = display?.view.departments ?? [],
nodes = new Map(all.map((d) => [d.id, d]))
const rows = all.map((d) => ({ department: d, levels: departmentLevels(all, d.id, nodes) }))
const departments = rows.filter(
({ department: d, levels }) =>
d.path.toLowerCase().includes(p.search.toLowerCase()) && (!level || levels.length === Number(level))
)
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 add = () => {
if (!newName.trim()) return
const next = [...regions, { id: 'region-' + newOperationID(), name: newName.trim() }]
try {
p.onCatalog?.(parseRegionDefinitions(next))
setNewName('')
setCatalogError('')
} catch {
setCatalogError('区域名称无效,请核对长度、重名或保留名称')
}
}
return (
<section className="qa-regions" aria-label="区域归属配置">
<div className="qa-region-heading">
@@ -85,7 +123,6 @@ export function RegionMappingView(p: Props) {
{p.state.revision_id || '尚未保存'}
</p>
) : null}
{p.error ? (
<p role="alert" className="error-banner">
{p.error}
@@ -98,13 +135,66 @@ export function RegionMappingView(p: Props) {
<p className="qa-ops-empty">暂无通讯录,请先同步。</p>
) : (
<>
<section className="qa-region-catalog" aria-label="区域设置">
<h4>区域设置</h4>
{catalogError ? (
<p role="alert" className="error-banner">
{catalogError}
</p>
) : null}
<div className="qa-region-names">
{regions.map((r) => (
<label key={r.id}>
区域名称
<input
aria-label={`区域名称 ${r.id}`}
value={r.name}
maxLength={100}
disabled={p.busy}
onChange={(e) =>
p.onCatalog?.(regions.map((x) => (x.id === r.id ? { ...x, name: e.target.value } : x)))
}
/>
</label>
))}
</div>
<form
onSubmit={(e) => {
e.preventDefault()
add()
}}
className="qa-region-add"
>
<input
aria-label="新区域名称"
value={newName}
maxLength={100}
disabled={p.busy}
placeholder="输入业务区域名称"
onChange={(e) => setNewName(e.target.value)}
/>
<button
disabled={
p.busy || !newName.trim() || regions.length >= 100 || regions.some((r) => r.name === newName.trim())
}
>
添加区域
</button>
</form>
</section>
<div className="qa-region-filters">
<label>
选择区域
<select value={p.selectedRegion} disabled={p.busy} onChange={(e) => p.onRegion(e.target.value)}>
{regionNames.map((r) => (
<option key={r}>{r}</option>
))}
{regions.length ? (
regions.map((r) => (
<option key={r.id} value={r.id}>
{r.name}
</option>
))
) : (
<option value="">请先添加区域</option>
)}
</select>
</label>
<label>
@@ -116,6 +206,47 @@ export function RegionMappingView(p: Props) {
placeholder="输入部门名称或完整路径"
/>
</label>
<label>
部门层级
<select aria-label="部门层级" value={level} onChange={(e) => setLevel(e.target.value)}>
<option value="">全部层级</option>
{Array.from({ length: maximum }, (_, i) => (
<option key={i} value={i + 1}>
第 {i + 1} 级
</option>
))}
</select>
</label>
</div>
<div className="qa-region-bulk">
<label>
<input
type="checkbox"
aria-label="全选当前列表"
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))
)
}}
/>
全选当前列表
</label>
<span>已勾选 {selected.length} 个部门</span>
<button
type="button"
disabled={p.busy || !selected.length || !regions.some((r) => r.id === p.selectedRegion)}
onClick={p.onApply}
>
批量归属
</button>
<button type="button" disabled={p.busy || !selected.length} onClick={() => p.onSelect?.([])}>
取消本次勾选
</button>
<button type="button" disabled={p.busy || !p.dirty} onClick={p.onPreview}>
预览影响
</button>
@@ -127,18 +258,16 @@ export function RegionMappingView(p: Props) {
<div className="qa-region-preview" aria-label="归属人数预览">
<strong>{p.preview ? '预览结果(未保存)' : '已保存归属'}</strong>
<span>通讯录人数:{display.view.total_people}</span>
{regionNames.map((r) => (
<span key={r}>
{r}:{display.view.regions[r]}
{organizationRegions(display).map((r) => (
<span key={r.id}>
{r.name}:{display.view.regions[r.id]}
</span>
))}
<span>未归属:{display.view.unassigned_people}</span>
<span>跨区域待核对:{display.view.conflicting_people}</span>
</div>
) : null}
{p.dirty && !p.preview ? (
<p className="qa-ops-muted">勾选已修改,人数仍为已保存结果;请预览后保存。</p>
) : null}
{p.dirty && !p.preview ? <p className="qa-ops-muted">人数仍为已保存结果;请预览后保存。</p> : null}
{display?.view.missing_departments.length ? (
<div role="alert" className="qa-ops-warning">
部分已配置部门不在当前通讯录中,原规则保留,需核对:
@@ -156,29 +285,60 @@ export function RegionMappingView(p: Props) {
<table className="qa-region-table">
<thead>
<tr>
<th>直接配置</th>
<th>选择</th>
<th>一级部门</th>
<th>二级部门</th>
<th>三级部门</th>
<th>四级及更深</th>
<th>完整部门路径</th>
<th>直接配置</th>
<th>{p.dirty && !p.preview ? '已保存归属' : '生效归属'}</th>
<th>依据</th>
</tr>
</thead>
<tbody>
{departments.map((d) => (
<tr key={d.id}>
<td>
<input
type="checkbox"
aria-label={`将 ${d.path} 直接归入 ${p.selectedRegion}`}
checked={p.rules.some((r) => r.department_id === d.id && r.region === p.selectedRegion)}
disabled={p.busy}
onChange={(e) => p.onToggle(d.id, e.target.checked)}
/>
</td>
<td>{d.path}</td>
<td>{d.region || '未归属'}</td>
<td>{d.explicit ? '直接配置' : d.inherited_from ? '继承上级' : '未配置'}</td>
</tr>
))}
{departments.map(({ department: d, levels }) => {
const direct = p.rules.find((r) => r.department_id === d.id)
return (
<tr key={d.id} data-department-id={d.id}>
<td>
<input
type="checkbox"
aria-label={`选择部门 ${d.path}`}
checked={selected.includes(d.id)}
disabled={p.busy}
onChange={(e) => choose(d.id, e.target.checked)}
/>
</td>
<td>{levels[0] || '—'}</td>
<td>{levels[1] || '—'}</td>
<td>{levels[2] || '—'}</td>
<td>{levels.slice(3).join(' / ') || '—'}</td>
<td>{d.path}</td>
<td>
{direct ? (
<>
<span>{label(direct.region)}</span>
<button
type="button"
aria-label={`清除直接配置 ${d.path}`}
disabled={p.busy}
onClick={() => p.onToggle(d.id, false)}
>
清除
</button>
</>
) : (
'—'
)}
</td>
<td>{d.region ? label(d.region, organizationRegions(display)) : '未归属'}</td>
<td className="qa-region-basis">
{d.explicit ? '直接配置' : d.inherited_from ? '继承上级' : '未配置'}
</td>
</tr>
)
})}
</tbody>
</table>
{!departments.length ? <p>没有匹配的部门路径</p> : null}
@@ -188,8 +348,8 @@ export function RegionMappingView(p: Props) {
</section>
)
}
function signature(rules: RegionRule[]) {
return JSON.stringify([...rules].sort((a, b) => a.department_id.localeCompare(b.department_id)))
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() {
const [syncStatus, setSyncStatus] = useState<DirectorySyncStatus | null>(null),
@@ -203,7 +363,9 @@ export function QARegions() {
const [state, setState] = useState<Organization | null>(null),
[preview, setPreview] = useState<Organization | null>(null),
[rules, setRules] = useState<RegionRule[]>([])
const [region, setRegion] = useState<string>(regionNames[0]),
const [regions, setRegions] = useState<RegionDefinition[]>([]),
[selected, setSelected] = useState<string[]>([])
const [region, setRegion] = useState<string>(''),
[search, setSearch] = useState(''),
[busy, setBusy] = useState(false),
[error, setError] = useState(''),
@@ -212,6 +374,11 @@ export function QARegions() {
const accept = (value: Organization) => {
setState(value)
setRules(value.rules)
setRegions(organizationRegions(value))
setRegion((current) =>
organizationRegions(value).some((r) => r.id === current) ? current : (organizationRegions(value)[0]?.id ?? '')
)
setSelected([])
setPreview(null)
}
const load = async () => {
@@ -238,7 +405,7 @@ export function QARegions() {
void load()
return () => request.current?.abort()
}, [])
const dirty = Boolean(state && signature(rules) !== signature(state.rules))
const dirty = Boolean(state && signature(rules, regions) !== signature(state.rules, organizationRegions(state)))
dirtyRef.current = dirty
const loadRef = useRef(load)
loadRef.current = load
@@ -320,8 +487,8 @@ export function QARegions() {
setNotice('')
try {
const value = await (save
? saveOrganization(state, rules, controller.signal)
: previewOrganization(state, rules, controller.signal))
? saveOrganization({ ...state, regions: parseRegionDefinitions(regions) }, rules, controller.signal)
: previewOrganization({ ...state, regions: parseRegionDefinitions(regions) }, rules, controller.signal))
if (!controller.signal.aborted) {
if (save) {
const readback = await fetchOrganization(controller.signal)
@@ -342,6 +509,16 @@ export function QARegions() {
}
return (
<RegionMappingView
regions={regions}
selectedIDs={selected}
onCatalog={(next) => {
setRegions(next)
setPreview(null)
setNotice('')
setError('')
}}
onSelect={setSelected}
onApply={() => edit(applyBulkRegionRules(rules, selected, region))}
syncStatus={syncStatus}
syncError={syncError}
syncSubmitting={syncSubmitting}
+10
View File
@@ -20,6 +20,16 @@ const usage = parseQAUsage({
rows: [{ key: 'unmatched', questions: 2, succeeded: 1, failed: 1, other: 0, users: null, roster_people: null }],
})
describe('usage statistics evidence', () => {
it('renders a custom label without inheriting Object prototype properties', () => {
const custom = {
...usage,
organization: { ...usage.organization, region_names: ['toString'] },
rows: usage.rows.map((r) => ({ ...r, key: 'toString' })),
}
const html = renderToStaticMarkup(<QAUsageView data={custom} loading={false} error="" onRetry={() => {}} />)
expect(html).toContain('toString')
})
it('shows a current-roster basis and unknown counts without performance claims', () => {
const html = renderToStaticMarkup(<QAUsageView data={usage} loading={false} error="" onRetry={() => {}} />)
expect(html).toContain('按当前通讯录回看')
+1 -1
View File
@@ -57,7 +57,7 @@ export function QAUsageView({ data, loading, error, onRetry }: Props) {
<tbody>
{data.rows.map((row) => (
<tr key={row.key}>
<td>{usageLabels[row.key]}</td>
<td>{usageLabels[row.key] ?? row.key}</td>
<td>{row.questions}</td>
<td>{row.succeeded}</td>
<td>{row.failed}</td>
+12
View File
@@ -2,6 +2,18 @@ import { describe, it, expect, vi } from 'vitest'
import { parseQAMonthly, fetchQAMonthly, beijingMonth } from './qaMonthly'
import { monthlyFixture } from './qaMonthly.fixture'
describe('personal natural-month contracts', () => {
it('accepts renamed custom regions only from the shared organization catalog', () => {
const custom = {
...monthlyFixture,
organization: { ...monthlyFixture.organization, region_names: ['国内教育'] },
rows: monthlyFixture.rows.map((r, i) => (i === 0 ? { ...r, region: '国内教育' } : r)),
}
expect(parseQAMonthly(custom).rows[0].region).toBe('国内教育')
expect(() =>
parseQAMonthly({ ...custom, organization: { ...custom.organization, region_names: ['别的区域'] } })
).toThrow()
})
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)
+1 -2
View File
@@ -60,7 +60,6 @@ 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)
@@ -117,7 +116,7 @@ export function parseQAMonthly(value: unknown): MonthlyPeople {
keys.has(key) ||
name.length > 1000 ||
!['matched', 'unassigned', 'cross_region'].includes(state) ||
(state === 'matched' && !regions.includes(region)) ||
(state === 'matched' && !(organization.region_names ?? []).includes(region)) ||
(state !== 'matched' && region !== '')
)
fail()
+9
View File
@@ -1,4 +1,5 @@
import { parseQAQuality } from './qaQuality'
import { regionNames, parseRegionDefinitions } from './qaOrg'
import type { QAQuality } from './qaQuality'
export const qaColumns = [
{ key: 'question_chinese', label: '中文问题' },
@@ -20,6 +21,7 @@ export const qaColumns = [
export type QAColumn = (typeof qaColumns)[number]['key']
export interface QAOrganizationVersion {
region_names?: string[]
state: 'ready' | 'empty'
directory_id: string
directory_source: string
@@ -40,7 +42,14 @@ export interface QARecordOrganization {
export function parseQAOrganizationVersion(value: unknown): QAOrganizationVersion {
const v = object(value)
if (!['ready', 'empty'].includes(text(v.state)) || v.basis !== 'current_directory') return invalid()
const region_names =
v.region_names === undefined
? [...regionNames]
: Array.isArray(v.region_names)
? parseRegionDefinitions(v.region_names.map((name) => ({ id: name, name }))).map((r) => r.name)
: invalid()
const result = {
region_names,
state: v.state as QAOrganizationVersion['state'],
directory_id: text(v.directory_id),
directory_source: text(v.directory_source),
+29
View File
@@ -30,6 +30,35 @@ export const directoryFixture = {
},
}
describe('department region configuration', () => {
it('uses configurable stable region IDs rather than a four-name whitelist', () => {
const catalog = [
{ id: 'education', name: '国内教育' },
{ id: 'west', name: '国外工业Amercia' },
]
const state = parseOrganization({
...directoryFixture,
regions: catalog,
rules: [{ department_id: 'root', region: 'education' }],
view: {
...directoryFixture.view,
departments: [{ ...directoryFixture.view.departments[0], region: 'education', explicit: true }],
regions: { education: 1, west: 0 },
unassigned_people: 0,
},
})
expect(state.regions).toEqual(catalog)
expect(state.rules[0].region).toBe('education')
expect(state.view.regions.education).toBe(1)
})
it('rejects undeclared region counts rather than silently dropping them', () => {
expect(() =>
parseOrganization({
...directoryFixture,
view: { ...directoryFixture.view, regions: { ...directoryFixture.view.regions, undeclared: 0 } },
})
).toThrow()
})
it('parses an honest dated snapshot without exposing employee identities', () => {
const state = parseOrganization(directoryFixture)
expect(state.directory_source).toBe('weekly_report_snapshot')
+53 -7
View File
@@ -1,4 +1,45 @@
export const regionNames = ['国内工业', 'APAC', 'EMEA', 'America'] as const
export interface RegionDefinition {
id: string
name: string
}
export const defaultRegions = (): RegionDefinition[] => regionNames.map((name) => ({ id: name, name }))
const reservedRegions = [
'unassigned',
'cross_region',
'unmatched',
'identity_conflict',
'no_identity',
'directory_missing',
'__proto__',
'constructor',
'prototype',
]
export function parseRegionDefinitions(raw: unknown): RegionDefinition[] {
if (!Array.isArray(raw) || raw.length > 100) return invalid()
const ids = new Set<string>(),
names = new Set<string>()
return raw.map((item) => {
const r = obj(item),
id = str(r.id),
name = str(r.name)
for (const value of [id, name])
if (
!value ||
value.trim() !== value ||
new TextEncoder().encode(value).length > 256 ||
/[\x00\r\n]/.test(value) ||
reservedRegions.includes(value)
)
return invalid()
if (ids.has(id) || names.has(name)) return invalid()
ids.add(id)
names.add(name)
return { id, name }
})
}
export const organizationRegions = (state: Organization | null): RegionDefinition[] =>
state?.regions ?? defaultRegions()
export interface RegionRule {
department_id: string
region: string
@@ -13,6 +54,7 @@ export interface DepartmentRegion {
inherited_from: string
}
export interface Organization {
regions?: RegionDefinition[]
state: 'empty' | 'ready'
directory_id: string
directory_source: string
@@ -49,7 +91,9 @@ export function instant(value: unknown): string | null {
export function parseOrganization(value: unknown): Organization {
const s = obj(value),
v = obj(s.view),
regions = obj(v.regions)
regions = obj(v.regions),
definitions = s.regions === undefined ? defaultRegions() : parseRegionDefinitions(s.regions),
regionIDs = definitions.map((r) => r.id)
if (
(s.state !== 'empty' && s.state !== 'ready') ||
!Array.isArray(s.rules) ||
@@ -60,13 +104,12 @@ export function parseOrganization(value: unknown): Organization {
const rules = s.rules.map((raw) => {
const r = obj(raw)
const region = str(r.region)
if (!regionNames.some((x) => x === region)) return invalid()
if (!regionIDs.includes(region)) return invalid()
return { department_id: str(r.department_id), region }
})
const departments = v.departments.map((raw) => {
const d = obj(raw)
if (typeof d.explicit !== 'boolean' || (d.region !== '' && !regionNames.some((x) => x === d.region)))
return invalid()
if (typeof d.explicit !== 'boolean' || (d.region !== '' && !regionIDs.includes(String(d.region)))) return invalid()
return {
id: str(d.id),
parent_id: str(d.parent_id),
@@ -86,9 +129,12 @@ export function parseOrganization(value: unknown): Organization {
const total = count(v.total_people),
unassigned = count(v.unassigned_people),
conflicting = count(v.conflicting_people)
const regionCounts = Object.fromEntries(regionNames.map((r) => [r, count(regions[r])]))
if (Object.keys(regions).length !== regionIDs.length || Object.keys(regions).some((id) => !regionIDs.includes(id)))
return invalid()
const regionCounts = Object.fromEntries(regionIDs.map((r) => [r, count(regions[r])]))
if (Object.values(regionCounts).reduce((a, b) => a + b, 0) + unassigned + conflicting !== total) return invalid()
const result: Organization = {
regions: definitions,
state: s.state,
directory_id: str(s.directory_id),
directory_source: str(s.directory_source),
@@ -140,13 +186,13 @@ export const previewOrganization = (state: Organization, rules: RegionRule[], si
requestOrganization(
'/preview',
'POST',
{ directory_id: state.directory_id, base_revision: state.revision_id, rules },
{ directory_id: state.directory_id, base_revision: state.revision_id, regions: organizationRegions(state), rules },
signal
)
export const saveOrganization = (state: Organization, rules: RegionRule[], signal?: AbortSignal) =>
requestOrganization(
'/regions',
'PUT',
{ directory_id: state.directory_id, base_revision: state.revision_id, rules },
{ directory_id: state.directory_id, base_revision: state.revision_id, regions: organizationRegions(state), rules },
signal
)
+34
View File
@@ -0,0 +1,34 @@
import { describe, it, expect } from 'vitest'
import { applyBulkRegionRules, departmentLevels } from './qaRegionSelection'
import type { DepartmentRegion } from './qaOrg'
describe('department multi-selection', () => {
it('applies only explicitly selected IDs without deleting child overrides or mutating saved rules', () => {
const saved = [
{ department_id: 'child', region: 'west' },
{ department_id: 'sibling', region: 'education' },
]
const draft = applyBulkRegionRules(saved, ['parent', 'other', 'parent'], 'education')
expect(draft).toEqual([
...saved,
{ department_id: 'parent', region: 'education' },
{ department_id: 'other', region: 'education' },
])
expect(saved).toHaveLength(2)
expect(applyBulkRegionRules(draft, [], 'west')).toEqual(draft)
})
it('derives every hierarchy level from parent IDs, not slashes in names or a three-level cutoff', () => {
const departments = Array.from({ length: 5 }, (_, i) => ({
id: String(i),
parent_id: i ? String(i - 1) : '',
name: `部门/${i}`,
path: '',
region: '',
explicit: false,
inherited_from: '',
})) as DepartmentRegion[]
expect(departmentLevels(departments, '4')).toEqual(departments.map((d) => d.name))
expect(() =>
departmentLevels([...departments, { ...departments[0], id: 'cycle', parent_id: 'cycle' }], 'cycle')
).toThrow()
})
})
+27
View File
@@ -0,0 +1,27 @@
import type { DepartmentRegion, RegionRule } from './qaOrg'
export function applyBulkRegionRules(rules: RegionRule[], ids: string[], region: string): RegionRule[] {
const selected = new Set(ids)
if (!selected.size) return [...rules]
if (!region) throw new Error('请先选择区域')
return [
...rules.filter((r) => !selected.has(r.department_id)),
...Array.from(selected, (department_id) => ({ department_id, region })),
]
}
export function departmentLevels(
departments: DepartmentRegion[],
id: string,
nodes = new Map(departments.map((d) => [d.id, d]))
): string[] {
const seen = new Set<string>(),
names: string[] = []
let current = id
while (current) {
const node = nodes.get(current)
if (!node || seen.has(current) || names.length > 100) throw new Error('通讯录部门层级无效,请重新同步')
seen.add(current)
names.unshift(node.name)
current = node.parent_id
}
return names
}
+24
View File
@@ -0,0 +1,24 @@
import { it, expect } from 'vitest'
import { parseQAUsage } from './qaUsage'
it('keeps custom region usage instead of rejecting or silently dropping its counts', () => {
const wire = {
organization: {
state: 'ready',
directory_id: 'd',
directory_source: 'weekly_report_live',
synced_at: '2026-10-17T00:00:00Z',
revision_id: 'r',
basis: 'current_directory',
region_names: ['国内教育'],
},
as_of: '2026-10-17T01:00:00Z',
start: '2026-10-16T00:00:00Z',
end: '2026-10-17T00:00:00Z',
keyword: '',
questions: 2,
identified_users: 1,
rows: [{ key: '国内教育', questions: 2, succeeded: 1, failed: 1, other: 0, users: 1, roster_people: 2 }],
}
expect(parseQAUsage(wire).rows[0].key).toBe('国内教育')
expect(() => parseQAUsage({ ...wire, organization: { ...wire.organization, region_names: ['其他'] } })).toThrow()
})
+73 -3
View File
@@ -59,6 +59,8 @@
border-collapse: collapse;
text-align: left;
font-size: 13px;
table-layout: fixed;
min-width: 960px;
}
.qa-region-table th,
.qa-region-table td {
@@ -74,11 +76,10 @@
white-space: nowrap;
}
.qa-region-table td:nth-child(2) {
min-width: 240px;
min-width: 0;
overflow-wrap: anywhere;
}
.qa-region-table td:nth-child(3),
.qa-region-table td:nth-child(4) {
.qa-region-table td.qa-region-basis {
white-space: nowrap;
}
.qa-region-table input[type='checkbox'] {
@@ -111,6 +112,75 @@
outline: 2px solid #1765c1;
outline-offset: 2px;
}
.qa-region-catalog {
border-bottom: 1px solid var(--line, #d8e1eb);
padding-bottom: 14px;
min-width: 0;
}
.qa-region-catalog h4 {
margin: 0 0 10px;
}
.qa-region-names {
display: grid;
grid-template-columns: repeat(auto-fit, minmax(170px, 1fr));
gap: 10px;
}
.qa-region-names label {
display: flex;
flex-direction: column;
gap: 4px;
color: var(--text-muted, #5e6d82);
font-size: 12px;
min-width: 0;
}
.qa-region-catalog input {
width: 100%;
min-width: 0;
box-sizing: border-box;
padding: 8px 10px;
border: 1px solid var(--line, #d8e1eb);
border-radius: 5px;
background: var(--panel, #fff);
color: inherit;
}
.qa-region-add,
.qa-region-bulk {
display: flex;
flex-wrap: wrap;
gap: 8px 12px;
align-items: center;
}
.qa-region-add {
margin-top: 10px;
}
.qa-region-add input {
max-width: 320px;
}
.qa-region-bulk label {
display: flex;
gap: 6px;
align-items: center;
}
.qa-region-tree-scroll {
max-height: 60vh;
}
.qa-region-table th {
white-space: normal;
}
.qa-region-table th:first-child {
width: 36px;
}
.qa-region-table th:nth-child(6) {
width: 23%;
}
.qa-region-table th:last-child {
width: 65px;
}
.qa-region-table td button {
padding: 3px 6px;
font-size: 11px;
margin-top: 4px;
}
@media (max-width: 700px) {
.qa-region-filters {
align-items: stretch;
+15 -5
View File
@@ -30,7 +30,7 @@ const stamp = (v: unknown) => {
const s = text(v)
return !Number.isNaN(Date.parse(s)) ? s : bad()
}
export const usageLabels: Record<string, string> = {
export const usageLabels: Record<string, string> = Object.assign(Object.create(null), {
国内工业: '国内工业',
APAC: 'APAC',
EMEA: 'EMEA',
@@ -41,14 +41,24 @@ export const usageLabels: Record<string, string> = {
identity_conflict: '身份冲突',
no_identity: '身份信息缺失',
directory_missing: '尚无完整通讯录',
}
})
export function parseQAUsage(value: unknown): QAUsage {
const v = obj(value)
const v = obj(value),
organization = parseQAOrganizationVersion(v.organization)
const allowed = new Set([
...(organization.region_names ?? []),
'unassigned',
'cross_region',
'unmatched',
'identity_conflict',
'no_identity',
'directory_missing',
])
if (!Array.isArray(v.rows)) return bad()
const rows = v.rows.map((raw) => {
const r = obj(raw)
const key = text(r.key)
if (!Object.hasOwn(usageLabels, key)) return bad()
if (!allowed.has(key)) return bad()
const row = {
key,
questions: count(r.questions),
@@ -62,7 +72,7 @@ export function parseQAUsage(value: unknown): QAUsage {
return row
})
const result = {
organization: parseQAOrganizationVersion(v.organization),
organization,
as_of: stamp(v.as_of),
start: stamp(v.start),
end: stamp(v.end),