feat: add customer authentication and scoped RBAC

This commit is contained in:
lingniu
2026-07-16 13:58:28 +08:00
parent 6d6c9ce534
commit a1195fb97d
28 changed files with 1738 additions and 97 deletions

View File

@@ -1,5 +1,6 @@
import type {
ApiEnvelope,
AdminUser,
AccessQuery,
AccessSummary,
AccessThresholdConfig,
@@ -41,6 +42,8 @@ import type {
RealtimeLocationRow,
SourceReadinessPlan,
SessionInfo,
LoginResponse,
CustomerUserInput,
TrackPlaybackResponse,
VehicleRealtimeRow,
VehicleCoverageRow,
@@ -171,6 +174,20 @@ function withTraceID(message: string, traceID?: string) {
export const api = {
session: (signal?: AbortSignal) => request<SessionInfo>('/api/v2/session', withSignal(undefined, signal)),
login: (credentials: { username: string; password: string }) => request<LoginResponse>('/api/v2/auth/login', {
method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(credentials)
}),
logout: () => request<{ loggedOut: boolean }>('/api/v2/auth/logout', { method: 'POST' }),
changePassword: (input: { currentPassword: string; newPassword: string }) => request<{ changed: boolean }>('/api/v2/auth/password', {
method: 'PUT', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(input)
}),
adminUsers: (signal?: AbortSignal) => request<AdminUser[]>('/api/v2/admin/users', withSignal(undefined, signal)),
createCustomerUser: (input: CustomerUserInput) => request<{ id: number }>('/api/v2/admin/users', {
method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(input)
}),
updateCustomerUser: (id: number, input: CustomerUserInput) => request<{ id: number }>(`/api/v2/admin/users/${id}`, {
method: 'PUT', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(input)
}),
monitorSummary: (params = new URLSearchParams(), signal?: AbortSignal) => request<MonitorSummary>(`/api/v2/monitor/summary?${params.toString()}`, signal ? { signal } : undefined),
monitorMap: (params = new URLSearchParams(), signal?: AbortSignal) => request<MonitorMapResponse>(`/api/v2/monitor/map?${params.toString()}`, signal ? { signal } : undefined),
monitorWorkspace: (params = new URLSearchParams(), signal?: AbortSignal) => request<MonitorWorkspaceResponse>(`/api/v2/monitor/workspace?${params.toString()}`, signal ? { signal } : undefined),

View File

@@ -5,11 +5,53 @@ export interface ApiEnvelope<T> {
}
export interface SessionInfo {
subjectId?: string;
name: string;
role: 'viewer' | 'operator' | 'admin';
username?: string;
role: 'viewer' | 'operator' | 'admin' | 'customer';
userType?: 'viewer' | 'operator' | 'admin' | 'customer';
authProvider?: 'local' | 'legacy-token' | 'disabled' | string;
menuKeys?: string[];
vehicleCount?: number;
customerRef?: string;
tenantRef?: string;
authMode: 'disabled' | 'enforce';
}
export interface LoginResponse {
accessToken: string;
expiresAt: string;
session: Omit<SessionInfo, 'authMode'>;
}
export interface AdminUser {
id: number;
username: string;
displayName: string;
userType: 'admin' | 'customer';
status: 'enabled' | 'disabled';
customerRef: string;
tenantRef: string;
authProvider: string;
externalSubject?: string;
menuKeys: string[];
vehicleVins: string[];
lastLoginAt?: string;
createdAt: string;
updatedAt: string;
}
export interface CustomerUserInput {
username?: string;
displayName: string;
password?: string;
status: 'enabled' | 'disabled';
customerRef: string;
tenantRef: string;
menuKeys: string[];
vehicleVins: string[];
}
export interface MonitorSummary {
totalVehicles: number;
onlineVehicles: number;

View File

@@ -1,5 +1,5 @@
import { QueryClient, QueryClientProvider } from '@tanstack/react-query';
import { useEffect } from 'react';
import { useEffect, type ReactNode } from 'react';
import { BrowserRouter, Navigate, Route, Routes } from 'react-router-dom';
import { AppShell } from './layout/AppShell';
import { AuthGate } from './auth/AuthGate';
@@ -7,6 +7,8 @@ import { PlatformErrorBoundary, RoutePage } from './routing/RouteBoundary';
import { RoutePageFactories, RoutePages } from './routing/routeModules';
import { ROUTER_FUTURE } from './routing/routerConfig';
import { QUERY_MEMORY } from './queryPolicy';
import { usePlatformSession } from './auth/AuthGate';
import { hasMenu } from './auth/session';
export function createPlatformQueryClient() {
return new QueryClient({
@@ -35,6 +37,17 @@ function PlatformReadySignal() {
return null;
}
function defaultPath(menuKeys: string[]) {
const first = ['monitor', 'vehicles', 'tracks', 'statistics'].find((key) => menuKeys.includes(key));
return first ? `/${first}` : '/monitor';
}
function ProtectedRoute({ menu, children }: { menu: string; children: ReactNode }) {
const { session } = usePlatformSession();
if (!hasMenu(session, menu)) return <Navigate to={defaultPath(session.menuKeys ?? [])} replace />;
return children;
}
export function AppV2() {
return (
<QueryClientProvider client={queryClient}>
@@ -43,15 +56,16 @@ export function AppV2() {
<AuthGate><BrowserRouter future={ROUTER_FUTURE}>
<Routes>
<Route element={<AppShell />}>
<Route index element={<Navigate to="/monitor" replace />} />
<Route path="/monitor" element={<RoutePage page={RoutePages.Monitor} recreatePage={RoutePageFactories.Monitor} label="全局监控" />} />
<Route path="/vehicles/:vin?" element={<RoutePage page={RoutePages.Vehicles} recreatePage={RoutePageFactories.Vehicles} label="车辆查询" />} />
<Route path="/tracks" element={<RoutePage page={RoutePages.Tracks} recreatePage={RoutePageFactories.Tracks} label="轨迹回放" />} />
<Route path="/history" element={<RoutePage page={RoutePages.History} recreatePage={RoutePageFactories.History} label="历史数据" />} />
<Route path="/statistics" element={<RoutePage page={RoutePages.Statistics} recreatePage={RoutePageFactories.Statistics} label="里程查询" />} />
<Route path="/access" element={<RoutePage page={RoutePages.Access} recreatePage={RoutePageFactories.Access} label="接入管理" />} />
<Route path="/alerts/*" element={<RoutePage page={RoutePages.Alerts} recreatePage={RoutePageFactories.Alerts} label="告警中心" />} />
<Route path="/operations" element={<RoutePage page={RoutePages.Operations} recreatePage={RoutePageFactories.Operations} label="运维质量" />} />
<Route index element={<SessionIndex />} />
<Route path="/monitor" element={<ProtectedRoute menu="monitor"><RoutePage page={RoutePages.Monitor} recreatePage={RoutePageFactories.Monitor} label="全局监控" /></ProtectedRoute>} />
<Route path="/vehicles/:vin?" element={<ProtectedRoute menu="vehicles"><RoutePage page={RoutePages.Vehicles} recreatePage={RoutePageFactories.Vehicles} label="车辆查询" /></ProtectedRoute>} />
<Route path="/tracks" element={<ProtectedRoute menu="tracks"><RoutePage page={RoutePages.Tracks} recreatePage={RoutePageFactories.Tracks} label="轨迹回放" /></ProtectedRoute>} />
<Route path="/history" element={<ProtectedRoute menu="history"><RoutePage page={RoutePages.History} recreatePage={RoutePageFactories.History} label="历史数据" /></ProtectedRoute>} />
<Route path="/statistics" element={<ProtectedRoute menu="statistics"><RoutePage page={RoutePages.Statistics} recreatePage={RoutePageFactories.Statistics} label="里程查询" /></ProtectedRoute>} />
<Route path="/access" element={<ProtectedRoute menu="access"><RoutePage page={RoutePages.Access} recreatePage={RoutePageFactories.Access} label="接入管理" /></ProtectedRoute>} />
<Route path="/alerts/*" element={<ProtectedRoute menu="alerts"><RoutePage page={RoutePages.Alerts} recreatePage={RoutePageFactories.Alerts} label="告警中心" /></ProtectedRoute>} />
<Route path="/operations" element={<ProtectedRoute menu="operations"><RoutePage page={RoutePages.Operations} recreatePage={RoutePageFactories.Operations} label="运维质量" /></ProtectedRoute>} />
<Route path="/users" element={<ProtectedRoute menu="users"><RoutePage page={RoutePages.Users} recreatePage={RoutePageFactories.Users} label="账号管理" /></ProtectedRoute>} />
<Route path="*" element={<Navigate to="/monitor" replace />} />
</Route>
</Routes>
@@ -60,3 +74,8 @@ export function AppV2() {
</QueryClientProvider>
);
}
function SessionIndex() {
const { session } = usePlatformSession();
return <Navigate to={defaultPath(session.menuKeys ?? [])} replace />;
}

View File

@@ -4,8 +4,8 @@ import { afterEach, expect, test, vi } from 'vitest';
import { getAccessToken, PLATFORM_UNAUTHORIZED_EVENT, setAccessToken } from './session';
import { AuthGate, usePlatformSession } from './AuthGate';
const mocks = vi.hoisted(() => ({ session: vi.fn() }));
vi.mock('../../api/client', () => ({ api: { session: mocks.session } }));
const mocks = vi.hoisted(() => ({ session: vi.fn(), login: vi.fn(), logout: vi.fn() }));
vi.mock('../../api/client', () => ({ api: { session: mocks.session, login: mocks.login, logout: mocks.logout } }));
function ProtectedWorkspace({ onAbort }: { onAbort: () => void }) {
const { session, logout } = usePlatformSession();
@@ -21,10 +21,14 @@ function ProtectedWorkspace({ onAbort }: { onAbort: () => void }) {
afterEach(() => {
cleanup();
mocks.session.mockReset();
mocks.login.mockReset();
mocks.logout.mockReset();
mocks.logout.mockResolvedValue({ loggedOut: true });
window.sessionStorage.clear();
});
test('treats login and logout as complete query and mutation cache boundaries', async () => {
mocks.logout.mockResolvedValue({ loggedOut: true });
const client = new QueryClient({ defaultOptions: { queries: { retry: false } } });
client.setQueryData(['previous-user-vehicle-data'], { plate: '粤A00001' });
client.getMutationCache().build(client, { mutationFn: async () => ({ ok: true }) });
@@ -33,11 +37,12 @@ test('treats login and logout as complete query and mutation cache boundaries',
if (getAccessToken() !== 'next-user-token') throw new Error('未登录');
return { name: 'next-user', role: 'viewer', authMode: 'enforce' };
});
mocks.login.mockResolvedValue({ accessToken: 'next-user-token', expiresAt: new Date().toISOString(), session: { name: 'next-user', role: 'customer' } });
render(<QueryClientProvider client={client}><AuthGate><ProtectedWorkspace onAbort={aborted} /></AuthGate></QueryClientProvider>);
const token = await screen.findByPlaceholderText('Bearer token');
fireEvent.change(token, { target: { value: 'next-user-token' } });
fireEvent.click(screen.getByRole('button', { name: '进入平台' }));
fireEvent.change(await screen.findByPlaceholderText('请输入用户名'), { target: { value: 'next-user' } });
fireEvent.change(screen.getByPlaceholderText('请输入密码'), { target: { value: 'StrongPass!1' } });
fireEvent.click(screen.getByRole('button', { name: '登录' }));
expect(await screen.findByText('next-user')).toBeInTheDocument();
expect(client.getQueryData(['previous-user-vehicle-data'])).toBeUndefined();
@@ -47,7 +52,7 @@ test('treats login and logout as complete query and mutation cache boundaries',
await waitFor(() => expect(client.getMutationCache().getAll()).toHaveLength(1));
fireEvent.click(screen.getByRole('button', { name: '退出测试会话' }));
expect(await screen.findByPlaceholderText('Bearer token')).toBeInTheDocument();
expect(await screen.findByPlaceholderText('请输入用户名')).toBeInTheDocument();
await waitFor(() => expect(aborted).toHaveBeenCalledTimes(1));
expect(client.getQueryCache().find({ queryKey: ['protected-vehicle-data'] })).toBeUndefined();
expect(client.getMutationCache().getAll()).toHaveLength(0);
@@ -55,6 +60,7 @@ test('treats login and logout as complete query and mutation cache boundaries',
});
test('an expired protected request returns to login and removes the active user cache', async () => {
mocks.logout.mockResolvedValue({ loggedOut: true });
const client = new QueryClient({ defaultOptions: { queries: { retry: false } } });
setAccessToken('next-user-token');
mocks.session.mockImplementation(async () => {
@@ -67,7 +73,7 @@ test('an expired protected request returns to login and removes the active user
client.setQueryData(['active-user-detail'], { plate: '粤A00002' });
window.dispatchEvent(new Event(PLATFORM_UNAUTHORIZED_EVENT));
expect(await screen.findByPlaceholderText('Bearer token')).toBeInTheDocument();
expect(await screen.findByPlaceholderText('请输入用户名')).toBeInTheDocument();
expect(client.getQueryCache().find({ queryKey: ['active-user-detail'] })).toBeUndefined();
expect(getAccessToken()).toBe('');
});

View File

@@ -1,5 +1,5 @@
import { useQuery, useQueryClient } from '@tanstack/react-query';
import { createContext, FormEvent, ReactNode, useCallback, useContext, useEffect, useState } from 'react';
import { FormEvent, ReactNode, useCallback, useContext, useEffect, useState, createContext } from 'react';
import { api } from '../../api/client';
import { clearAccessToken, getAccessToken, PLATFORM_UNAUTHORIZED_EVENT, PlatformSession, setAccessToken } from './session';
@@ -19,8 +19,13 @@ export function usePlatformSession() {
export function AuthGate({ children }: { children: ReactNode }) {
const queryClient = useQueryClient();
const [tokenVersion, setTokenVersion] = useState(0);
const [username, setUsername] = useState('');
const [password, setPassword] = useState('');
const [draftToken, setDraftToken] = useState('');
const [legacyMode, setLegacyMode] = useState(false);
const [attempted, setAttempted] = useState(() => Boolean(getAccessToken()));
const [loginPending, setLoginPending] = useState(false);
const [loginError, setLoginError] = useState('');
const session = useQuery({
queryKey: ['platform-session', tokenVersion],
queryFn: ({ signal }) => api.session(signal),
@@ -31,31 +36,73 @@ export function AuthGate({ children }: { children: ReactNode }) {
void queryClient.cancelQueries();
queryClient.clear();
}, [queryClient]);
const logout = useCallback(() => {
const finishLogout = useCallback(() => {
clearAccessToken();
clearClientSession();
setPassword('');
setDraftToken('');
setAttempted(false);
setLoginError('');
setTokenVersion((value) => value + 1);
}, [clearClientSession]);
const logout = useCallback(() => {
void api.logout().catch(() => undefined).finally(finishLogout);
}, [finishLogout]);
useEffect(() => {
window.addEventListener(PLATFORM_UNAUTHORIZED_EVENT, logout);
return () => window.removeEventListener(PLATFORM_UNAUTHORIZED_EVENT, logout);
}, [logout]);
window.addEventListener(PLATFORM_UNAUTHORIZED_EVENT, finishLogout);
return () => window.removeEventListener(PLATFORM_UNAUTHORIZED_EVENT, finishLogout);
}, [finishLogout]);
const login = (event: FormEvent) => {
const login = async (event: FormEvent) => {
event.preventDefault();
setAccessToken(draftToken);
clearClientSession();
setAttempted(true);
setTokenVersion((value) => value + 1);
setLoginError('');
setLoginPending(true);
try {
if (legacyMode) {
setAccessToken(draftToken);
} else {
const result = await api.login({ username: username.trim(), password });
setAccessToken(result.accessToken);
}
clearClientSession();
setTokenVersion((value) => value + 1);
} catch (error) {
clearAccessToken();
setLoginError(error instanceof Error ? error.message : '登录失败,请稍后重试');
} finally {
setLoginPending(false);
}
};
if (session.isPending) {
return <div className="v2-auth-screen"><div className="v2-auth-card"><img className="v2-auth-logo" src="/brand-logo.svg" alt="牛智能" /><i className="v2-auth-spinner" /><strong>访</strong></div></div>;
return <div className="v2-auth-screen"><div className="v2-auth-card v2-auth-loading"><img className="v2-auth-logo" src="/brand-logo.svg" alt="牛智能" /><i className="v2-auth-spinner" /><strong></strong></div></div>;
}
if (!session.data) {
return <div className="v2-auth-screen"><form className="v2-auth-card" onSubmit={login}><img className="v2-auth-logo" src="/brand-logo.svg" alt="灵牛智能" /><h1></h1><p>访</p><label><span>访</span><input autoFocus required type="password" autoComplete="current-password" value={draftToken} onChange={(event) => setDraftToken(event.target.value)} placeholder="Bearer token" /></label>{attempted && session.error ? <em>{session.error.message}</em> : null}<button type="submit" disabled={!draftToken.trim()}></button></form></div>;
const error = loginError || (attempted && session.error ? session.error.message : '');
return <div className="v2-auth-screen">
<section className="v2-auth-intro" aria-hidden="true">
<img src="/brand-logo.svg" alt="" />
<h2><br /></h2>
<p></p>
<div><span></span><span></span><span></span></div>
</section>
<form className="v2-auth-card" onSubmit={login}>
<img className="v2-auth-logo" src="/brand-logo.svg" alt="羚牛智能" />
<h1></h1>
<p>{legacyMode ? '仅供平台运维使用,输入服务器访问令牌。' : '使用管理员为你开通的账号登录。'}</p>
{legacyMode ? <label><span>访</span><input autoFocus required type="password" autoComplete="off" value={draftToken} onChange={(event) => setDraftToken(event.target.value)} placeholder="Bearer token" /></label> : <>
<label><span></span><input autoFocus required autoComplete="username" value={username} onChange={(event) => setUsername(event.target.value)} placeholder="请输入用户名" /></label>
<label><span></span><input required type="password" autoComplete="current-password" value={password} onChange={(event) => setPassword(event.target.value)} placeholder="请输入密码" /></label>
</>}
{error ? <em role="alert">{error}</em> : null}
<button type="submit" disabled={loginPending || (legacyMode ? !draftToken.trim() : !username.trim() || !password)}>{loginPending ? '正在登录…' : '登录'}</button>
<button className="v2-auth-mode-switch" type="button" onClick={() => { setLegacyMode((value) => !value); setLoginError(''); }}>
{legacyMode ? '返回账号密码登录' : '使用运维令牌登录'}
</button>
<small></small>
</form>
</div>;
}
return <AuthContext.Provider value={{ session: session.data, logout }}>{children}</AuthContext.Provider>;
}

View File

@@ -1,13 +1,7 @@
const TOKEN_KEY = 'vehicle-platform.access-token';
export const PLATFORM_UNAUTHORIZED_EVENT = 'vehicle-platform:unauthorized';
export type PlatformRole = 'viewer' | 'operator' | 'admin';
export interface PlatformSession {
name: string;
role: PlatformRole;
authMode: 'disabled' | 'enforce';
}
export type PlatformSession = SessionInfo;
export function getAccessToken() {
return window.sessionStorage.getItem(TOKEN_KEY) ?? '';
@@ -34,6 +28,13 @@ export function canOperate(session: PlatformSession) {
return session.role === 'operator' || session.role === 'admin';
}
export function hasMenu(session: PlatformSession, menu: string) {
if (session.role === 'admin') return true;
if (!session.menuKeys) return session.role !== 'customer';
return session.menuKeys.includes(menu);
}
export function canAdminister(session: PlatformSession) {
return session.role === 'admin';
}
import type { SessionInfo } from '../../api/types';

View File

@@ -8,10 +8,11 @@ const routing = vi.hoisted(() => ({
scheduleIdleRoutePreloads: vi.fn(() => vi.fn()),
shouldPreloadRouteOnIntent: vi.fn(() => true)
}));
const auth = vi.hoisted(() => ({ session: { name: 'test-user', role: 'viewer' as const } as any }));
vi.mock('../routing/routeModules', () => routing);
vi.mock('../auth/AuthGate', () => ({
usePlatformSession: () => ({ session: { name: 'test-user', role: 'viewer' }, logout: vi.fn() })
usePlatformSession: () => ({ session: auth.session, logout: vi.fn() })
}));
import { AppShell } from './AppShell';
@@ -19,6 +20,24 @@ import { AppShell } from './AppShell';
afterEach(() => {
cleanup();
vi.clearAllMocks();
auth.session = { name: 'test-user', role: 'viewer' };
});
test('renders only explicitly assigned customer menus', () => {
auth.session = { name: '客户甲', role: 'customer', userType: 'customer', menuKeys: ['monitor', 'vehicles', 'tracks', 'statistics'] };
render(<MemoryRouter future={ROUTER_FUTURE} initialEntries={['/monitor']}>
<Routes><Route element={<AppShell />}><Route path="*" element={<span></span>} /></Route></Routes>
</MemoryRouter>);
expect(screen.getByRole('link', { name: '全局监控' })).toBeInTheDocument();
expect(screen.getByRole('link', { name: '车辆查询' })).toBeInTheDocument();
expect(screen.getByRole('link', { name: '轨迹回放' })).toBeInTheDocument();
expect(screen.getByRole('link', { name: '里程查询' })).toBeInTheDocument();
expect(screen.queryByRole('link', { name: '历史数据' })).not.toBeInTheDocument();
expect(screen.queryByRole('link', { name: '告警中心' })).not.toBeInTheDocument();
expect(screen.queryByRole('link', { name: '接入管理' })).not.toBeInTheDocument();
expect(screen.queryByRole('link', { name: '账号管理' })).not.toBeInTheDocument();
expect(screen.queryByRole('link', { name: '运维质量' })).not.toBeInTheDocument();
});
test('reschedules likely route preloads when the active module changes', async () => {

View File

@@ -12,19 +12,22 @@ import {
IconUser,
IconExit
} from '@douyinfe/semi-icons';
import { useEffect, useState } from 'react';
import { FormEvent, useEffect, useState } from 'react';
import { NavLink, Outlet, useLocation } from 'react-router-dom';
import { api } from '../../api/client';
import { usePlatformSession } from '../auth/AuthGate';
import { hasMenu } from '../auth/session';
import { preloadRoute, scheduleIdleRoutePreloads, shouldPreloadRouteOnIntent } from '../routing/routeModules';
const navigation = [
{ to: '/monitor', label: '全局监控', icon: IconHome },
{ to: '/vehicles', label: '车辆查询', icon: IconSearch },
{ to: '/tracks', label: '轨迹回放', icon: IconMapPin },
{ to: '/history', label: '历史数据', icon: IconBarChartHStroked },
{ to: '/statistics', label: '里程查询', icon: IconBarChartHStroked },
{ to: '/alerts', label: '告警中心', icon: IconAlarm },
{ to: '/access', label: '接入管理', icon: IconBox }
{ to: '/monitor', menu: 'monitor', label: '全局监控', icon: IconHome },
{ to: '/vehicles', menu: 'vehicles', label: '车辆查询', icon: IconSearch },
{ to: '/tracks', menu: 'tracks', label: '轨迹回放', icon: IconMapPin },
{ to: '/history', menu: 'history', label: '历史数据', icon: IconBarChartHStroked },
{ to: '/statistics', menu: 'statistics', label: '里程查询', icon: IconBarChartHStroked },
{ to: '/alerts', menu: 'alerts', label: '告警中心', icon: IconAlarm },
{ to: '/access', menu: 'access', label: '接入管理', icon: IconBox },
{ to: '/users', menu: 'users', label: '账号管理', icon: IconUser }
];
const pageNames: Record<string, string> = {
@@ -35,7 +38,8 @@ const pageNames: Record<string, string> = {
statistics: '里程查询',
alerts: '告警中心',
access: '接入管理',
operations: '运维质量'
operations: '运维质量',
users: '账号管理'
};
const pageHelp: Record<string, { summary: string; tips: string[] }> = {
@@ -46,7 +50,8 @@ const pageHelp: Record<string, { summary: string; tips: string[] }> = {
statistics: { summary: '按日期区间比较车辆每日里程与总里程。', tips: ['未选择车牌时按车队分页展示。', '可配置 JT808、GB32960、YUTONG_MQTT 的启用状态与优先级。'] },
alerts: { summary: '查看、确认和关闭车辆业务告警。', tips: ['筛选条件会限定列表和统计口径。', '处置前请核对证据与版本,避免覆盖其他人员的操作。'] },
access: { summary: '核对车辆接入覆盖、身份差异和协议质量。', tips: ['差异列表是主要工作区,可从统计卡片快速下钻。', '阈值配置仅对有权限的账号开放。'] },
operations: { summary: '查看数据源、查询链路和服务健康状态。', tips: ['优先处理红色异常,再检查数据新鲜度和来源就绪状态。', '页面会自动刷新,也可以手动触发即时检查。'] }
operations: { summary: '查看数据源、查询链路和服务健康状态。', tips: ['优先处理红色异常,再检查数据新鲜度和来源就绪状态。', '页面会自动刷新,也可以手动触发即时检查。'] },
users: { summary: '创建客户账号并分配菜单和车辆数据范围。', tips: ['客户只能使用四个对外菜单中的已分配项。', '停用账号或重置密码会立即撤销其旧会话。', '车辆权限修改最多在 30 秒内对活跃会话生效。'] }
};
function ContextHelp({ section, onClose }: { section: string; onClose: () => void }) {
@@ -72,8 +77,9 @@ export function AppShell() {
const activeRoutePath = `/${section}`;
const { session, logout } = usePlatformSession();
const [helpOpen, setHelpOpen] = useState(false);
const [passwordOpen, setPasswordOpen] = useState(false);
const [mobileLayout, setMobileLayout] = useState(() => typeof window !== 'undefined' && window.matchMedia('(max-width: 680px)').matches);
const roleLabel = { viewer: '只读', operator: '处置员', admin: '管理员' }[session.role];
const roleLabel = { viewer: '只读', operator: '处置员', admin: '管理员', customer: '客户' }[session.role];
useEffect(() => scheduleIdleRoutePreloads({ activePathname: activeRoutePath }), [activeRoutePath]);
useEffect(() => {
const media = window.matchMedia('(max-width: 680px)');
@@ -91,24 +97,61 @@ export function AppShell() {
<h1>{pageNames[section] ?? '车辆数据中台'}</h1>
<div className="v2-topbar-actions">
<button type="button" aria-label="帮助" aria-expanded={helpOpen} aria-controls="v2-context-help" onClick={() => setHelpOpen(true)}><IconHelpCircle /></button>
<span className="v2-current-user"><IconUser /><b>{session.name}</b><small>{roleLabel}</small></span>
<button type="button" className="v2-current-user" title="修改密码" onClick={() => setPasswordOpen(true)}><IconUser /><b>{session.name}</b><small>{roleLabel}</small></button>
<button type="button" className="v2-password-mobile" aria-label="修改密码" onClick={() => setPasswordOpen(true)}><IconUser /></button>
<button type="button" aria-label="退出登录" title="退出登录" onClick={logout}><IconExit /></button>
</div>
</header>
<main className="v2-content"><Outlet /></main>
</div>
{helpOpen ? <div id="v2-context-help"><ContextHelp section={section} onClose={() => setHelpOpen(false)} /></div> : null}
{passwordOpen ? <PasswordDialog onClose={() => setPasswordOpen(false)} onChanged={logout} /> : null}
</div>
);
}
function PasswordDialog({ onClose, onChanged }: { onClose: () => void; onChanged: () => void }) {
const [currentPassword, setCurrentPassword] = useState('');
const [newPassword, setNewPassword] = useState('');
const [confirmPassword, setConfirmPassword] = useState('');
const [pending, setPending] = useState(false);
const [error, setError] = useState('');
const submit = async (event: FormEvent) => {
event.preventDefault();
if (newPassword !== confirmPassword) { setError('两次输入的新密码不一致'); return; }
setPending(true); setError('');
try {
await api.changePassword({ currentPassword, newPassword });
onChanged();
} catch (reason) {
setError(reason instanceof Error ? reason.message : '密码修改失败');
} finally { setPending(false); }
};
useEffect(() => {
const closeOnEscape = (event: KeyboardEvent) => { if (event.key === 'Escape' && !pending) onClose(); };
window.addEventListener('keydown', closeOnEscape);
return () => window.removeEventListener('keydown', closeOnEscape);
}, [onClose, pending]);
return <div className="v2-password-backdrop" role="presentation" onMouseDown={(event) => { if (event.target === event.currentTarget && !pending) onClose(); }}><form className="v2-password-dialog" role="dialog" aria-modal="true" aria-labelledby="v2-password-title" onSubmit={submit}>
<header><div><h2 id="v2-password-title"></h2><p></p></div><button type="button" aria-label="关闭修改密码" onClick={onClose}>×</button></header>
<label><span></span><input autoFocus required type="password" autoComplete="current-password" value={currentPassword} onChange={(event) => setCurrentPassword(event.target.value)} /></label>
<label><span></span><input required minLength={10} type="password" autoComplete="new-password" value={newPassword} onChange={(event) => setNewPassword(event.target.value)} placeholder="至少 10 位,包含三类字符" /></label>
<label><span></span><input required minLength={10} type="password" autoComplete="new-password" value={confirmPassword} onChange={(event) => setConfirmPassword(event.target.value)} /></label>
{error ? <em role="alert">{error}</em> : null}
<footer><button type="button" onClick={onClose} disabled={pending}></button><button type="submit" disabled={pending || !currentPassword || !newPassword || !confirmPassword}>{pending ? '正在修改…' : '确认修改'}</button></footer>
</form></div>;
}
const mobilePrimaryNavigation = [navigation[0], navigation[1], navigation[2], navigation[4]];
const mobileMoreNavigation = [navigation[3], navigation[5], navigation[6], { to: '/operations', label: '运维质量', icon: IconSetting }];
const mobileMoreNavigation = [navigation[3], navigation[5], navigation[6], navigation[7], { to: '/operations', menu: 'operations', label: '运维质量', icon: IconSetting }];
function MobileNavigation() {
const location = useLocation();
const { session } = usePlatformSession();
const [moreOpen, setMoreOpen] = useState(false);
const moreActive = mobileMoreNavigation.some((item) => location.pathname.startsWith(item.to));
const primary = mobilePrimaryNavigation.filter((item) => hasMenu(session, item.menu));
const more = mobileMoreNavigation.filter((item) => hasMenu(session, item.menu));
const moreActive = more.some((item) => location.pathname.startsWith(item.to));
const warmRoute = (path: string) => { if (shouldPreloadRouteOnIntent()) void preloadRoute(path); };
useEffect(() => setMoreOpen(false), [location.pathname]);
useEffect(() => {
@@ -120,17 +163,19 @@ function MobileNavigation() {
const link = ({ to, label, icon: Icon }: (typeof navigation)[number]) => <NavLink key={to} to={to} aria-label={label} onPointerDown={() => warmRoute(to)} className={({ isActive }) => `v2-mobile-nav-item ${isActive ? 'is-active' : ''}`}><Icon size="large" /><span>{label}</span></NavLink>;
return <>
{moreOpen ? <div className="v2-mobile-more-backdrop" role="presentation" onMouseDown={(event) => { if (event.target === event.currentTarget) setMoreOpen(false); }}><section className="v2-mobile-more-sheet" role="dialog" aria-modal="true" aria-label="更多功能"><header><div><strong></strong><span></span></div><button type="button" aria-label="关闭更多功能" onClick={() => setMoreOpen(false)}>×</button></header><nav>{mobileMoreNavigation.map(link)}</nav></section></div> : null}
{moreOpen && more.length ? <div className="v2-mobile-more-backdrop" role="presentation" onMouseDown={(event) => { if (event.target === event.currentTarget) setMoreOpen(false); }}><section className="v2-mobile-more-sheet" role="dialog" aria-modal="true" aria-label="更多功能"><header><div><strong></strong><span></span></div><button type="button" aria-label="关闭更多功能" onClick={() => setMoreOpen(false)}>×</button></header><nav>{more.map(link)}</nav></section></div> : null}
<nav className="v2-mobile-navigation" aria-label="主导航">
{mobilePrimaryNavigation.map(link)}
<button type="button" className={`v2-mobile-nav-item${moreActive ? ' is-active' : ''}`} aria-label="更多功能" aria-expanded={moreOpen} onClick={() => setMoreOpen((value) => !value)}><IconMore size="large" /><span></span></button>
{primary.map(link)}
{more.length ? <button type="button" className={`v2-mobile-nav-item${moreActive ? ' is-active' : ''}`} aria-label="更多功能" aria-expanded={moreOpen} onClick={() => setMoreOpen((value) => !value)}><IconMore size="large" /><span></span></button> : null}
</nav>
</>;
}
function Sidebar() {
const { session } = usePlatformSession();
const [collapsed, setCollapsed] = useState(false);
const warmRoute = (path: string) => { if (shouldPreloadRouteOnIntent()) void preloadRoute(path); };
const visibleNavigation = navigation.filter((item) => hasMenu(session, item.menu));
return (
<aside className={`v2-sidebar${collapsed ? ' is-collapsed' : ''}`}>
@@ -139,17 +184,17 @@ function Sidebar() {
<img className="v2-brand-symbol" src="/brand-mark.svg" alt="" aria-hidden="true" />
</div>
<nav className="v2-navigation" aria-label="主导航">
{navigation.map(({ to, label, icon: Icon }) => (
{visibleNavigation.map(({ to, label, icon: Icon }) => (
<NavLink key={to} to={to} aria-label={label} title={collapsed ? label : undefined} onPointerEnter={() => warmRoute(to)} onFocus={() => warmRoute(to)} onPointerDown={() => warmRoute(to)} className={({ isActive }) => `v2-nav-item ${isActive ? 'is-active' : ''}`}>
<Icon size="large" />
<span className="v2-nav-label">{label}</span>
</NavLink>
))}
</nav>
<NavLink to="/operations" aria-label="运维质量" title={collapsed ? '运维质量' : undefined} onPointerEnter={() => warmRoute('/operations')} onFocus={() => warmRoute('/operations')} onPointerDown={() => warmRoute('/operations')} className={({ isActive }) => `v2-nav-item v2-nav-operations ${isActive ? 'is-active' : ''}`}>
{hasMenu(session, 'operations') ? <NavLink to="/operations" aria-label="运维质量" title={collapsed ? '运维质量' : undefined} onPointerEnter={() => warmRoute('/operations')} onFocus={() => warmRoute('/operations')} onPointerDown={() => warmRoute('/operations')} className={({ isActive }) => `v2-nav-item v2-nav-operations ${isActive ? 'is-active' : ''}`}>
<IconSetting size="large" />
<span className="v2-nav-label"></span>
</NavLink>
</NavLink> : null}
<button className="v2-collapse" type="button" onClick={() => setCollapsed((value) => !value)} aria-label={collapsed ? '展开侧栏' : '收起侧栏'}>
<IconChevronLeft />
<span></span>

View File

@@ -0,0 +1,137 @@
import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query';
import { FormEvent, useDeferredValue, useEffect, useMemo, useState } from 'react';
import { api } from '../../api/client';
import type { AdminUser, CustomerUserInput } from '../../api/types';
const customerMenus = [
{ key: 'monitor', label: '全局监控', description: '查看授权车辆的实时位置与状态' },
{ key: 'vehicles', label: '车辆查询', description: '查看车辆档案与最新遥测' },
{ key: 'tracks', label: '轨迹回放', description: '查询授权车辆的历史轨迹' },
{ key: 'statistics', label: '里程查询', description: '查询授权车辆的每日与区间里程' }
];
type Draft = {
username: string;
displayName: string;
password: string;
status: 'enabled' | 'disabled';
customerRef: string;
tenantRef: string;
menuKeys: string[];
vehicleVins: string[];
};
const emptyDraft: Draft = { username: '', displayName: '', password: '', status: 'enabled', customerRef: '', tenantRef: '', menuKeys: ['monitor', 'vehicles', 'tracks', 'statistics'], vehicleVins: [] };
function draftFromUser(user?: AdminUser): Draft {
if (!user) return { ...emptyDraft, menuKeys: [...emptyDraft.menuKeys], vehicleVins: [] };
return { username: user.username, displayName: user.displayName, password: '', status: user.status, customerRef: user.customerRef, tenantRef: user.tenantRef, menuKeys: [...user.menuKeys], vehicleVins: [...user.vehicleVins] };
}
function formatTime(value?: string) {
if (!value) return '尚未登录';
return new Date(value).toLocaleString('zh-CN', { hour12: false });
}
export default function UsersPage() {
const queryClient = useQueryClient();
const users = useQuery({ queryKey: ['admin-users'], queryFn: ({ signal }) => api.adminUsers(signal), staleTime: 10_000 });
const customers = useMemo(() => (users.data ?? []).filter((user) => user.userType === 'customer'), [users.data]);
const [selectedID, setSelectedID] = useState<number | null>(null);
const [creating, setCreating] = useState(false);
const selected = useMemo(() => customers.find((user) => user.id === selectedID), [customers, selectedID]);
const [draft, setDraft] = useState<Draft>(() => draftFromUser());
const [vehicleKeyword, setVehicleKeyword] = useState('');
const deferredVehicleKeyword = useDeferredValue(vehicleKeyword.trim());
const [bulkVINs, setBulkVINs] = useState('');
const [feedback, setFeedback] = useState('');
useEffect(() => {
if (!creating && selected) setDraft(draftFromUser(selected));
}, [creating, selected]);
const candidates = useQuery({
queryKey: ['permission-vehicle-candidates', deferredVehicleKeyword],
queryFn: ({ signal }) => api.vehicles(new URLSearchParams({ keyword: deferredVehicleKeyword, limit: '20', offset: '0' }), signal),
enabled: deferredVehicleKeyword.length >= 1,
staleTime: 30_000
});
const assigned = useMemo(() => new Set(draft.vehicleVins), [draft.vehicleVins]);
const save = useMutation({
mutationFn: async () => {
const input: CustomerUserInput = { displayName: draft.displayName.trim(), password: draft.password || undefined, status: draft.status, customerRef: draft.customerRef.trim(), tenantRef: draft.tenantRef.trim(), menuKeys: draft.menuKeys, vehicleVins: draft.vehicleVins };
if (creating) return api.createCustomerUser({ ...input, username: draft.username.trim(), password: draft.password });
if (!selected) throw new Error('请先选择客户账号');
return api.updateCustomerUser(selected.id, input);
},
onSuccess: async (result) => {
setFeedback(creating ? '客户账号已创建' : '账号与权限已更新');
setCreating(false);
setSelectedID(result.id);
setDraft((value) => ({ ...value, password: '' }));
await queryClient.invalidateQueries({ queryKey: ['admin-users'] });
},
onError: (error) => setFeedback(error instanceof Error ? error.message : '保存失败')
});
const startCreate = () => {
setCreating(true);
setSelectedID(null);
setDraft(draftFromUser());
setVehicleKeyword('');
setBulkVINs('');
setFeedback('');
};
const selectCustomer = (user: AdminUser) => {
setCreating(false);
setSelectedID(user.id);
setDraft(draftFromUser(user));
setVehicleKeyword('');
setBulkVINs('');
setFeedback('');
};
const toggleVIN = (vin: string) => setDraft((value) => ({ ...value, vehicleVins: value.vehicleVins.includes(vin) ? value.vehicleVins.filter((item) => item !== vin) : [...value.vehicleVins, vin].sort() }));
const addBulkVINs = () => {
const next = bulkVINs.split(/[\s,;]+/).map((value) => value.trim().toUpperCase()).filter(Boolean);
setDraft((value) => ({ ...value, vehicleVins: [...new Set([...value.vehicleVins, ...next])].sort() }));
setBulkVINs('');
};
const submit = (event: FormEvent) => { event.preventDefault(); setFeedback(''); save.mutate(); };
return <div className="v2-user-admin">
<header className="v2-user-admin-heading">
<div><h2></h2><p> 30 </p></div>
<button type="button" onClick={startCreate}></button>
</header>
<div className="v2-user-admin-grid">
<aside className="v2-user-list">
<div className="v2-user-list-summary"><strong>{customers.length}</strong><span></span></div>
{users.isPending ? <p className="v2-user-empty"></p> : customers.length === 0 ? <p className="v2-user-empty"></p> : customers.map((user) => <button key={user.id} type="button" className={selectedID === user.id && !creating ? 'is-active' : ''} onClick={() => selectCustomer(user)}>
<span className="v2-user-avatar">{user.displayName.slice(0, 1)}</span>
<span><b>{user.displayName}</b><small>@{user.username} · {user.vehicleVins.length} </small></span>
<i className={user.status === 'enabled' ? 'is-enabled' : ''}>{user.status === 'enabled' ? '启用' : '停用'}</i>
</button>)}
</aside>
<main className="v2-user-editor">
{!creating && !selected ? <div className="v2-user-editor-empty"><strong></strong><p></p><button type="button" onClick={startCreate}></button></div> : <form onSubmit={submit}>
<div className="v2-user-editor-title"><div><h3>{creating ? '创建客户账号' : selected?.displayName}</h3><p>{creating ? '设置登录身份和最小必要权限' : `最近登录:${formatTime(selected?.lastLoginAt)}`}</p></div><label className="v2-user-status"><input type="checkbox" checked={draft.status === 'enabled'} onChange={(event) => setDraft((value) => ({ ...value, status: event.target.checked ? 'enabled' : 'disabled' }))} /><span>{draft.status === 'enabled' ? '账号启用' : '账号停用'}</span></label></div>
<section><h4></h4><div className="v2-user-fields">
<label><span></span><input required disabled={!creating} value={draft.username} onChange={(event) => setDraft((value) => ({ ...value, username: event.target.value }))} placeholder="例如 customer-huadong" /></label>
<label><span></span><input required value={draft.displayName} onChange={(event) => setDraft((value) => ({ ...value, displayName: event.target.value }))} placeholder="显示在平台右上角" /></label>
<label><span>{creating ? '初始密码' : '重置密码(可选)'}</span><input required={creating} type="password" autoComplete="new-password" value={draft.password} onChange={(event) => setDraft((value) => ({ ...value, password: event.target.value }))} placeholder="至少 10 位,包含三类字符" /></label>
<label><span></span><input value={draft.customerRef} onChange={(event) => setDraft((value) => ({ ...value, customerRef: event.target.value }))} placeholder="为 OneOS / RuoYi 映射预留" /></label>
</div></section>
<section><h4> <small></small></h4><div className="v2-menu-permissions">{customerMenus.map((menu) => <label key={menu.key} className={draft.menuKeys.includes(menu.key) ? 'is-selected' : ''}><input type="checkbox" checked={draft.menuKeys.includes(menu.key)} onChange={() => setDraft((value) => ({ ...value, menuKeys: value.menuKeys.includes(menu.key) ? value.menuKeys.filter((item) => item !== menu.key) : [...value.menuKeys, menu.key] }))} /><span><b>{menu.label}</b><small>{menu.description}</small></span></label>)}</div></section>
<section><div className="v2-vehicle-permission-heading"><h4> <small> {draft.vehicleVins.length} </small></h4>{draft.vehicleVins.length ? <button type="button" onClick={() => setDraft((value) => ({ ...value, vehicleVins: [] }))}></button> : null}</div>
<div className="v2-vehicle-permission-tools"><label><span> VIN </span><input value={vehicleKeyword} onChange={(event) => setVehicleKeyword(event.target.value)} placeholder="输入后显示候选车辆" /></label><label><span> VIN</span><span className="v2-bulk-vin"><input value={bulkVINs} onChange={(event) => setBulkVINs(event.target.value)} placeholder="空格、逗号或换行分隔" /><button type="button" disabled={!bulkVINs.trim()} onClick={addBulkVINs}></button></span></label></div>
{deferredVehicleKeyword ? <div className="v2-vehicle-candidates">{candidates.isPending ? <p></p> : (candidates.data?.items ?? []).length === 0 ? <p></p> : candidates.data?.items.map((vehicle) => <button type="button" className={assigned.has(vehicle.vin) ? 'is-selected' : ''} key={`${vehicle.vin}-${vehicle.protocol}`} onClick={() => toggleVIN(vehicle.vin)}><span><b>{vehicle.plate || '未登记车牌'}</b><small>{vehicle.vin}</small></span><i>{assigned.has(vehicle.vin) ? '已分配' : '选择'}</i></button>)}</div> : null}
{draft.vehicleVins.length ? <div className="v2-assigned-vins">{draft.vehicleVins.map((vin) => <button type="button" key={vin} onClick={() => toggleVIN(vin)}>{vin}<span>×</span></button>)}</div> : <p className="v2-user-empty"></p>}
</section>
{feedback ? <p className={`v2-user-feedback${save.isError ? ' is-error' : ''}`} role="status">{feedback}</p> : null}
<footer><button type="submit" disabled={save.isPending}>{save.isPending ? '正在保存…' : creating ? '创建账号' : '保存权限'}</button></footer>
</form>}
</main>
</div>
</div>;
}

View File

@@ -1,6 +1,6 @@
import { lazy, type ComponentType } from 'react';
export type RouteSection = 'monitor' | 'vehicles' | 'tracks' | 'history' | 'statistics' | 'access' | 'alerts' | 'operations';
export type RouteSection = 'monitor' | 'vehicles' | 'tracks' | 'history' | 'statistics' | 'access' | 'alerts' | 'operations' | 'users';
type RouteModule = { default: ComponentType };
type RoutePreloadConnection = { saveData?: boolean; effectiveType?: string };
type RoutePreloadRuntime = { visibilityState?: DocumentVisibilityState; deviceMemory?: number };
@@ -18,7 +18,8 @@ const importers: Record<RouteSection, () => Promise<RouteModule>> = {
statistics: () => import('../pages/StatisticsPage'),
access: () => import('../pages/AccessPage'),
alerts: () => import('../pages/AlertsPage'),
operations: () => import('../pages/OperationsPage')
operations: () => import('../pages/OperationsPage'),
users: () => import('../pages/UsersPage')
};
const pendingModules = new Map<RouteSection, Promise<RouteModule>>();
@@ -30,7 +31,8 @@ const likelyNextRoutes: Record<RouteSection, RouteSection[]> = {
statistics: ['history', 'vehicles'],
access: ['monitor', 'operations'],
alerts: ['monitor', 'access'],
operations: ['access', 'monitor']
operations: ['access', 'monitor'],
users: ['monitor', 'vehicles']
};
function routeLoadTimeout<T>(promise: Promise<T>, section: string, timeoutMs: number) {
@@ -195,7 +197,8 @@ export const RoutePages = {
Statistics: createRouteComponent('statistics'),
Access: createRouteComponent('access'),
Alerts: createRouteComponent('alerts'),
Operations: createRouteComponent('operations')
Operations: createRouteComponent('operations'),
Users: createRouteComponent('users')
} as const;
export const RoutePageFactories = {
@@ -206,5 +209,6 @@ export const RoutePageFactories = {
Statistics: () => createRouteComponent('statistics'),
Access: () => createRouteComponent('access'),
Alerts: () => createRouteComponent('alerts'),
Operations: () => createRouteComponent('operations')
Operations: () => createRouteComponent('operations'),
Users: () => createRouteComponent('users')
} as const;

View File

@@ -18,13 +18,23 @@ body { margin: 0; background: var(--v2-bg); color: var(--v2-text); font-family:
button, input, select { font: inherit; }
button, a { -webkit-tap-highlight-color: transparent; }
.v2-auth-screen { display: grid; min-height: 100vh; place-items: center; background: radial-gradient(circle at 50% 10%, #edf4ff 0, #f4f7fb 42%, #eef2f7 100%); padding: 20px; }
.v2-auth-card { display: flex; width: min(390px, 100%); flex-direction: column; align-items: stretch; border: 1px solid var(--v2-border); border-radius: 16px; background: #fff; padding: 34px; box-shadow: 0 22px 70px rgba(21, 32, 51, .12); }
.v2-auth-screen { display: grid; min-height: 100vh; grid-template-columns: minmax(360px, 1.15fr) minmax(420px, .85fr); align-items: center; background: #f3f6fa; padding: clamp(28px, 5vw, 80px); }
.v2-auth-intro { max-width: 640px; padding: 36px 8vw 36px 4vw; }
.v2-auth-intro > img { width: 176px; }
.v2-auth-intro h2 { margin: 54px 0 20px; color: #14223a; font-size: clamp(34px, 4vw, 58px); font-weight: 720; line-height: 1.16; letter-spacing: -.055em; }
.v2-auth-intro p { max-width: 520px; margin: 0; color: #617087; font-size: 16px; line-height: 1.9; }
.v2-auth-intro > div { display: flex; flex-wrap: wrap; gap: 24px; margin-top: 42px; color: #3f5068; font-size: 13px; font-weight: 650; }
.v2-auth-intro > div span::before { display: inline-block; width: 7px; height: 7px; margin-right: 8px; border-radius: 50%; background: var(--v2-blue); content: ""; }
.v2-auth-card { display: flex; width: min(430px, 100%); flex-direction: column; align-items: stretch; border: 1px solid #e0e7f0; border-radius: 18px; background: #fff; padding: 42px; box-shadow: 0 28px 80px rgba(21, 32, 51, .11); }
.v2-auth-loading { grid-column: 1 / -1; justify-self: center; }
.v2-auth-card > strong { margin-top: 12px; text-align: center; }
.v2-auth-logo { display: block; width: 150px; height: auto; margin: 0 auto 18px; }
.v2-auth-card h1 { margin: 0; text-align: center; font-size: 22px; }.v2-auth-card p { margin: 10px 0 24px; color: var(--v2-muted); text-align: center; font-size: 12px; line-height: 1.7; }
.v2-auth-card label { display: flex; flex-direction: column; gap: 7px; color: #58667a; font-size: 12px; font-weight: 600; }.v2-auth-card input { height: 40px; border: 1px solid #d7e0ec; border-radius: 8px; padding: 0 11px; outline: 0; }.v2-auth-card input:focus { border-color: #8bb6fb; box-shadow: 0 0 0 3px rgba(18,104,243,.08); }
.v2-auth-card em { margin-top: 9px; color: var(--v2-red); font-size: 11px; font-style: normal; }.v2-auth-card button { height: 40px; margin-top: 18px; border: 0; border-radius: 8px; background: var(--v2-blue); color: #fff; cursor: pointer; font-weight: 700; }.v2-auth-card button:disabled { opacity: .45; cursor: not-allowed; }
.v2-auth-card h1 { margin: 2px 0 0; text-align: center; font-size: 24px; letter-spacing: -.035em; }.v2-auth-card p { margin: 11px 0 26px; color: var(--v2-muted); text-align: center; font-size: 13px; line-height: 1.7; }
.v2-auth-card label { display: flex; flex-direction: column; gap: 8px; margin-top: 15px; color: #44536a; font-size: 13px; font-weight: 650; }.v2-auth-card input { height: 46px; border: 1px solid #d5deea; border-radius: 9px; padding: 0 13px; outline: 0; font-size: 14px; }.v2-auth-card input:focus { border-color: #7aaafb; box-shadow: 0 0 0 3px rgba(18,104,243,.08); }
.v2-auth-card em { margin-top: 12px; color: var(--v2-red); font-size: 12px; font-style: normal; }.v2-auth-card button { height: 46px; margin-top: 22px; border: 0; border-radius: 9px; background: var(--v2-blue); color: #fff; cursor: pointer; font-size: 14px; font-weight: 700; }.v2-auth-card button:disabled { opacity: .45; cursor: not-allowed; }
.v2-auth-card .v2-auth-mode-switch { height: 36px; margin-top: 8px; background: transparent; color: #68778c; font-size: 12px; font-weight: 600; }
.v2-auth-card .v2-auth-mode-switch:hover { color: var(--v2-blue); }
.v2-auth-card > small { margin-top: 14px; color: #9aa5b5; text-align: center; font-size: 10px; }
.v2-auth-spinner { width: 24px; height: 24px; margin: auto; border: 3px solid #d8e5fa; border-top-color: var(--v2-blue); border-radius: 50%; animation: v2-spin .8s linear infinite; }
.v2-shell { height: 100vh; height: 100dvh; overflow: hidden; background: var(--v2-bg); }
@@ -58,6 +68,13 @@ button, a { -webkit-tap-highlight-color: transparent; }
.v2-help-panel > footer { display: flex; align-items: center; gap: 6px; margin-top: 14px; color: #8996a8; font-size: 10px; }
.v2-help-panel kbd { border: 1px solid #dce4ef; border-radius: 4px; background: #fff; padding: 2px 5px; color: #59677c; font-family: inherit; }
.v2-current-user { display: flex; align-items: center; gap: 6px; margin: 0 5px; color: #59677c; font-size: 11px; }.v2-current-user b { max-width: 140px; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }.v2-current-user small, .v2-role-badge { border-radius: 10px; background: var(--v2-blue-soft); padding: 2px 6px; color: var(--v2-blue); font-size: 9px; }
.v2-topbar-actions .v2-current-user { display: flex; width: auto; padding: 0 7px; }
.v2-password-mobile { display: none !important; }
.v2-password-backdrop { position: fixed; z-index: 1400; inset: 0; display: grid; place-items: center; background: rgba(15,23,42,.28); padding: 16px; }
.v2-password-dialog { width: min(410px,100%); border: 1px solid #e0e7ef; border-radius: 14px; background: #fff; padding: 22px; box-shadow: 0 28px 80px rgba(15,23,42,.2); }
.v2-password-dialog header { display: flex; align-items: flex-start; justify-content: space-between; gap: 20px; }.v2-password-dialog h2 { margin: 0; font-size: 19px; }.v2-password-dialog header p { margin: 6px 0 0; color: #8491a3; font-size: 10px; }.v2-password-dialog header button { width: 30px; height: 30px; border: 0; border-radius: 7px; background: #f2f5f8; color: #66758a; cursor: pointer; }
.v2-password-dialog > label { display: flex; flex-direction: column; gap: 6px; margin-top: 14px; color: #5a6980; font-size: 11px; font-weight: 650; }.v2-password-dialog input { height: 40px; border: 1px solid #d8e1ec; border-radius: 8px; padding: 0 10px; outline: 0; font-size: 13px; }.v2-password-dialog input:focus { border-color: #84b0f7; box-shadow: 0 0 0 3px rgba(18,104,243,.07); }.v2-password-dialog > em { display: block; margin-top: 10px; color: var(--v2-red); font-size: 10px; font-style: normal; }
.v2-password-dialog footer { display: flex; justify-content: flex-end; gap: 8px; margin-top: 20px; }.v2-password-dialog footer button { height: 36px; border: 1px solid #d7e0eb; border-radius: 7px; background: #fff; padding: 0 14px; color: #5d6d83; cursor: pointer; font-size: 11px; font-weight: 650; }.v2-password-dialog footer button[type="submit"] { border-color: var(--v2-blue); background: var(--v2-blue); color: #fff; }.v2-password-dialog footer button:disabled { opacity: .5; }
.v2-role-notice { margin: 6px 0; border-radius: 6px; background: #f6f8fb; padding: 8px; color: var(--v2-muted); font-size: 8px; line-height: 1.5; }
.v2-content { min-width: 0; min-height: 0; flex: 1; overflow: auto; }
.v2-sidebar.is-collapsed { width: 68px; }
@@ -1359,6 +1376,78 @@ button, a { -webkit-tap-highlight-color: transparent; }
.v2-mileage-evidence { flex-direction: column; line-height: 1.5; }
}
/* Account administration follows the platform's open table/workspace layout. */
.v2-user-admin { min-height: 100%; padding: 22px 24px 34px; }
.v2-user-admin-heading { display: flex; align-items: center; justify-content: space-between; gap: 24px; margin: 0 auto 18px; max-width: 1480px; }
.v2-user-admin-heading h2 { margin: 0; font-size: 22px; letter-spacing: -.035em; }
.v2-user-admin-heading p { margin: 7px 0 0; color: var(--v2-muted); font-size: 12px; }
.v2-user-admin-heading > button, .v2-user-editor form > footer button, .v2-user-editor-empty button { height: 38px; border: 0; border-radius: 8px; background: var(--v2-blue); padding: 0 16px; color: #fff; cursor: pointer; font-size: 12px; font-weight: 700; }
.v2-user-admin-grid { display: grid; max-width: 1480px; min-height: 690px; margin: 0 auto; grid-template-columns: 300px minmax(0, 1fr); overflow: hidden; border: 1px solid var(--v2-border); border-radius: 13px; background: #fff; box-shadow: var(--v2-shadow); }
.v2-user-list { min-width: 0; border-right: 1px solid var(--v2-border); background: #f9fbfd; padding: 12px; }
.v2-user-list-summary { display: flex; align-items: baseline; gap: 7px; padding: 8px 9px 14px; color: #7a8798; font-size: 11px; }
.v2-user-list-summary strong { color: #26364e; font-size: 20px; }
.v2-user-list > button { display: grid; width: 100%; grid-template-columns: 38px minmax(0,1fr) auto; align-items: center; gap: 10px; border: 0; border-radius: 9px; background: transparent; padding: 10px; color: #273750; text-align: left; cursor: pointer; }
.v2-user-list > button:hover { background: #f0f4f9; }
.v2-user-list > button.is-active { background: #eaf2ff; box-shadow: inset 3px 0 var(--v2-blue); }
.v2-user-avatar { display: grid; width: 38px; height: 38px; place-items: center; border-radius: 9px; background: #dfe9f8; color: #3a5e91; font-weight: 800; }
.v2-user-list button > span:nth-child(2) { min-width: 0; }
.v2-user-list button b, .v2-user-list button small { display: block; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
.v2-user-list button b { font-size: 12px; }
.v2-user-list button small { margin-top: 4px; color: #8290a3; font-size: 9px; }
.v2-user-list button i { border-radius: 10px; background: #f0f2f5; padding: 3px 6px; color: #8a96a6; font-size: 8px; font-style: normal; }
.v2-user-list button i.is-enabled { background: #e9f8f2; color: #16805b; }
.v2-user-editor { min-width: 0; }
.v2-user-editor-empty { display: grid; height: 100%; place-content: center; justify-items: center; color: #4a5b72; text-align: center; }
.v2-user-editor-empty strong { font-size: 18px; }.v2-user-editor-empty p { margin: 8px 0 18px; color: #8a96a7; font-size: 12px; }
.v2-user-editor form { height: 100%; padding: 24px 28px 82px; }
.v2-user-editor-title { display: flex; align-items: flex-start; justify-content: space-between; gap: 20px; padding-bottom: 20px; border-bottom: 1px solid #edf1f5; }
.v2-user-editor-title h3 { margin: 0; font-size: 20px; }.v2-user-editor-title p { margin: 6px 0 0; color: #8591a2; font-size: 10px; }
.v2-user-status { display: flex; align-items: center; gap: 8px; color: #45556c; font-size: 11px; font-weight: 650; }
.v2-user-status input { width: 16px; height: 16px; accent-color: var(--v2-blue); }
.v2-user-editor section { padding: 20px 0; border-bottom: 1px solid #edf1f5; }
.v2-user-editor h4 { margin: 0 0 14px; color: #2c3d54; font-size: 13px; }
.v2-user-editor h4 small { margin-left: 7px; color: #91a0b2; font-size: 9px; font-weight: 500; }
.v2-user-fields { display: grid; grid-template-columns: repeat(2,minmax(0,1fr)); gap: 14px; }
.v2-user-fields label, .v2-vehicle-permission-tools label { display: flex; min-width: 0; flex-direction: column; gap: 6px; color: #637188; font-size: 10px; font-weight: 650; }
.v2-user-fields input, .v2-vehicle-permission-tools input { width: 100%; height: 38px; border: 1px solid #dbe3ed; border-radius: 7px; padding: 0 10px; outline: 0; color: #273750; font-size: 12px; }
.v2-user-fields input:focus, .v2-vehicle-permission-tools input:focus { border-color: #8ab4f7; box-shadow: 0 0 0 3px rgba(18,104,243,.07); }
.v2-user-fields input:disabled { background: #f5f7fa; color: #8390a0; }
.v2-menu-permissions { display: grid; grid-template-columns: repeat(2,minmax(0,1fr)); gap: 9px; }
.v2-menu-permissions label { display: flex; min-width: 0; align-items: flex-start; gap: 10px; border: 1px solid #e0e7ef; border-radius: 8px; padding: 11px; cursor: pointer; }
.v2-menu-permissions label.is-selected { border-color: #a9c8fb; background: #f3f7ff; }
.v2-menu-permissions input { margin-top: 2px; accent-color: var(--v2-blue); }.v2-menu-permissions span { min-width: 0; }.v2-menu-permissions b, .v2-menu-permissions small { display: block; }.v2-menu-permissions b { color: #33445c; font-size: 11px; }.v2-menu-permissions small { margin-top: 4px; color: #8491a3; font-size: 9px; line-height: 1.5; }
.v2-vehicle-permission-heading { display: flex; align-items: center; justify-content: space-between; }.v2-vehicle-permission-heading h4 { margin-bottom: 14px; }.v2-vehicle-permission-heading > button { border: 0; background: transparent; color: #7d899a; cursor: pointer; font-size: 10px; }
.v2-vehicle-permission-tools { display: grid; grid-template-columns: repeat(2,minmax(0,1fr)); gap: 12px; }
.v2-bulk-vin { display: flex; gap: 6px; }.v2-bulk-vin button { flex: 0 0 auto; border: 1px solid #cbd8e9; border-radius: 7px; background: #f7f9fc; padding: 0 11px; color: #46607e; cursor: pointer; font-size: 10px; }
.v2-vehicle-candidates { display: grid; max-height: 194px; margin-top: 10px; grid-template-columns: repeat(2,minmax(0,1fr)); overflow: auto; border: 1px solid #e1e7ef; border-radius: 8px; padding: 5px; }
.v2-vehicle-candidates > p { grid-column: 1/-1; margin: 16px; color: #8996a7; font-size: 10px; }
.v2-vehicle-candidates > button { display: flex; min-width: 0; align-items: center; justify-content: space-between; gap: 8px; border: 0; border-radius: 6px; background: transparent; padding: 8px; text-align: left; cursor: pointer; }.v2-vehicle-candidates > button:hover { background: #f4f7fa; }.v2-vehicle-candidates > button.is-selected { background: #edf4ff; }
.v2-vehicle-candidates b, .v2-vehicle-candidates small { display: block; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }.v2-vehicle-candidates b { color: #34455c; font-size: 10px; }.v2-vehicle-candidates small { margin-top: 3px; color: #8a96a6; font-size: 8px; }.v2-vehicle-candidates i { color: var(--v2-blue); font-size: 9px; font-style: normal; }
.v2-assigned-vins { display: flex; max-height: 118px; flex-wrap: wrap; gap: 6px; overflow: auto; margin-top: 10px; }.v2-assigned-vins button { height: 26px; border: 1px solid #dbe4ef; border-radius: 6px; background: #f7f9fc; padding: 0 7px; color: #52637a; cursor: pointer; font: 9px ui-monospace, SFMono-Regular, Menlo, monospace; }.v2-assigned-vins button span { margin-left: 6px; color: #99a4b3; }
.v2-user-empty { margin: 14px 4px; color: #8b97a7; font-size: 10px; line-height: 1.6; }
.v2-user-feedback { margin: 14px 0 0; color: #16805b; font-size: 11px; }.v2-user-feedback.is-error { color: var(--v2-red); }
.v2-user-editor form > footer { display: flex; justify-content: flex-end; margin-top: 18px; }.v2-user-editor form > footer button:disabled { opacity: .5; }
@media (max-width: 900px) {
.v2-auth-screen { grid-template-columns: 1fr; }
.v2-auth-intro { display: none; }
.v2-auth-card { justify-self: center; }
.v2-user-admin { padding: 12px; }
.v2-user-admin-grid { grid-template-columns: 230px minmax(560px,1fr); overflow-x: auto; }
}
@media (max-width: 680px) {
.v2-auth-screen { min-height: 100dvh; padding: 16px; }
.v2-auth-card { padding: 28px 22px; }
.v2-user-admin { padding: 8px 8px 82px; }
.v2-user-admin-heading { align-items: flex-start; margin-bottom: 10px; }.v2-user-admin-heading h2 { font-size: 17px; }.v2-user-admin-heading p { display: none; }.v2-user-admin-heading > button { height: 34px; flex: 0 0 auto; padding: 0 10px; font-size: 10px; }
.v2-user-admin-grid { display: flex; min-height: 0; overflow: visible; border: 0; box-shadow: none; flex-direction: column; gap: 8px; background: transparent; }
.v2-user-list { display: flex; border: 1px solid var(--v2-border); border-radius: 10px; overflow-x: auto; padding: 6px; background: #fff; }.v2-user-list-summary { flex: 0 0 auto; padding: 8px; }.v2-user-list > button { min-width: 210px; }
.v2-user-editor { border: 1px solid var(--v2-border); border-radius: 10px; overflow: hidden; background: #fff; }.v2-user-editor form { padding: 16px 14px 22px; }.v2-user-fields, .v2-menu-permissions, .v2-vehicle-permission-tools, .v2-vehicle-candidates { grid-template-columns: 1fr; }
.v2-password-mobile { display: grid !important; }
.v2-topbar-actions .v2-current-user { display: none; }
}
@media (max-width: 1280px) {
.v2-access-filter-v3 { grid-template-columns: minmax(210px, 1.3fr) repeat(3, minmax(120px, .75fr)) auto auto; }
.v2-access-filter-v3 > button { min-width: 76px; }