Commit acb9f81c by 张立顺

fix(access): sync server permissions and preserve API behavior after merge

1 parent 069c56e4
...@@ -97,14 +97,15 @@ export function normalizePermissions(raw: unknown): string[] { ...@@ -97,14 +97,15 @@ export function normalizePermissions(raw: unknown): string[] {
return raw.filter((x): x is string => typeof x === 'string').map(toFrontendPoint); return raw.filter((x): x is string => typeof x === 'string').map(toFrontendPoint);
} }
// 2) 包裹对象:{ permissions: string[] } / { list: string[] } / { data: { permissions } } // 2) 登录/info 的 permCodes 为权威字段,空值也不回退到旧权限字段。
if (typeof raw === 'object') { if (typeof raw === 'object') {
const o = raw as Record<string, unknown>; const o = raw as Record<string, unknown>;
if (Object.hasOwn(o, 'permCodes')) return normalizePermissions(o.permCodes);
if (Array.isArray(o.permissions)) return normalizePermissions(o.permissions); if (Array.isArray(o.permissions)) return normalizePermissions(o.permissions);
if (Array.isArray(o.list)) return normalizePermissions(o.list); if (Array.isArray(o.list)) return normalizePermissions(o.list);
if (o.data && typeof o.data === 'object') { if (o.data && typeof o.data === 'object') {
const d = o.data as Record<string, unknown>; const d = o.data as Record<string, unknown>;
return normalizePermissions(d.permissions ?? d); return normalizePermissions(d);
} }
} }
......
import { createContext, useContext, useEffect, useMemo, useState, type ReactNode } from 'react'; import {
import { defaultMatrix, type PermissionMatrix, type ResourceKey, type RoleKey } from '../model'; createContext,
useCallback,
useContext,
useEffect,
useMemo,
useState,
type ReactNode,
} from 'react';
import {
defaultMatrix,
roleLabels,
type PermissionMatrix,
type ResourceKey,
type RoleKey,
} from '../model';
import { normalizePermissions, matrixToPoints } from '../backend/adapter'; import { normalizePermissions, matrixToPoints } from '../backend/adapter';
import { auth } from '../../api/modules/auth'; import { auth } from '../../api/modules/auth';
import { getToken } from '../../api/core/token'; import { getToken } from '../../api/core/token';
import { getLoginSession, saveLoginSession } from '../session';
/** 登录/info 返回的会话数据(仅取权限相关字段,解耦 access 与具体后端响应结构) */ /** 登录/info 返回的会话数据(仅取权限相关字段,解耦 access 与具体后端响应结构) */
export interface LoginSession { export interface LoginSession {
...@@ -29,14 +44,21 @@ interface AccessContextValue { ...@@ -29,14 +44,21 @@ interface AccessContextValue {
const AccessContext = createContext<AccessContextValue | null>(null); const AccessContext = createContext<AccessContextValue | null>(null);
function sessionRole(codes: string[]): RoleKey {
return codes.find((code): code is RoleKey => Object.hasOwn(roleLabels, code)) ?? 'VIEWER';
}
export function AccessProvider({ children }: { children: ReactNode }) { export function AccessProvider({ children }: { children: ReactNode }) {
const [role, setRoleState] = useState<RoleKey>('SYS_ADMIN'); const [savedSession] = useState(getLoginSession);
const [roleCodes, setRoleCodes] = useState<string[]>([]); const [role, setRoleState] = useState<RoleKey>(() => sessionRole(savedSession?.roleCodes ?? []));
const [roleCodes, setRoleCodes] = useState<string[]>(savedSession?.roleCodes ?? []);
const [matrix] = useState<PermissionMatrix>(defaultMatrix); const [matrix] = useState<PermissionMatrix>(defaultMatrix);
// 默认按超级管理员矩阵给一份(无后端时的开发兜底,避免首屏权限全空) // 刷新时沿用登录返回的真实权限;没有有效会话时不授予业务权限。
const [points, setPoints] = useState<Set<string>>( const [points, setPoints] = useState<Set<string>>(() => {
() => new Set(matrixToPoints(matrix, 'SYS_ADMIN')), const next = new Set(normalizePermissions(savedSession?.permCodes));
); if (savedSession) next.add('dashboard');
return next;
});
// 开发兜底:按角色矩阵推导权限点(无后端时本地演示用) // 开发兜底:按角色矩阵推导权限点(无后端时本地演示用)
const setRole = (r: RoleKey) => { const setRole = (r: RoleKey) => {
...@@ -45,16 +67,17 @@ export function AccessProvider({ children }: { children: ReactNode }) { ...@@ -45,16 +67,17 @@ export function AccessProvider({ children }: { children: ReactNode }) {
}; };
// 真实登录:直接用后端返回的权限码(页面/按钮级统一以 points 为准) // 真实登录:直接用后端返回的权限码(页面/按钮级统一以 points 为准)
const applyLogin = (session: LoginSession) => { const applyLogin = useCallback((session: LoginSession) => {
const codes = session.roleCodes ?? []; const codes = session.roleCodes ?? [];
setRoleCodes(codes); setRoleCodes(codes);
const next = new Set(normalizePermissions(session.permCodes)); setRoleState(sessionRole(codes));
const next = new Set(normalizePermissions(session));
// 后端未下发 dashboard 权限码,前端按约定补齐: // 后端未下发 dashboard 权限码,前端按约定补齐:
// 工作台是所有角色的落地页,登录即可见,不该被权限挡住。 // 工作台是所有角色的落地页,登录即可见,不该被权限挡住。
//(原 access.manage 权限矩阵调试页已下线:后端菜单树与 permCodes 均无该权限点) //(原 access.manage 权限矩阵调试页已下线:后端菜单树与 permCodes 均无该权限点)
next.add('dashboard'); next.add('dashboard');
setPoints(next); setPoints(next);
}; }, []);
const loadPermissions = (raw: unknown) => { const loadPermissions = (raw: unknown) => {
setPoints(new Set(normalizePermissions(raw))); setPoints(new Set(normalizePermissions(raw)));
...@@ -62,14 +85,30 @@ export function AccessProvider({ children }: { children: ReactNode }) { ...@@ -62,14 +85,30 @@ export function AccessProvider({ children }: { children: ReactNode }) {
// 刷新/重进:若本地已有令牌,拉取当前用户信息恢复权限(令牌失效由 http 401 处理) // 刷新/重进:若本地已有令牌,拉取当前用户信息恢复权限(令牌失效由 http 401 处理)
useEffect(() => { useEffect(() => {
if (!getToken()) return; const token = getToken();
if (!token) return;
let active = true;
auth auth
.info() .info()
.then((info) => applyLogin(info)) .then((info) => {
if (!active || getToken() !== token) return;
const currentSession = getLoginSession();
if (currentSession?.token === token) {
saveLoginSession({
...currentSession,
roleCodes: info.roleCodes ?? [],
permCodes: normalizePermissions(info),
});
}
applyLogin(info);
})
.catch(() => { .catch(() => {
/* 忽略:令牌失效时 http 拦截器会清除本地令牌,登录态由路由守卫兜底 */ /* 忽略:令牌失效时 http 拦截器会清除本地令牌,登录态由路由守卫兜底 */
}); });
}, []); return () => {
active = false;
};
}, [applyLogin]);
const value = useMemo<AccessContextValue>( const value = useMemo<AccessContextValue>(
() => ({ () => ({
...@@ -88,7 +127,7 @@ export function AccessProvider({ children }: { children: ReactNode }) { ...@@ -88,7 +127,7 @@ export function AccessProvider({ children }: { children: ReactNode }) {
loadPermissions, loadPermissions,
applyLogin, applyLogin,
}), }),
[role, roleCodes, matrix, points], [role, roleCodes, matrix, points, applyLogin],
); );
return <AccessContext.Provider value={value}>{children}</AccessContext.Provider>; return <AccessContext.Provider value={value}>{children}</AccessContext.Provider>;
......
...@@ -13,6 +13,7 @@ import { ...@@ -13,6 +13,7 @@ import {
} from './sign'; } from './sign';
import { SIGN_CONFIG, SIGN_ENABLED } from './config'; import { SIGN_CONFIG, SIGN_ENABLED } from './config';
import { getToken, clearToken } from './token'; import { getToken, clearToken } from './token';
import { parseStoreResponse } from './storeJson';
const http: AxiosInstance = axios.create({ const http: AxiosInstance = axios.create({
baseURL: SIGN_CONFIG.BASE_URL, baseURL: SIGN_CONFIG.BASE_URL,
...@@ -23,6 +24,12 @@ const http: AxiosInstance = axios.create({ ...@@ -23,6 +24,12 @@ const http: AxiosInstance = axios.create({
// ---------- 请求拦截:前端加签 ---------- // ---------- 请求拦截:前端加签 ----------
http.interceptors.request.use((config: any) => { http.interceptors.request.use((config: any) => {
// 登录鉴权独立于请求签名,关闭签名或缺少私钥时仍须携带当前令牌。
const headers: Record<string, any> = config.headers || {};
const token = getToken();
if (token) headers['Authorization'] = `Bearer ${token}`;
config.headers = headers;
// 未启用签名(开发期借后端宽松模式直接放行)或未配置私钥时不签名 // 未启用签名(开发期借后端宽松模式直接放行)或未配置私钥时不签名
if (!SIGN_ENABLED || !isSignReady()) return config; if (!SIGN_ENABLED || !isSignReady()) return config;
...@@ -61,7 +68,6 @@ http.interceptors.request.use((config: any) => { ...@@ -61,7 +68,6 @@ http.interceptors.request.use((config: any) => {
const query = full.search.slice(1).split('&').filter(Boolean).sort().join('&'); const query = full.search.slice(1).split('&').filter(Boolean).sort().join('&');
// 3) Content-Type 仅取媒体类型;文件上传固定 multipart/form-data,且请求体不参与签名(§3.1/§9.6) // 3) Content-Type 仅取媒体类型;文件上传固定 multipart/form-data,且请求体不参与签名(§3.1/§9.6)
const headers: Record<string, any> = config.headers || {};
const existingCt = headers['Content-Type'] || headers['content-type']; const existingCt = headers['Content-Type'] || headers['content-type'];
const media = isForm const media = isForm
? 'multipart/form-data' ? 'multipart/form-data'
...@@ -112,11 +118,6 @@ http.interceptors.request.use((config: any) => { ...@@ -112,11 +118,6 @@ http.interceptors.request.use((config: any) => {
if (config.data && !isForm && !existingCt) { if (config.data && !isForm && !existingCt) {
headers['Content-Type'] = 'application/json'; headers['Content-Type'] = 'application/json';
} }
// 登录令牌:从本地读取并注入 Authorization 头(登录接口本身无 token,getToken 返回 null 时不注入)
const token = getToken();
if (token) {
headers['Authorization'] = `Bearer ${token}`;
}
config.headers = headers; config.headers = headers;
return config; return config;
}); });
...@@ -181,7 +182,7 @@ http.interceptors.response.use( ...@@ -181,7 +182,7 @@ http.interceptors.response.use(
} }
} }
const body = raw ? JSON.parse(raw) : null; const body = raw ? parseStoreResponse(raw, response.config?.url) : null;
if (body && typeof body === 'object' && 'code' in body && body.code !== 200) { if (body && typeof body === 'object' && 'code' in body && body.code !== 200) {
// 令牌失效/未登录:先自清除令牌,保证后续请求不再携带已失效凭据; // 令牌失效/未登录:先自清除令牌,保证后续请求不再携带已失效凭据;
// 再通知上层统一登出——必须同时清掉会话 session 并把 loggedIn 置 false, // 再通知上层统一登出——必须同时清掉会话 session 并把 loggedIn 置 false,
...@@ -190,7 +191,11 @@ http.interceptors.response.use( ...@@ -190,7 +191,11 @@ http.interceptors.response.use(
clearToken(); clearToken();
_unauthorizedHandler?.(); _unauthorizedHandler?.();
} }
const err: any = new Error(body.message || '请求失败'); const err: any = new Error(
'message' in body && typeof body.message === 'string' && body.message
? body.message
: '请求失败',
);
err.code = body.code; err.code = body.code;
err.data = 'data' in body ? body.data : undefined; err.data = 'data' in body ? body.data : undefined;
return Promise.reject(err); return Promise.reject(err);
......
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import type { AxiosAdapter, InternalAxiosRequestConfig } from 'axios'; import type { AxiosAdapter, InternalAxiosRequestConfig } from 'axios';
import { http } from '../../core/http'; import { http } from '../../core/http';
import { setToken } from '../../core/token';
import * as signing from '../../core/sign';
import { store } from '../store'; import { store } from '../store';
const originalAdapter = http.defaults.adapter; const originalAdapter = http.defaults.adapter;
...@@ -182,23 +184,32 @@ describe('store API contract', () => { ...@@ -182,23 +184,32 @@ describe('store API contract', () => {
}); });
}); });
it('retains existing import upload and submission behavior', async () => { it.each([undefined, '补充门店上架资料'])(
const file = new File(['example'], 'import.xlsx'); 'uploads the file and optional remark (%s), then submits listing IDs',
// 契约对齐 store.ts:submitImport 只接收 listingIds(草稿记录 ID 列表) async (remark) => {
const payload = { listingIds: [1001, 1002] }; const file = new File(['example'], 'import.xlsx');
serve((config) => { const payload = { listingIds: [1001, 1002] };
if (config.url === '/store/import/check') { const checked = { ...payload, submitted: false };
expect(config.data.get('file')).toBe(file); const submitted = { ...payload, submitted: true };
expect(config.data.get('templateVersion')).toBe('V1.0.1'); serve((config) => {
return { data: result({ taskId: 'task-1' }) }; if (config.url === '/store/import/check') {
} expect(config.method).toBe('post');
expect(config.url).toBe('/store/import/submit'); expect(config.data).toBeInstanceOf(FormData);
expect(JSON.parse(config.data)).toEqual(payload); expect(config.data.get('file')).toBe(file);
return { data: result({ approveId: 'approval-1' }) }; expect(config.data.get('remark')).toBe(remark ?? null);
}); expect([...config.data.keys()]).toEqual(
expect(await store.uploadImport({ file })).toEqual({ taskId: 'task-1' }); remark === undefined ? ['file'] : ['file', 'remark'],
expect(await store.submitImport(payload)).toEqual({ approveId: 'approval-1' }); );
}); return { data: result(checked) };
}
expect(config.url).toBe('/store/import/submit');
expect(JSON.parse(config.data)).toEqual(payload);
return { data: result(submitted) };
});
expect(await store.uploadImport({ file, remark })).toEqual(checked);
expect(await store.submitImport(payload)).toEqual(submitted);
},
);
}); });
describe('direct store export', () => { describe('direct store export', () => {
...@@ -221,14 +232,16 @@ describe('direct store export', () => { ...@@ -221,14 +232,16 @@ describe('direct store export', () => {
return { downloads, createObjectURL, revokeObjectURL }; return { downloads, createObjectURL, revokeObjectURL };
} }
it('downloads the binary response with authorization, filters and UTF-8 filename', async () => { it('downloads with the current token, filters and UTF-8 filename even when signing is unavailable', async () => {
vi.useFakeTimers(); vi.useFakeTimers();
localStorage.setItem('session', JSON.stringify({ token: 'test-token', tokenType: 'Bearer' })); vi.spyOn(signing, 'isSignReady').mockReturnValue(false);
setToken('test-token');
const watched = watchDownloads(); const watched = watchDownloads();
serve((config) => { serve((config) => {
expect(config.url).toBe('/store/listing/export'); expect(config.url).toBe('/store/listing/export');
expect(config.responseType).toBe('arraybuffer'); expect(config.responseType).toBe('arraybuffer');
expect(config.headers.get('Authorization')).toBe('Bearer test-token'); expect(config.headers.get('Authorization')).toBe('Bearer test-token');
expect(config.headers.get('X-Sign')).toBeUndefined();
expect(config.params).toEqual({ expect(config.params).toEqual({
businessScene: 'AFTER_SALE_MEMBER', businessScene: 'AFTER_SALE_MEMBER',
startDate: '2026-10-01', startDate: '2026-10-01',
......
...@@ -40,7 +40,7 @@ function invalidDownload(payload: unknown): Error { ...@@ -40,7 +40,7 @@ function invalidDownload(payload: unknown): Error {
export async function downloadStoreExport(http: AxiosInstance, params: ListingPageParams) { export async function downloadStoreExport(http: AxiosInstance, params: ListingPageParams) {
let filename = DEFAULT_FILENAME; let filename = DEFAULT_FILENAME;
let mime = 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'; let mime = 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet';
const payload: unknown = await http.request({ const response: unknown = await http.request({
method: 'GET', method: 'GET',
url: '/store/listing/export', url: '/store/listing/export',
params, params,
...@@ -57,6 +57,11 @@ export async function downloadStoreExport(http: AxiosInstance, params: ListingPa ...@@ -57,6 +57,11 @@ export async function downloadStoreExport(http: AxiosInstance, params: ListingPa
], ],
}); });
// 非 JSON 响应由共享拦截器包装为 { data, headers },先取出文件内容。
const payload =
response && typeof response === 'object' && 'headers' in response && 'data' in response
? response.data
: response;
if (!(payload instanceof ArrayBuffer)) throw invalidDownload(payload); if (!(payload instanceof ArrayBuffer)) throw invalidDownload(payload);
const blob = new Blob([payload], { type: mime }); const blob = new Blob([payload], { type: mime });
......
import { fireEvent, render, screen } from '@testing-library/react'; import { act, fireEvent, render, screen } from '@testing-library/react';
import { describe, expect, it, vi } from 'vitest'; import { beforeEach, describe, expect, it, vi } from 'vitest';
import { AccessProvider, PermButton, P, saveUserInfo, useAccess } from '@/access'; import {
AccessProvider,
PermButton,
P,
getLoginSession,
normalizePermissions,
saveLoginSession,
useAccess,
} from '@/access';
import { AccessTestProvider } from '@/test/AccessTestProvider';
import { setToken } from '@/api/core/token';
import { DataTable } from '../DataTable'; import { DataTable } from '../DataTable';
const authInfo = vi.hoisted(() => vi.fn());
vi.mock('@/api/modules/auth', () => ({ auth: { info: authInfo } }));
beforeEach(() => {
authInfo.mockReset();
authInfo.mockImplementation(() => new Promise(() => {}));
});
function PermissionProbe() {
const { can, canPoint, role, roleCodes } = useAccess();
return (
<>
{can('store:approve') && <span>审批菜单</span>}
{can('store:list') && <span>门店菜单</span>}
{can('system:user') && <span>管理员菜单</span>}
{canPoint('store:approve:pass') && <span>审批通过权限</span>}
<output aria-label="当前角色">{role}</output>
<output aria-label="后端角色">{roleCodes.join(',')}</output>
</>
);
}
describe('门店操作权限', () => { describe('门店操作权限', () => {
it('表格沿用后端权限码显示审核与导出,无打回权限不显示打回', () => { it('表格沿用登录 permCodes 显示审核与导出,无打回权限不显示打回', () => {
saveUserInfo({ permCodes: ['store:approve:pass', 'store:list:export'] });
render( render(
<AccessProvider> <AccessTestProvider permCodes={['store:approve:pass', 'store:list:export']}>
<DataTable <DataTable
columns={[{ title: '门店', dataIndex: 'name' }]} columns={[{ title: '门店', dataIndex: 'name' }]}
rowKey="id" rowKey="id"
...@@ -18,7 +49,7 @@ describe('门店操作权限', () => { ...@@ -18,7 +49,7 @@ describe('门店操作权限', () => {
{ label: '打回', permission: P.STORE_APPROVE_REJECT, onClick: vi.fn() }, { label: '打回', permission: P.STORE_APPROVE_REJECT, onClick: vi.fn() },
]} ]}
/> />
</AccessProvider>, </AccessTestProvider>,
); );
expect(screen.getByRole('button', { name: '审核' })).toBeInTheDocument(); expect(screen.getByRole('button', { name: '审核' })).toBeInTheDocument();
expect(screen.getByRole('button', { name: /导\s*出/ })).toBeInTheDocument(); expect(screen.getByRole('button', { name: /导\s*出/ })).toBeInTheDocument();
...@@ -28,7 +59,7 @@ describe('门店操作权限', () => { ...@@ -28,7 +59,7 @@ describe('门店操作权限', () => {
it('业务 disabled=false 不能覆盖无权限禁用', () => { it('业务 disabled=false 不能覆盖无权限禁用', () => {
const action = vi.fn(); const action = vi.fn();
render( render(
<AccessProvider> <AccessTestProvider permCodes={[]}>
<PermButton <PermButton
permission="store:approve:pass" permission="store:approve:pass"
fallback="disabled" fallback="disabled"
...@@ -37,7 +68,7 @@ describe('门店操作权限', () => { ...@@ -37,7 +68,7 @@ describe('门店操作权限', () => {
> >
审批通过 审批通过
</PermButton> </PermButton>
</AccessProvider>, </AccessTestProvider>,
); );
const button = screen.getByRole('button', { name: '审批通过' }); const button = screen.getByRole('button', { name: '审批通过' });
expect(button).toBeDisabled(); expect(button).toBeDisabled();
...@@ -45,23 +76,158 @@ describe('门店操作权限', () => { ...@@ -45,23 +76,158 @@ describe('门店操作权限', () => {
expect(action).not.toHaveBeenCalled(); expect(action).not.toHaveBeenCalled();
}); });
it('门店菜单以真实权限为准,刷新后不自动放大成管理员权限', () => { it('没有登录会话时不授予管理员或门店菜单权限', () => {
saveUserInfo({ permCodes: ['store:approve:view'] }); render(
function Probe() { <AccessProvider>
const { can } = useAccess(); <PermissionProbe />
</AccessProvider>,
);
expect(screen.queryByText('管理员菜单')).not.toBeInTheDocument();
expect(screen.queryByText('审批菜单')).not.toBeInTheDocument();
expect(screen.queryByText('门店菜单')).not.toBeInTheDocument();
expect(screen.queryByText('审批通过权限')).not.toBeInTheDocument();
});
it('刷新后仅从有效登录会话恢复角色与 permCodes', () => {
saveLoginSession({
token: 'test-token',
tokenType: 'Bearer',
expireAt: '2099-01-01T00:00:00Z',
userId: 1,
account: 'test-finance',
name: '测试财务',
orgId: 1,
dataScope: 3,
roleCodes: ['YJ_FINANCE_MGR'],
permCodes: ['store:approve:view'],
});
render(
<AccessProvider>
<PermissionProbe />
</AccessProvider>,
);
expect(screen.getByText('审批菜单')).toBeInTheDocument();
expect(screen.queryByText('门店菜单')).not.toBeInTheDocument();
expect(screen.queryByText('管理员菜单')).not.toBeInTheDocument();
expect(screen.getByLabelText('当前角色')).toHaveTextContent('YJ_FINANCE_MGR');
expect(screen.getByLabelText('后端角色')).toHaveTextContent('YJ_FINANCE_MGR');
});
it('applyLogin 切换账号时替换权限与角色,不继承上一账号操作权', () => {
const view = render(
<AccessTestProvider
permCodes={['store:approve:view', 'store:approve:pass']}
roleCodes={['YJ_FINANCE_MGR']}
>
<PermissionProbe />
</AccessTestProvider>,
);
expect(screen.getByText('审批通过权限')).toBeInTheDocument();
expect(screen.getByLabelText('当前角色')).toHaveTextContent('YJ_FINANCE_MGR');
view.rerender(
<AccessTestProvider permCodes={['store:list:view']} roleCodes={['VIEWER']}>
<PermissionProbe />
</AccessTestProvider>,
);
expect(screen.queryByText('审批通过权限')).not.toBeInTheDocument();
expect(screen.queryByText('审批菜单')).not.toBeInTheDocument();
expect(screen.getByText('门店菜单')).toBeInTheDocument();
expect(screen.getByLabelText('当前角色')).toHaveTextContent('VIEWER');
expect(screen.getByLabelText('后端角色')).toHaveTextContent('VIEWER');
});
it('登录信息刷新同步会话权限,重新挂载时已撤销的权限不会恢复', async () => {
const savedSession = {
token: 'test-current-token',
tokenType: 'Bearer',
expireAt: '2099-01-01T00:00:00Z',
userId: 1,
account: 'test-finance',
name: '测试财务',
orgId: 1,
dataScope: 3,
roleCodes: ['YJ_FINANCE_MGR'],
permCodes: ['store:approve:view', 'store:approve:pass'],
};
saveLoginSession(savedSession);
setToken(savedSession.token);
authInfo.mockResolvedValue({ roleCodes: ['VIEWER'], permCodes: ['store:list:view'] });
const view = render(
<AccessProvider>
<PermissionProbe />
</AccessProvider>,
);
expect(await screen.findByText('门店菜单')).toBeInTheDocument();
expect(screen.getByLabelText('当前角色')).toHaveTextContent('VIEWER');
expect(screen.queryByText('管理员菜单')).not.toBeInTheDocument();
expect(screen.queryByText('审批通过权限')).not.toBeInTheDocument();
expect(getLoginSession()).toEqual({
...savedSession,
roleCodes: ['VIEWER'],
permCodes: ['store:list:view'],
});
view.unmount();
authInfo.mockImplementation(() => new Promise(() => {}));
render(
<AccessProvider>
<PermissionProbe />
</AccessProvider>,
);
expect(screen.getByText('门店菜单')).toBeInTheDocument();
expect(screen.getByLabelText('当前角色')).toHaveTextContent('VIEWER');
expect(screen.queryByText('审批通过权限')).not.toBeInTheDocument();
expect(screen.queryByText('审批菜单')).not.toBeInTheDocument();
});
it('切换账号后旧登录信息响应不能恢复上一账号的操作权限', async () => {
let resolveOldInfo: (info: { roleCodes: string[]; permCodes: string[] }) => void = () => {};
authInfo.mockImplementation(
() =>
new Promise((resolve) => {
resolveOldInfo = resolve;
}),
);
setToken('test-old-token');
function SwitchAccount() {
const { applyLogin } = useAccess();
return ( return (
<> <button
{can('store:approve') && <span>审批菜单</span>} onClick={() => {
{can('store:list') && <span>门店菜单</span>} setToken('test-new-token');
</> applyLogin({ roleCodes: ['VIEWER'], permCodes: ['store:list:view'] });
}}
>
切换账号
</button>
); );
} }
render( render(
<AccessProvider> <AccessProvider>
<Probe /> <PermissionProbe />
<SwitchAccount />
</AccessProvider>, </AccessProvider>,
); );
expect(screen.getByText('审批菜单')).toBeInTheDocument(); fireEvent.click(screen.getByRole('button', { name: '切换账号' }));
expect(screen.queryByText('门店菜单')).not.toBeInTheDocument(); await act(async () => {
resolveOldInfo({
roleCodes: ['YJ_FINANCE_MGR'],
permCodes: ['store:approve:view', 'store:approve:pass'],
});
});
expect(screen.getByText('门店菜单')).toBeInTheDocument();
expect(screen.queryByText('审批菜单')).not.toBeInTheDocument();
expect(screen.queryByText('审批通过权限')).not.toBeInTheDocument();
expect(screen.getByLabelText('当前角色')).toHaveTextContent('VIEWER');
});
it.each([
[{ permCodes: ['store:list:view'], permissions: ['store:approve:pass'] }, ['store:list:view']],
[{ permCodes: [], permissions: ['store:approve:pass'] }, []],
[
{ data: { permCodes: ['store:list:view'], permissions: ['store:approve:pass'] } },
['store:list:view'],
],
])('归一权限时以新的 permCodes 字段为准:%j', (raw, expected) => {
expect(normalizePermissions(raw)).toEqual(expected);
}); });
}); });
import { Layout, Menu, Avatar, Dropdown, Input, Button, Breadcrumb } from 'antd'; import { Layout, Menu, Avatar, Dropdown, Button, Breadcrumb } from 'antd';
import { Suspense, useEffect, useState } from 'react'; import { Suspense, useEffect, useState } from 'react';
import { Outlet, useLocation, useNavigate } from 'react-router-dom'; import { Outlet, useLocation, useNavigate } from 'react-router-dom';
import { import {
DashboardOutlined, DashboardOutlined,
ShopOutlined, ShopOutlined,
UploadOutlined, UploadOutlined,
SearchOutlined,
LogoutOutlined, LogoutOutlined,
UserOutlined, UserOutlined,
TeamOutlined, TeamOutlined,
......
...@@ -2,7 +2,7 @@ import { render, screen, fireEvent, waitFor, within } from '@testing-library/rea ...@@ -2,7 +2,7 @@ import { render, screen, fireEvent, waitFor, within } from '@testing-library/rea
import { App, ConfigProvider } from 'antd'; import { App, ConfigProvider } from 'antd';
import { QueryClient, QueryClientProvider } from '@tanstack/react-query'; import { QueryClient, QueryClientProvider } from '@tanstack/react-query';
import { beforeEach, describe, expect, it, vi } from 'vitest'; import { beforeEach, describe, expect, it, vi } from 'vitest';
import { AccessProvider, saveUserInfo } from '@/access'; import { AccessTestProvider } from '@/test/AccessTestProvider';
import type { ApprovalRow } from '@/api'; import type { ApprovalRow } from '@/api';
import StoreApprove from '../index'; import StoreApprove from '../index';
...@@ -15,6 +15,7 @@ const api = vi.hoisted(() => ({ ...@@ -15,6 +15,7 @@ const api = vi.hoisted(() => ({
revokeApproval: vi.fn(), revokeApproval: vi.fn(),
})); }));
vi.mock('@/api', () => ({ store: api })); vi.mock('@/api', () => ({ store: api }));
vi.mock('@/api/modules/auth', () => ({ auth: { info: vi.fn() } }));
const row = { const row = {
listingId: '101', listingId: '101',
...@@ -68,10 +69,9 @@ beforeEach(() => { ...@@ -68,10 +69,9 @@ beforeEach(() => {
}; };
}, },
); );
saveUserInfo({ permCodes: ['store:approve:view', 'store:approve:pass', 'store:approve:reject'] });
}); });
function mount() { function mount(permCodes = ['store:approve:view', 'store:approve:pass', 'store:approve:reject']) {
const client = new QueryClient({ const client = new QueryClient({
defaultOptions: { queries: { retry: false, staleTime: 30_000 }, mutations: { retry: false } }, defaultOptions: { queries: { retry: false, staleTime: 30_000 }, mutations: { retry: false } },
}); });
...@@ -81,9 +81,9 @@ function mount() { ...@@ -81,9 +81,9 @@ function mount() {
<ConfigProvider button={{ autoInsertSpace: false }}> <ConfigProvider button={{ autoInsertSpace: false }}>
<App> <App>
<QueryClientProvider client={client}> <QueryClientProvider client={client}>
<AccessProvider> <AccessTestProvider permCodes={permCodes}>
<StoreApprove /> <StoreApprove />
</AccessProvider> </AccessTestProvider>
</QueryClientProvider> </QueryClientProvider>
</App> </App>
</ConfigProvider>, </ConfigProvider>,
...@@ -315,8 +315,7 @@ describe('门店审批页面', () => { ...@@ -315,8 +315,7 @@ describe('门店审批页面', () => {
}); });
it('仅打回权限保留审核入口,但不显示多选与批量审批', async () => { it('仅打回权限保留审核入口,但不显示多选与批量审批', async () => {
saveUserInfo({ permCodes: ['store:approve:view', 'store:approve:reject'] }); mount(['store:approve:view', 'store:approve:reject']);
mount();
await screen.findByText('测试门店'); await screen.findByText('测试门店');
expect(screen.getByRole('button', { name: '审核' })).toBeInTheDocument(); expect(screen.getByRole('button', { name: '审核' })).toBeInTheDocument();
expect(screen.queryByRole('checkbox')).not.toBeInTheDocument(); expect(screen.queryByRole('checkbox')).not.toBeInTheDocument();
...@@ -324,10 +323,18 @@ describe('门店审批页面', () => { ...@@ -324,10 +323,18 @@ describe('门店审批页面', () => {
}); });
it('无审批查看权限时不加载业务数据', async () => { it('无审批查看权限时不加载业务数据', async () => {
saveUserInfo({ permCodes: [] }); mount([]);
mount(); expect(screen.getByText('无门店审批访问权限')).toBeInTheDocument();
expect(api.listApprovals).not.toHaveBeenCalled();
});
it('仅有通过权限不能替代页面查看权限,也不加载审批详情', () => {
mount(['store:approve:pass']);
expect(screen.getByText('无门店审批访问权限')).toBeInTheDocument(); expect(screen.getByText('无门店审批访问权限')).toBeInTheDocument();
expect(screen.queryByRole('button', { name: '审核' })).not.toBeInTheDocument();
expect(screen.queryByRole('button', { name: '批量审批' })).not.toBeInTheDocument();
expect(api.listApprovals).not.toHaveBeenCalled(); expect(api.listApprovals).not.toHaveBeenCalled();
expect(api.getApproval).not.toHaveBeenCalled();
}); });
it('重复查询同一条件仍刷新服务端', async () => { it('重复查询同一条件仍刷新服务端', async () => {
...@@ -363,14 +370,14 @@ describe('门店审批页面', () => { ...@@ -363,14 +370,14 @@ describe('门店审批页面', () => {
expect(screen.queryByRole('button', { name: '撤回' })).not.toBeInTheDocument(); expect(screen.queryByRole('button', { name: '撤回' })).not.toBeInTheDocument();
}); });
it('本人待办撤回需确认并刷新状态与操作区', async () => { it('仅查看权限也允许本人待办撤回,确认后刷新状态与操作区', async () => {
mine = [ mine = [
{ ...row, listingId: '202', status: 'PENDING', statusLabel: '待审批', actionable: false }, { ...row, listingId: '202', status: 'PENDING', statusLabel: '待审批', actionable: false },
]; ];
api.revokeApproval.mockImplementation(async () => { api.revokeApproval.mockImplementation(async () => {
mine = [{ ...mine[0], status: 'REVOKED', statusLabel: '已撤回' }]; mine = [{ ...mine[0], status: 'REVOKED', statusLabel: '已撤回' }];
}); });
mount(); mount(['store:approve:view']);
await screen.findByText('测试门店'); await screen.findByText('测试门店');
fireEvent.click(screen.getByRole('tab', { name: /我发起的/ })); fireEvent.click(screen.getByRole('tab', { name: /我发起的/ }));
fireEvent.click(await screen.findByRole('button', { name: '撤回' })); fireEvent.click(await screen.findByRole('button', { name: '撤回' }));
...@@ -385,8 +392,7 @@ describe('门店审批页面', () => { ...@@ -385,8 +392,7 @@ describe('门店审批页面', () => {
}); });
it('没有处置权限只显示查看,不渲染批量入口和选择框', async () => { it('没有处置权限只显示查看,不渲染批量入口和选择框', async () => {
saveUserInfo({ permCodes: ['store:approve:view'] }); mount(['store:approve:view']);
mount();
await screen.findByText('测试门店'); await screen.findByText('测试门店');
expect(screen.getByRole('button', { name: '查看' })).toBeInTheDocument(); expect(screen.getByRole('button', { name: '查看' })).toBeInTheDocument();
expect(screen.queryByRole('button', { name: '审核' })).not.toBeInTheDocument(); expect(screen.queryByRole('button', { name: '审核' })).not.toBeInTheDocument();
......
...@@ -3,7 +3,7 @@ import zhCN from 'antd/locale/zh_CN'; ...@@ -3,7 +3,7 @@ import zhCN from 'antd/locale/zh_CN';
import { QueryClient, QueryClientProvider } from '@tanstack/react-query'; import { QueryClient, QueryClientProvider } from '@tanstack/react-query';
import { cleanup, fireEvent, render, screen, waitFor, within } from '@testing-library/react'; import { cleanup, fireEvent, render, screen, waitFor, within } from '@testing-library/react';
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import { AccessProvider, saveUserInfo } from '@/access'; import { AccessTestProvider } from '@/test/AccessTestProvider';
import StoreListing from './index'; import StoreListing from './index';
const api = vi.hoisted(() => ({ const api = vi.hoisted(() => ({
...@@ -15,6 +15,7 @@ const api = vi.hoisted(() => ({ ...@@ -15,6 +15,7 @@ const api = vi.hoisted(() => ({
exportStores: vi.fn(), exportStores: vi.fn(),
})); }));
vi.mock('@/api', () => ({ store: api })); vi.mock('@/api', () => ({ store: api }));
vi.mock('@/api/modules/auth', () => ({ auth: { info: vi.fn() } }));
const rows = [ const rows = [
{ {
...@@ -40,7 +41,6 @@ const columns = ['storeName', 'merchantNo', 'businessScene', 'effectiveTime', 'c ...@@ -40,7 +41,6 @@ const columns = ['storeName', 'merchantNo', 'businessScene', 'effectiveTime', 'c
const queryClients: QueryClient[] = []; const queryClients: QueryClient[] = [];
function renderPage(permissions = ['store:list:view', 'store:list:export']) { function renderPage(permissions = ['store:list:view', 'store:list:export']) {
saveUserInfo({ permCodes: permissions, dataScope: 3 });
const client = new QueryClient({ const client = new QueryClient({
defaultOptions: { queries: { retry: false, staleTime: 30_000 }, mutations: { retry: false } }, defaultOptions: { queries: { retry: false, staleTime: 30_000 }, mutations: { retry: false } },
}); });
...@@ -49,9 +49,9 @@ function renderPage(permissions = ['store:list:view', 'store:list:export']) { ...@@ -49,9 +49,9 @@ function renderPage(permissions = ['store:list:view', 'store:list:export']) {
<ConfigProvider locale={zhCN}> <ConfigProvider locale={zhCN}>
<App> <App>
<QueryClientProvider client={client}> <QueryClientProvider client={client}>
<AccessProvider> <AccessTestProvider permCodes={permissions}>
<StoreListing /> <StoreListing />
</AccessProvider> </AccessTestProvider>
</QueryClientProvider> </QueryClientProvider>
</App> </App>
</ConfigProvider>, </ConfigProvider>,
...@@ -381,6 +381,16 @@ describe('门店列表', () => { ...@@ -381,6 +381,16 @@ describe('门店列表', () => {
expect(api.getStore).not.toHaveBeenCalled(); expect(api.getStore).not.toHaveBeenCalled();
}); });
it('仅有导出权限不能替代列表查看权限,也不显示导出操作', async () => {
renderPage(['store:list:export']);
expect(await screen.findByText('无门店列表访问权限')).toBeInTheDocument();
expect(screen.queryByRole('button', { name: /导\s*出/ })).not.toBeInTheDocument();
expect(screen.queryByRole('button', { name: '查看详情' })).not.toBeInTheDocument();
expect(api.listStores).not.toHaveBeenCalled();
expect(api.getColumnConfig).not.toHaveBeenCalled();
expect(api.exportStores).not.toHaveBeenCalled();
});
it('总数减少造成当前页越界时自动回到最后有效页', async () => { it('总数减少造成当前页越界时自动回到最后有效页', async () => {
api.listStores.mockImplementation(async (params) => ({ api.listStores.mockImplementation(async (params) => ({
records: params.current === 3 ? [] : rows, records: params.current === 3 ? [] : rows,
......
import { useLayoutEffect, useRef, useState, type ReactNode } from 'react';
import { AccessProvider, useAccess } from '@/access';
const defaultRoles = ['VIEWER'];
interface Props {
permCodes: string[];
roleCodes?: string[];
children: ReactNode;
}
function ApplyTestLogin({ permCodes, roleCodes = defaultRoles, children }: Props) {
const { applyLogin } = useAccess();
const login = useRef(applyLogin);
login.current = applyLogin;
const [ready, setReady] = useState(false);
useLayoutEffect(() => {
login.current({ permCodes, roleCodes });
setReady(true);
}, [permCodes, roleCodes]);
return ready ? children : null;
}
/** Exercise the same permission entry point used after a real login. */
export function AccessTestProvider(props: Props) {
return (
<AccessProvider>
<ApplyTestLogin {...props} />
</AccessProvider>
);
}
// Tests never load signing keys from the filesystem.
export default '';
...@@ -8,6 +8,12 @@ export default defineConfig({ ...@@ -8,6 +8,12 @@ export default defineConfig({
alias: { alias: {
'@': fileURLToPath(new URL('./src', import.meta.url)), '@': fileURLToPath(new URL('./src', import.meta.url)),
'@uj/ui': fileURLToPath(new URL('./packages/ui/src/index.ts', import.meta.url)), '@uj/ui': fileURLToPath(new URL('./packages/ui/src/index.ts', import.meta.url)),
'virtual:server-public-key': fileURLToPath(
new URL('./src/test/virtual-key-stub.ts', import.meta.url),
),
'virtual:client-private-key': fileURLToPath(
new URL('./src/test/virtual-key-stub.ts', import.meta.url),
),
}, },
}, },
test: { environment: 'jsdom', setupFiles: ['./src/test/setup.ts'] }, test: { environment: 'jsdom', setupFiles: ['./src/test/setup.ts'] },
......
Markdown is supported
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!