diff --git a/backend/src/main/java/cn/yunsheng/quality/common/WorkspaceStateController.java b/backend/src/main/java/cn/yunsheng/quality/common/WorkspaceStateController.java new file mode 100644 index 0000000..f386fc6 --- /dev/null +++ b/backend/src/main/java/cn/yunsheng/quality/common/WorkspaceStateController.java @@ -0,0 +1,42 @@ +package cn.yunsheng.quality.common; + +import cn.yunsheng.quality.governance.GovernanceAccessService; +import cn.yunsheng.quality.identity.AppUserPrincipal; +import java.nio.charset.StandardCharsets; +import java.security.MessageDigest; +import java.util.HexFormat; +import java.util.List; +import java.util.Map; +import org.springframework.jdbc.core.JdbcTemplate; +import org.springframework.security.core.annotation.AuthenticationPrincipal; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.RestController; + +/** 只校验缓存依赖,不读取业务事实表,也不向前端返回权限策略正文。 */ +@RestController +public class WorkspaceStateController { + private final JdbcTemplate jdbc; + private final GovernanceAccessService access; + public WorkspaceStateController(JdbcTemplate jdbc, GovernanceAccessService access) { + this.jdbc = jdbc; this.access = access; + } + @GetMapping("/api/workspace/state") + public Map state(@AuthenticationPrincipal AppUserPrincipal actor) { + access.requireUserActivePolicy(actor); + var policy = jdbc.queryForList("SELECT detail_allowed,evidence_allowed,original_download_allowed,CAST(allowed_fields AS CHAR) AS allowed_fields,valid_until,inherit_department_children,row_version FROM user_access_policy WHERE user_id=?", actor.getId().toString()); + String auth = digest(List.of(actor.getId(), actor.getRoleCodes().stream().sorted().toList(), + actor.getDepartments().stream().sorted().toList(), actor.getGroups().stream().sorted().toList(), policy)); + String data = digest(List.of( + jdbc.queryForList("SELECT * FROM current_release ORDER BY dataset_id"), + jdbc.queryForList("SELECT * FROM platform_metadata ORDER BY metadata_key"), + jdbc.queryForList("SELECT id,row_version FROM target_version WHERE status='ACTIVE' ORDER BY id"), + jdbc.queryForList("SELECT * FROM query_filter_field ORDER BY field_key"), + jdbc.queryForList("SELECT id,row_version FROM service_identity ORDER BY id"), + jdbc.queryForList("SELECT * FROM service_binding ORDER BY service_type"))); + return Map.of("authRevision", auth, "dataRevision", data); + } + private static String digest(Object value) { + try { return HexFormat.of().formatHex(MessageDigest.getInstance("SHA-256").digest(value.toString().getBytes(StandardCharsets.UTF_8))); } + catch (java.security.NoSuchAlgorithmException exception) { throw new IllegalStateException(exception); } + } +} diff --git a/backend/src/test/java/cn/yunsheng/quality/common/WorkspaceStateControllerTest.java b/backend/src/test/java/cn/yunsheng/quality/common/WorkspaceStateControllerTest.java new file mode 100644 index 0000000..54f4908 --- /dev/null +++ b/backend/src/test/java/cn/yunsheng/quality/common/WorkspaceStateControllerTest.java @@ -0,0 +1,44 @@ +package cn.yunsheng.quality.common; + +import static org.junit.jupiter.api.Assertions.*; +import static org.mockito.Mockito.*; +import cn.yunsheng.quality.governance.GovernanceAccessService; +import cn.yunsheng.quality.identity.AppUserPrincipal; +import java.util.*; +import org.junit.jupiter.api.Test; +import org.springframework.jdbc.core.JdbcTemplate; + +class WorkspaceStateControllerTest { + final JdbcTemplate jdbc = mock(JdbcTemplate.class); + final GovernanceAccessService access = mock(GovernanceAccessService.class); + final WorkspaceStateController controller = new WorkspaceStateController(jdbc, access); + final UUID id = UUID.randomUUID(); + AppUserPrincipal actor(List departments) { + return new AppUserPrincipal(id,"test","","test",true,false,List.of("QUALITY_VIEWER"),departments,List.of("*"),List.of()); + } + @Test void stableDigestIgnoresScopeOrderAndDoesNotExposePolicy() { + when(jdbc.queryForList(contains("user_access_policy"), any(Object[].class))).thenReturn(List.of(Map.of("allowed_fields","private-field"))); + var first = controller.state(actor(List.of("A","B"))); + assertEquals(first, controller.state(actor(List.of("B","A")))); + assertTrue(first.values().stream().allMatch(value -> value.matches("[a-f0-9]{64}"))); + assertFalse(first.toString().contains("private-field")); + verify(access,times(2)).requireUserActivePolicy(any()); + } + @Test void permissionAndTargetChangesInvalidateSeparateDependencies() { + var before = controller.state(actor(List.of("A"))); + var scoped = controller.state(actor(List.of("B"))); + assertNotEquals(before.get("authRevision"),scoped.get("authRevision")); + assertEquals(before.get("dataRevision"),scoped.get("dataRevision")); + when(jdbc.queryForList(contains("target_version"))).thenReturn(List.of(Map.of("id","target","row_version",2))); + var target = controller.state(actor(List.of("A"))); + assertEquals(before.get("authRevision"),target.get("authRevision")); + assertNotEquals(before.get("dataRevision"),target.get("dataRevision")); + verify(jdbc,never()).queryForList(contains("fact_")); + } + @Test void expiredAuthorizationStopsBeforeLoadingCacheMetadata() { + var actor=actor(List.of("A")); + doThrow(new IllegalStateException("expired")).when(access).requireUserActivePolicy(actor); + assertThrows(IllegalStateException.class,()->controller.state(actor)); + verifyNoInteractions(jdbc); + } +} diff --git a/web/src/AnalysisApiSettings.tsx b/web/src/AnalysisApiSettings.tsx index 56611fa..5b998b8 100644 --- a/web/src/AnalysisApiSettings.tsx +++ b/web/src/AnalysisApiSettings.tsx @@ -1,3 +1,4 @@ +import { usePageCache } from './pageCache'; import { useRef, useState } from 'react'; import { Alert, App, Button, Form, Input, Modal, Select, Spin, Tag } from 'antd'; import { SettingOutlined } from '@ant-design/icons'; @@ -10,6 +11,7 @@ export type AnalysisModelSettingsInput = { baseUrl: string; model: string; apiKe export function AnalysisApiSettings({ onUnauthorized }: { onUnauthorized: (error: unknown) => boolean }) { const { message } = App.useApp(); const [form] = Form.useForm(); + const { active } = usePageCache(); const [open, setOpen] = useState(false); const [loading, setLoading] = useState(false); const [saving, setSaving] = useState(false); @@ -54,7 +56,7 @@ export function AnalysisApiSettings({ onUnauthorized }: { onUnauthorized: (error }; return <> - + diff --git a/web/src/CachedWorkspacePages.tsx b/web/src/CachedWorkspacePages.tsx new file mode 100644 index 0000000..43305a9 --- /dev/null +++ b/web/src/CachedWorkspacePages.tsx @@ -0,0 +1,97 @@ +import { forwardRef, lazy, Suspense, useEffect, useImperativeHandle, useLayoutEffect, useRef, useState } from 'react'; +import { Alert, Button, Spin } from 'antd'; +import { api } from './api'; +import type { AuthUser, QueryParams } from './types'; +import type { PageKey } from './QualityWorkspace'; +import { PageCacheContext, WORKSPACE_INVALIDATED } from './pageCache'; + +const QueryPage = lazy(() => import('./QueryPage')); +const ManagementPages = lazy(() => import('./ManagementPages')); +const QUERY_PAGES: PageKey[] = ['overall', 'department', 'group', 'product']; +const retained = (page: PageKey) => QUERY_PAGES.includes(page) || page === 'analysis'; +type ResultRef = { kind: 'TOP'; resultId: string; releaseId: string }; +type Entry = { initialSearch: string; search: string; key: number; scroll: number }; +export type WorkspaceNavigation = { navigate: (page: PageKey, query?: QueryParams, resultRef?: ResultRef) => void; syncLocation: () => void }; +function encode(value: unknown) { + const bytes = new TextEncoder().encode(JSON.stringify(value)); + return btoa(Array.from(bytes, byte => String.fromCharCode(byte)).join('')).replace(/=/g, '').replace(/\+/g, '-').replace(/\//g, '_'); +} + +export const CachedWorkspacePages = forwardRef void; onUserChange: (user: AuthUser) => void; onUnauthorized: (error: unknown) => boolean; +}>(function CachedWorkspacePages({ page, user, onPageChange, onUserChange, onUnauthorized }, ref) { + const entries = useRef(new Map([[page, { initialSearch: location.search, search: location.search, key: 0, scroll: 0 }]])); + const current = useRef(page), generation = useRef(0), key = useRef(0); + const revisions = useRef<{ authRevision: string; dataRevision: string } | null>(null); + const [refreshKey, setRefreshKey] = useState(0), [, render] = useState(0); + const [ready, setReady] = useState(false), [error, setError] = useState(''); + const alive = useRef(true); + const validate = async (currentSelection = () => true) => { + const state = await api.workspaceState(); + if (!alive.current || !currentSelection()) return false; + if (revisions.current && state.authRevision !== revisions.current.authRevision) { + // 权限改变后销毁旧缓存,服务端随后按最新身份重新查询。 + const latest = await api.me(); + if (!alive.current || !currentSelection()) return false; + onUserChange(latest); entries.current.clear(); + } + if (revisions.current && state.dataRevision !== revisions.current.dataRevision) setRefreshKey(value => value + 1); + revisions.current = state; + return true; + }; + const remember = (updateSearch = true) => { + const entry = entries.current.get(current.current); + if (entry) { if (updateSearch) entry.search = location.search; entry.scroll = window.scrollY; } + }; + const enter = async (next: PageKey, search: string, force = false, pop = false) => { + remember(!pop); + const selection = ++generation.current; + try { + if (!await validate(() => generation.current === selection) || generation.current !== selection) return; + const previous = entries.current.get(next); + if (!previous || force) entries.current.set(next, { initialSearch: search, search, key: ++key.current, scroll: 0 }); + const entry = entries.current.get(next)!; + if (!pop) history.pushState({}, '', `${location.pathname}${entry.search}`); + current.current = next; setError(''); onPageChange(next); render(value => value + 1); + } catch (value) { + if (alive.current && generation.current === selection && !onUnauthorized(value)) setError(value instanceof Error ? value.message : '页面状态校验失败,请重试'); + } + }; + const navigate = (next: PageKey, query?: QueryParams, resultRef?: ResultRef) => { + if (next === 'imports') next = 'sources'; + if (next === current.current && !query && !resultRef) return; + const params = new URLSearchParams({ page: next }); + if (query) params.set('context', encode({ query, ...(resultRef ? { resultRef } : {}) })); + const cached = entries.current.get(next); + void enter(next, query || resultRef || !cached ? `?${params}` : cached.search, Boolean(query || resultRef) || !retained(next)); + }; + useImperativeHandle(ref, () => ({ navigate, syncLocation: () => { + const next = new URLSearchParams(location.search).get('page') as PageKey || 'overall'; + const entry = entries.current.get(next); + void enter(next, location.search, !entry || entry.search !== location.search, true); + } })); + useEffect(() => { + alive.current = true; + void validate().then(ok => { if (ok) setReady(true); }).catch(value => { if (alive.current && !onUnauthorized(value)) setError(String(value)); }); + const invalidate = () => setRefreshKey(value => value + 1); + window.addEventListener(WORKSPACE_INVALIDATED, invalidate); + return () => { alive.current = false; generation.current++; window.removeEventListener(WORKSPACE_INVALIDATED, invalidate); }; + }, []); + useLayoutEffect(() => { + if (!ready) return; + const frame = requestAnimationFrame(() => window.scrollTo(0, entries.current.get(page)?.scroll || 0)); + return () => cancelAnimationFrame(frame); + }, [page, ready]); + if (error) return location.reload()}>重新连接} />; + if (!ready) return
正在打开工作台…
; + return <>{Array.from(entries.current.entries()).filter(([name]) => retained(name) || name === page).map(([name, entry]) => { + const active = name === page; + return }> + {QUERY_PAGES.includes(name) ? : } + + + ; + })}; +}); diff --git a/web/src/ManagementPages.tsx b/web/src/ManagementPages.tsx index 454ddd2..d40058c 100644 --- a/web/src/ManagementPages.tsx +++ b/web/src/ManagementPages.tsx @@ -1,3 +1,4 @@ +import { usePageCache } from './pageCache'; import { FilterFieldSettings } from './FilterFieldSettings'; import { isInternalDataField, publicJson } from './publicDataDisplay'; import { useCallback, useEffect, useMemo, useRef, useState } from 'react'; @@ -951,10 +952,12 @@ function AnalysisPage({ onUnauthorized, user }: { onUnauthorized: (error: unknow const [renameTarget, setRenameTarget] = useState | null>(null); const [renameTitle, setRenameTitle] = useState(''); const [renaming, setRenaming] = useState(false); - const initialParams = new URLSearchParams(window.location.search); + const { active, initialSearch, refreshKey, onLocationChange } = usePageCache(); + const activePage = useRef(active); activePage.current = active; + const initialParams = new URLSearchParams(initialSearch ?? window.location.search); const initialSessionId = initialParams.get('sessionId') || ''; const initialTurnId = initialParams.get('turnId') || ''; - const [initialLink] = useState(() => decodeAnalysisLinkContext(new URLSearchParams(window.location.search).get('context'))); + const [initialLink] = useState(() => decodeAnalysisLinkContext(initialParams.get('context'))); const [query, setQuery] = useState(''); const [sessionId, setSessionId] = useState(initialSessionId); const [sessionContext, setSessionContext] = useState | null>(null); @@ -979,14 +982,19 @@ function AnalysisPage({ onUnauthorized, user }: { onUnauthorized: (error: unknow const conversation = useRef(null); const followOutput = useRef(true); const previousScrollTop = useRef(0); + const readingPosition = useRef(0); + useEffect(() => { + const element = conversation.current; + if (active && element) element.scrollTop = followOutput.current ? element.scrollHeight : readingPosition.current; + }, [active]); useEffect(() => { followOutput.current = true; previousScrollTop.current = 0; }, [sessionId]); useEffect(() => { const element = conversation.current; - if (element && followOutput.current) { + if (active && element && followOutput.current) { element.scrollTop = element.scrollHeight; previousScrollTop.current = element.scrollTop; } - }, [lastTurn, busy, turns, sessionId]); + }, [lastTurn, busy, turns, sessionId, active]); const loadSessions = async () => { try { const items = collectionItems(await api.analysisSessions()); if (mounted.current) setSessions(items); } @@ -1079,14 +1087,26 @@ function AnalysisPage({ onUnauthorized, user }: { onUnauthorized: (error: unknow const writeAnalysisLocation = (selectedSessionId?: string, selectedTurnId?: string) => { if (!mounted.current) return; if (selectedSessionId) rememberAnalysisSession(user.id, selectedSessionId); + if (!activePage.current) return; const url = new URL(window.location.href); url.searchParams.set('page', 'analysis'); if (selectedSessionId) url.searchParams.set('sessionId', selectedSessionId); else url.searchParams.delete('sessionId'); if (selectedTurnId) url.searchParams.set('turnId', selectedTurnId); else url.searchParams.delete('turnId'); url.searchParams.delete('context'); window.history.replaceState({}, '', `${url.pathname}${url.search}${url.hash}`); + onLocationChange(url.search); }; + useEffect(() => { + if (active && !historyLoading) writeAnalysisLocation(sessionId || undefined, activeTurnId || undefined); + }, [active, historyLoading, sessionId, activeTurnId]); + const refreshSeen = useRef(refreshKey); + useEffect(() => { + if (!active || refreshSeen.current === refreshKey) return; + refreshSeen.current = refreshKey; void loadSessions(); + if (sessionId && !busy) void openSession(sessionId); + }, [active, refreshKey]); + const openSession = async (id: string, focusTurnId?: string): Promise => { userSelectionMade.current = true; beginAnalysisSelection(user.id); @@ -1259,7 +1279,7 @@ function AnalysisPage({ onUnauthorized, user }: { onUnauthorized: (error: unknow const settledTurn = settledAnalysisTurn(id, question, detail, streamedResult, terminalEventStatus); setLastTurn(settledTurn); if (ANALYSIS_FINAL_STATUSES.has(String(settledTurn.status || '').toUpperCase())) { - setRetryQuestion(''); setQuery(''); + setRetryQuestion(''); const parentSessionId = sessionOverride || sessionId; if (parentSessionId) { try { @@ -1438,10 +1458,12 @@ function AnalysisPage({ onUnauthorized, user }: { onUnauthorized: (error: unknow
{ if (event.deltaY < 0 && event.currentTarget.scrollTop > 0) followOutput.current = false; }} onScroll={event => { + if (!activePage.current) return; const element = event.currentTarget; followOutput.current = analysisScrollFollows(previousScrollTop.current, element.scrollTop, element.scrollHeight - element.clientHeight - element.scrollTop, followOutput.current); previousScrollTop.current = element.scrollTop; + readingPosition.current = element.scrollTop; }}> {turns.map((turn, index) => void retryTurn(turns.find(item => String(item.id || '') === id) || turn)} onResume={id => { if (!historyLoading) void followTurn(id, String(turn.question || '')); }} onGenerateReport={() => void submit(generateReportPrompt(turn))} retryDisabled={busy || historyLoading} />)} {lastTurn && void retryTurn(lastTurn)} onResume={id => { if (!historyLoading) void followTurn(id, String(lastTurn.question || '')); }} onGenerateReport={() => void submit(generateReportPrompt(lastTurn))} retryDisabled={busy || historyLoading} />} diff --git a/web/src/QualityWorkspace.tsx b/web/src/QualityWorkspace.tsx index 9737bb9..a2e9cd0 100644 --- a/web/src/QualityWorkspace.tsx +++ b/web/src/QualityWorkspace.tsx @@ -1,4 +1,4 @@ -import { lazy, Suspense, useCallback, useEffect, useState, type ReactNode } from 'react'; +import { useCallback, useEffect, useRef, useState } from 'react'; import { Alert, App, @@ -34,8 +34,7 @@ import { workspaceThemes, type WorkspaceThemeId } from './ui-themes'; import { readableSelectPopup } from './readableSelectPopup'; import PersonalAccount, { type AccountTab } from './PersonalAccount'; -const QueryPage = lazy(() => import('./QueryPage')); -const ManagementPages = lazy(() => import('./ManagementPages')); +import { CachedWorkspacePages, type WorkspaceNavigation } from './CachedWorkspacePages'; export type PageKey = 'overall' | 'department' | 'group' | 'product' | 'basis' | 'analysis' | 'sources' | 'imports' | 'rules' | 'mappings' | 'masterData' | 'tasks' | 'access'; @@ -99,10 +98,6 @@ function shownDepartment(value: string): string { return value === '质量管理部' ? '质量中心' : value; } -function PageReveal({ page, children }: { page: PageKey; children: ReactNode }) { - return
{children}
; -} - type QualityWorkspaceProps = { appearance: (typeof workspaceThemes)[number]; onAppearanceChange: (themeId: WorkspaceThemeId) => void; @@ -115,6 +110,7 @@ export default function QualityWorkspace({ appearance, onAppearanceChange }: Qua const [sessionLoading, setSessionLoading] = useState(true); const [sessionError, setSessionError] = useState(''); const [accountTab, setAccountTab] = useState(null); + const workspaceNavigation = useRef(null); useEffect(() => { const syncFromLocation = () => { @@ -125,7 +121,7 @@ export default function QualityWorkspace({ appearance, onAppearanceChange }: Qua url.searchParams.set('page', currentPage === 'basis' ? 'overall' : currentPage === 'scrap' ? 'product' : 'sources'); window.history.replaceState({}, '', `${url.pathname}${url.search}${url.hash}`); } - setPage(pageFromLocation()); + if (workspaceNavigation.current) workspaceNavigation.current.syncLocation(); else setPage(pageFromLocation()); }; syncFromLocation(); window.addEventListener('popstate', syncFromLocation); @@ -153,6 +149,7 @@ export default function QualityWorkspace({ appearance, onAppearanceChange }: Qua }, []); const navigate = (next: PageKey, query?: QueryParams, resultRef?: TopResultRef) => { + if (workspaceNavigation.current) { workspaceNavigation.current.navigate(next, query, resultRef); return; } const url = new URL(window.location.href); if (next === 'imports') { next = 'sources'; url.searchParams.set('showImportHistory', '1'); } else url.searchParams.delete('showImportHistory'); @@ -259,13 +256,7 @@ export default function QualityWorkspace({ appearance, onAppearanceChange }: Qua
- 正在打开页面…
}> - - {['overall', 'department', 'group', 'product'].includes(page) - ? - : } - - + setAccountTab(null)} onUserChange={setUser} diff --git a/web/src/QueryPage.tsx b/web/src/QueryPage.tsx index 569c394..516e6eb 100644 --- a/web/src/QueryPage.tsx +++ b/web/src/QueryPage.tsx @@ -1,3 +1,4 @@ +import { usePageCache } from './pageCache'; import { useCallback, useEffect, useLayoutEffect, useMemo, useRef, useState } from 'react'; import * as echarts from 'echarts/core'; import { BarChart, LineChart } from 'echarts/charts'; @@ -202,8 +203,8 @@ function escapeTooltipText(value: string): string { return value.replace(/[&<>"']/g, character => ({ '&': '&', '<': '<', '>': '>', '"': '"', "'": ''' })[character]!); } -function queryFromLocation(): Partial { - const context = new URLSearchParams(window.location.search).get('context'); +function queryFromLocation(search = window.location.search): Partial { + const context = new URLSearchParams(search).get('context'); if (!context) return {}; try { const binary = atob(context.replace(/-/g, '+').replace(/_/g, '/') + '='.repeat((4 - context.length % 4) % 4)); @@ -266,11 +267,11 @@ export default function QueryPage({ page, onUnauthorized }: { onNavigate?: (page: PageKey, query: QueryParams, resultRef?: TopResultRef) => void; }) { const { message } = App.useApp(); + const { active, initialSearch, refreshKey, onLocationChange } = usePageCache(); const baseView = SCOPE[page] || 'overall'; - const initialQuery = queryFromLocation(); + const [initialQuery] = useState(() => queryFromLocation(initialSearch)); const [viewOverrideState, setViewOverrideState] = useState<{ page: PageKey; view: ViewKind } | undefined>(() => initialQuery.view && initialQuery.view !== baseView ? { page, view: initialQuery.view } : undefined); - const routeViewOverride = initialQuery.view && initialQuery.view !== baseView ? initialQuery.view : undefined; - const viewOverride = routeViewOverride || (viewOverrideState?.page === page ? viewOverrideState.view : undefined); + const viewOverride = viewOverrideState?.page === page ? viewOverrideState.view : undefined; const setViewOverride = (next?: ViewKind) => setViewOverrideState(next ? { page, view: next } : undefined); const view = viewOverride || baseView; const scopeName = viewOverride ? ({ overall: '总体', department: '产业部', group: '产业部-业务分组', product: '产品', projectGroup: '项目组' } as Record)[viewOverride] : SCOPE_NAMES[page] || '总体'; @@ -290,8 +291,8 @@ export default function QueryPage({ page, onUnauthorized }: { const [extraFilters, setExtraFilters] = useState>(initialQuery.extraFilters || {}); const [includeUnassigned, setIncludeUnassigned] = useState(initialQuery.includeUnassigned === true); const [trendGranularity, setTrendGranularity] = useState<'month' | 'quarter' | 'year'>(initialQuery.trendGranularity || (initialQuery.quarter ? 'quarter' : 'month')); - const [search, setSearch] = useState(''); - const [appliedSearch, setAppliedSearch] = useState(''); + const [search, setSearch] = useState(initialQuery.productSearch || ''); + const [appliedSearch, setAppliedSearch] = useState(initialQuery.productSearch || ''); const [fullFields, setFullFields] = useState(false); const [data, setData] = useState(null); const [dataKey, setDataKey] = useState(''); @@ -319,17 +320,15 @@ export default function QueryPage({ page, onUnauthorized }: { const [basisOpen, setBasisOpen] = useState(false); const trendAnchorTop = useRef(null); const tableContent = useRef(null); + const trendSection = useRef(null); + const refreshSeen = useRef(refreshKey); + useEffect(() => { + if (active && refreshSeen.current !== refreshKey) { refreshSeen.current = refreshKey; setQueryRevision(value => value + 1); } + if (!active) { setRecordsOpen(false); setBasisOpen(false); } + }, [active, refreshKey]); const tableHeight = useRef(525); - useEffect(() => { - setTrendObject(''); - setDrilledProduct(''); - setSearch(''); - setAppliedSearch(''); - setViewOverrideState(undefined); - setRecordsOpen(false); - setSelectedRecord(null); - }, [page]); + useEffect(() => { let alive = true; @@ -344,7 +343,7 @@ export default function QueryPage({ page, onUnauthorized }: { if (alive) setOptionsError(chooseError(errorValue)); }).finally(() => { if (alive) setOptionsLoading(false); }); return () => { alive = false; }; - }, [onUnauthorized]); + }, [onUnauthorized, queryRevision]); const allowedGroups = useMemo(() => { const parents = new Set(department); @@ -406,6 +405,7 @@ export default function QueryPage({ page, onUnauthorized }: { trendKeyRef.current = trendKey; useEffect(() => { + if (!active) return; const url = new URL(window.location.href); if (!['overall', 'department', 'group', 'product'].includes(url.searchParams.get('page') || '')) return; const bytes = new TextEncoder().encode(JSON.stringify({ query: queryParams })); @@ -414,7 +414,8 @@ export default function QueryPage({ page, onUnauthorized }: { const context = btoa(binary).replace(/=/g, '').replace(/\+/g, '-').replace(/\//g, '_'); url.searchParams.set('context', context); window.history.replaceState(window.history.state, '', `${url.pathname}${url.search}${url.hash}`); - }, [queryKey]); + onLocationChange(url.search); + }, [queryKey, active]); useEffect(() => { const controller = new AbortController(); @@ -498,7 +499,7 @@ export default function QueryPage({ page, onUnauthorized }: { } }); return () => { alive = false; }; - }, [trendKey, onUnauthorized]); + }, [trendKey, queryRevision, onUnauthorized]); const currentTrendTarget = trendTargetKey === trendKey ? trendTarget : null; const visibleTrendData = useMemo(() => fullYearTrend(trendDataKey === trendKey ? trendData : [], year, trendGranularity), [trendData, trendDataKey, trendKey, year, trendGranularity]); @@ -546,7 +547,7 @@ export default function QueryPage({ page, onUnauthorized }: { setRecordsOpen(true); }, []); const captureTrendAnchor = useCallback(() => { - trendAnchorTop.current = document.getElementById('monthly-trend')?.getBoundingClientRect().top ?? null; + trendAnchorTop.current = trendSection.current?.getBoundingClientRect().top ?? null; }, []); const selectTrendPeriod = useCallback((value: number | string) => { const raw = String(value); @@ -581,8 +582,8 @@ export default function QueryPage({ page, onUnauthorized }: { }, [period, year, month, quarter, captureTrendAnchor]); useLayoutEffect(() => { - if (trendAnchorTop.current == null) return; - const nextTop = document.getElementById('monthly-trend')?.getBoundingClientRect().top; + if (!active || trendAnchorTop.current == null) return; + const nextTop = trendSection.current?.getBoundingClientRect().top; if (nextTop != null) window.scrollBy(0, nextTop - trendAnchorTop.current); // Keep the anchor through the response as the new result may have a // different row count. Clearing it at request start allowed a second jump. @@ -698,7 +699,7 @@ export default function QueryPage({ page, onUnauthorized }: { {filterSelect('业务分组', group, allowedGroups, values => { setGroup(values); setProduct([]); }, !department.length)} {filterSelect('产品', product, department.length || group.length ? organizationPathOptions.products : options?.products, setProduct)} - + setIncludeUnassigned(event.target.checked)}>包含未分类行
{queryBusy ? '正在查询' : currentMetricsError ? '查询失败' : '查询完成'} @@ -737,6 +738,7 @@ export default function QueryPage({ page, onUnauthorized }: { setFullFields(value === 'full')} aria-label="字段显示" /> } {drilledProduct && }
@@ -771,8 +773,8 @@ export default function QueryPage({ page, onUnauthorized }: { emptyText={queryBusy ? '正在更新数据…' : currentMetricsError ? '查询失败,暂无可展示结果' : '当前条件下暂无数据'} onDrilldown={row => { if (view === 'overall') setViewOverride('department'); - else if (view === 'department' && row.department) { setDepartment([row.department]); setViewOverride('group'); } - else if (view === 'group' && row.group) { setGroup([row.group]); setViewOverride('product'); } + else if (view === 'department' && row.department) { setSearch(''); setAppliedSearch(''); setTrendObject(''); setGroup([]); setProduct([]); setDepartment([row.department]); setViewOverride('group'); } + else if (view === 'group' && row.group) { setSearch(''); setAppliedSearch(''); setTrendObject(''); setProduct([]); setGroup([row.group]); setViewOverride('product'); } else if (view === 'product') { const selectedProduct = row.product || row.label; if (!selectedProduct) return; @@ -789,7 +791,7 @@ export default function QueryPage({ page, onUnauthorized }: {
-
+
setTrendMode(value as typeof trendMode)} aria-label="趋势视图" /> @@ -828,7 +830,7 @@ export default function QueryPage({ page, onUnauthorized }: {
; })}
- {currentMetricsData ? item.name === '外废')?.weight} onUnauthorized={onUnauthorized} /> :
{queryBusy ? '正在更新不良数据…' : '不良数据暂不可用'}
} + {currentMetricsData ? item.name === '外废')?.weight} onUnauthorized={onUnauthorized} /> :
{queryBusy ? '正在更新不良数据…' : '不良数据暂不可用'}
} diff --git a/web/src/api.ts b/web/src/api.ts index b018df7..49e2a3c 100644 --- a/web/src/api.ts +++ b/web/src/api.ts @@ -1,3 +1,4 @@ +import { WORKSPACE_INVALIDATED } from './pageCache'; import { consumeEventStream, type StreamEvent } from './eventStream'; import { publicErrorMessage } from './publicDataDisplay'; import type { @@ -120,11 +121,13 @@ export async function refreshCsrf(): Promise { async function mutate(path: string, body?: unknown, method = 'POST'): Promise { const token = csrfToken ?? await refreshCsrf(); const headers = new Headers({ 'X-XSRF-TOKEN': token }); - return request(path, { + const result = await request(path, { method, headers, ...(body === undefined ? {} : { body: JSON.stringify(body) }), }); + if (!/^\/api\/(?:analysis|auth)(?:\/|$)/.test(path)) window.dispatchEvent(new Event(WORKSPACE_INVALIDATED)); + return result; } async function queryPost(path: string, body: unknown, signal?: AbortSignal): Promise { @@ -134,10 +137,13 @@ async function queryPost(path: string, body: unknown, signal?: AbortSignal): async function mutateForm(path: string, body: FormData): Promise { const token = csrfToken ?? await refreshCsrf(); - return request(path, { method: 'POST', headers: { 'X-XSRF-TOKEN': token }, body }); + const result = await request(path, { method: 'POST', headers: { 'X-XSRF-TOKEN': token }, body }); + window.dispatchEvent(new Event(WORKSPACE_INVALIDATED)); + return result; } export const api = { + workspaceState() { return request<{ authRevision: string; dataRevision: string }>('/api/workspace/state'); }, filterFields(manage = false) { return request(`/api/filter-fields?manage=${manage}`); }, filterFieldOptions(key: string, search = '') { return request<{ values: string[]; hasMore: boolean }>(`/api/filter-fields/options?${toQuery({key, search})}`); }, filterFieldColumns() { return request<{ black: string[]; bright: string[] }>('/api/filter-fields/columns'); }, diff --git a/web/src/pageCache.tsx b/web/src/pageCache.tsx new file mode 100644 index 0000000..f7ebb75 --- /dev/null +++ b/web/src/pageCache.tsx @@ -0,0 +1,5 @@ +import { createContext, useContext } from 'react'; + +export const WORKSPACE_INVALIDATED = 'quality-workspace-invalidated'; +export const PageCacheContext = createContext({ active: true, initialSearch: undefined as string | undefined, refreshKey: 0, onLocationChange: (_search: string) => {} }); +export const usePageCache = () => useContext(PageCacheContext);