优化:缓存查询与智能分析页面,修复组织下钻和草稿保留
This commit is contained in:
@@ -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<String, String> 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); }
|
||||
}
|
||||
}
|
||||
@@ -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<String> 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);
|
||||
}
|
||||
}
|
||||
@@ -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<AnalysisModelSettingsInput>();
|
||||
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 <>
|
||||
<Button type="text" size="small" icon={<SettingOutlined />} onClick={() => void load()}>API 配置</Button>
|
||||
<Modal title="API 配置" open={open} width={540} onCancel={close} footer={<>
|
||||
<Modal title="API 配置" open={active && open} width={540} onCancel={close} footer={<>
|
||||
<Button onClick={close} disabled={saving}>关闭</Button>
|
||||
<Button loading={testing} disabled={loading || saving || !settings} onClick={() => void submit(true)}>测试连接</Button>
|
||||
<Button type="primary" loading={saving} disabled={loading || testing || !settings} onClick={() => void submit(false)}>保存并使用</Button>
|
||||
|
||||
@@ -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<WorkspaceNavigation, {
|
||||
page: PageKey; user: AuthUser; onPageChange: (page: PageKey) => void; onUserChange: (user: AuthUser) => void; onUnauthorized: (error: unknown) => boolean;
|
||||
}>(function CachedWorkspacePages({ page, user, onPageChange, onUserChange, onUnauthorized }, ref) {
|
||||
const entries = useRef(new Map<PageKey, Entry>([[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 <Alert type="error" showIcon message="页面暂不可用" description={error} action={<Button onClick={() => location.reload()}>重新连接</Button>} />;
|
||||
if (!ready) return <div className="loading-panel"><Spin />正在打开工作台…</div>;
|
||||
return <>{Array.from(entries.current.entries()).filter(([name]) => retained(name) || name === page).map(([name, entry]) => {
|
||||
const active = name === page;
|
||||
return <div key={`${name}-${entry.key}`} className="page-view" data-page={name} hidden={!active} style={!active ? { display: 'none' } : undefined}>
|
||||
<PageCacheContext.Provider value={{ active, initialSearch: entry.initialSearch, refreshKey, onLocationChange: search => { entry.search = search; } }}>
|
||||
<Suspense fallback={<div className="loading-panel"><Spin />正在打开页面…</div>}>
|
||||
{QUERY_PAGES.includes(name) ? <QueryPage page={name} onUnauthorized={onUnauthorized} onNavigate={navigate} /> : <ManagementPages page={name} user={user} onUnauthorized={onUnauthorized} onNavigate={navigate} />}
|
||||
</Suspense>
|
||||
</PageCacheContext.Provider>
|
||||
</div>;
|
||||
})}</>;
|
||||
});
|
||||
@@ -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<Record<string, unknown> | 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<Record<string, unknown> | null>(null);
|
||||
@@ -979,14 +982,19 @@ function AnalysisPage({ onUnauthorized, user }: { onUnauthorized: (error: unknow
|
||||
const conversation = useRef<HTMLDivElement>(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<boolean> => {
|
||||
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
|
||||
<div className="analysis-conversation" ref={conversation} aria-live="polite" onWheel={event => {
|
||||
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) => <AnalysisTurn key={String(turn.id || index)} turn={turn} onRetry={(id) => 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 && <AnalysisTurn turn={lastTurn} onRetry={() => void retryTurn(lastTurn)} onResume={id => { if (!historyLoading) void followTurn(id, String(lastTurn.question || '')); }} onGenerateReport={() => void submit(generateReportPrompt(lastTurn))} retryDisabled={busy || historyLoading} />}
|
||||
|
||||
@@ -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 <div className="page-view" data-page={page}>{children}</div>;
|
||||
}
|
||||
|
||||
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<AccountTab | null>(null);
|
||||
const workspaceNavigation = useRef<WorkspaceNavigation>(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
|
||||
<Button type="text" icon={<UserOutlined />} aria-label="打开个人账户" onClick={() => setAccountTab('profile')} />
|
||||
</div>
|
||||
<div className="page-content">
|
||||
<Suspense fallback={<div className="loading-panel"><Spin />正在打开页面…</div>}>
|
||||
<PageReveal page={page}>
|
||||
{['overall', 'department', 'group', 'product'].includes(page)
|
||||
? <QueryPage page={page} onUnauthorized={handleUnauthorized} onNavigate={navigate} />
|
||||
: <ManagementPages page={page} user={user} onUnauthorized={handleUnauthorized} onNavigate={navigate} />}
|
||||
</PageReveal>
|
||||
</Suspense>
|
||||
<CachedWorkspacePages ref={workspaceNavigation} page={page} user={user} onPageChange={setPage} onUserChange={setUser} onUnauthorized={handleUnauthorized} />
|
||||
</div>
|
||||
</main>
|
||||
<PersonalAccount user={user} tab={accountTab} onClose={() => setAccountTab(null)} onUserChange={setUser}
|
||||
|
||||
+29
-27
@@ -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<QueryParams> {
|
||||
const context = new URLSearchParams(window.location.search).get('context');
|
||||
function queryFromLocation(search = window.location.search): Partial<QueryParams> {
|
||||
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<ViewKind, string>)[viewOverride] : SCOPE_NAMES[page] || '总体';
|
||||
@@ -290,8 +291,8 @@ export default function QueryPage({ page, onUnauthorized }: {
|
||||
const [extraFilters, setExtraFilters] = useState<Record<string,string[]>>(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<MetricsResponse | null>(null);
|
||||
const [dataKey, setDataKey] = useState('');
|
||||
@@ -319,17 +320,15 @@ export default function QueryPage({ page, onUnauthorized }: {
|
||||
const [basisOpen, setBasisOpen] = useState(false);
|
||||
const trendAnchorTop = useRef<number | null>(null);
|
||||
const tableContent = useRef<HTMLDivElement>(null);
|
||||
const trendSection = useRef<HTMLElement>(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)}
|
||||
|
||||
<ExtraQueryFilters projectGroup={projectGroup} projectGroups={options?.projectGroupStatus === 'READY' ? options.projectGroups : undefined} onProjectGroup={setProjectGroup} value={extraFilters} onChange={setExtraFilters} onUnauthorized={onUnauthorized} />
|
||||
<ExtraQueryFilters key={queryRevision} projectGroup={projectGroup} projectGroups={options?.projectGroupStatus === 'READY' ? options.projectGroups : undefined} onProjectGroup={setProjectGroup} value={extraFilters} onChange={setExtraFilters} onUnauthorized={onUnauthorized} />
|
||||
<Checkbox className="query-unassigned" checked={includeUnassigned} onChange={event => setIncludeUnassigned(event.target.checked)}>包含未分类行</Checkbox>
|
||||
<div className="query-toolbar-tail">
|
||||
<span className={`query-status ${queryBusy ? 'busy' : currentMetricsError ? 'failed' : ''}`}><i />{queryBusy ? '正在查询' : currentMetricsError ? '查询失败' : '查询完成'}</span>
|
||||
@@ -737,6 +738,7 @@ export default function QueryPage({ page, onUnauthorized }: {
|
||||
<Button type="primary" disabled={Boolean(drilledProduct)} onClick={() => applySearch()} aria-label="开始搜索">搜索</Button>
|
||||
<Segmented value={fullFields ? 'full' : 'key'} options={[{ label: '关键指标', value: 'key' }, { label: '完整字段', value: 'full' }]} onChange={value => setFullFields(value === 'full')} aria-label="字段显示" />
|
||||
<Tooltip title="点击综合合格率可查看计算依据"><Button type="text" icon={<InfoCircleOutlined />} aria-label="查看计算依据" onClick={() => setBasisOpen(true)} /></Tooltip>
|
||||
{!drilledProduct && (view === 'group' || view === 'product' && (group.length > 0 || department.length > 0)) && <Button onClick={() => { setSearch(''); setAppliedSearch(''); setTrendObject(''); if (view === 'product') { setProduct([]); setGroup([]); setViewOverride('group'); } else { setGroup([]); setDepartment([]); setViewOverride('department'); } }}>{view === 'product' ? '返回业务分组' : '返回产业部'}</Button>}
|
||||
{drilledProduct && <Button onClick={() => { setDrilledProduct(''); setTrendObject(''); setTrendMode('production'); }}>返回产品汇总</Button>}
|
||||
</div>
|
||||
</div>
|
||||
@@ -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 }: {
|
||||
</section>
|
||||
|
||||
<div className="analysis-stack">
|
||||
<section className="panel section-panel trend-panel" id="monthly-trend">
|
||||
<section className="panel section-panel trend-panel" ref={trendSection} id={active ? 'monthly-trend' : undefined}>
|
||||
<div className="section-heading-row trend-heading-row">
|
||||
<SectionHeading title={`${trendGranularity === 'month' ? '月度' : trendGranularity === 'quarter' ? '季度' : '年度'}变化趋势`} subtitle={`${trendGranularity === 'year' ? '全部实际数据年份' : `${year} 年`} · ${trendObject || `当前${scopeName}筛选`}`} />
|
||||
<Segmented value={trendMode} options={[{ label: '合格率与产量', value: 'production' }, { label: '不良率', value: 'defects' }, { label: `${trendGranularity === 'quarter' ? '季度' : trendGranularity === 'year' ? '年度' : '月度'}数据`, value: 'data' }]} onChange={value => setTrendMode(value as typeof trendMode)} aria-label="趋势视图" />
|
||||
@@ -828,7 +830,7 @@ export default function QueryPage({ page, onUnauthorized }: {
|
||||
</section>;
|
||||
})}
|
||||
</div>
|
||||
{currentMetricsData ? <DefectParetoPanel key={defectQueryKey} releaseId={currentMetricsData.release?.id} query={defectQueryParams} externalScrapWeight={blackDefectItems.find(item => item.name === '外废')?.weight} onUnauthorized={onUnauthorized} /> : <div className="defect-pareto-status">{queryBusy ? '正在更新不良数据…' : '不良数据暂不可用'}</div>}
|
||||
{currentMetricsData ? <DefectParetoPanel key={`${currentMetricsData.release?.id}:${defectQueryKey}:${queryRevision}`} releaseId={currentMetricsData.release?.id} query={defectQueryParams} externalScrapWeight={blackDefectItems.find(item => item.name === '外废')?.weight} onUnauthorized={onUnauthorized} /> : <div className="defect-pareto-status">{queryBusy ? '正在更新不良数据…' : '不良数据暂不可用'}</div>}
|
||||
</section>
|
||||
</div>
|
||||
</>
|
||||
|
||||
+8
-2
@@ -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<string> {
|
||||
async function mutate<T>(path: string, body?: unknown, method = 'POST'): Promise<T> {
|
||||
const token = csrfToken ?? await refreshCsrf();
|
||||
const headers = new Headers({ 'X-XSRF-TOKEN': token });
|
||||
return request<T>(path, {
|
||||
const result = await request<T>(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<T>(path: string, body: unknown, signal?: AbortSignal): Promise<T> {
|
||||
@@ -134,10 +137,13 @@ async function queryPost<T>(path: string, body: unknown, signal?: AbortSignal):
|
||||
|
||||
async function mutateForm<T>(path: string, body: FormData): Promise<T> {
|
||||
const token = csrfToken ?? await refreshCsrf();
|
||||
return request<T>(path, { method: 'POST', headers: { 'X-XSRF-TOKEN': token }, body });
|
||||
const result = await request<T>(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<FilterField[]>(`/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'); },
|
||||
|
||||
@@ -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);
|
||||
Reference in New Issue
Block a user