diff --git a/CHANGELOG.md b/CHANGELOG.md index a9503c4..5c8c9ed 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -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 diff --git a/api/openapi.yaml b/api/openapi.yaml index 8eae267..ad45d34 100644 --- a/api/openapi.yaml +++ b/api/openapi.yaml @@ -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"]}}}}}}, diff --git a/internal/qaopsmirror/department_statistics_cache.go b/internal/qaopsmirror/department_statistics_cache.go index f7fc3f2..7b32add 100644 --- a/internal/qaopsmirror/department_statistics_cache.go +++ b/internal/qaopsmirror/department_statistics_cache.go @@ -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"` diff --git a/internal/qaopsmirror/department_statistics_store.go b/internal/qaopsmirror/department_statistics_store.go index 7022b82..06213e3 100644 --- a/internal/qaopsmirror/department_statistics_store.go +++ b/internal/qaopsmirror/department_statistics_store.go @@ -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 diff --git a/internal/qaopsmirror/department_statistics_week_integration_test.go b/internal/qaopsmirror/department_statistics_week_integration_test.go new file mode 100644 index 0000000..9018df4 --- /dev/null +++ b/internal/qaopsmirror/department_statistics_week_integration_test.go @@ -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") + } +} diff --git a/internal/qaopsmirror/department_statistics_week_test.go b/internal/qaopsmirror/department_statistics_week_test.go new file mode 100644 index 0000000..3b7d334 --- /dev/null +++ b/internal/qaopsmirror/department_statistics_week_test.go @@ -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) + } + } +} diff --git a/web/src/QADepartmentStatistics.test.tsx b/web/src/QADepartmentStatistics.test.tsx index f72f70f..0d029ce 100644 --- a/web/src/QADepartmentStatistics.test.tsx +++ b/web/src/QADepartmentStatistics.test.tsx @@ -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() + 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() diff --git a/web/src/QADepartmentStatistics.tsx b/web/src/QADepartmentStatistics.tsx index 6b9599f..9c938cb 100644 --- a/web/src/QADepartmentStatistics.tsx +++ b/web/src/QADepartmentStatistics.tsx @@ -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(), + collapsed = p.collapsed ?? defaultDepartmentCollapsed(p.data.rows), rows = departmentTree(p.data.rows, collapsed, p.search ?? '', p.region ?? '') return (
@@ -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 ( +
+ 已勾选 {selectedCount} 个部门 + + +
+ ) +} +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(null), @@ -133,12 +182,23 @@ export function QARegionalStatistics() { const [selected, setSelected] = useState([]), [collapsed, setCollapsed] = useState>(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(null), + query = useMemo( + () => + 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 (
@@ -192,24 +289,39 @@ export function QARegionalStatistics() { 重新读取统计
- -