feat(qaops): 完成区域统计与部门绑定六项联动
build / build (push) Successful in 1m20s

新增北京时间自然周校验与缓存隔离,默认展开到业务二级部门。
选中部门在统计页就地绑定;区域名称列表原位增删改,双版本锁、自动预览、独立读回及删除确认。
筛选和两张区域看板使用同一已保存目录,删除失效筛选回全部。

验证:完整 make verify、全 mirror 隔离 PostgreSQL race、自然周边界与缓存键负例通过;真实恢复库327部门逐行对拍及六项浏览器验收通过。
schema57无迁移,不改真实公司区域绑定或原始问答,不连接DobotAI生产源库;PNG导出本轮不冒充已验证。
This commit is contained in:
姚章浩
2026-10-19 23:41:01 +08:00
parent 9470a127f7
commit 154b0b62ad
18 changed files with 933 additions and 560 deletions
+13
View File
@@ -76,6 +76,19 @@
> `0.1.12`),由 `scripts/version.py` 从 git **算出来**;开发交付的独立说明写入本文件“开发快照”章节,并打 `snapshot/vX.Y.Z` 注释标签 ⇒ 每次开发交付均可追溯,
> 但"发布版本"仍然只能由人定(CI 不会自动升版本、不会打 tag)。
## 开发快照 snapshot/v0.1.40 - 2026-10-19
### Added
- 区域统计明确支持按累计、北京时间自然月、北京时间自然周三种范围;自然周按周一至周日,可选择历史周,校验跨年周次、非法周和未来周,独立缓存包含周次及组织版本。
### Changed
- 部门树默认显示公司、中心及二级部门,更深层收起;保留手动展开与搜索,父行去重人数和提问次数不随收起变化。
- 选中部门后在当前统计页选择区域并绑定,复用预览、双版本锁和保存后独立读回,不跳转另一张映射表;父选仍覆盖后代,既有非选中部门规则保留。
- 区域设置重做为原页面内的名称列表面板,支持新增、改名、删除及未保存草稿保护。删除已绑定区域须确认解除直接绑定,目录与规则一次保存,不删除原问答;重复点击原删除位置只取消确认。
- 区域筛选及绑定选项取已保存目录,新增/改名/删除后刷新,删除当前筛选项回全部;问题统计看板的平均使用频率和使用覆盖率沿用同一已保存组织配置,保留自然月口径与零分母未知,不重新计算冻结历史。
## 开发快照 snapshot/v0.1.39 - 2026-10-19
### Changed
+57 -52
View File
@@ -45,65 +45,70 @@
],
"paths": {
"/api/v1/qa-ops/departments/statistics": {
"post": {
"operationId": "qaDepartmentStatistics",
"summary": "部门树访问统计,当前通讯录整支人员去重",
"description": "仅独立治理总表,不读取生产或更改原问答;后台单聚合并发,响应202或60秒缓存结果。当前目录和区域配置版本加入缓存键;父行包含自身及全部后代,人员按当前稳定身份去重,调岗归当前部门;零分母比例为null,最近提问时间来自真实事件。访问指已入总表的提问事件,不含未记录的网页浏览。管理员同源只读POST,操作头qa-department-statistics。",
"requestBody": {
"required": true,
"content": {
"application/json": {
"schema": {
"type": "object",
"additionalProperties": false,
"required": [
"period"
],
"properties": {
"period": {
"type": "string",
"enum": [
"all",
"month"
]
},
"month": {
"type": "string",
"pattern": "^[0-9]{4}-[0-9]{2}$"
"post": {
"operationId": "qaDepartmentStatistics",
"summary": "部门树访问统计,当前通讯录整支人员去重",
"description": "仅独立治理总表,不读取生产或更改原问答;后台单聚合并发,响应202或60秒缓存结果。当前目录和区域配置版本加入缓存键;父行包含自身及全部后代,人员按当前稳定身份去重,调岗归当前部门;零分母比例为null,最近提问时间来自真实事件。访问指已入总表的提问事件,不含未记录的网页浏览。管理员同源只读POST,操作头qa-department-statistics。 统计范围all/month/week;week使用YYYY-Www的合法ISO自然周,按北京时间周一至次周一不含结束,当前周截到当前,禁止未来周或混用month/week。",
"requestBody": {
"required": true,
"content": {
"application/json": {
"schema": {
"type": "object",
"additionalProperties": false,
"required": [
"period"
],
"properties": {
"period": {
"type": "string",
"enum": [
"all",
"month",
"week"
]
},
"month": {
"type": "string",
"pattern": "^[0-9]{4}-[0-9]{2}$"
},
"week": {
"type": "string",
"pattern": "^[0-9]{4}-W[0-9]{2}$"
}
}
}
}
}
}
},
"responses": {
"200": {
"$ref": "#/components/responses/Envelope"
},
"400": {
"$ref": "#/components/responses/BadRequest"
},
"401": {
"description": "需要登录"
},
"403": {
"description": "仅管理员同源读取"
},
"409": {
"description": "质量输入指纹变化,拒绝混合数据"
},
"500": {
"$ref": "#/components/responses/InternalError"
},
"503": {
"description": "本地副本或一致性投影不可用,不返回伪零"
},
"202": {
"description": "后台聚合中;同条件合并单次执行,请按Retry-After轮询,不返回虚构零数据"
"responses": {
"200": {
"$ref": "#/components/responses/Envelope"
},
"400": {
"$ref": "#/components/responses/BadRequest"
},
"401": {
"description": "需要登录"
},
"403": {
"description": "仅管理员同源读取"
},
"409": {
"description": "质量输入指纹变化,拒绝混合数据"
},
"500": {
"$ref": "#/components/responses/InternalError"
},
"503": {
"description": "本地副本或一致性投影不可用,不返回伪零"
},
"202": {
"description": "后台聚合中;同条件合并单次执行,请按Retry-After轮询,不返回虚构零数据"
}
}
}
}
},
},
"/api/v1/qa-ops/ai/settings": {"get": {"operationId": "getQAAISettings", "tags": ["QA operations"], "summary": "读取独立模型配置的安全状态,不返回密钥", "description": "管理员会话限定、固定治理租户、禁止共享缓存;不修改DobotAI源数据库。", "responses": {"200": {"description": "成功;返回实际持久化状态,不将进度100%当成全成功", "content": {"application/json": {"schema": {"type": "object", "additionalProperties": false, "properties": {"data": {"$ref": "#/components/schemas/QAAISafeSettings"}}, "required": ["data"]}}}}, "400": {"$ref": "#/components/responses/BadRequest"}, "401": {"description": "需要登录"}, "403": {"description": "仅管理员;写操作要求同源与明确意图"}, "409": {"description": "版本、范围或操作收据冲突,未覆盖现有结论"}, "422": {"description": "供应商明确拒绝或结构不合格,不伪造结果"}, "500": {"$ref": "#/components/responses/InternalError"}, "503": {"description": "存储、密钥或执行配置不可用;不返回伪零"}}}, "post": {"operationId": "saveQAAISettings", "tags": ["QA operations"], "summary": "验证并加密保存独立模型配置;不启动历史或自动任务", "description": "管理员会话限定、固定治理租户、禁止共享缓存;不修改DobotAI源数据库。", "responses": {"200": {"description": "成功;返回实际持久化状态,不将进度100%当成全成功", "content": {"application/json": {"schema": {"type": "object", "additionalProperties": false, "properties": {"data": {"$ref": "#/components/schemas/QAAISafeSettings"}}, "required": ["data"]}}}}, "400": {"$ref": "#/components/responses/BadRequest"}, "401": {"description": "需要登录"}, "403": {"description": "仅管理员;写操作要求同源与明确意图"}, "409": {"description": "版本、范围或操作收据冲突,未覆盖现有结论"}, "422": {"description": "供应商明确拒绝或结构不合格,不伪造结果"}, "500": {"$ref": "#/components/responses/InternalError"}, "503": {"description": "存储、密钥或执行配置不可用;不返回伪零"}}, "parameters": [{"name": "X-Governance-Action", "in": "header", "required": true, "schema": {"const": "qa-ai"}}], "requestBody": {"required": true, "content": {"application/json": {"schema": {"$ref": "#/components/schemas/QAAISaveSettings"}}}}}},
"/api/v1/qa-ops/ai/settings/test": {"post": {"operationId": "testQAAISettings", "tags": ["QA operations"], "summary": "发送最小非公司数据真实模型探测;不保存配置", "description": "管理员会话限定、固定治理租户、禁止共享缓存;不修改DobotAI源数据库。", "responses": {"200": {"description": "成功;返回实际持久化状态,不将进度100%当成全成功", "content": {"application/json": {"schema": {"type": "object", "additionalProperties": false, "properties": {"data": {"$ref": "#/components/schemas/QAAISafeSettings"}}, "required": ["data"]}}}}, "400": {"$ref": "#/components/responses/BadRequest"}, "401": {"description": "需要登录"}, "403": {"description": "仅管理员;写操作要求同源与明确意图"}, "409": {"description": "版本、范围或操作收据冲突,未覆盖现有结论"}, "422": {"description": "供应商明确拒绝或结构不合格,不伪造结果"}, "500": {"$ref": "#/components/responses/InternalError"}, "503": {"description": "存储、密钥或执行配置不可用;不返回伪零"}}, "parameters": [{"name": "X-Governance-Action", "in": "header", "required": true, "schema": {"const": "qa-ai"}}], "requestBody": {"required": true, "content": {"application/json": {"schema": {"$ref": "#/components/schemas/QAAISaveSettings"}}}}}},
"/api/v1/qa-ops/ai/automation": {"post": {"operationId": "setQAAIAutomation", "tags": ["QA operations"], "summary": "按任务启停增量;首次排除历史,关闭停止新增与未开始任务", "description": "管理员会话限定、固定治理租户、禁止共享缓存;不修改DobotAI源数据库。", "responses": {"200": {"description": "成功;返回实际持久化状态,不将进度100%当成全成功", "content": {"application/json": {"schema": {"type": "object", "additionalProperties": false, "properties": {"data": {"$ref": "#/components/schemas/QAAISafeSettings"}}, "required": ["data"]}}}}, "400": {"$ref": "#/components/responses/BadRequest"}, "401": {"description": "需要登录"}, "403": {"description": "仅管理员;写操作要求同源与明确意图"}, "409": {"description": "版本、范围或操作收据冲突,未覆盖现有结论"}, "422": {"description": "供应商明确拒绝或结构不合格,不伪造结果"}, "500": {"$ref": "#/components/responses/InternalError"}, "503": {"description": "存储、密钥或执行配置不可用;不返回伪零"}}, "parameters": [{"name": "X-Governance-Action", "in": "header", "required": true, "schema": {"const": "qa-ai"}}], "requestBody": {"required": true, "content": {"application/json": {"schema": {"type": "object", "additionalProperties": false, "properties": {"kind": {"type": "string", "enum": ["evaluation", "translation"]}, "enabled": {"type": "boolean"}}, "required": ["kind", "enabled"]}}}}}},
@@ -11,6 +11,7 @@ import (
type DepartmentStatisticsQuery struct {
Period string `json:"period"`
Month string `json:"month,omitempty"`
Week string `json:"week,omitempty"`
}
type DepartmentStatisticsSnapshot struct {
Regions []qaopsorg.RegionDefinition `json:"regions"`
@@ -18,6 +19,7 @@ type DepartmentStatisticsSnapshot struct {
Organization dobotaiops.OrganizationVersion `json:"organization"`
Period string `json:"period"`
Month string `json:"month"`
Week string `json:"week"`
Start *time.Time `json:"start"`
End time.Time `json:"end"`
GeneratedAt time.Time `json:"generated_at"`
@@ -8,14 +8,36 @@ import (
"github.com/jackc/pgx/v5"
"knowledge-governance/internal/dobotaiops"
"knowledge-governance/internal/qaopsorg"
"strconv"
"time"
)
func (q DepartmentStatisticsQuery) Bounds(now time.Time) (*time.Time, time.Time, error) {
if q.Period == "all" && q.Month == "" {
if q.Period == "all" && q.Month == "" && q.Week == "" {
return nil, now, nil
}
if q.Period != "month" {
if q.Period == "week" && q.Month == "" {
if len(q.Week) != 8 || q.Week[4:6] != "-W" || q.Week[6] < '0' || q.Week[6] > '9' || q.Week[7] < '0' || q.Week[7] > '9' {
return nil, time.Time{}, dobotaiops.ErrInvalidQuery
}
year, ey := strconv.Atoi(q.Week[:4])
week, ew := strconv.Atoi(q.Week[6:])
if ey != nil || ew != nil || year < 2000 || year > 9998 || week < 1 || week > 53 {
return nil, time.Time{}, dobotaiops.ErrInvalidQuery
}
jan4 := time.Date(year, time.January, 4, 0, 0, 0, 0, time.FixedZone("Asia/Shanghai", 8*3600))
start := jan4.AddDate(0, 0, -(int(jan4.Weekday())+6)%7+7*(week-1))
actualYear, actualWeek := start.ISOWeek()
if actualYear != year || actualWeek != week || start.After(now) {
return nil, time.Time{}, dobotaiops.ErrInvalidQuery
}
end := start.AddDate(0, 0, 7)
if end.After(now) {
end = now
}
return &start, end, nil
}
if q.Period != "month" || q.Week != "" {
return nil, time.Time{}, dobotaiops.ErrInvalidQuery
}
zone := time.FixedZone("Asia/Shanghai", 8*3600)
@@ -42,7 +64,7 @@ func (s *Store) ReadDepartmentStatistics(ctx context.Context, q DepartmentStatis
if err != nil || directory == "" {
return DepartmentStatisticsResult{}, dobotaiops.ErrUnavailable
}
raw, _ := json.Marshal([]string{s.tenant, directory, revision, q.Period, q.Month})
raw, _ := json.Marshal([]string{s.tenant, directory, revision, q.Period, q.Month, q.Week})
digest := sha256.Sum256(raw)
key := hex.EncodeToString(digest[:])
return s.departmentStats.get(key, now, func(background context.Context) (DepartmentStatisticsSnapshot, error) {
@@ -50,7 +72,7 @@ func (s *Store) ReadDepartmentStatistics(ctx context.Context, q DepartmentStatis
})
}
func (s *Store) loadDepartmentStatistics(ctx context.Context, q DepartmentStatisticsQuery, start *time.Time, end time.Time, directory, revision string) (DepartmentStatisticsSnapshot, error) {
out := DepartmentStatisticsSnapshot{Period: q.Period, Month: q.Month, Start: start, End: end}
out := DepartmentStatisticsSnapshot{Period: q.Period, Month: q.Month, Week: q.Week, Start: start, End: end}
tx, err := s.pool.BeginTx(ctx, pgx.TxOptions{IsoLevel: pgx.RepeatableRead, AccessMode: pgx.ReadOnly})
if err != nil {
return out, dobotaiops.ErrUnavailable
@@ -0,0 +1,56 @@
package qaopsmirror
import (
"context"
"encoding/json"
"knowledge-governance/internal/qaopsorg"
"testing"
"time"
)
func TestDepartmentStatisticsNaturalWeekBoundaryAndCacheIsolation(t *testing.T) {
p := mirrorFixture(t)
s := NewStore(p, "fixture-department-natural-week")
now, _ := time.Parse(time.RFC3339, "2026-10-21T11:00:00+08:00")
ctx := context.Background()
dir := qaopsorg.Directory{Departments: []qaopsorg.Department{{ID: "root", Name: "Fixture center"}, {ID: "child", ParentID: "root", Name: "Fixture department"}}, People: []qaopsorg.Person{{ID: "p1", Name: "Fixture person", DepartmentIDs: []string{"root", "child"}}}}
if _, err := qaopsorg.NewStore(p, s.tenant).ReplaceDirectory(ctx, qaopsorg.Import{Source: "weekly_report_snapshot", SyncedAt: time.Now(), Complete: true, Directory: dir}); err != nil {
t.Fatal(err)
}
for i, stamp := range []string{"2026-10-11T23:59:59+08:00", "2026-10-12T00:00:00+08:00", "2026-10-18T23:59:59+08:00", "2026-10-19T00:00:00+08:00"} {
_, err := p.Exec(ctx, `INSERT INTO qa_ops_master_records(tenant_key,id,event_key,origin,asked_at,question,status,identity,quality_hash,payload)VALUES($1,$2,repeat('a',64),'dobotai_2_0',$3,'non-business boundary fixture','succeeded','{"staff_id":"p1"}',repeat('b',64),jsonb_build_object('id',$2::text))`, s.tenant, "boundary-"+time.Date(2000, 1, i+1, 0, 0, 0, 0, time.UTC).Format("02"), stamp)
if err != nil {
t.Fatal(err)
}
}
read := func(week string) DepartmentStatisticsResult {
var q DepartmentStatisticsQuery
raw, _ := json.Marshal(map[string]string{"period": "week", "week": week})
_ = json.Unmarshal(raw, &q)
deadline := time.Now().Add(5 * time.Second)
for time.Now().Before(deadline) {
r, err := s.ReadDepartmentStatistics(ctx, q, now)
if err != nil {
t.Fatal(err)
}
if r.State == "ready" {
return r
}
time.Sleep(time.Millisecond)
}
t.Fatal("background natural week did not finish")
return DepartmentStatisticsResult{}
}
first, second := read("2026-W42"), read("2026-W43")
if first.CacheKey == second.CacheKey || first.Snapshot.TotalVisits != 2 || second.Snapshot.TotalVisits != 1 {
t.Fatalf("week boundaries/cache contaminated: first=%+v second=%+v", first, second)
}
for _, r := range first.Snapshot.Rows {
if r.Visits != 2 || r.Visitors != 1 || r.TotalPeople != 1 {
t.Fatalf("current branch person was double-counted: %+v", r)
}
}
if repeated := read("2026-W42"); !repeated.CacheHit || repeated.Snapshot.GeneratedAt != first.Snapshot.GeneratedAt {
t.Fatal("same natural week was not cached")
}
}
@@ -0,0 +1,35 @@
package qaopsmirror
import (
"encoding/json"
"testing"
"time"
)
func TestDepartmentStatisticsNaturalWeekUsesBeijingISOCalendar(t *testing.T) {
now, _ := time.Parse(time.RFC3339, "2026-10-21T11:00:00+08:00")
for _, tc := range []struct{ raw, start, end string }{
{`{"period":"week","week":"2026-W43"}`, "2026-10-19T00:00:00+08:00", "2026-10-21T11:00:00+08:00"},
{`{"period":"week","week":"2026-W42"}`, "2026-10-12T00:00:00+08:00", "2026-10-19T00:00:00+08:00"},
{`{"period":"week","week":"2020-W53"}`, "2020-12-28T00:00:00+08:00", "2021-01-04T00:00:00+08:00"},
} {
var q DepartmentStatisticsQuery
if json.Unmarshal([]byte(tc.raw), &q) != nil {
t.Fatal("invalid test input")
}
start, end, err := q.Bounds(now)
if err != nil || start == nil || start.Format(time.RFC3339) != tc.start || end.Format(time.RFC3339) != tc.end {
t.Fatalf("natural week bounds incorrect: %s start=%v end=%v error=%v", tc.raw, start, end, err)
}
}
}
func TestDepartmentStatisticsRejectsInvalidMixedOrFutureWeeks(t *testing.T) {
now, _ := time.Parse(time.RFC3339, "2026-10-21T11:00:00+08:00")
for _, raw := range []string{`{"period":"week"}`, `{"period":"week","week":"2021-W53"}`, `{"period":"week","week":"2026-W00"}`, `{"period":"week","week":"2026-W44"}`, `{"period":"week","week":"2026-W1"}`, `{"period":"week","week":"2026-W+1"}`, `{"period":"week","week":"1999-W01"}`, `{"period":"week","week":"2026-W43","month":"2026-10"}`, `{"period":"all","week":"2026-W43"}`, `{"period":"month","month":"2026-10","week":"2026-W43"}`} {
var q DepartmentStatisticsQuery
_ = json.Unmarshal([]byte(raw), &q)
if _, _, err := q.Bounds(now); err == nil {
t.Fatal("invalid period accepted", raw)
}
}
}
+7 -1
View File
@@ -1,8 +1,14 @@
import { it, expect } from 'vitest'
import { renderToStaticMarkup } from 'react-dom/server'
import { DepartmentStatisticsView } from './QADepartmentStatistics'
import { DepartmentStatisticsView, QARegionalStatistics } from './QADepartmentStatistics'
import { parseDepartmentStatistics } from './qaDepartmentStatistics'
import { departmentStatisticsFixture } from './qaDepartmentStatistics.fixture'
it('offers all, natural-month and natural-week scopes and never switches the selected-department action to a second mapping page', () => {
const html = renderToStaticMarkup(<QARegionalStatistics />)
for (const label of ['按累计统计', '按自然月统计', '按自然周统计', '绑定选中部门']) expect(html).toContain(label)
expect(html).not.toContain('设置选中部门的区域')
expect(html).not.toContain('返回部门统计')
})
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} />)
+165 -21
View File
@@ -1,7 +1,10 @@
import { useEffect, useMemo, useRef, useState } from 'react'
import type { DepartmentStatisticsSnapshot } from './qaDepartmentStatistics'
import type { DepartmentStatisticsSnapshot, DepartmentStatisticsQuery } from './qaDepartmentStatistics'
import { fetchDepartmentStatistics } from './qaDepartmentStatistics'
import { departmentTree, selectDepartmentBranch, subtreeIDs } from './qaRegionSelection'
import { departmentTree, selectDepartmentBranch, subtreeIDs, defaultDepartmentCollapsed } from './qaRegionSelection'
import { currentQAWeek, qaWeek } from './qaWeeks'
import { bindOrganizationDepartments } from './qaOrg'
import type { RegionDefinition } from './qaOrg'
import { QARegions } from './QARegions'
import './qaDepartmentStatistics.css'
export interface DepartmentStatisticsViewProps {
@@ -25,7 +28,7 @@ export const departmentTime = (value: string) =>
})
export function DepartmentStatisticsView(p: DepartmentStatisticsViewProps) {
const selected = p.selected ?? [],
collapsed = p.collapsed ?? new Set<string>(),
collapsed = p.collapsed ?? defaultDepartmentCollapsed(p.data.rows),
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}>
@@ -121,9 +124,55 @@ const currentMonth = () => {
}).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'),
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 = () => {
const w = currentQAWeek()
return `${w.year}-W${String(w.week).padStart(2, '0')}`
}
export function QARegionalStatistics({ onSaved }: { onSaved?: () => void } = {}) {
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),
@@ -133,12 +182,23 @@ export function QARegionalStatistics() {
const [selected, setSelected] = useState<string[]>([]),
[collapsed, setCollapsed] = useState<Set<string>>(new Set()),
[search, setSearch] = useState(''),
[region, setRegion] = useState('')
[region, setRegion] = useState(''),
[binding, setBinding] = useState(false),
[bindingError, setBindingError] = useState(''),
[bindingNotice, setBindingNotice] = useState(''),
[catalogDirty, setCatalogDirty] = useState(false)
const key = useRef(''),
condition = useRef(''),
query = useMemo(
() => (period === 'all' ? { period: 'all' as const } : { period: 'month' as const, month }),
[period, month]
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()
@@ -166,7 +226,10 @@ export function QARegionalStatistics() {
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))))
if (collapsedDirectory.current !== fresh.organization.directory_id) {
setCollapsed(defaultDepartmentCollapsed(fresh.rows))
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)
@@ -183,6 +246,40 @@ export function QARegionalStatistics() {
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">
@@ -192,24 +289,39 @@ export function QARegionalStatistics() {
重新读取统计
</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}>
<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')}
onChange={(e) => setPeriod(e.target.value as 'all' | 'month' | 'week')}
>
<option value="all">累计提问访问</option>
<option value="month">按自然月</option>
<option value="all">按累计统计</option>
<option value="month">按自然月统计</option>
<option value="week">按自然周统计</option>
</select>
</label>
{period === 'month' ? (
@@ -225,6 +337,28 @@ export function QARegionalStatistics() {
/>
</label>
) : null}
{period === 'week' ? (
<label>
统计周次(北京时间周一至周日)
<input
aria-label="部门统计周次"
type="week"
min="2000-W01"
max={currentWeekValue()}
value={week}
onChange={(e) => setWeek(e.target.value)}
/>
<small>
{(() => {
try {
return qaWeek(Number(week.slice(0, 4)), Number(week.slice(6))).label
} catch {
return '请选择有效自然周'
}
})()}
</small>
</label>
) : null}
<label>
部门
<input
@@ -246,13 +380,23 @@ export function QARegionalStatistics() {
))}
</select>
</label>
<button type="button" disabled={!selected.length} onClick={() => setSettings(true)}>
设置选中部门的区域{selected.length ? `(${selected.length})` : ''}
</button>
<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>
</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
+6 -1
View File
@@ -601,7 +601,12 @@ export function QAOperations() {
</>
) : null}
{view === 'regions' ? (
<QARegionalStatistics />
<QARegionalStatistics
onSaved={() => {
setRevision((v) => v + 1)
setQualityRevision((v) => v + 1)
}}
/>
) : view === 'weekly' ? (
<QAWeekly query={query} />
) : view === 'dashboard' ? (
+33 -38
View File
@@ -2,7 +2,7 @@ import { renderToStaticMarkup } from 'react-dom/server'
// @ts-expect-error The test runner provides Node; the browser bundle intentionally omits @types/node.
import { readFileSync } from 'node:fs'
import { describe, expect, it, vi } from 'vitest'
import { RegionMappingView } from './QARegions'
import { RegionCatalogView } from './QARegions'
import { parseOrganization } from './qaOrg'
const state = parseOrganization({
state: 'ready',
@@ -36,52 +36,47 @@ const props = {
state,
preview: null,
rules: state.rules,
selectedRegion: 'APAC',
search: '',
busy: false,
error: '',
notice: '',
dirty: false,
onRegion: vi.fn(),
onSearch: vi.fn(),
onToggle: vi.fn(),
onPreview: vi.fn(),
onSave: vi.fn(),
onReload: vi.fn(),
onRemoveMissing: vi.fn(),
}
describe('region mapping workbench', () => {
it('allows removing unused region definitions but protects regions referenced by department rules', () => {
describe('region catalog settings', () => {
it('uses a region-name list without a second department mapping page', () => {
const html = renderToStaticMarkup(<RegionCatalogView {...props} />)
expect(html).toContain('区域名称列表')
expect(html).toContain('保存区域设置')
expect(html).not.toContain('qa-region-table')
expect(html).not.toContain('批量归属')
expect(html).not.toContain('全选当前列表')
})
it('shows direct binding counts and enters local confirmation before removing a bound region', () => {
const regions = [
{ id: 'APAC', name: 'Assigned' },
{ id: 'spare', name: 'Spare' },
]
const html = renderToStaticMarkup(<RegionMappingView {...props} regions={regions} />)
const html = renderToStaticMarkup(<RegionCatalogView {...props} regions={regions} />)
expect(html).toContain('删除区域 Spare')
expect(html).toMatch(/aria-label="删除区域 Assigned"[^>]*disabled=""/)
expect(html).toContain('直接绑定 1 个部门')
expect(html).not.toMatch(/aria-label="删除区域 Assigned"[^>]*disabled=""/)
expect(html).not.toContain('确认删除')
})
it('separates multiselect from bulk application and renders hierarchy and editable region names', () => {
it('shows editable saved region names but keeps department binding out of the settings list', () => {
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',
])
const html = renderToStaticMarkup(<RegionCatalogView {...props} state={custom} />)
for (const label of ['区域设置', '添加区域', '区域名称列表', '保存区域设置', '国外工业Amercia'])
expect(html).toContain(label)
expect(html).toMatch(/disabled=""[^>]*>批量归属/)
for (const removed of ['一级部门', '二级部门', '批量归属', '全选当前列表', 'qa-region-table'])
expect(html).not.toContain(removed)
expect(html).not.toContain('将 示例公司/')
})
@@ -99,36 +94,36 @@ describe('region mapping workbench', () => {
result: null,
},
}
const html = renderToStaticMarkup(<RegionMappingView {...props} syncStatus={syncStatus} />)
const html = renderToStaticMarkup(<RegionCatalogView {...props} syncStatus={syncStatus} />)
expect(html).toContain('正在读取并校验通讯录')
expect(html).not.toMatch(/\d+%/)
expect(html).toMatch(/disabled=""[^>]*>同步通讯录/)
const dirty = renderToStaticMarkup(
<RegionMappingView {...props} dirty syncStatus={{ configured: true, worker_ready: true, job: null }} />
<RegionCatalogView {...props} dirty syncStatus={{ configured: true, worker_ready: true, job: null }} />
)
expect(dirty).toContain('未保存的区域修改')
expect(dirty).toMatch(/disabled=""[^>]*>同步通讯录/)
})
it('lets long directory paths wrap instead of inheriting the global nowrap table rule', () => {
it('uses a responsive catalog list with wrapping warnings and no obsolete mapping-table styles', () => {
const css = readFileSync(new URL('./qaRegions.css', import.meta.url), 'utf8')
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\.qa-region-basis\s*\{([^}]+)\}/)?.[1] ?? ''
expect(statusRule).toMatch(/white-space:\s*nowrap/)
expect(css).toMatch(/\.qa-region-catalog-list/)
expect(css).toMatch(/minmax\(0,\s*1fr\)/)
expect(css).toMatch(/\.qa-region-row-actions/)
expect(css).toMatch(/overflow-wrap:\s*anywhere/)
expect(css).not.toContain('.qa-region-table')
})
it('shows a dated historical roster, conflicts and no invented performance verdict', () => {
const html = renderToStaticMarkup(<RegionMappingView {...props} />)
const html = renderToStaticMarkup(<RegionCatalogView {...props} />)
expect(html).toContain('历史快照')
expect(html).toContain('跨区域待核对:1')
expect(html).not.toContain('配置区域归属不等于纳入绩效考核')
expect(html).not.toContain('<script>test</script>')
expect(html).not.toContain('达标率')
expect(html).toMatch(/disabled=""[^>]*>保存归属/)
expect(html).toMatch(/disabled=""[^>]*>保存区域设置/)
})
it('requires a preview of the current draft before enabling save', () => {
const html = renderToStaticMarkup(<RegionMappingView {...props} dirty preview={state} />)
it('keeps optional preview visible and lets save invoke the same preview automatically', () => {
const html = renderToStaticMarkup(<RegionCatalogView {...props} dirty preview={state} />)
expect(html).toContain('预览结果(未保存)')
expect(html).not.toMatch(/disabled=""[^>]*>保存归属/)
expect(html).not.toMatch(/disabled=""[^>]*>保存区域设置/)
})
})
+152 -296
View File
@@ -1,24 +1,20 @@
import { useEffect, useRef, useState } from 'react'
import {
changeRegionRule,
fetchOrganization,
previewOrganization,
organizationRegions,
parseRegionDefinitions,
saveOrganization,
commitOrganization,
} from './qaOrg'
import type { Organization, RegionRule, RegionDefinition } from './qaOrg'
import './qaRegions.css'
import { applyBulkRegionRules, departmentLevels, selectDepartmentBranch } 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
onRemoveRegion?: (id: string) => void
syncStatus?: DirectorySyncStatus | null
syncError?: string
syncSubmitting?: boolean
@@ -26,56 +22,46 @@ interface Props {
state: Organization | null
preview: Organization | null
rules: RegionRule[]
selectedRegion: string
search: string
busy: boolean
error: string
notice: string
dirty: boolean
onRegion: (value: string) => void
onSearch: (value: string) => void
onToggle: (id: string, checked: boolean) => void
onRemoveMissing: (id: string) => void
onPreview: () => void
onSave: () => void
onReload: () => void
}
export function RegionMappingView(p: Props) {
export function RegionCatalogView(p: Props) {
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?.(selectDepartmentBranch(all, selected, id, checked))
[catalogError, setCatalogError] = useState(''),
[removeID, setRemoveID] = useState('')
const available = p.state?.state === 'ready',
regions = p.regions ?? organizationRegions(p.state),
display = p.preview ?? p.state
const add = () => {
if (!newName.trim()) return
const next = [...regions, { id: 'region-' + newOperationID(), name: newName.trim() }]
try {
p.onCatalog?.(parseRegionDefinitions(next))
p.onCatalog?.(parseRegionDefinitions([...regions, { id: 'region-' + newOperationID(), name: newName.trim() }]))
setNewName('')
setCatalogError('')
} catch {
setCatalogError('区域名称无效,请核对长度、重名或保留名称')
}
}
const remove = (id: string) => {
p.onRemoveRegion?.(id)
setRemoveID('')
}
return (
<section className="qa-regions" aria-label="区域归属配置">
<section className="qa-regions" aria-label="区域设置">
<div className="qa-region-heading">
<h3>区域归属配置</h3>
<h3>区域名称</h3>
<button type="button" disabled={p.busy} onClick={p.onReload}>
{p.dirty ? '放弃修改并重读' : '重新读取'}
</button>
</div>
<p className="qa-ops-muted">区域名称、筛选及看板使用同一份配置;部门绑定在左侧统计表完成。</p>
<div className="qa-region-directory-status">
<button
type="button"
disabled={
@@ -90,183 +76,122 @@ export function RegionMappingView(p: Props) {
>
同步通讯录
</button>
<small role="status" aria-label="通讯录后台同步状态">
{!p.syncStatus
? '正在读取后台同步状态…'
: !p.syncStatus.configured
? '后台同步未接线'
: p.syncStatus.job
? {
pending: '等待后台执行器',
running: '正在读取并校验通讯录',
retry: '上次同步失败,等待后台重试;保留原快照',
completed: '同步已完成,完整快照已落库',
failed: '同步失败,保留原快照;可重新同步',
cancelled: '同步已取消,保留原快照',
}[p.syncStatus.job.state]
: p.syncStatus.worker_ready
? '后台执行器在线,尚未发起同步'
: '后台执行器未在线,不会创建无人处理的任务'}
{p.dirty ? ';存在未保存的区域修改,请先保存或放弃后同步' : ''}
</small>
</div>
<div className="qa-ops-muted" aria-label="通讯录后台同步状态" role="status">
{!p.syncStatus
? '正在读取后台同步状态…'
: !p.syncStatus.configured
? '后台同步未接线'
: p.syncStatus.job
? {
pending: '等待后台执行器',
running: '正在读取并校验通讯录',
retry: '上次同步失败,等待后台重试;保留原快照',
completed: '同步已完成,完整快照已落库',
failed: '同步失败,保留原快照;可重新同步',
cancelled: '同步已取消,保留原快照',
}[p.syncStatus.job.state]
: p.syncStatus.worker_ready
? '后台执行器在线,尚未发起同步'
: '后台执行器未在线,不会创建无人处理的任务'}
{p.dirty ? ';存在未保存的区域修改,请先保存或放弃后同步' : ''}
</div>
{p.syncError ? (
<p role="alert" className="error-banner">
{p.syncError}
</p>
) : null}
{p.state?.directory_synced_at ? (
<p className="qa-ops-muted">
{p.state.directory_source === 'weekly_report_snapshot' ? '历史快照' : '全量同步快照'} · 通讯录同步时间:
{new Date(p.state.directory_synced_at).toLocaleString('zh-CN', { hour12: false })} · 配置版本:
{p.state.revision_id || '尚未保存'}
{new Date(p.state.directory_synced_at).toLocaleString('zh-CN', { hour12: false })}
</p>
) : null}
{p.error ? (
<p role="alert" className="error-banner">
{p.error}
{[p.error, p.syncError, catalogError].filter(Boolean).map((error, index) => (
<p role="alert" className="error-banner" key={index}>
{error}
</p>
) : null}
))}
{p.notice ? <p role="status">{p.notice}</p> : null}
{!p.state ? (
<p role="status">{p.busy ? '正在读取通讯录…' : '尚未读取通讯录'}</p>
<p role="status">{p.busy ? '正在读取区域设置…' : '尚未读取区域设置'}</p>
) : !available ? (
<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)))
}
/>
<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>
<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)}>
{regions.length ? (
regions.map((r) => (
<option key={r.id} value={r.id}>
{r.name}
</option>
))
) : (
<option value="">请先添加区域</option>
)}
</select>
</label>
<label>
搜索完整部门路径
<input
type="search"
value={p.search}
onChange={(e) => p.onSearch(e.target.value)}
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) => {
let next = [...selected]
for (const row of departments)
next = selectDepartmentBranch(all, next, row.department.id, e.target.checked)
p.onSelect?.(next)
}}
/>
全选当前列表
</label>
<span>已勾选 {selected.length} 个部门</span>
<ul className="qa-region-catalog-list" aria-label="区域名称列表">
{regions.map((r) => {
const count = p.rules.filter((rule) => rule.region === r.id).length
return (
<li key={r.id} data-region-id={r.id}>
<label>
<span>区域名称</span>
<input
aria-label={`区域名称 ${r.id}`}
value={r.name}
maxLength={100}
disabled={p.busy}
onChange={(e) =>
p.onCatalog?.(
regions.map((item) => (item.id === r.id ? { ...item, name: e.target.value } : item))
)
}
/>
</label>
<small>直接绑定 {count} 个部门</small>
<div className="qa-region-row-actions">
{removeID === r.id ? (
<>
<button type="button" disabled={p.busy} onClick={() => setRemoveID('')}>
取消
</button>
<button type="button" disabled={p.busy} onClick={() => remove(r.id)}>
确认删除
</button>
</>
) : (
<button
type="button"
aria-label={`删除区域 ${r.name}`}
disabled={p.busy}
onClick={() => (count ? setRemoveID(r.id) : remove(r.id))}
>
删除
</button>
)}
</div>
{removeID === r.id ? (
<p role="alert" className="qa-region-removal-warning">
保存后将删除“{r.name}”并解除 {count}{' '}
个部门的直接绑定;这些部门将重新按剩余上级规则计算归属,不删除问答。
</p>
) : null}
</li>
)
})}
</ul>
{!regions.length ? <p>暂无区域,请添加区域名称。</p> : null}
<form
className="qa-region-add"
onSubmit={(e) => {
e.preventDefault()
add()
}}
>
<input
aria-label="新区域名称"
value={newName}
maxLength={100}
disabled={p.busy}
placeholder="输入新的区域名称"
onChange={(e) => setNewName(e.target.value)}
/>
<button
type="button"
disabled={p.busy || !selected.length || !regions.some((r) => r.id === p.selectedRegion)}
onClick={p.onApply}
disabled={
p.busy || !newName.trim() || regions.length >= 100 || regions.some((r) => r.name === newName.trim())
}
>
批量归属
添加区域
</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>
<button type="button" disabled={p.busy || !p.dirty || !p.preview} onClick={p.onSave}>
保存归属
</button>
</div>
{display ? (
</form>
{p.preview && display ? (
<div className="qa-region-preview" aria-label="归属人数预览">
<strong>{p.preview ? '预览结果(未保存)' : '已保存归属'}</strong>
<strong>预览结果(未保存)</strong>
<span>通讯录人数:{display.view.total_people}</span>
{organizationRegions(display).map((r) => (
<span key={r.id}>
@@ -276,14 +201,17 @@ export function RegionMappingView(p: Props) {
<span>未归属:{display.view.unassigned_people}</span>
<span>跨区域待核对:{display.view.conflicting_people}</span>
</div>
) : display ? (
<small>
已保存:通讯录人数 {display.view.total_people},跨区域待核对:{display.view.conflicting_people}
</small>
) : null}
{p.dirty && !p.preview ? <p className="qa-ops-muted">人数仍为已保存结果;请预览后保存。</p> : null}
{display?.view.missing_departments.length ? (
<div role="alert" className="qa-ops-warning">
部分已配置部门不在当前通讯录中,原规则保留,需核对:
部分历史绑定不在当前通讯录中:
{display.view.missing_departments.map((id) => (
<span key={id}>
{id}{' '}
{id}
<button type="button" disabled={p.busy} onClick={() => p.onRemoveMissing(id)}>
移除此规则
</button>
@@ -291,81 +219,28 @@ export function RegionMappingView(p: Props) {
))}
</div>
) : null}
<div className="qa-region-tree-scroll">
<table className="qa-region-table">
<thead>
<tr>
<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(({ 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}
</div>
<footer className="qa-region-save-actions">
<button type="button" disabled={p.busy || !p.dirty} onClick={p.onPreview}>
预览影响
</button>
<button type="button" disabled={p.busy || !p.dirty} onClick={p.onSave}>
{p.busy ? '正在处理…' : '保存区域设置'}
</button>
</footer>
</>
)}
</section>
)
}
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({
selection,
onSelectionChange,
onSaved,
}: { selection?: string[]; onSelectionChange?: (ids: string[]) => void; onSaved?: () => void } = {}) {
onDirtyChange,
open = true,
}: { onSaved?: (value: Organization) => void; onDirtyChange?: (dirty: boolean) => void; open?: boolean } = {}) {
const [syncStatus, setSyncStatus] = useState<DirectorySyncStatus | null>(null),
[syncError, setSyncError] = useState(''),
[syncSubmitting, setSyncSubmitting] = useState(false)
@@ -377,16 +252,8 @@ export function QARegions({
const [state, setState] = useState<Organization | null>(null),
[preview, setPreview] = useState<Organization | null>(null),
[rules, setRules] = useState<RegionRule[]>([])
const [regions, setRegions] = useState<RegionDefinition[]>([]),
[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),
const [regions, setRegions] = useState<RegionDefinition[]>([])
const [busy, setBusy] = useState(false),
[error, setError] = useState(''),
[notice, setNotice] = useState('')
const request = useRef<AbortController | null>(null)
@@ -394,10 +261,6 @@ export function QARegions({
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 () => {
@@ -420,12 +283,10 @@ export function QARegions({
if (!controller.signal.aborted) setBusy(false)
}
}
useEffect(() => {
void load()
return () => request.current?.abort()
}, [])
useEffect(() => () => request.current?.abort(), [])
const dirty = Boolean(state && signature(rules, regions) !== signature(state.rules, organizationRegions(state)))
dirtyRef.current = dirty
useEffect(() => onDirtyChange?.(dirty), [dirty, onDirtyChange])
const loadRef = useRef(load)
loadRef.current = load
useEffect(() => {
@@ -496,8 +357,11 @@ export function QARegions({
setNotice('')
setError('')
}
useEffect(() => {
if (open && !dirtyRef.current) void load()
}, [open])
const act = async (save: boolean) => {
if (!state || busy || (save && !preview)) return
if (!state || busy) return
const controller = new AbortController()
request.current?.abort()
request.current = controller
@@ -506,16 +370,13 @@ export function QARegions({
setNotice('')
try {
const value = await (save
? saveOrganization({ ...state, regions: parseRegionDefinitions(regions) }, rules, controller.signal)
? commitOrganization(state, 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)
if (controller.signal.aborted) return
accept(readback)
if (readback.revision_id !== value.revision_id) throw new Error('保存后配置再次变化,已读取最新版本,请核对')
setNotice('区域归属已保存并重新读取')
onSaved?.()
accept(value)
setNotice('区域设置已保存,筛选和看板将使用此版本')
onSaved?.(value)
} else setPreview(value)
}
} catch (e) {
@@ -528,18 +389,18 @@ export function QARegions({
}
}
return (
<RegionMappingView
<RegionCatalogView
onRemoveRegion={(id) => {
setRegions((old) => old.filter((r) => r.id !== id))
edit(rules.filter((rule) => rule.region !== id))
}}
regions={regions}
selectedIDs={selected}
onCatalog={(next) => {
setRegions(next)
setRegion((old) => (next.some((r) => r.id === old) ? old : (next[0]?.id ?? '')))
setPreview(null)
setNotice('')
setError('')
}}
onSelect={setSelected}
onApply={() => edit(applyBulkRegionRules(rules, selected, region))}
syncStatus={syncStatus}
syncError={syncError}
syncSubmitting={syncSubmitting}
@@ -547,15 +408,10 @@ export function QARegions({
state={state}
preview={preview}
rules={rules}
selectedRegion={region}
search={search}
busy={busy}
error={error}
notice={notice}
dirty={dirty}
onRegion={setRegion}
onSearch={setSearch}
onToggle={(id, checked) => edit(changeRegionRule(rules, id, region, checked))}
onRemoveMissing={(id) => edit(rules.filter((r) => r.department_id !== id))}
onPreview={() => void act(false)}
onSave={() => void act(true)}
+56
View File
@@ -172,3 +172,59 @@
max-width: 100%;
}
}
.qa-department-binding {
display: flex;
flex-wrap: wrap;
align-items: center;
gap: 8px;
border-left: 1px solid #e5ebf2;
padding-left: 12px;
}
.qa-department-binding > span {
color: #64748b;
font-size: 12px;
}
.qa-region-settings-panel {
position: fixed;
inset: 0 0 0 auto;
z-index: 80;
display: flex;
flex-direction: column;
width: min(560px, 100vw);
box-sizing: border-box;
border-left: 1px solid #d8e1eb;
background: #fff;
color: #334155;
box-shadow: -10px 0 30px #33415514;
}
.qa-region-settings-panel[hidden] {
display: none;
}
.qa-region-settings-panel > header {
display: flex;
align-items: center;
justify-content: space-between;
padding: 18px 20px;
border-bottom: 1px solid #e5ebf2;
gap: 12px;
}
.qa-region-settings-panel > header h3 {
margin: 0;
font-size: 18px;
}
.qa-region-settings-content {
overflow: auto;
min-height: 0;
padding: 20px;
}
@media (max-width: 680px) {
.qa-department-binding {
border-left: 0;
padding-left: 0;
flex-basis: 100%;
}
.qa-region-settings-content {
padding: 16px;
}
}
+23 -2
View File
@@ -1,11 +1,13 @@
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'
period: 'all' | 'month' | 'week'
month?: string
week?: string
}
export interface DepartmentStatistic {
id: string
@@ -25,8 +27,9 @@ export interface DepartmentStatisticsSnapshot {
total_people: number
organization: QAOrganizationVersion
regions: RegionDefinition[]
period: 'all' | 'month'
period: 'all' | 'month' | 'week'
month: string
week: string
start: string | null
end: string
generated_at: string
@@ -68,7 +71,9 @@ export function parseDepartmentStatistics(raw: unknown, query: DepartmentStatist
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 ||
@@ -85,6 +90,21 @@ export function parseDepartmentStatistics(raw: unknown, query: DepartmentStatist
(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)
@@ -161,6 +181,7 @@ export function parseDepartmentStatistics(raw: unknown, query: DepartmentStatist
regions,
period: query.period,
month: query.month ?? '',
week: query.week ?? '',
start,
end,
generated_at: generated,
+41
View File
@@ -1,3 +1,4 @@
import { applyBulkRegionRules } from './qaRegionSelection'
export const regionNames = ['国内工业', 'APAC', 'EMEA', 'America'] as const
export interface RegionDefinition {
id: string
@@ -189,6 +190,46 @@ export const previewOrganization = (state: Organization, rules: RegionRule[], si
{ directory_id: state.directory_id, base_revision: state.revision_id, regions: organizationRegions(state), rules },
signal
)
export async function bindOrganizationDepartments(
expected: { directory_id: string; revision_id: string },
ids: string[],
region: string,
signal?: AbortSignal
): Promise<Organization> {
const state = await fetchOrganization(signal),
catalog = organizationRegions(state)
if (state.directory_id !== expected.directory_id || state.revision_id !== expected.revision_id)
throw new Error('通讯录或区域版本已变化,请重新读取统计后绑定')
const known = new Set(state.view.departments.map((d) => d.id))
if (!ids.length || ids.some((id) => !known.has(id)) || !catalog.some((r) => r.id === region))
throw new Error('选中部门或目标区域无效,请重新读取')
return commitOrganization(state, catalog, applyBulkRegionRules(state.rules, ids, region), signal)
}
const organizationCommitSignature = (regions: RegionDefinition[], rules: RegionRule[]) =>
JSON.stringify({
regions: [...regions].sort((a, b) => a.id.localeCompare(b.id)),
rules: [...rules].sort((a, b) => a.department_id.localeCompare(b.department_id)),
})
export async function commitOrganization(
state: Organization,
regions: RegionDefinition[],
rules: RegionRule[],
signal?: AbortSignal
): Promise<Organization> {
const catalog = parseRegionDefinitions(regions),
base = { ...state, regions: catalog }
await previewOrganization(base, rules, signal)
const saved = await saveOrganization(base, rules, signal),
readback = await fetchOrganization(signal)
if (
readback.directory_id !== state.directory_id ||
readback.revision_id !== saved.revision_id ||
organizationCommitSignature(organizationRegions(readback), readback.rules) !==
organizationCommitSignature(catalog, rules)
)
throw new Error('保存后配置再次变化,未将旧结果标为成功,请重新读取核对')
return readback
}
export const saveOrganization = (state: Organization, rules: RegionRule[], signal?: AbortSignal) =>
requestOrganization(
'/regions',
+115
View File
@@ -0,0 +1,115 @@
import { it, expect, vi } from 'vitest'
import { commitOrganization, parseOrganization, bindOrganizationDepartments } from './qaOrg'
const raw = {
state: 'ready',
directory_id: 'fixture-dir',
directory_source: 'weekly_report_snapshot',
directory_synced_at: '2026-10-18T00:00:00Z',
revision_id: 'old',
updated_by: 'fixture-admin',
updated_at: null,
regions: [{ id: 'new-region', name: '业务区域' }],
rules: [{ department_id: 'root', region: 'new-region' }],
view: {
departments: [
{
id: 'root',
parent_id: '',
name: 'Fixture',
path: 'Fixture',
region: 'new-region',
explicit: true,
inherited_from: '',
},
],
regions: { 'new-region': 1 },
total_people: 1,
unassigned_people: 0,
conflicting_people: 0,
missing_departments: [],
},
}
const response = (v: unknown) => ({ ok: true, status: 200, json: async () => ({ data: v }) })
it('binds selected current department IDs in place and verifies the persisted version', async () => {
const fetch = vi
.fn()
.mockResolvedValueOnce(response(raw))
.mockResolvedValueOnce(response(raw))
.mockResolvedValueOnce(response({ ...raw, revision_id: 'new' }))
.mockResolvedValueOnce(response({ ...raw, revision_id: 'new' }))
vi.stubGlobal('fetch', fetch)
try {
const saved = await bindOrganizationDepartments(
{ directory_id: 'fixture-dir', revision_id: 'old' },
['root'],
'new-region'
)
expect(saved.revision_id).toBe('new')
expect(fetch.mock.calls.map((c) => c[1]?.method)).toEqual(['GET', 'POST', 'PUT', 'GET'])
expect(JSON.parse(fetch.mock.calls[2][1].body).rules).toEqual(raw.rules)
} finally {
vi.unstubAllGlobals()
}
})
it('refuses binding a stale directory/revision or a missing department before any write', async () => {
for (const [revision, ids] of [
['stale', ['root']],
['old', ['missing']],
] as const) {
const fetch = vi.fn().mockResolvedValue(response(raw))
vi.stubGlobal('fetch', fetch)
try {
await expect(
bindOrganizationDepartments({ directory_id: 'fixture-dir', revision_id: revision }, [...ids], 'new-region')
).rejects.toThrow()
expect(fetch).toHaveBeenCalledTimes(1)
} finally {
vi.unstubAllGlobals()
}
}
})
it('previews and persists the same versioned catalog/rules before independent exact readback', async () => {
const state = parseOrganization(raw),
receipt = { ...raw, revision_id: 'new' }
const fetch = vi
.fn()
.mockResolvedValueOnce(response(raw))
.mockResolvedValueOnce(response(receipt))
.mockResolvedValueOnce(response(receipt))
vi.stubGlobal('fetch', fetch)
try {
expect((await commitOrganization(state, state.regions!, state.rules)).revision_id).toBe('new')
expect(fetch.mock.calls.map((c) => c[0])).toEqual([
'/api/v1/qa-ops/organization/preview',
'/api/v1/qa-ops/organization/regions',
'/api/v1/qa-ops/organization',
])
for (const call of fetch.mock.calls.slice(0, 2)) {
const input = JSON.parse(call[1].body)
expect(input).toMatchObject({
directory_id: 'fixture-dir',
base_revision: 'old',
regions: raw.regions,
rules: raw.rules,
})
}
} finally {
vi.unstubAllGlobals()
}
})
it('does not claim a successful save when another revision wins before readback', async () => {
vi.stubGlobal(
'fetch',
vi
.fn()
.mockResolvedValueOnce(response(raw))
.mockResolvedValueOnce(response({ ...raw, revision_id: 'new' }))
.mockResolvedValueOnce(response({ ...raw, revision_id: 'other' }))
)
try {
const state = parseOrganization(raw)
await expect(commitOrganization(state, state.regions!, state.rules)).rejects.toThrow('保存后配置')
} finally {
vi.unstubAllGlobals()
}
})
+7
View File
@@ -1,5 +1,12 @@
import type { DepartmentRegion, RegionRule } from './qaOrg'
export type DepartmentNode = { id: string; parent_id: string; name: string }
export function defaultDepartmentCollapsed(nodes: DepartmentNode[]): Set<string> {
return new Set(
departmentTree(nodes, new Set())
.filter((r) => r.depth >= 2 && r.hasChildren)
.map((r) => r.department.id)
)
}
export function subtreeIDs(nodes: DepartmentNode[], ids: string[]): string[] {
const children = new Map<string, string[]>(),
known = new Set(nodes.map((n) => n.id))
+41
View File
@@ -0,0 +1,41 @@
import { it, expect } from 'vitest'
import { defaultDepartmentCollapsed, departmentTree } from './qaRegionSelection'
import { parseDepartmentStatistics } from './qaDepartmentStatistics'
import { departmentStatisticsFixture as f } from './qaDepartmentStatistics.fixture'
it('defaults to company, business centers and second-level departments while preserving deeper search and expansion', () => {
const nodes = [
{ id: 'company', parent_id: '', name: '示例公司' },
{ id: 'finance', parent_id: 'company', name: '财务中心' },
{ id: 'department', parent_id: 'finance', name: '财务部' },
{ id: 'office', parent_id: 'department', name: '更深财务组' },
{ id: 'global', parent_id: 'company', name: '全球业务支持中心' },
{ id: 'solution', parent_id: 'global', name: '解决方案部' },
{ id: 'support', parent_id: 'global', name: '全球技术支持部' },
]
const collapsed = defaultDepartmentCollapsed(nodes)
expect(departmentTree(nodes, collapsed).map((r) => r.department.id)).not.toContain('office')
expect(new Set(departmentTree(nodes, collapsed).map((r) => r.department.id))).toEqual(
new Set(nodes.filter((n) => n.id !== 'office').map((n) => n.id))
)
expect(departmentTree(nodes, collapsed, '更深财务组').some((r) => r.department.id === 'office')).toBe(true)
collapsed.delete('department')
expect(departmentTree(nodes, collapsed).some((r) => r.department.id === 'office')).toBe(true)
})
it('accepts an exact natural week response and rejects a mismatched week or non-Monday start', () => {
const raw = {
...f,
snapshot: {
...f.snapshot,
period: 'week',
week: '2026-W42',
start: '2026-10-12T00:00:00+08:00',
end: '2026-10-19T00:00:00+08:00',
},
}
const query = JSON.parse('{"period":"week","week":"2026-W42"}')
expect(parseDepartmentStatistics(raw, query).snapshot?.period).toBe('week')
expect(() => parseDepartmentStatistics({ ...raw, snapshot: { ...raw.snapshot, week: '2026-W43' } }, query)).toThrow()
expect(() =>
parseDepartmentStatistics({ ...raw, snapshot: { ...raw.snapshot, start: '2026-10-11T00:00:00+08:00' } }, query)
).toThrow()
})
+98 -145
View File
@@ -2,8 +2,8 @@
display: flex;
flex-direction: column;
min-height: 0;
gap: 12px;
flex: 1;
min-width: 0;
gap: 14px;
}
.qa-region-heading {
display: flex;
@@ -13,80 +13,108 @@
}
.qa-region-heading h3 {
margin: 0;
font-size: 15px;
}
.qa-region-filters {
.qa-region-directory-status {
display: flex;
gap: 12px;
align-items: end;
align-items: center;
flex-wrap: wrap;
gap: 8px;
}
.qa-region-filters label {
.qa-region-directory-status small {
color: #64748b;
line-height: 1.6;
}
.qa-region-catalog-list {
padding: 0;
margin: 0;
list-style: none;
border-top: 1px solid #e5ebf2;
}
.qa-region-catalog-list > li {
display: grid;
grid-template-columns: minmax(0, 1fr) auto;
align-items: center;
gap: 7px 12px;
padding: 14px 0;
border-bottom: 1px solid #e5ebf2;
}
.qa-region-catalog-list label {
display: flex;
flex-direction: column;
gap: 6px;
gap: 5px;
grid-column: 1;
min-width: 0;
font-size: 12px;
color: #64748b;
}
.qa-region-filters label:nth-child(2) {
flex: 1;
min-width: 220px;
.qa-region-catalog-list small {
grid-column: 1;
color: #8190a4;
font-size: 11px;
}
.qa-region-filters input,
.qa-region-filters select {
.qa-region-catalog-list input,
.qa-region-add input {
box-sizing: border-box;
width: 100%;
min-width: 0;
min-height: 36px;
padding: 6px 10px;
border: 1px solid var(--line, #d8e1eb);
border-radius: 6px;
background: var(--panel, #fff);
color: inherit;
padding: 7px 10px;
border: 1px solid #d8e1eb;
border-radius: 5px;
background: #fff;
color: #334155;
}
.qa-region-row-actions {
min-width: 152px;
justify-content: flex-start;
display: flex;
flex-wrap: nowrap;
gap: 8px;
grid-column: 2;
grid-row: 1 / span 2;
}
.qa-region-row-actions button {
min-width: 48px;
white-space: nowrap;
}
.qa-region-removal-warning {
grid-column: 1 / -1;
color: #97572d;
line-height: 1.6;
overflow-wrap: anywhere;
font-size: 12px;
}
.qa-region-add {
display: flex;
gap: 8px;
align-items: center;
}
.qa-region-add input {
flex: 1;
}
.qa-region-add button {
flex: none;
}
.qa-region-save-actions {
display: flex;
justify-content: flex-end;
gap: 8px;
position: sticky;
bottom: -20px;
padding: 12px 0;
border-top: 1px solid #e5ebf2;
background: #fff;
}
.qa-region-preview {
display: flex;
gap: 8px 18px;
gap: 8px 16px;
flex-wrap: wrap;
padding: 12px 14px;
border: 1px solid var(--line, #d8e1eb);
background: var(--panel-muted, #f3f7fc);
border-radius: 6px;
}
.qa-region-tree-scroll {
min-height: 120px;
overflow: auto;
flex: 1;
border: 1px solid var(--line, #d8e1eb);
border-radius: 6px;
}
.qa-region-table {
width: 100%;
border-collapse: collapse;
text-align: left;
font-size: 13px;
table-layout: fixed;
min-width: 960px;
}
.qa-region-table th,
.qa-region-table td {
padding: 10px 12px;
border-bottom: 1px solid var(--line, #d8e1eb);
white-space: normal;
overflow-wrap: anywhere;
}
.qa-region-table th {
position: sticky;
top: 0;
background: var(--panel, #fff);
white-space: nowrap;
}
.qa-region-table td:nth-child(2) {
min-width: 0;
overflow-wrap: anywhere;
}
.qa-region-table td.qa-region-basis {
white-space: nowrap;
}
.qa-region-table input[type='checkbox'] {
width: 17px;
height: 17px;
cursor: pointer;
accent-color: #1765c1;
padding: 12px;
border: 1px solid #d8e1eb;
background: #f3f7fc;
border-radius: 5px;
font-size: 12px;
}
.qa-region-tabs {
display: flex;
@@ -112,89 +140,14 @@
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;
}
.qa-region-filters label {
flex: 1;
}
.qa-region-tree-scroll {
min-height: 300px;
}
.qa-region-preview {
font-size: 13px;
}
@media (max-width: 480px) {
.qa-region-heading {
flex-wrap: wrap;
}
.qa-region-catalog-list > li {
gap: 7px 8px;
}
.qa-region-row-actions {
gap: 5px;
}
}