Commit d5a060df by chenwq

Merge branch 'v1.0.0' of http://192.168.3.233:8090/ujia/uj-store into v1.0.0

2 parents 19fdacb6 a1c2d15a
Pipeline #328 for d5a060df failed in 0 seconds
......@@ -103,14 +103,15 @@ export function normalizePermissions(raw: unknown): string[] {
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') {
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.list)) return normalizePermissions(o.list);
if (o.data && typeof o.data === 'object') {
const d = o.data as Record<string, unknown>;
return normalizePermissions(d.permissions ?? d);
return normalizePermissions(d);
}
}
......
......@@ -16,6 +16,8 @@ export const P = {
/** 「审核」按钮挂在后端的审批通过动作码上 */
STORE_APPROVE_AUDIT: 'store:approve:pass',
STORE_APPROVE_REJECT: 'store:approve:reject',
/** 后端「撤回」按钮的权限码为 submit,不能用页面查看权限替代。 */
STORE_APPROVE_REVOKE: 'store:approve:submit',
// 门店列表(后端码:store:list:*)
/** 页面级裸资源:供 can() 判定页面可见性,不用于 canPoint */
STORE_LISTING: 'store:list',
......
import { createContext, useContext, useEffect, useMemo, useState, type ReactNode } from 'react';
import { defaultMatrix, type PermissionMatrix, type ResourceKey, type RoleKey } from '../model';
import {
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 { auth } from '../../api/modules/auth';
import { getToken } from '../../api/core/token';
import { getLoginSession, saveLoginSession } from '../session';
/** 登录/info 返回的会话数据(仅取权限相关字段,解耦 access 与具体后端响应结构) */
export interface LoginSession {
......@@ -15,7 +30,7 @@ interface AccessContextValue {
roleCodes: string[];
setRole: (r: RoleKey) => void;
matrix: PermissionMatrix;
/** 页面级权限:统一以 points 为准(页面资源裸码 = 可见,:manage = 完全权) */
/** 页面级权限:门店审批与列表必须有精确 :view,其他资源沿用既有规则。 */
can: (resource: ResourceKey, required?: 'view' | 'full') => boolean;
/** 当前账号持有的权限点集合(后端返回,经适配器归一化) */
points: Set<string>;
......@@ -29,14 +44,21 @@ interface AccessContextValue {
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 }) {
const [role, setRoleState] = useState<RoleKey>('SYS_ADMIN');
const [roleCodes, setRoleCodes] = useState<string[]>([]);
const [savedSession] = useState(getLoginSession);
const [role, setRoleState] = useState<RoleKey>(() => sessionRole(savedSession?.roleCodes ?? []));
const [roleCodes, setRoleCodes] = useState<string[]>(savedSession?.roleCodes ?? []);
const [matrix] = useState<PermissionMatrix>(defaultMatrix);
// 默认按超级管理员矩阵给一份(无后端时的开发兜底,避免首屏权限全空)
const [points, setPoints] = useState<Set<string>>(
() => new Set(matrixToPoints(matrix, 'SYS_ADMIN')),
);
// 刷新时沿用登录返回的真实权限;没有有效会话时不授予业务权限。
const [points, setPoints] = useState<Set<string>>(() => {
const next = new Set(normalizePermissions(savedSession?.permCodes));
if (savedSession) next.add('dashboard');
return next;
});
// 开发兜底:按角色矩阵推导权限点(无后端时本地演示用)
const setRole = (r: RoleKey) => {
......@@ -45,16 +67,17 @@ export function AccessProvider({ children }: { children: ReactNode }) {
};
// 真实登录:直接用后端返回的权限码(页面/按钮级统一以 points 为准)
const applyLogin = (session: LoginSession) => {
const applyLogin = useCallback((session: LoginSession) => {
const codes = session.roleCodes ?? [];
setRoleCodes(codes);
const next = new Set(normalizePermissions(session.permCodes));
setRoleState(sessionRole(codes));
const next = new Set(normalizePermissions(session));
// 后端未下发 dashboard 权限码,前端按约定补齐:
// 工作台是所有角色的落地页,登录即可见,不该被权限挡住。
//(原 access.manage 权限矩阵调试页已下线:后端菜单树与 permCodes 均无该权限点)
next.add('dashboard');
setPoints(next);
};
}, []);
const loadPermissions = (raw: unknown) => {
setPoints(new Set(normalizePermissions(raw)));
......@@ -62,14 +85,30 @@ export function AccessProvider({ children }: { children: ReactNode }) {
// 刷新/重进:若本地已有令牌,拉取当前用户信息恢复权限(令牌失效由 http 401 处理)
useEffect(() => {
if (!getToken()) return;
const token = getToken();
if (!token) return;
let active = true;
auth
.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(() => {
/* 忽略:令牌失效时 http 拦截器会清除本地令牌,登录态由路由守卫兜底 */
});
}, []);
return () => {
active = false;
};
}, [applyLogin]);
const value = useMemo<AccessContextValue>(
() => ({
......@@ -78,9 +117,12 @@ export function AccessProvider({ children }: { children: ReactNode }) {
setRole,
matrix,
can: (resource, required = 'view') => {
if (required === 'view' && (resource === 'store:approve' || resource === 'store:list')) {
return points.has(`${resource}:view`);
}
if (points.has(resource)) return true;
if (required === 'full') return points.has(`${resource}:manage`);
// 后端若只下发叶子权限码(如 store:list:export),亦视为该资源可见
// 其他资源仍兼容仅下发叶子权限码的情况。
return [...points].some((p) => p.startsWith(`${resource}:`));
},
points,
......@@ -88,7 +130,7 @@ export function AccessProvider({ children }: { children: ReactNode }) {
loadPermissions,
applyLogin,
}),
[role, roleCodes, matrix, points],
[role, roleCodes, matrix, points, applyLogin],
);
return <AccessContext.Provider value={value}>{children}</AccessContext.Provider>;
......
......@@ -13,6 +13,7 @@ import {
} from './sign';
import { SIGN_CONFIG, SIGN_ENABLED } from './config';
import { getToken, clearToken } from './token';
import { parseStoreResponse } from './storeJson';
const http: AxiosInstance = axios.create({
baseURL: SIGN_CONFIG.BASE_URL,
......@@ -23,6 +24,12 @@ const http: AxiosInstance = axios.create({
// ---------- 请求拦截:前端加签 ----------
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;
......@@ -61,7 +68,6 @@ http.interceptors.request.use((config: any) => {
const query = full.search.slice(1).split('&').filter(Boolean).sort().join('&');
// 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 media = isForm
? 'multipart/form-data'
......@@ -112,11 +118,6 @@ http.interceptors.request.use((config: any) => {
if (config.data && !isForm && !existingCt) {
headers['Content-Type'] = 'application/json';
}
// 登录令牌:从本地读取并注入 Authorization 头(登录接口本身无 token,getToken 返回 null 时不注入)
const token = getToken();
if (token) {
headers['Authorization'] = `Bearer ${token}`;
}
config.headers = headers;
return config;
});
......@@ -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) {
// 令牌失效/未登录:先自清除令牌,保证后续请求不再携带已失效凭据;
// 再通知上层统一登出——必须同时清掉会话 session 并把 loggedIn 置 false,
......@@ -190,7 +191,11 @@ http.interceptors.response.use(
clearToken();
_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.data = 'data' in body ? body.data : undefined;
return Promise.reject(err);
......
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import type { AxiosAdapter, InternalAxiosRequestConfig } from 'axios';
import { http } from '../../core/http';
import { setToken } from '../../core/token';
import * as signing from '../../core/sign';
import { store } from '../store';
const originalAdapter = http.defaults.adapter;
......@@ -182,23 +184,32 @@ describe('store API contract', () => {
});
});
it('retains existing import upload and submission behavior', async () => {
const file = new File(['example'], 'import.xlsx');
// 契约对齐 store.ts:submitImport 只接收 listingIds(草稿记录 ID 列表)
const payload = { listingIds: [1001, 1002] };
serve((config) => {
if (config.url === '/store/import/check') {
expect(config.data.get('file')).toBe(file);
expect(config.data.get('templateVersion')).toBe('V1.0.1');
return { data: result({ taskId: 'task-1' }) };
}
expect(config.url).toBe('/store/import/submit');
expect(JSON.parse(config.data)).toEqual(payload);
return { data: result({ approveId: 'approval-1' }) };
});
expect(await store.uploadImport({ file })).toEqual({ taskId: 'task-1' });
expect(await store.submitImport(payload)).toEqual({ approveId: 'approval-1' });
});
it.each([undefined, '补充门店上架资料'])(
'uploads the file and optional remark (%s), then submits listing IDs',
async (remark) => {
const file = new File(['example'], 'import.xlsx');
const payload = { listingIds: [1001, 1002] };
const checked = { ...payload, submitted: false };
const submitted = { ...payload, submitted: true };
serve((config) => {
if (config.url === '/store/import/check') {
expect(config.method).toBe('post');
expect(config.data).toBeInstanceOf(FormData);
expect(config.data.get('file')).toBe(file);
expect(config.data.get('remark')).toBe(remark ?? null);
expect([...config.data.keys()]).toEqual(
remark === undefined ? ['file'] : ['file', 'remark'],
);
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', () => {
......@@ -221,14 +232,16 @@ describe('direct store export', () => {
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();
localStorage.setItem('session', JSON.stringify({ token: 'test-token', tokenType: 'Bearer' }));
vi.spyOn(signing, 'isSignReady').mockReturnValue(false);
setToken('test-token');
const watched = watchDownloads();
serve((config) => {
expect(config.url).toBe('/store/listing/export');
expect(config.responseType).toBe('arraybuffer');
expect(config.headers.get('Authorization')).toBe('Bearer test-token');
expect(config.headers.get('X-Sign')).toBeUndefined();
expect(config.params).toEqual({
businessScene: 'AFTER_SALE_MEMBER',
startDate: '2026-10-01',
......
......@@ -40,7 +40,7 @@ function invalidDownload(payload: unknown): Error {
export async function downloadStoreExport(http: AxiosInstance, params: ListingPageParams) {
let filename = DEFAULT_FILENAME;
let mime = 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet';
const payload: unknown = await http.request({
const response: unknown = await http.request({
method: 'GET',
url: '/store/listing/export',
params,
......@@ -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);
const blob = new Blob([payload], { type: mime });
......
......@@ -11,6 +11,12 @@ export const DEFAULT_PAGE_SIZE = 10;
export type DataTableColumn<T> = ColumnsType<T>[number] & { line?: number };
export type DataTableColumnsType<T> = DataTableColumn<T>[];
/** 通用行选择配置,兼容原生受控选中值、回调和逐行禁用。 */
export interface DataTableRowSelection<T> extends NonNullable<TableProps<T>['rowSelection']> {
/** 暂停整组选择交互,保留已有勾选,适用于请求或批量操作期间。 */
disabled?: boolean;
}
/** 列表行操作配置;配置 permission 时自动使用权限按钮。 */
export interface RowActionSchema<T> extends Omit<ActionSchema, 'danger' | 'label' | 'onClick'> {
/** 可按当前行动态生成操作文案。 */
......@@ -23,17 +29,11 @@ export interface RowActionSchema<T> extends Omit<ActionSchema, 'danger' | 'label
export interface DataTableProps<T> extends Pick<
TableProps<T>,
| 'dataSource'
| 'loading'
| 'rowKey'
| 'rowSelection'
| 'onChange'
| 'scroll'
| 'size'
| 'locale'
| 'className'
'dataSource' | 'loading' | 'rowKey' | 'onChange' | 'scroll' | 'size' | 'locale' | 'className'
> {
columns: DataTableColumnsType<T>;
/** true 开启默认多选,false/省略关闭;对象可配置受控选择与禁用规则。 */
rowSelection?: boolean | DataTableRowSelection<T>;
showIndex?: boolean;
pagination?:
| {
......@@ -76,6 +76,7 @@ export function DataTable<T extends object>({
pagination,
actions,
rowActions,
rowSelection,
actionColumnTitle = '操作',
actionColumnWidth,
actionColumnFixed,
......@@ -91,6 +92,26 @@ export function DataTable<T extends object>({
}: DataTableProps<T>) {
const records = pageData?.[recordsKey];
const dataSource = Array.isArray(records) ? (records as T[]) : props.dataSource;
const { disabled, getCheckboxProps, getTitleCheckboxProps, ...selectionOptions } =
typeof rowSelection === 'object' ? rowSelection : {};
const resolvedSelection: TableProps<T>['rowSelection'] = rowSelection
? {
type: 'checkbox',
fixed: 'left',
columnWidth: 48,
preserveSelectedRowKeys: false,
...selectionOptions,
selections: disabled ? false : selectionOptions.selections,
getCheckboxProps: (record) => {
const checkboxProps = getCheckboxProps?.(record);
return { ...checkboxProps, disabled: disabled || checkboxProps?.disabled };
},
getTitleCheckboxProps: () => {
const checkboxProps = getTitleCheckboxProps?.();
return { ...checkboxProps, disabled: disabled || checkboxProps?.disabled };
},
}
: undefined;
const resolvedPagination = pagination
? {
...pagination,
......@@ -189,6 +210,7 @@ export function DataTable<T extends object>({
dataSource={dataSource}
columns={tableColumns}
tableLayout={hasLineLimit ? 'fixed' : undefined}
rowSelection={resolvedSelection}
pagination={
resolvedPagination === false
? false
......
import { useState, type Key } from 'react';
import { fireEvent, render, screen, within } from '@testing-library/react';
import userEvent from '@testing-library/user-event';
import { describe, expect, it, vi } from 'vitest';
import { DataTable } from '../DataTable';
const records = [
{ id: '9007199254740993', name: '可选门店甲', locked: false },
{ id: '102', name: '可选门店乙', locked: false },
{ id: '103', name: '不可选门店', locked: true },
];
const columns = [{ title: '门店', dataIndex: 'name' }];
const checkboxFor = (name: string) =>
within(screen.getByRole('row', { name: new RegExp(name) })).getByRole('checkbox');
describe('DataTable 多选', () => {
it.each([false, true])(
'使用快捷开关启用多选,支持逐行和全选切换(fillHeight=%s)',
(fillHeight) => {
const view = render(
<DataTable
rowKey="id"
columns={columns}
dataSource={records}
pagination={false}
fillHeight={fillHeight}
/>,
);
expect(screen.queryByRole('checkbox')).not.toBeInTheDocument();
view.rerender(
<DataTable
rowKey="id"
columns={columns}
dataSource={records}
pagination={false}
fillHeight={fillHeight}
rowSelection
/>,
);
fireEvent.click(checkboxFor('可选门店甲'));
expect(checkboxFor('可选门店甲')).toBeChecked();
const all = screen.getByRole('checkbox', { name: 'Select all' });
expect(all).toBePartiallyChecked();
fireEvent.click(all);
expect(
screen.getAllByRole('checkbox').every((checkbox) => (checkbox as HTMLInputElement).checked),
).toBe(true);
fireEvent.click(all);
expect(
screen
.getAllByRole('checkbox')
.every((checkbox) => !(checkbox as HTMLInputElement).checked),
).toBe(true);
view.rerender(
<DataTable
rowKey="id"
columns={columns}
dataSource={records}
pagination={false}
rowSelection={false}
/>,
);
expect(screen.queryByRole('checkbox')).not.toBeInTheDocument();
},
);
it('受控选择保留完整ID,全选排除禁用行,并响应外部清空', () => {
const onChange = vi.fn();
function ControlledTable() {
const [keys, setKeys] = useState<Key[]>([]);
return (
<>
<button onClick={() => setKeys([])}>清空选择</button>
<DataTable
rowKey="id"
columns={columns}
dataSource={records}
pagination={false}
rowSelection={{
selectedRowKeys: keys,
onChange: (nextKeys, rows, info) => {
setKeys(nextKeys);
onChange(nextKeys, rows, info);
},
getCheckboxProps: (record) => ({ disabled: record.locked }),
}}
/>
</>
);
}
render(<ControlledTable />);
expect(checkboxFor('不可选门店')).toBeDisabled();
fireEvent.click(screen.getByRole('checkbox', { name: 'Select all' }));
expect(onChange).toHaveBeenLastCalledWith(['9007199254740993', '102'], records.slice(0, 2), {
type: 'all',
});
expect(checkboxFor('不可选门店')).not.toBeChecked();
fireEvent.click(screen.getByRole('button', { name: '清空选择' }));
expect(checkboxFor('可选门店甲')).not.toBeChecked();
expect(checkboxFor('可选门店乙')).not.toBeChecked();
});
it('整组禁用优先于单行和表头配置,保留已选状态并禁止变更', async () => {
const user = userEvent.setup();
const onChange = vi.fn();
render(
<DataTable
rowKey="id"
columns={columns}
dataSource={records}
pagination={false}
rowSelection={{
disabled: true,
selectedRowKeys: [records[0].id],
onChange,
getCheckboxProps: () => ({ disabled: false }),
getTitleCheckboxProps: () => ({ disabled: false }),
}}
/>,
);
expect(checkboxFor('可选门店甲')).toBeChecked();
for (const checkbox of screen.getAllByRole('checkbox')) {
expect(checkbox).toBeDisabled();
await user.click(checkbox.closest('label')!);
}
expect(onChange).not.toHaveBeenCalled();
});
it('没有可选行时禁用全选,空表也不能发出选择回调', () => {
const onChange = vi.fn();
const view = render(
<DataTable
rowKey="id"
columns={columns}
dataSource={records}
pagination={false}
rowSelection={{ onChange, getCheckboxProps: () => ({ disabled: true }) }}
/>,
);
expect(screen.getByRole('checkbox', { name: 'Select all' })).toBeDisabled();
view.rerender(
<DataTable
rowKey="id"
columns={columns}
dataSource={[]}
pagination={false}
rowSelection={{ onChange }}
/>,
);
expect(screen.getByRole('checkbox', { name: 'Select all' })).toBeDisabled();
expect(onChange).not.toHaveBeenCalled();
});
});
......@@ -9,6 +9,7 @@ export type {
DataTableColumn,
DataTableColumnsType,
DataTableProps,
DataTableRowSelection,
RowActionSchema,
} from './DataTable';
export { ConfirmModal } from './ConfirmModal';
......
import type { TableColumnsType } from 'antd';
import { UTable } from '@uj/ui';
import type { StoreListingDetail, StoreListingItem } from '@/api';
import type { StoreDictionaries } from './dictionaries';
import { dictionaryLabel, formatMoney, formatPolicyValue } from './formatters';
import './approvalPolicy.css';
interface PanelProps {
detail: StoreListingDetail;
spec?: StoreDictionaries;
}
type PolicyPrefix = 'marketFee1' | 'marketFee2' | 'sunshine1' | 'sunshine2';
type PolicyRow = StoreListingItem & { displayKey: string };
function categoryCount(detail: StoreListingDetail): number | undefined {
if (
typeof detail.categoryCount === 'number' &&
Number.isSafeInteger(detail.categoryCount) &&
detail.categoryCount >= 0
) {
return detail.categoryCount;
}
if (!detail.items) return undefined;
return new Set(detail.items.map((item) => item.productCategory?.trim()).filter(Boolean)).size;
}
export function ApprovalPolicyPanel({
detail,
spec,
kind,
}: PanelProps & { kind: 'market' | 'sunshine' }) {
const market = kind === 'market';
const name = market ? '管理层市场费' : '一线阳光激励';
const prefixes: PolicyPrefix[] = market
? ['marketFee1', 'marketFee2']
: ['sunshine1', 'sunshine2'];
const columns: TableColumnsType<PolicyRow> = [
{
title: '产品分类',
key: 'category',
width: market ? 120 : 110,
fixed: 'left',
render: (_, item) => (
<span className="approval-policy-panel__category">
{dictionaryLabel(spec?.productCategories, item.productCategory)}
</span>
),
},
...prefixes.flatMap((prefix, index): TableColumnsType<PolicyRow> => [
...(prefix === 'sunshine1' || prefix === 'sunshine2'
? [
{
title: '开启线上积分',
key: `${prefix}OnlinePoint`,
width: 100,
render: (_: unknown, item: PolicyRow) =>
dictionaryLabel(spec?.onlinePointFlags, item[`${prefix}OnlinePoint`]),
},
]
: []),
{
title: `${market ? '市场费' : '激励'}${index + 1}计算模式`,
key: `${prefix}CalcMode`,
width: market ? 110 : 100,
render: (_, item) => dictionaryLabel(spec?.calcModes, item[`${prefix}CalcMode`]),
},
{
title: '计算方式',
key: `${prefix}CalcWay`,
width: market ? 90 : 80,
render: (_, item) => dictionaryLabel(spec?.calcWays, item[`${prefix}CalcWay`]),
},
{
title: `${market ? '市场费' : '激励费'}${index + 1}`,
key: `${prefix}Value`,
width: 80,
align: 'right',
render: (_, item) => (
<span className="approval-policy-panel__value">
{formatPolicyValue(item[`${prefix}Value`], item[`${prefix}Unit`] ?? undefined)}
</span>
),
},
]),
];
const rows = (detail.items || []).map((item, index) => ({
...item,
displayKey: `${item.itemId ?? 'item'}-${index}`,
}));
const count = categoryCount(detail);
return (
<section className="approval-policy-panel" aria-label={`${name}政策`}>
<div className="approval-policy-panel__table">
<UTable<PolicyRow>
rowKey="displayKey"
size="small"
pagination={false}
columns={columns}
dataSource={rows}
scroll={{ x: 'max-content' }}
/>
</div>
<p className="approval-policy-panel__note">
本页签展示本审批记录({detail.storeName || '—'} ·{' '}
{dictionaryLabel(spec?.businessScenes, detail.businessScene)})下
{count === undefined ? '的产品分类' : ` ${count} 个产品分类`}的{name}
政策,仅展示,不参与逐项勾选。
</p>
{!market && (
<p className="approval-policy-panel__note">
「开启线上积分」按记录中的是否值展示,激励费按各项政策的计算方式与单位展示。
</p>
)}
</section>
);
}
interface CostRow {
key: string;
name: string;
value: string;
description: string;
total?: boolean;
}
export function ApprovalCostPanel({ detail, spec }: PanelProps) {
// The heading supplies the currency unit. All digits still come from the shared formatter.
const amount = (value: StoreListingDetail['costTotal']) => formatMoney(value).replace(/^¥/, '');
const rows: CostRow[] = [
{
key: 'decoration',
name: '装修、设备总投入',
value: amount(detail.costDecoration),
description: '门店装修与设备投入',
},
{
key: 'monthly',
name: '当月产生(房租、水电、耗材等)',
value: amount(detail.costMonthly),
description: '门店当月房租、水电、耗材等费用',
},
{
key: 'labor',
name: '人工成本',
value: amount(detail.costLabor),
description: '门店人工成本',
},
{
key: 'total',
name: '运营成本合计',
value: amount(detail.costTotal),
description: '门店维度的运营成本合计',
total: true,
},
{
key: 'categories',
name: '本场景产品分类行数',
value: String(categoryCount(detail) ?? '—'),
description: dictionaryLabel(spec?.businessScenes, detail.businessScene),
},
];
const columns: TableColumnsType<CostRow> = [
{
title: '项目',
dataIndex: 'name',
key: 'name',
width: 240,
render: (value: string) => <span className="approval-cost-panel__name">{value}</span>,
},
{
title: '金额(元)',
dataIndex: 'value',
key: 'value',
width: 130,
align: 'right',
render: (value: string, row) =>
row.total ? <strong className="approval-cost-panel__total">{value}</strong> : value,
},
{
title: '说明',
dataIndex: 'description',
key: 'description',
className: 'approval-cost-panel__description',
},
];
return (
<section className="approval-policy-panel approval-cost-panel" aria-label="运营成本明细">
<div className="approval-policy-panel__table">
<UTable<CostRow>
rowKey="key"
size="small"
pagination={false}
columns={columns}
dataSource={rows}
scroll={{ x: 'max-content' }}
/>
</div>
<p className="approval-policy-panel__note">
运营成本为门店维度,不随产品分类数或业务场景数重复累计。
</p>
</section>
);
}
import type { StoreChangeLog } from '@/api';
import { STORE_STATUS, type StoreStatus } from '@/config/storeStatus';
import type { StoreDictionaries } from './dictionaries';
import { dictionaryLabel, formatMoney } from './formatters';
import './listingHistory.css';
const EMPTY = '—';
const FIELD_LABELS: Record<string, string> = {
storeName: '门店名称',
merchantNo: '门店商户号',
status: '上架状态',
businessScene: '业务场景',
productCategory: '产品分类',
productCategories: '产品分类',
categoryCount: '产品分类数',
costDecoration: '装修、设备总投入',
costMonthly: '当月产生费用',
costLabor: '人工成本',
costTotal: '运营成本合计',
};
const COST_FIELDS = new Set(['costDecoration', 'costMonthly', 'costLabor', 'costTotal']);
const COST_LABELS = new Set([
'运营成本',
'装修、设备总投入',
'当月产生费用',
'人工成本',
'运营成本合计',
]);
const POLICY_LABELS: Record<string, string> = {
marketFee1: '管理层市场费 1',
marketFee2: '管理层市场费 2',
sunshine1: '一线阳光激励费 1',
sunshine2: '一线阳光激励费 2',
};
const POLICY_SUFFIX_LABELS: Record<string, string> = {
CalcMode: '计算模式',
CalcWay: '计算方式',
Value: '数值',
Unit: '单位',
OnlinePoint: '开启线上积分',
};
interface HistoryGroup {
key: string;
version?: number;
changes: StoreChangeLog[];
effectiveTime?: string;
}
function policyField(field: string) {
return field.match(/^(marketFee[12]|sunshine[12])(CalcMode|CalcWay|Value|Unit|OnlinePoint)$/);
}
function fieldLabel(field: string): string {
if (Object.hasOwn(FIELD_LABELS, field)) return FIELD_LABELS[field];
const policy = policyField(field);
if (policy) return `${POLICY_LABELS[policy[1]]} ${POLICY_SUFFIX_LABELS[policy[2]]}`;
return field || '变更字段未提供';
}
function changeCategory(field: string): string {
if (COST_FIELDS.has(field) || COST_LABELS.has(field)) return '运营成本';
if (policyField(field) || /市场费|阳光激励|激励计算|激励政策/.test(field)) return '激励政策';
if (field === 'businessScene' || field === '业务场景') return '业务场景';
if (
['productCategory', 'productCategories', 'categoryCount', '产品分类', '产品分类数'].includes(
field,
)
) {
return '产品分类';
}
return fieldLabel(field);
}
function isFirstListing(group: HistoryGroup): boolean {
return (
group.version === 1 &&
group.changes.some(
(change) =>
change.changeField === 'status' &&
change.afterValue === 'APPROVED' &&
change.beforeValue !== 'APPROVED',
)
);
}
function groupTitle(group: HistoryGroup): string {
if (isFirstListing(group)) return '首次上架';
const categories = [
...new Set(group.changes.map((change) => changeCategory(change.changeField || ''))),
];
if (
categories.length === 2 &&
categories.includes('激励政策') &&
categories.includes('运营成本')
) {
return '激励政策与运营成本调整';
}
if (
categories.length === 2 &&
categories.includes('业务场景') &&
categories.includes('产品分类')
) {
return '业务场景与产品分类调整';
}
if (categories.every((category) => category === '变更字段未提供')) return '门店信息变更';
return `${categories.join('与')}调整`;
}
function dateText(value?: string, includeTime = false): string {
const match = value?.trim().match(/^(\d{4}-\d{2}-\d{2})(?:[T ](\d{2}:\d{2}))?/);
if (!match) return EMPTY;
return includeTime && match[2] ? `${match[1]} ${match[2]}` : match[1];
}
function groupHistory(history: StoreChangeLog[]): HistoryGroup[] {
const groups: HistoryGroup[] = [];
const versions = new Map<number, HistoryGroup>();
history.forEach((change, index) => {
const version =
typeof change.versionNo === 'number' &&
Number.isSafeInteger(change.versionNo) &&
change.versionNo > 0
? change.versionNo
: undefined;
let group = version === undefined ? undefined : versions.get(version);
if (!group) {
group = {
key: version === undefined ? `unknown-${index}` : `version-${version}`,
version,
changes: [],
};
groups.push(group);
if (version !== undefined) versions.set(version, group);
}
group.changes.push(change);
const effectiveTime = change.effectiveTime?.trim();
if (
effectiveTime &&
dateText(effectiveTime) !== EMPTY &&
(!group.effectiveTime ||
effectiveTime.replace('T', ' ') > group.effectiveTime.replace('T', ' '))
) {
group.effectiveTime = effectiveTime;
}
});
return groups.sort((a, b) => {
if (a.version !== undefined && b.version !== undefined) return a.version > b.version ? -1 : 1;
if (a.version !== undefined) return -1;
if (b.version !== undefined) return 1;
return (b.effectiveTime || '').localeCompare(a.effectiveTime || '');
});
}
function categoryValue(value: string, spec?: StoreDictionaries): string {
// Multi-category audit values may be serialized arrays; preserve other API text verbatim.
if (value.trim().startsWith('[')) {
try {
const categories: unknown = JSON.parse(value);
if (
Array.isArray(categories) &&
categories.every((category) => typeof category === 'string')
) {
return categories.length
? categories
.map((category) => dictionaryLabel(spec?.productCategories, category))
.join(' / ')
: EMPTY;
}
} catch {
return value;
}
}
return dictionaryLabel(spec?.productCategories, value);
}
function changeValue(field: string, value: unknown, spec?: StoreDictionaries): string {
if (value === null || value === undefined || String(value).trim() === '') return EMPTY;
const text = String(value);
if (COST_FIELDS.has(field)) {
const formatted = formatMoney(value);
return formatted === EMPTY ? text : formatted;
}
if (field === 'status') {
return Object.hasOwn(STORE_STATUS, text) ? STORE_STATUS[text as StoreStatus].label : text;
}
if (field === 'businessScene') return dictionaryLabel(spec?.businessScenes, text);
if (field === 'productCategory' || field === 'productCategories')
return categoryValue(text, spec);
const policy = policyField(field);
if (policy?.[2] === 'CalcMode') return dictionaryLabel(spec?.calcModes, text);
if (policy?.[2] === 'CalcWay') return dictionaryLabel(spec?.calcWays, text);
if (policy?.[2] === 'OnlinePoint') return dictionaryLabel(spec?.onlinePointFlags, text);
if (policy?.[2] === 'Unit') return text === 'AMOUNT' ? '金额' : text === 'RATIO' ? '比例' : text;
// Policy values carry no unit in the audit DTO; do not infer money or percentages.
return text;
}
export function ListingChangeHistory({
history,
spec,
}: {
history: StoreChangeLog[] | null | undefined;
spec?: StoreDictionaries;
}) {
const groups = groupHistory(history || []);
return (
<section className="listing-change-history" aria-label="变更历史(只读)">
<h3 className="listing-change-history__heading">变更历史(只读)</h3>
{groups.length ? (
groups.map((group) => {
const versionLabel = group.version === undefined ? '版本未提供' : `v${group.version}`;
const users = [
...new Set(
group.changes.map((change) => change.changeUserName?.trim()).filter(Boolean),
),
];
return (
<article
key={group.key}
className="listing-change-history__version"
aria-label={group.version === undefined ? versionLabel : `版本 ${versionLabel}`}
>
<div className="listing-change-history__version-meta">
<strong>{versionLabel}</strong>
<span>{dateText(group.effectiveTime)}</span>
</div>
<div className="listing-change-history__content">
<h4>{groupTitle(group)}</h4>
{isFirstListing(group) && (
<p className="listing-change-history__description">
门店在系统中完成首次上架并生效。
</p>
)}
<dl className="listing-change-history__changes">
{group.changes.map((change, index) => {
const field = change.changeField?.trim() || '';
return (
<div key={`${change.changeId ?? 'change'}-${index}`}>
<dt>{fieldLabel(field)}</dt>
<dd>
{changeValue(field, change.beforeValue, spec)} →{' '}
{changeValue(field, change.afterValue, spec)}
</dd>
</div>
);
})}
</dl>
<p className="listing-change-history__audit">
变更人:{users.join('、') || EMPTY} · 生效时间{' '}
{dateText(group.effectiveTime, true)}
</p>
</div>
</article>
);
})
) : (
<p className="listing-change-history__empty">暂无变更历史</p>
)}
</section>
);
}
import type { StoreListingDetail } from '@/api';
import { formatMoney } from './formatters';
import './listingCost.css';
export function ListingCostPanel({ detail }: { detail: StoreListingDetail }) {
return (
<section className="listing-cost-panel" aria-label="运营成本(门店维度)">
<h3 className="listing-cost-panel__title">运营成本(门店维度)</h3>
<dl className="listing-cost-panel__fields">
<div>
<dt>装修、设备总投入</dt>
<dd>
<span className="listing-cost-panel__amount">{formatMoney(detail.costDecoration)}</span>
</dd>
</div>
<div>
<dt>当月产生费用</dt>
<dd>
<span className="listing-cost-panel__amount">{formatMoney(detail.costMonthly)}</span>
<span className="listing-cost-panel__hint">房租、水电、耗材等</span>
</dd>
</div>
<div>
<dt>人工成本</dt>
<dd>
<span className="listing-cost-panel__amount">{formatMoney(detail.costLabor)}</span>
<span className="listing-cost-panel__hint">按人力成本维度合并填写</span>
</dd>
</div>
<div>
<dt>运营成本合计</dt>
<dd>
<strong className="listing-cost-panel__amount">{formatMoney(detail.costTotal)}</strong>
</dd>
</div>
</dl>
<p className="listing-cost-panel__note">
运营成本为门店维度字段,同一门店的各业务场景记录需保持一致,系统在上传时校验一致性。
</p>
</section>
);
}
import { CloseOutlined } from '@ant-design/icons';
import { UButton } from '@uj/ui';
import type { StoreListingDetail } from '@/api';
import { STORE_STATUS, type StoreStatus } from '@/config/storeStatus';
import type { StoreDictionaries } from './dictionaries';
import { dictionaryLabel } from './formatters';
import './listingDetail.css';
const EMPTY = '—';
function categoryCount(detail: StoreListingDetail): string {
if (
typeof detail.categoryCount === 'number' &&
Number.isSafeInteger(detail.categoryCount) &&
detail.categoryCount >= 0
) {
return `${detail.categoryCount} 个`;
}
if (!detail.items) return EMPTY;
const categories = detail.items
.map((item) => item.productCategory?.trim())
.filter((category): category is string => !!category);
return `${new Set(categories).size} 个`;
}
function currentVersion(detail: StoreListingDetail): string {
const versions = (detail.changeHistory || [])
.map((change) => change.versionNo)
.filter(
(version): version is number =>
typeof version === 'number' && Number.isSafeInteger(version) && version > 0,
);
return versions.length
? `v${versions.reduce((latest, version) => Math.max(latest, version))}`
: EMPTY;
}
/** Format the API's calendar fields as text, preserving its original time zone. */
function effectiveDate(detail: StoreListingDetail, includeTime = false): string {
const value = detail.effectiveTime?.trim() || detail.approveTime?.trim();
const match = value?.match(/^(\d{4}-\d{2}-\d{2})(?:[T ](\d{2}:\d{2}))?/);
if (!match) return EMPTY;
return includeTime && match[2] ? `${match[1]} ${match[2]}` : match[1];
}
function ListingStatus({ detail }: { detail: StoreListingDetail }) {
const knownStatus = Object.hasOwn(STORE_STATUS, detail.status || '')
? STORE_STATUS[detail.status as StoreStatus]
: undefined;
const tone =
detail.status === 'APPROVED'
? 'approved'
: detail.status === 'PENDING'
? 'pending'
: detail.status === 'REJECTED'
? 'rejected'
: 'neutral';
return (
<span className={`listing-detail-status listing-detail-status--${tone}`}>
<span className="listing-detail-status__dot" aria-hidden="true" />
{detail.statusLabel?.trim() || knownStatus?.label || EMPTY}
</span>
);
}
export function ListingDetailHeader({
detail,
onClose,
}: {
detail: StoreListingDetail;
onClose: () => void;
}) {
return (
<section className="listing-detail-header" aria-label="门店概览">
<div className="listing-detail-header__top">
<h2>{detail.storeName?.trim() || EMPTY}</h2>
<div className="listing-detail-header__actions">
<ListingStatus detail={detail} />
<UButton
type="text"
className="listing-detail-header__close"
aria-label="关闭"
icon={<CloseOutlined />}
onClick={onClose}
/>
</div>
</div>
<dl className="listing-detail-meta">
<div>
<dt>商户号</dt>
<dd>{detail.merchantNo?.trim() || EMPTY}</dd>
</div>
<div>
<dt>业务场景</dt>
<dd>{detail.businessScene?.trim() ? '1 个' : EMPTY}</dd>
</div>
<div>
<dt>产品分类</dt>
<dd>{categoryCount(detail)}</dd>
</div>
<div>
<dt>上架时间</dt>
<dd>{effectiveDate(detail)}</dd>
</div>
<div>
<dt>当前版本</dt>
<dd>{currentVersion(detail)}</dd>
</div>
</dl>
</section>
);
}
export function ListingStoreInfo({
detail,
spec,
}: {
detail: StoreListingDetail;
spec?: StoreDictionaries;
}) {
const scene = detail.businessScene?.trim();
return (
<section className="listing-store-info" aria-label="门店信息">
<h3 className="listing-store-info__title">门店信息</h3>
<dl className="listing-store-info__fields">
<div>
<dt>门店名称</dt>
<dd>{detail.storeName?.trim() || EMPTY}</dd>
</div>
<div>
<dt>门店商户号</dt>
<dd>{detail.merchantNo?.trim() || EMPTY}</dd>
</div>
<div>
<dt>业务场景</dt>
<dd>
{scene ? (
<span className="listing-store-info__scene">
{dictionaryLabel(spec?.businessScenes, scene)}
</span>
) : (
EMPTY
)}
<span className="listing-store-info__hint">
同一门店的每个业务场景均覆盖全部产品分类
</span>
</dd>
</div>
<div>
<dt>产品分类数</dt>
<dd>
<span>{categoryCount(detail)}</span>
<span className="listing-store-info__hint">完整清单见「产品与场景」页签</span>
</dd>
</div>
<div>
<dt>上架状态</dt>
<dd>
<ListingStatus detail={detail} />
</dd>
</div>
<div>
<dt>生效时间</dt>
<dd>{effectiveDate(detail, true)}</dd>
</div>
</dl>
</section>
);
}
......@@ -115,6 +115,75 @@ function show(overrides: Partial<React.ComponentProps<typeof StoreDetailDrawer>>
}
describe('store detail presentation', () => {
it('renders the approval prototype header and audit cards without inventing a single-stage flow', () => {
show();
const header = within(screen.getByLabelText('审批概览'));
expect(header.getByRole('heading', { name: '当前门店' })).toBeInTheDocument();
expect(header.getByText('待审批')).toBeInTheDocument();
expect(header.getByText('90,071,992,547,409.91 元')).toBeInTheDocument();
const flow = within(screen.getByLabelText('审批流程'));
expect(flow.getByText('两级审批')).toBeInTheDocument();
expect(flow.getByText('优加商务经理')).toBeInTheDocument();
expect(flow.getByText('优加财务经理')).toBeInTheDocument();
fireEvent.click(screen.getByRole('tab', { name: '审批留痕' }));
const trail = within(screen.getByLabelText('审批留痕列表'));
expect(trail.getByText(/商务甲/)).toBeInTheDocument();
expect(trail.getByText('请核对政策')).toBeInTheDocument();
expect(trail.getByText(/192\.0\.2\.1/)).toBeInTheDocument();
});
it('renders the listing prototype overview and store information using real record fields', () => {
const onClose = vi.fn();
show({
mode: 'listing',
onClose,
detail: {
...detail,
status: 'APPROVED',
categoryCount: 6,
effectiveTime: '2026-10-09T15:03:37',
changeHistory: [
{ versionNo: 3, effectiveTime: '2026-10-01T10:00:00' },
{ versionNo: 1, effectiveTime: '2026-10-09T10:00:00' },
],
},
});
const overview = within(screen.getByLabelText('门店概览'));
expect(overview.getByRole('heading', { name: '当前门店' })).toBeInTheDocument();
for (const text of ['SQ001', '1 个', '6 个', '2026-10-09', 'v3', '已生效']) {
expect(overview.getByText(text)).toBeInTheDocument();
}
expect(overview.queryByText('提交人')).not.toBeInTheDocument();
expect(overview.queryByText('运营成本合计')).not.toBeInTheDocument();
const panel = within(screen.getByRole('tabpanel', { name: '门店信息' }));
expect(panel.queryByRole('table')).not.toBeInTheDocument();
expect(panel.getByRole('heading', { name: '门店信息' })).toBeInTheDocument();
expect(panel.getByText('售后会员权益升级')).toBeInTheDocument();
expect(panel.queryByText('售前延保')).not.toBeInTheDocument();
expect(panel.getByText('完整清单见「产品与场景」页签')).toBeInTheDocument();
expect(panel.getByText('2026-10-09 15:03')).toBeInTheDocument();
fireEvent.click(overview.getByRole('button', { name: '关闭' }));
expect(onClose).toHaveBeenCalledOnce();
});
it('does not invent a version or scene count when listing fields are missing', () => {
show({
mode: 'listing',
detail: {
...detail,
businessScene: '',
items: undefined,
categoryCount: undefined,
changeHistory: [{ changeField: 'status' }],
},
});
const overview = within(screen.getByLabelText('门店概览'));
expect(overview.getByText('当前版本')).toBeInTheDocument();
expect(overview.queryByText(/^v\d/)).not.toBeInTheDocument();
expect(overview.queryByText('1 个')).not.toBeInTheDocument();
expect(overview.queryByText('0 个')).not.toBeInTheDocument();
});
it('uses local dictionaries for real Chinese policy values and numeric point flags', () => {
show({
spec: STORE_DICTIONARIES,
......@@ -163,13 +232,24 @@ describe('store detail presentation', () => {
expect(screen.queryByRole('button', { name: '通过' })).not.toBeInTheDocument();
});
it('displays the authoritative total even when the cost components differ', () => {
show();
fireEvent.click(screen.getByRole('tab', { name: '运营成本' }));
expect(screen.getAllByText('¥90,071,992,547,409.91').length).toBeGreaterThan(0);
expect(screen.queryByText('¥1,500.00')).not.toBeInTheDocument();
expect(screen.getAllByText('¥500.00')).toHaveLength(3);
});
it.each(['approval', 'listing'] as const)(
'displays the authoritative %s total even when the cost components differ',
(mode) => {
show({ mode });
fireEvent.click(screen.getByRole('tab', { name: '运营成本' }));
const panel = within(screen.getByRole('tabpanel', { name: '运营成本' }));
const currency = mode === 'listing' ? '¥' : '';
expect(panel.getByText(`${currency}90,071,992,547,409.91`)).toBeInTheDocument();
expect(panel.queryByText(`${currency}1,500.00`)).not.toBeInTheDocument();
expect(panel.getAllByText(`${currency}500.00`)).toHaveLength(3);
if (mode === 'listing') {
expect(panel.getByRole('heading', { name: '运营成本(门店维度)' })).toBeInTheDocument();
expect(panel.queryByRole('table')).not.toBeInTheDocument();
expect(panel.getByText('当月产生费用')).toBeInTheDocument();
expect(panel.getByText('房租、水电、耗材等')).toBeInTheDocument();
}
},
);
it('renders zero point flags and zero policy values without treating them as missing', () => {
show();
......@@ -216,6 +296,67 @@ describe('store detail presentation', () => {
expect(screen.queryByRole('tab', { name: '审批留痕' })).not.toBeInTheDocument();
});
it('renders the real first-launch history in the prototype layout with readable status values', () => {
show({
mode: 'listing',
initialTab: 'history',
detail: {
...detail,
status: 'APPROVED',
changeHistory: [
{
changeId: 9,
listingId: 1,
versionNo: 1,
changeField: 'status',
beforeValue: 'PENDING',
afterValue: 'APPROVED',
changeUserName: '优加财务',
effectiveTime: '2026-10-09T15:03:37',
},
],
},
});
const panel = within(screen.getByRole('tabpanel', { name: '变更历史' }));
expect(panel.getByRole('heading', { name: '变更历史(只读)' })).toBeInTheDocument();
expect(panel.getByText('首次上架')).toBeInTheDocument();
expect(panel.getByText('门店在系统中完成首次上架并生效。')).toBeInTheDocument();
expect(panel.getByText('待审批 → 已生效')).toBeInTheDocument();
expect(panel.getByText('2026-10-09')).toBeInTheDocument();
expect(panel.getByText(/变更人:.*优加财务.*生效时间.*2026-10-09 15:03/)).toBeInTheDocument();
expect(panel.queryByText(/PENDING|APPROVED/)).not.toBeInTheDocument();
});
it('groups history by version and preserves cost values, zero values and policy units', () => {
show({
mode: 'listing',
initialTab: 'history',
detail: {
...detail,
changeHistory: [
{
versionNo: 2,
changeField: 'businessScene',
beforeValue: 'AFTER_SALES',
afterValue: 'PRE_SALES',
},
{ versionNo: 3, changeField: 'costDecoration', beforeValue: '800', afterValue: '500' },
{ versionNo: 3, changeField: 'costLabor', beforeValue: null, afterValue: '0' },
{ versionNo: 3, changeField: 'sunshine1Value', beforeValue: '3%', afterValue: '5%' },
],
},
});
const panel = within(screen.getByRole('tabpanel', { name: '变更历史' }));
const versions = panel.getAllByRole('article');
expect(versions).toHaveLength(2);
expect(within(versions[0]).getByText('v3')).toBeInTheDocument();
expect(within(versions[0]).getByText('¥800.00 → ¥500.00')).toBeInTheDocument();
expect(within(versions[0]).getByText('— → ¥0.00')).toBeInTheDocument();
expect(within(versions[0]).getByText('3% → 5%')).toBeInTheDocument();
expect(within(versions[1]).getByText('v2')).toBeInTheDocument();
expect(within(versions[1]).getByText('售后会员权益升级 → 售前延保')).toBeInTheDocument();
});
it('renders the batch-pass audit action as a readable business action', () => {
show({ detail: { ...detail, approvalLogs: [{ logId: 'batch', action: 'BATCH_PASS' }] } });
fireEvent.click(screen.getByRole('tab', { name: '审批留痕' }));
......@@ -227,7 +368,9 @@ describe('store detail presentation', () => {
'uses approveTime for the %s effective date when effectiveTime is absent',
(mode) => {
show({ mode, detail: { ...detail, status: 'APPROVED', approveTime: '2026-10-09T12:30:45' } });
expect(screen.getByText('2026-10-09 12:30:45')).toBeInTheDocument();
expect(
screen.getByText(mode === 'listing' ? '2026-10-09 12:30' : '2026-10-09 12:30:45'),
).toBeInTheDocument();
},
);
......@@ -241,7 +384,7 @@ describe('store detail presentation', () => {
approveTime: '2026-10-09T12:30:45',
},
});
expect(screen.getByText('2026-10-09 12:45:00')).toBeInTheDocument();
expect(screen.getByText('2026-10-09 12:45')).toBeInTheDocument();
expect(screen.queryByText('2026-10-09 12:30:45')).not.toBeInTheDocument();
});
......
.approval-detail-header {
color: #202733;
font-weight: 400;
}
.approval-detail-header__top,
.approval-detail-header__identity {
display: flex;
align-items: flex-start;
gap: 12px;
}
.approval-detail-header__top {
justify-content: space-between;
}
.approval-detail-header__identity {
min-width: 0;
align-items: baseline;
}
.approval-detail-header__identity h2 {
min-width: 0;
margin: 0;
color: #151b24;
font-size: 20px;
font-weight: 600;
line-height: 32px;
overflow-wrap: anywhere;
}
.approval-detail-header__close.ant-btn {
flex: none;
width: 32px;
min-width: 32px;
height: 32px;
padding: 0;
border-radius: 7px;
background: #eef1f6;
color: #596579;
font-size: 18px;
}
.approval-detail-header__close.ant-btn:hover {
background: #e2e7f0;
color: #202733;
}
.approval-detail-status {
display: inline-flex;
flex: none;
align-items: center;
gap: 6px;
padding: 2px 9px;
border-radius: 6px;
font-size: 14px;
font-weight: 400;
line-height: 23px;
white-space: nowrap;
}
.approval-detail-status__dot {
width: 6px;
height: 6px;
border-radius: 50%;
background: currentColor;
}
.approval-detail-status--pending {
background: #fff6e5;
color: #a86808;
}
.approval-detail-status--approved {
background: #e6f5ee;
color: #087b54;
}
.approval-detail-status--rejected {
background: #fff0ee;
color: #c43c3c;
}
.approval-detail-status--neutral {
background: #f0f2f5;
color: #758195;
}
.approval-detail-meta {
display: flex;
flex-wrap: wrap;
gap: 10px 18px;
margin: 12px 0 0;
font-size: 14px;
line-height: 24px;
}
.approval-detail-meta > div {
display: flex;
align-items: baseline;
gap: 5px;
min-width: 0;
}
.approval-detail-meta dt {
flex: none;
color: #758195;
}
.approval-detail-meta dd {
min-width: 0;
margin: 0;
font-weight: 600;
overflow-wrap: anywhere;
}
.approval-detail-meta__time {
color: #758195;
font-weight: 400;
}
.approval-detail-flow {
margin-bottom: 20px;
}
.approval-detail-flow__heading {
display: flex;
align-items: center;
gap: 10px;
margin-bottom: 12px;
}
.approval-detail-flow__heading h3 {
margin: 0;
color: #28313f;
font-size: 14px;
font-weight: 600;
line-height: 24px;
}
.approval-detail-flow__heading > span {
padding: 1px 8px;
border-radius: 4px;
background: #e4f5f4;
color: #008f88;
font-size: 13px;
line-height: 22px;
}
.approval-detail-flow__nodes {
display: flex;
margin: 0;
padding: 6px 0 14px;
overflow-x: auto;
list-style: none;
}
.approval-detail-flow__node {
position: relative;
display: flex;
flex: 1 0 120px;
flex-direction: column;
align-items: center;
padding: 0 5px;
text-align: center;
}
.approval-detail-flow__node:not(:last-child)::after {
position: absolute;
top: 14px;
right: calc(-50% + 24px);
left: calc(50% + 24px);
height: 2px;
background: #e2e6ed;
content: '';
}
.approval-detail-flow__node--done:not(:last-child)::after {
background: #0da370;
}
.approval-detail-flow__icon {
position: relative;
z-index: 1;
display: grid;
place-items: center;
width: 30px;
height: 30px;
margin-bottom: 10px;
border: 1.5px solid #cbd3df;
border-radius: 50%;
background: #fff;
color: #758195;
font-size: 15px;
font-weight: 600;
}
.approval-detail-flow__node--done .approval-detail-flow__icon,
.approval-detail-chaincard__icon--done {
border-color: #0da370;
background: #0da370;
color: #fff;
}
.approval-detail-flow__node--current .approval-detail-flow__icon,
.approval-detail-chaincard__icon--current {
border-color: #315efb;
background: #315efb;
color: #fff;
}
.approval-detail-flow__node--current .approval-detail-flow__icon {
box-shadow: 0 0 0 4px #e0e8ff;
}
.approval-detail-flow__node--rejected .approval-detail-flow__icon,
.approval-detail-chaincard__icon--rejected {
border-color: #d64a49;
background: #d64a49;
color: #fff;
}
.approval-detail-flow__node > strong {
color: #465164;
font-size: 14px;
font-weight: 500;
line-height: 22px;
}
.approval-detail-flow__node--current > strong {
color: #315efb;
font-weight: 600;
}
.approval-detail-flow__node--rejected > strong {
color: #c43c3c;
}
.approval-detail-flow__caption,
.approval-detail-flow__time {
max-width: 100%;
color: #97a3b7;
font-size: 12px;
line-height: 18px;
overflow-wrap: anywhere;
}
.approval-detail-flow__caption {
margin-top: 3px;
}
.store-approval-detail .ant-tabs > .ant-tabs-nav {
margin-bottom: 20px;
}
.store-approval-detail .ant-tabs > .ant-tabs-nav::before {
border-bottom-color: #e2e6ed;
}
.store-approval-detail .ant-tabs-tab {
padding: 12px 16px;
color: #758195;
font-size: 16px;
line-height: 24px;
}
.store-approval-detail .ant-tabs-tab + .ant-tabs-tab {
margin-left: 4px;
}
.store-approval-detail .ant-tabs-tab.ant-tabs-tab-active .ant-tabs-tab-btn {
color: #315efb;
font-weight: 600;
}
.store-approval-detail .ant-tabs-ink-bar {
background: #315efb;
}
.approval-detail-tab-count {
display: inline-flex;
align-items: center;
justify-content: center;
min-width: 20px;
height: 20px;
margin-left: 6px;
padding: 0 5px;
border-radius: 10px;
background: #eef1f6;
color: #596579;
font-size: 12px;
font-weight: 400;
}
.approval-detail-audit {
display: flex;
flex-direction: column;
gap: 12px;
}
.approval-detail-chaincard {
display: flex;
align-items: flex-start;
gap: 12px;
padding: 14px 16px;
border: 1px solid #e0e6ef;
border-radius: 8px;
background: #fff;
}
.approval-detail-chaincard__icon {
display: grid;
flex: 0 0 30px;
place-items: center;
width: 30px;
height: 30px;
margin-top: 3px;
border-radius: 50%;
font-size: 15px;
font-weight: 600;
}
.approval-detail-chaincard__icon--waiting,
.approval-detail-chaincard__icon--stopped {
background: #eef1f6;
color: #758195;
}
.approval-detail-chaincard__content {
flex: 1;
min-width: 0;
overflow-wrap: anywhere;
}
.approval-detail-chaincard__title {
color: #28313f;
font-size: 14px;
font-weight: 500;
line-height: 24px;
}
.approval-detail-chaincard__title strong {
font-weight: inherit;
}
.approval-detail-chaincard__meta {
display: flex;
flex-wrap: wrap;
gap: 0 8px;
margin-top: 2px;
color: #758195;
font-size: 13px;
line-height: 22px;
}
.approval-detail-chaincard__meta > span + span::before {
margin-right: 8px;
content: '·';
}
.approval-detail-chaincard__reason {
margin: 6px 0 0;
color: #596579;
font-size: 13px;
line-height: 22px;
white-space: pre-wrap;
}
.approval-detail-audit__empty {
margin: 0;
color: #97a3b7;
font-size: 13px;
}
@media (max-width: 600px) {
.approval-detail-header__identity {
flex-wrap: wrap;
gap: 6px 10px;
}
.approval-detail-header__identity h2 {
font-size: 18px;
line-height: 28px;
}
.approval-detail-meta {
gap: 6px 14px;
}
.approval-detail-flow__node {
flex-basis: 110px;
}
.store-approval-detail .ant-tabs-tab {
padding: 10px 8px;
font-size: 14px;
}
.approval-detail-chaincard {
gap: 10px;
padding: 12px;
}
}
.approval-policy-panel {
min-width: 0;
}
.approval-policy-panel__table {
overflow: hidden;
border: 1px solid #e0e6ef;
border-radius: 8px;
background: #fff;
}
.approval-policy-panel .ant-table {
color: #465164;
font-size: 13px;
}
.approval-policy-panel .ant-table-thead > tr > th {
height: 38px;
padding: 9px 12px;
border-bottom-color: #e0e6ef;
background: #fafbfc;
color: #758195;
font-size: 12px;
font-weight: 500;
line-height: 20px;
white-space: nowrap;
}
.approval-policy-panel .ant-table-tbody > tr > td {
height: 44px;
padding: 8px 12px;
border-bottom-color: #eef1f6;
font-variant-numeric: tabular-nums;
line-height: 22px;
}
.approval-policy-panel .ant-table-tbody > tr:last-child > td {
border-bottom: 0;
}
.approval-policy-panel .ant-table-tbody > tr.ant-table-row:hover > td {
background: #fafbfc;
}
.approval-policy-panel__category {
display: inline-block;
max-width: 280px;
padding: 1px 7px;
border-radius: 4px;
background: #e4f5f4;
color: #07796f;
font-size: 12px;
font-weight: 500;
line-height: 20px;
overflow-wrap: anywhere;
}
.approval-policy-panel__value {
color: #465164;
font-variant-numeric: tabular-nums;
}
.approval-policy-panel__note {
margin: 10px 0 0;
color: #97a3b7;
font-size: 12px;
line-height: 20px;
overflow-wrap: anywhere;
}
.approval-cost-panel__name {
color: #28313f;
font-weight: 500;
}
.approval-cost-panel__total {
color: #28313f;
font-weight: 600;
}
.approval-cost-panel .ant-table-tbody .approval-cost-panel__description {
color: #97a3b7;
}
@media (max-width: 600px) {
.approval-policy-panel .ant-table-thead > tr > th,
.approval-policy-panel .ant-table-tbody > tr > td {
padding-right: 10px;
padding-left: 10px;
}
}
.listing-cost-panel {
color: #28313f;
font-size: 14px;
line-height: 22px;
}
.listing-cost-panel__title {
display: flex;
align-items: center;
gap: 9px;
margin: 0;
padding-bottom: 12px;
border-bottom: 1px solid #e9edf3;
font-size: 14px;
font-weight: 600;
line-height: 22px;
}
.listing-cost-panel__title::before {
flex: none;
width: 3px;
height: 14px;
border-radius: 2px;
background: #315efb;
content: '';
}
.listing-cost-panel__fields {
margin: 10px 0 0;
}
.listing-cost-panel__fields > div {
display: grid;
grid-template-columns: 144px minmax(0, 1fr);
align-items: start;
min-height: 36px;
padding: 6px 0;
}
.listing-cost-panel__fields dt {
padding-right: 12px;
color: #758195;
}
.listing-cost-panel__fields dd {
display: flex;
flex-wrap: wrap;
align-items: baseline;
gap: 4px 14px;
min-width: 0;
margin: 0;
overflow-wrap: anywhere;
}
.listing-cost-panel__amount {
font-variant-numeric: tabular-nums;
}
strong.listing-cost-panel__amount {
font-weight: 600;
}
.listing-cost-panel__hint,
.listing-cost-panel__note {
color: #97a3b7;
font-size: 13px;
}
.listing-cost-panel__note {
margin: 22px 0 0;
line-height: 22px;
}
@media (max-width: 600px) {
.listing-cost-panel__fields > div {
grid-template-columns: 132px minmax(0, 1fr);
}
}
.listing-detail-header {
color: #202733;
font-weight: 400;
}
.listing-detail-header__top {
display: flex;
align-items: flex-start;
justify-content: space-between;
gap: 16px;
}
.listing-detail-header__top h2 {
min-width: 0;
margin: 0;
color: #151b24;
font-size: 20px;
font-weight: 600;
line-height: 32px;
overflow-wrap: anywhere;
}
.listing-detail-header__actions {
display: flex;
flex: none;
align-items: center;
gap: 10px;
}
.listing-detail-header__close.ant-btn {
width: 32px;
min-width: 32px;
height: 32px;
padding: 0;
border-radius: 7px;
background: #eef1f6;
color: #596579;
font-size: 18px;
}
.listing-detail-header__close.ant-btn:hover {
background: #e2e7f0;
color: #202733;
}
.listing-detail-meta {
display: flex;
flex-wrap: wrap;
gap: 8px 20px;
margin: 12px 0 0;
font-size: 14px;
font-weight: 400;
line-height: 22px;
}
.listing-detail-meta > div {
display: flex;
align-items: baseline;
gap: 5px;
min-width: 0;
}
.listing-detail-meta dt {
flex: none;
color: #758195;
}
.listing-detail-meta dd {
margin: 0;
font-weight: 600;
overflow-wrap: anywhere;
}
.listing-detail-status {
display: inline-flex;
align-items: center;
gap: 6px;
min-height: 25px;
padding: 2px 9px;
border-radius: 6px;
font-size: 14px;
font-weight: 400;
line-height: 21px;
white-space: nowrap;
}
.listing-detail-status__dot {
flex: none;
width: 6px;
height: 6px;
border-radius: 50%;
background: currentColor;
}
.listing-detail-status--approved {
background: #e6f5ee;
color: #087b54;
}
.listing-detail-status--pending {
background: #fff8e2;
color: #ad7c00;
}
.listing-detail-status--rejected {
background: #fff0ee;
color: #c43c3c;
}
.listing-detail-status--neutral {
background: #f0f2f5;
color: #758195;
}
.store-listing-detail .ant-tabs > .ant-tabs-nav {
margin-bottom: 22px;
}
.store-listing-detail .ant-tabs > .ant-tabs-nav::before {
border-bottom-color: #e2e6ed;
}
.store-listing-detail .ant-tabs-tab {
padding: 12px 18px;
color: #758195;
font-size: 16px;
line-height: 24px;
}
.store-listing-detail .ant-tabs-tab + .ant-tabs-tab {
margin-left: 4px;
}
.store-listing-detail .ant-tabs-tab.ant-tabs-tab-active .ant-tabs-tab-btn {
color: #315efb;
font-weight: 600;
}
.store-listing-detail .ant-tabs-ink-bar {
background: #315efb;
}
.listing-store-info {
color: #28313f;
font-size: 14px;
line-height: 22px;
}
.listing-store-info__title {
display: flex;
align-items: center;
gap: 9px;
margin: 0;
padding-bottom: 12px;
border-bottom: 1px solid #e9edf3;
font-size: 14px;
font-weight: 600;
line-height: 22px;
}
.listing-store-info__title::before {
flex: none;
width: 3px;
height: 14px;
border-radius: 2px;
background: #315efb;
content: '';
}
.listing-store-info__fields {
margin: 10px 0 0;
}
.listing-store-info__fields > div {
display: grid;
grid-template-columns: 144px minmax(0, 1fr);
align-items: start;
min-height: 36px;
padding: 6px 0;
}
.listing-store-info__fields dt {
color: #758195;
}
.listing-store-info__fields dd {
display: flex;
flex-wrap: wrap;
align-items: center;
gap: 6px 9px;
min-width: 0;
margin: 0;
overflow-wrap: anywhere;
}
.listing-store-info__scene {
display: inline-block;
max-width: 100%;
padding: 1px 8px;
border-radius: 4px;
background: #e4f5f4;
color: #008f88;
font-size: 13px;
line-height: 22px;
}
.listing-store-info__hint {
color: #97a3b7;
font-size: 13px;
}
@media (max-width: 600px) {
.listing-detail-header__top {
gap: 10px;
}
.listing-detail-header__top h2 {
font-size: 18px;
line-height: 28px;
}
.listing-detail-header__actions {
gap: 6px;
}
.listing-detail-meta {
gap: 6px 14px;
}
.store-listing-detail .ant-tabs-tab {
padding: 10px 8px;
font-size: 14px;
}
.listing-store-info__fields > div {
grid-template-columns: 110px minmax(0, 1fr);
}
}
.listing-change-history {
color: #28313f;
font-size: 14px;
line-height: 24px;
}
.listing-change-history__heading {
display: flex;
align-items: center;
gap: 9px;
margin: 0;
padding-bottom: 12px;
border-bottom: 1px solid #e9edf3;
font-size: 14px;
font-weight: 600;
line-height: 22px;
}
.listing-change-history__heading::before {
flex: none;
width: 3px;
height: 14px;
border-radius: 2px;
background: #315efb;
content: '';
}
.listing-change-history__version {
display: grid;
grid-template-columns: 110px minmax(0, 1fr);
gap: 12px;
padding: 16px 0;
border-bottom: 1px solid #e9edf3;
}
.listing-change-history__version:first-of-type {
padding-top: 24px;
}
.listing-change-history__version-meta {
display: flex;
flex-direction: column;
align-items: flex-start;
gap: 4px;
min-width: 0;
overflow-wrap: anywhere;
}
.listing-change-history__version-meta strong {
color: #315efb;
font-size: 13px;
font-weight: 600;
}
.listing-change-history__version-meta span,
.listing-change-history__audit,
.listing-change-history__empty {
color: #97a3b7;
font-size: 13px;
}
.listing-change-history__content {
min-width: 0;
overflow-wrap: anywhere;
}
.listing-change-history__content h4 {
margin: 0 0 8px;
color: #28313f;
font-size: 14px;
font-weight: 400;
line-height: 24px;
}
.listing-change-history__description {
margin: 0 0 4px;
color: #596579;
}
.listing-change-history__changes {
margin: 0;
color: #596579;
}
.listing-change-history__changes > div {
display: flex;
flex-wrap: wrap;
align-items: baseline;
column-gap: 12px;
margin-top: 2px;
}
.listing-change-history__changes dt {
max-width: 100%;
}
.listing-change-history__changes dd {
min-width: 0;
margin: 0;
white-space: pre-wrap;
overflow-wrap: anywhere;
}
.listing-change-history__audit {
margin: 8px 0 0;
}
.listing-change-history__empty {
margin: 16px 0;
}
@media (max-width: 600px) {
.listing-change-history__version {
grid-template-columns: 80px minmax(0, 1fr);
gap: 10px;
}
}
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 { Outlet, useLocation, useNavigate } from 'react-router-dom';
import {
DashboardOutlined,
ShopOutlined,
UploadOutlined,
SearchOutlined,
LogoutOutlined,
UserOutlined,
TeamOutlined,
......
.store-approve-table.ant-table-wrapper .ant-table .ant-table-thead > tr > th {
height: 38px;
padding: 0 12px;
background: #fbfcfd;
color: #6b7686;
font-size: 12px;
font-weight: 500;
white-space: nowrap;
}
.store-approve-table.ant-table-wrapper .ant-table .ant-table-tbody > tr > td {
height: 44px;
padding: 8px 12px;
color: #333c4a;
font-size: 13px;
line-height: 20px;
vertical-align: middle;
white-space: nowrap;
}
.store-approve-table .ant-table-tbody .ant-btn-link {
height: 28px;
padding: 0 8px;
font-size: 13px;
}
.store-approve-merchant {
color: #2b5ce6;
font-family: 'JetBrains Mono', 'SFMono-Regular', Consolas, monospace;
font-size: 12px;
}
.store-approve-categories {
display: inline-flex;
align-items: center;
gap: 4px;
white-space: nowrap;
}
.store-approve-tag {
display: inline-flex;
align-items: center;
height: 20px;
padding: 0 7px;
border-radius: 4px;
background: #e6f7f5;
color: #07796f;
font-size: 11px;
font-weight: 500;
white-space: nowrap;
}
.store-approve-category-count {
color: #333c4a;
font-size: 13px;
}
.store-approve-money {
font-variant-numeric: tabular-nums;
white-space: nowrap;
}
.store-approve-submit-time {
display: block;
color: #9aa5b5;
font-size: 12px;
white-space: nowrap;
}
.store-approve-stay {
display: inline-flex;
align-items: center;
gap: 5px;
height: 22px;
padding: 0 8px;
border-radius: 5px;
font-size: 11.5px;
font-weight: 500;
white-space: nowrap;
}
.store-approve-stay::before {
width: 5px;
height: 5px;
flex: 0 0 5px;
border-radius: 50%;
background: currentColor;
content: '';
}
.store-approve-stay--normal {
background: #e8f7f0;
color: #0b6b47;
}
.store-approve-stay--warning {
background: #fdf4e3;
color: #9a5f08;
}
.store-approve-stay--danger {
background: #fdecec;
color: #a3262c;
}
......@@ -2,14 +2,14 @@ import { useEffect, useRef, useState } from 'react';
import { useMutation, useQueries, useQuery, useQueryClient } from '@tanstack/react-query';
import { App } from 'antd';
import { Skeleton, UAlert, UButton, UCard, UResult, UTabs, UTitle, UText } from '@uj/ui';
import { P, PermButton, getLoginSession, useAccess } from '@/access';
import { P, PermButton, useAccess } from '@/access';
import {
DataTable,
DEFAULT_PAGE_SIZE,
SearchForm,
type FieldSchema,
type RowActionSchema,
} from '@/components';
import { getDataScopeLabel } from '@/constants/dataScope';
import {
store,
type ApprovalPageParams,
......@@ -19,7 +19,7 @@ import {
} from '@/api';
import { StoreDetailDrawer } from '@/features/store/StoreDetailDrawer';
import { STORE_DICTIONARIES } from '@/features/store/dictionaries';
import { ApproveTable } from './components/ApproveTable';
import { buildApproveColumns } from './tools/columns';
import { ApprovalActionModal, type ApprovalAction } from './components/ApprovalActionModal';
import { errorMessage, tabDefs } from './tools/consts';
import '@/features/store/store.css';
......@@ -37,6 +37,9 @@ export default function StoreApprove() {
const allowed = canPoint(P.STORE_APPROVE_VIEW);
const canPass = canPoint(P.STORE_APPROVE_AUDIT);
const canReject = canPoint(P.STORE_APPROVE_REJECT);
const canRevoke = canPoint(P.STORE_APPROVE_REVOKE);
const canAct = (type: ApprovalAction['type']) =>
allowed && (type === 'revoke' ? canRevoke : type === 'reject' ? canReject : canPass);
const { message } = App.useApp();
const client = useQueryClient();
const [tab, setTab] = useState<ApproveTab>(() =>
......@@ -135,7 +138,7 @@ export default function StoreApprove() {
},
});
const openAction = (next: ApprovalAction) => {
if (mutation.isPending) return;
if (mutation.isPending || !canAct(next.type)) return;
setAction(next);
setConfirmed(false);
setReason('');
......@@ -155,11 +158,7 @@ export default function StoreApprove() {
setActionError('请填写 1–200 字的打回原因');
return;
}
if (
((action.type === 'pass' || action.type === 'batch') && !canPass) ||
(action.type === 'reject' && !canReject)
)
return;
if (!canAct(action.type)) return;
submissionLock.current = true;
mutation.mutate({ ...action, reason: reason.trim() });
};
......@@ -223,7 +222,7 @@ export default function StoreApprove() {
},
{
label: '撤回',
permission: P.STORE_APPROVE_VIEW,
permission: P.STORE_APPROVE_REVOKE,
disabled: mutation.isPending,
visible: (row) => tab === 'mine' && row.status === 'PENDING',
onClick: (row) => openAction({ type: 'revoke', records: [row] }),
......@@ -247,8 +246,6 @@ export default function StoreApprove() {
drawer.source === 'todo' &&
drawer.row.actionable === true &&
detail.data?.status === 'PENDING';
const scope = getLoginSession()?.dataScope;
const dataScope = getDataScopeLabel(scope, '以账号授权范围为准');
if (!allowed)
return (
<UResult status="403" title="无门店审批访问权限" subTitle="请联系管理员确认账号权限。" />
......@@ -310,9 +307,13 @@ export default function StoreApprove() {
<Skeleton variant="table" />
) : (
<div className="store-table-card">
<ApproveTable
tab={tab}
spec={STORE_DICTIONARIES}
<DataTable<ApprovalRow>
className="store-approve-table"
columns={buildApproveColumns(tab, STORE_DICTIONARIES)}
rowKey="listingId"
scroll={{ x: tab === 'done' ? 1340 : tab === 'todo' ? 1216 : 1290 }}
actionColumnWidth={tab === 'done' ? 80 : 130}
actionColumnFixed="right"
dataSource={list.data?.records ?? []}
loading={list.isFetching}
rowActions={rowActions}
......@@ -338,15 +339,15 @@ export default function StoreApprove() {
rowSelection={
tab === 'todo' && canPass
? {
columnWidth: 40,
disabled: mutation.isPending || list.isFetching,
selectedRowKeys: selectedCurrent.map((row) => row.listingId),
onChange: (_, rows) => setSelected(rows),
getCheckboxProps: (row) => ({
disabled:
row.status !== 'PENDING' || row.actionable !== true || mutation.isPending,
disabled: row.status !== 'PENDING' || row.actionable !== true,
}),
preserveSelectedRowKeys: false,
}
: undefined
: false
}
pagination={{
current: page.current,
......@@ -370,6 +371,11 @@ export default function StoreApprove() {
error={detail.error}
spec={STORE_DICTIONARIES}
mode="approval"
pendingHours={
detail.data?.status === 'PENDING' && detail.data.currentLevel === drawer?.row.currentLevel
? drawer?.row.pendingHours
: undefined
}
onClose={() => {
if (!mutation.isPending) setDrawer(undefined);
}}
......@@ -408,7 +414,7 @@ export default function StoreApprove() {
detail.data?.status === 'PENDING' &&
drawerRecord && (
<PermButton
permission={P.STORE_APPROVE_VIEW}
permission={P.STORE_APPROVE_REVOKE}
disabled={mutation.isPending}
onClick={() => openAction({ type: 'revoke', records: [drawerRecord] })}
>
......@@ -418,20 +424,22 @@ export default function StoreApprove() {
</div>
}
/>
<ApprovalActionModal
action={action}
spec={STORE_DICTIONARIES}
pending={mutation.isPending}
confirmed={confirmed}
reason={reason}
error={actionError}
onConfirmed={setConfirmed}
onReason={setReason}
onCancel={() => {
if (!mutation.isPending) setAction(undefined);
}}
onConfirm={confirmAction}
/>
{(!action || canAct(action.type)) && (
<ApprovalActionModal
action={action}
spec={STORE_DICTIONARIES}
pending={mutation.isPending}
confirmed={confirmed}
reason={reason}
error={actionError}
onConfirmed={setConfirmed}
onReason={setReason}
onCancel={() => {
if (!mutation.isPending) setAction(undefined);
}}
onConfirm={confirmAction}
/>
)}
</div>
);
}
import type { ColumnsType } from 'antd/es/table';
import { UTag } from '@uj/ui';
import { DataTable, type RowActionSchema } from '@/components';
import type { DataTableProps } from '@/components/DataTable';
import { StatusTag } from '@/components/StatusTag';
import type { ApprovalRow, ApproveTab } from '@/api';
import type { StoreDictionaries } from '@/features/store/dictionaries';
import { dictionaryLabel, formatDateTime, formatMoney } from '@/features/store/formatters';
import '../approveTable.css';
interface Props extends Omit<DataTableProps<ApprovalRow>, 'columns'> {
tab: ApproveTab;
spec?: StoreDictionaries;
rowActions: RowActionSchema<ApprovalRow>[];
function formatSubmitTime(value?: string | null): string {
const text = formatDateTime(value);
const match =
/^\d{4}-(\d{2}-\d{2}) (\d{2}:\d{2})(?::\d{2}(?:\.\d+)?)?(?:Z|[+-]\d{2}:?\d{2})?$/.exec(text);
return match ? `${match[1]} ${match[2]}` : text;
}
export function ApproveTable({ tab, spec, ...props }: Props) {
export function buildApproveColumns(
tab: ApproveTab,
spec?: StoreDictionaries,
): ColumnsType<ApprovalRow> {
const columns: ColumnsType<ApprovalRow> = [
{
title: '门店名称',
dataIndex: 'storeName',
width: 220,
width: tab === 'mine' ? 230 : 220,
fixed: 'left',
render: (value) => <strong>{value}</strong>,
},
{
title: '门店商户号',
dataIndex: 'merchantNo',
width: 140,
render: (value) => <span className="store-code">{value}</span>,
width: tab === 'mine' ? 120 : 110,
render: (value) => <span className="store-approve-merchant">{value || '—'}</span>,
},
{
title: '产品分类',
key: 'categories',
width: 180,
width: tab === 'todo' ? 170 : 200,
render: (_, row) => {
const categories = row.productCategories ?? [];
const count = row.categoryCount ?? categories.length;
return (
<>
<span className="store-approve-categories">
{categories[0] ? (
<UTag>{dictionaryLabel(spec?.productCategories, categories[0])}</UTag>
<span className="store-approve-tag">
{dictionaryLabel(spec?.productCategories, categories[0])}
</span>
) : (
'—'
)}
{count > 1 && <span className="store-subtext">等 {count} 个分类</span>}
</>
{count > 1 && <span className="store-approve-category-count">等 {count} 个分类</span>}
</span>
);
},
},
{
title: '业务场景',
dataIndex: 'businessScene',
width: 200,
render: (value) => <UTag color="blue">{dictionaryLabel(spec?.businessScenes, value)}</UTag>,
width: tab === 'todo' ? 200 : tab === 'done' ? 150 : 160,
render: (value) => (
<span className="store-approve-tag">{dictionaryLabel(spec?.businessScenes, value)}</span>
),
},
];
if (tab === 'todo')
......@@ -58,44 +66,42 @@ export function ApproveTable({ tab, spec, ...props }: Props) {
{
title: '运营成本合计',
dataIndex: 'costTotal',
width: 150,
width: 110,
align: 'right',
render: formatMoney,
render: (value) => (
<span className="store-approve-money">
{formatMoney(value).replace(/^¥/, '').replace(/\.00$/, '')}
</span>
),
},
{
title: '提交人 / 提交时间',
width: 180,
title: '提交人 / 时间',
width: 150,
render: (_, row) => (
<>
{row.submitUserName || '—'}
<span className="store-subtext">{formatDateTime(row.submitTime)}</span>
<span className="store-approve-submit-time">{formatSubmitTime(row.submitTime)}</span>
</>
),
},
{
title: '停留时长',
width: 110,
width: 86,
render: (_, row) => {
const hours = row.pendingHours;
if (typeof hours !== 'number' || !Number.isFinite(hours) || hours < 0) return '—';
const level =
row.timeoutLevel ??
(row.pendingHours != null && row.pendingHours > 48
? 'DANGER'
: row.pendingHours != null && row.pendingHours > 24
? 'WARNING'
: 'NORMAL');
row.timeoutLevel ?? (hours > 48 ? 'DANGER' : hours > 24 ? 'WARNING' : 'NORMAL');
const tone =
level === 'DANGER'
? 'danger'
: level === 'WARNING'
? 'warning'
: level === 'NORMAL'
? 'normal'
: 'unknown';
return (
<span
style={{
color:
level === 'DANGER'
? 'var(--uj-error)'
: level === 'WARNING'
? 'var(--uj-warning)'
: undefined,
}}
>
{row.pendingHours == null ? '—' : `${row.pendingHours} 小时`}
</span>
<span className={`store-approve-stay store-approve-stay--${tone}`}>{hours} 小时</span>
);
},
},
......@@ -104,7 +110,7 @@ export function ApproveTable({ tab, spec, ...props }: Props) {
columns.push(
{
title: '我的动作',
width: 100,
width: 110,
render: (_, row) => (
<UTag
color={
......@@ -116,20 +122,20 @@ export function ApproveTable({ tab, spec, ...props }: Props) {
</UTag>
),
},
{ title: '处理时间', dataIndex: 'handleTime', width: 180, render: formatDateTime },
{ title: '处理时间', dataIndex: 'handleTime', width: 150, render: formatDateTime },
{
title: '处理意见',
width: 220,
render: (_, row) => row.handleOpinion || row.rejectReason || '—',
},
{ title: '记录状态', width: 110, render: (_, row) => <StatusTag status={row.status} /> },
{ title: '记录状态', width: 100, render: (_, row) => <StatusTag status={row.status} /> },
);
if (tab === 'mine')
columns.push(
{ title: '状态', width: 110, render: (_, row) => <StatusTag status={row.status} /> },
{ title: '状态', width: 130, render: (_, row) => <StatusTag status={row.status} /> },
{
title: '审批进度',
width: 170,
width: 150,
render: (_, row) =>
row.status === 'PENDING'
? (row.totalLevel ?? 2) === 1 || row.currentLevel === 2
......@@ -143,16 +149,7 @@ export function ApproveTable({ tab, spec, ...props }: Props) {
? '已完成'
: '—',
},
{ title: '提交时间', dataIndex: 'submitTime', width: 180, render: formatDateTime },
{ title: '提交时间', dataIndex: 'submitTime', width: 170, render: formatDateTime },
);
return (
<DataTable<ApprovalRow>
{...props}
columns={columns}
rowKey="listingId"
scroll={{ x: tab === 'done' ? 1500 : 1410 }}
actionColumnWidth={200}
actionColumnFixed="right"
/>
);
return columns;
}
......@@ -3,7 +3,7 @@ import zhCN from 'antd/locale/zh_CN';
import { QueryClient, QueryClientProvider } from '@tanstack/react-query';
import { cleanup, fireEvent, render, screen, waitFor, within } from '@testing-library/react';
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import { AccessProvider, saveUserInfo } from '@/access';
import { AccessTestProvider } from '@/test/AccessTestProvider';
import StoreListing from './index';
const api = vi.hoisted(() => ({
......@@ -15,6 +15,7 @@ const api = vi.hoisted(() => ({
exportStores: vi.fn(),
}));
vi.mock('@/api', () => ({ store: api }));
vi.mock('@/api/modules/auth', () => ({ auth: { info: vi.fn() } }));
const rows = [
{
......@@ -40,7 +41,6 @@ const columns = ['storeName', 'merchantNo', 'businessScene', 'effectiveTime', 'c
const queryClients: QueryClient[] = [];
function renderPage(permissions = ['store:list:view', 'store:list:export']) {
saveUserInfo({ permCodes: permissions, dataScope: 3 });
const client = new QueryClient({
defaultOptions: { queries: { retry: false, staleTime: 30_000 }, mutations: { retry: false } },
});
......@@ -49,9 +49,9 @@ function renderPage(permissions = ['store:list:view', 'store:list:export']) {
<ConfigProvider locale={zhCN}>
<App>
<QueryClientProvider client={client}>
<AccessProvider>
<AccessTestProvider permCodes={permissions}>
<StoreListing />
</AccessProvider>
</AccessTestProvider>
</QueryClientProvider>
</App>
</ConfigProvider>,
......@@ -149,29 +149,39 @@ describe('门店列表', () => {
expect(api.listStores.mock.lastCall?.[0].merchantNo).toBeUndefined();
expect(screen.getByLabelText('门店名称')).toHaveValue('');
expect(screen.getByLabelText('门店商户号')).toHaveValue('');
expect(screen.getByText('数据可见范围:本部门')).toBeInTheDocument();
expect(screen.queryByText(/数据可见范围/)).not.toBeInTheDocument();
});
it('服务端排序并仅导出当前筛选与排序,不传分页', async () => {
it('原型表头不切换排序,导出保留当前筛选与默认排序但不传分页', async () => {
renderPage();
const input = await screen.findByLabelText('门店名称');
fireEvent.change(input, { target: { value: '目标门店' } });
fireEvent.click(screen.getByRole('button', { name: /查\s*询/ }));
await waitFor(() => expect(api.listStores.mock.lastCall?.[0].storeName).toBe('目标门店'));
fireEvent.click(screen.getByRole('columnheader', { name: /变更次数/ }));
await waitFor(() =>
expect(api.listStores.mock.lastCall?.[0]).toEqual(
expect.objectContaining({ sortField: 'changeCount', sortOrder: 'asc' }),
),
);
const requestCount = api.listStores.mock.calls.length;
for (const name of ['上架时间', '变更次数']) {
const header = screen.getByRole('columnheader', { name });
expect(header).not.toHaveAttribute('aria-sort');
expect(header).not.toHaveAttribute('tabindex');
fireEvent.click(header);
}
expect(api.listStores).toHaveBeenCalledTimes(requestCount);
expect(screen.getAllByRole('columnheader').map((header) => header.textContent)).toEqual([
'门店名称',
'门店商户号',
'业务场景',
'上架时间',
'变更次数',
'操作',
]);
const exportButton = screen.getByRole('button', { name: /导\s*出/ });
await waitFor(() => expect(exportButton).not.toBeDisabled());
fireEvent.click(exportButton);
await waitFor(() =>
expect(api.exportStores).toHaveBeenCalledWith({
storeName: '目标门店',
sortField: 'changeCount',
sortOrder: 'asc',
sortField: 'effectiveDate',
sortOrder: 'desc',
}),
);
});
......@@ -187,41 +197,81 @@ describe('门店列表', () => {
expect(within(drawer).queryByText('售后会员权益升级')).not.toBeInTheDocument();
});
it('点击门店名称打开对应记录详情', async () => {
it('门店名称与变更次数使用普通文本,详情与历史通过操作列打开', async () => {
renderPage();
const names = await screen.findAllByRole('button', { name: '同名门店' });
fireEvent.click(names[0]);
await waitFor(() => expect(api.getStore).toHaveBeenCalledWith(101));
const drawer = await screen.findByRole('dialog');
await screen.findAllByText('同名门店');
expect(screen.queryByRole('button', { name: '同名门店' })).not.toBeInTheDocument();
expect(screen.queryByRole('button', { name: '查看同名门店变更历史' })).not.toBeInTheDocument();
fireEvent.click(screen.getAllByRole('button', { name: '变更历史' })[0]);
await waitFor(() => expect(api.getChanges).toHaveBeenCalledWith(101));
expect(await screen.findByRole('tab', { name: '变更历史' })).toHaveAttribute(
'aria-selected',
'true',
);
});
it('后端乱序与重复列按原型顺序展示,未配置列保持隐藏', async () => {
api.getColumnConfig.mockResolvedValue({
columns: [
'changeCount',
'effectiveTime',
'businessScene',
'effectiveTime',
'storeName',
'changeCount',
'retiredColumn',
],
});
renderPage();
await screen.findAllByText('同名门店');
await waitFor(() =>
expect(within(drawer).getAllByText('售后会员权益升级').length).toBeGreaterThan(0),
expect(screen.queryByRole('columnheader', { name: '门店商户号' })).not.toBeInTheDocument(),
);
expect(screen.getAllByRole('columnheader').map((header) => header.textContent)).toEqual([
'门店名称',
'业务场景',
'上架时间',
'变更次数',
'操作',
]);
expect(api.saveColumnConfig).not.toHaveBeenCalled();
});
it('取消列配置不写入,保存按勾选顺序提交并使用服务端配置', async () => {
it('列配置只控制显隐,取消不写入,保存和回显固定按原型顺序', async () => {
api.getColumnConfig.mockResolvedValue({
columns: ['changeCount', 'effectiveTime', 'storeName', 'businessScene', 'merchantNo'],
});
renderPage();
fireEvent.click(await screen.findByRole('button', { name: '列配置' }));
let dialog = await screen.findByRole('dialog');
expect(within(dialog).queryAllByRole('button', { name: /上移|下移/ })).toHaveLength(0);
fireEvent.click(within(dialog).getByLabelText('门店商户号'));
fireEvent.click(within(dialog).getByRole('button', { name: /取\s*消/ }));
expect(api.saveColumnConfig).not.toHaveBeenCalled();
expect(screen.getByRole('columnheader', { name: '门店商户号' })).toBeInTheDocument();
fireEvent.click(screen.getByRole('button', { name: '列配置' }));
dialog = await screen.findByRole('dialog');
expect(within(dialog).queryAllByRole('button', { name: /上移|下移/ })).toHaveLength(0);
fireEvent.click(within(dialog).getByLabelText('门店商户号'));
fireEvent.click(within(dialog).getByRole('button', { name: '上移上架时间' }));
fireEvent.click(within(dialog).getByRole('button', { name: /保\s*存/ }));
await waitFor(() =>
expect(api.saveColumnConfig).toHaveBeenCalledWith([
'storeName',
'effectiveTime',
'businessScene',
'effectiveTime',
'changeCount',
]),
);
await waitFor(() =>
expect(screen.queryByRole('columnheader', { name: '门店商户号' })).not.toBeInTheDocument(),
);
expect(screen.getAllByRole('columnheader').map((header) => header.textContent)).toEqual([
'门店名称',
'业务场景',
'上架时间',
'变更次数',
'操作',
]);
});
it('列配置读取失败可重试且不能用默认值覆盖服务器', async () => {
......@@ -331,6 +381,16 @@ describe('门店列表', () => {
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 () => {
api.listStores.mockImplementation(async (params) => ({
records: params.current === 3 ? [] : rows,
......
import { useEffect, useState } from 'react';
import { ArrowDownOutlined, ArrowUpOutlined } from '@ant-design/icons';
import { UAlert, UButton, UCheckbox, UModal, UText } from '@uj/ui';
import { COLUMN_LABELS, DEFAULT_COLUMNS, errorText, type ListingColumn } from '../tools/listing';
......@@ -16,26 +15,13 @@ interface Props {
}
export function ColumnConfigModal(props: Props) {
const [order, setOrder] = useState<ListingColumn[]>(DEFAULT_COLUMNS);
const [selected, setSelected] = useState<ListingColumn[]>(props.columns);
useEffect(() => {
if (props.open) {
setOrder([
...props.columns,
...DEFAULT_COLUMNS.filter((column) => !props.columns.includes(column)),
]);
setSelected(props.columns);
}
}, [props.open, props.columns]);
function move(index: number, offset: number) {
setOrder((current) => {
const next = [...current];
[next[index], next[index + offset]] = [next[index + offset], next[index]];
return next;
});
}
return (
<UModal
title="列配置"
......@@ -46,9 +32,9 @@ export function ColumnConfigModal(props: Props) {
confirmLoading={props.saving}
okButtonProps={{ disabled: props.loading || Boolean(props.error) || props.saving }}
cancelButtonProps={{ disabled: props.saving }}
onOk={() => props.onSave(order.filter((column) => selected.includes(column)))}
onOk={() => props.onSave(DEFAULT_COLUMNS.filter((column) => selected.includes(column)))}
>
<UText type="secondary">门店名称和操作列始终显示。勾选显示列,使用箭头调整顺序。</UText>
<UText type="secondary">门店名称和操作列始终显示,其余列可勾选显示,字段顺序固定。</UText>
{props.error ? (
<UAlert
type="error"
......@@ -63,7 +49,7 @@ export function ColumnConfigModal(props: Props) {
) : null}
{props.loading && <p role="status">正在加载列配置…</p>}
<div className="store-column-options">
{order.map((column, index) => (
{DEFAULT_COLUMNS.map((column) => (
<div className="store-column-option" key={column}>
<UCheckbox
checked={selected.includes(column)}
......@@ -80,28 +66,6 @@ export function ColumnConfigModal(props: Props) {
>
{COLUMN_LABELS[column]}
</UCheckbox>
<div>
<UButton
type="text"
icon={<ArrowUpOutlined />}
aria-label={`上移${COLUMN_LABELS[column]}`}
disabled={index < 2 || props.loading || Boolean(props.error) || props.saving}
onClick={() => move(index, -1)}
/>
<UButton
type="text"
icon={<ArrowDownOutlined />}
aria-label={`下移${COLUMN_LABELS[column]}`}
disabled={
index === 0 ||
index === order.length - 1 ||
props.loading ||
Boolean(props.error) ||
props.saving
}
onClick={() => move(index, 1)}
/>
</div>
</div>
))}
</div>
......
import type { ColumnsType } from 'antd/es/table';
import { UButton, UTag } from '@uj/ui';
import { P, Perm } from '@/access';
import type { ListingPageParams, StoreListingRow } from '@/api';
import type { StoreListingRow } from '@/api';
import type { StoreDictionaries } from '@/features/store/dictionaries';
import { dictionaryLabel, formatDateTime } from '@/features/store/formatters';
import { COLUMN_LABELS, type ListingColumn } from '../tools/listing';
export function buildColumns({
visible,
params,
spec,
onDetail,
onHistory,
}: {
visible: ListingColumn[];
params: ListingPageParams;
spec?: StoreDictionaries;
onDetail: (row: StoreListingRow) => void;
onHistory: (row: StoreListingRow) => void;
}): ColumnsType<StoreListingRow> {
const sortOrder = params.sortOrder === 'asc' ? 'ascend' : 'descend';
const definitions: Record<ListingColumn, ColumnsType<StoreListingRow>[number]> = {
storeName: {
title: COLUMN_LABELS.storeName,
dataIndex: 'storeName',
key: 'storeName',
width: 230,
fixed: 'left',
render: (value: string, row) => (
<UButton type="link" className="store-listing-name" onClick={() => onDetail(row)}>
{value || '—'}
</UButton>
),
render: (value: string) => <span className="store-listing-name">{value || '—'}</span>,
},
merchantNo: {
title: COLUMN_LABELS.merchantNo,
dataIndex: 'merchantNo',
key: 'merchantNo',
width: 170,
width: 120,
render: (value: string) => <span className="store-code">{value || '—'}</span>,
},
businessScene: {
title: COLUMN_LABELS.businessScene,
dataIndex: 'businessScene',
key: 'businessScene',
width: 210,
width: 230,
render: (value: string) => (
<UTag color="blue">{dictionaryLabel(spec?.businessScenes, value)}</UTag>
<span className="store-listing-scene">{dictionaryLabel(spec?.businessScenes, value)}</span>
),
},
effectiveTime: {
title: COLUMN_LABELS.effectiveTime,
dataIndex: 'effectiveTime',
key: 'effectiveTime',
width: 150,
sorter: true,
sortOrder: params.sortField === 'effectiveDate' ? sortOrder : null,
width: 130,
render: (value: string | null) => formatDateTime(value).split(' ')[0],
},
changeCount: {
title: COLUMN_LABELS.changeCount,
dataIndex: 'changeCount',
key: 'changeCount',
width: 120,
width: 90,
align: 'right',
sorter: true,
sortOrder: params.sortField === 'changeCount' ? sortOrder : null,
render: (value: number | null | undefined, row) => (
<Perm permission={P.STORE_LISTING_VIEW} fallback={value ?? '—'}>
<UButton
type="link"
aria-label={`查看${row.storeName}变更历史`}
onClick={() => onHistory(row)}
>
{value ?? '—'}
</UButton>
</Perm>
),
render: (value: number | null | undefined) => value ?? '—',
},
};
return visible.map((column) => definitions[column]);
......
import { useEffect, useMemo, useState } from 'react';
import { keepPreviousData, useMutation, useQuery, useQueryClient } from '@tanstack/react-query';
import { App } from 'antd';
import type { TableProps } from 'antd';
import { DownloadOutlined, SettingOutlined } from '@ant-design/icons';
import { Skeleton, UAlert, UButton, UCard, UResult, UText, UTitle } from '@uj/ui';
import { getLoginSession, getUserInfo, P, useAccess } from '@/access';
import { P, useAccess } from '@/access';
import { store, type ListingPageParams, type StoreId, type StoreListingRow } from '@/api';
import { getDataScopeLabel } from '@/constants/dataScope';
import {
DataTable,
DEFAULT_PAGE_SIZE,
......@@ -111,10 +109,7 @@ export default function StoreListing() {
];
const columns = buildColumns({
visible: configuredColumns,
params,
spec: STORE_DICTIONARIES,
onDetail: (row) => openDetail(row),
onHistory: (row) => openDetail(row, 'history'),
});
const rowActions: RowActionSchema<StoreListingRow>[] = [
{ label: '查看详情', permission: P.STORE_LISTING_VIEW, onClick: (row) => openDetail(row) },
......@@ -153,32 +148,6 @@ export default function StoreListing() {
},
},
];
const scope = getUserInfo()?.dataScope ?? getLoginSession()?.dataScope;
const scopeLabel = getDataScopeLabel(
typeof scope === 'number' ? scope : undefined,
'以账号授权范围为准',
);
const onTableChange: TableProps<StoreListingRow>['onChange'] = (
_pagination,
_filters,
sorter,
extra,
) => {
if (extra.action !== 'sort') return;
const current = Array.isArray(sorter) ? sorter[0] : sorter;
setParams((previous) => ({
...previous,
current: 1,
sortField: current.order
? current.columnKey === 'changeCount'
? 'changeCount'
: 'effectiveDate'
: undefined,
sortOrder:
current.order === 'ascend' ? 'asc' : current.order === 'descend' ? 'desc' : undefined,
}));
if (!exportFile.isPending) exportFile.reset();
};
if (!allowed)
return (
......@@ -241,12 +210,13 @@ export default function StoreListing() {
{overExportLimit ? (
<UAlert type="warning" showIcon title="筛选结果超过 50,000 条,请缩小范围后导出。" />
) : null}
<UCard className="store-table-card" size="small" styles={{ body: { padding: 0 } }}>
<div className="store-listing-section">
<DataTable<StoreListingRow>
className="store-listing-table"
rowKey="listingId"
columns={columns}
rowActions={rowActions}
actionColumnWidth={190}
actionColumnWidth={150}
actionColumnFixed="right"
toolbarTitle={
<UText strong>
......@@ -257,15 +227,15 @@ export default function StoreListing() {
actions={actions}
dataSource={listing.data?.records ?? []}
loading={listing.isFetching}
scroll={{ x: 1100 }}
onChange={onTableChange}
scroll={{ x: 950 }}
pagination={{
current: params.current ?? 1,
pageSize: params.size ?? DEFAULT_PAGE_SIZE,
total,
showSizeChanger: true,
showSizeChanger: false,
pageSizeOptions: [10, 20, 50, 100],
showTotal: (count) => `共 ${count} 条`,
showTotal: (count, range) =>
`共 ${count.toLocaleString('zh-CN')} 条记录 · 每页 ${params.size ?? DEFAULT_PAGE_SIZE} 条 · 当前 ${range[0]}–${range[1]} 条`,
onChange: (current, size) =>
setParams((previous) => ({
...previous,
......@@ -274,7 +244,7 @@ export default function StoreListing() {
})),
}}
/>
</UCard>
</div>
<ColumnConfigModal
open={configOpen}
columns={configuredColumns}
......
.store-listing-section {
min-width: 0;
}
.store-listing-toolbar {
padding: 16px 20px;
}
.store-listing-name {
padding: 0;
.store-listing-table.ant-table-wrapper {
min-width: 0;
overflow: hidden;
border: 1px solid #e1e6ed;
border-radius: 10px;
background: #fff;
box-shadow: none;
}
.store-listing-table .ant-table:is(.ant-table-middle, .ant-table-medium) {
color: #333c4a;
font-size: 13px;
line-height: 1.57;
}
.store-listing-table
.ant-table:is(.ant-table-middle, .ant-table-medium)
.ant-table-thead
> tr
> th {
height: 38px;
padding: 0 12px;
border-bottom: 1px solid #e1e6ed;
background: #fbfcfd;
color: #6b7686;
font-size: 12px;
font-weight: 500;
line-height: 1.57;
white-space: nowrap;
}
.store-listing-table .ant-table-thead > tr > th::before {
display: none;
}
.store-listing-table
.ant-table:is(.ant-table-middle, .ant-table-medium)
.ant-table-tbody
> tr
> td {
height: 44px;
padding: 8px 12px;
border-bottom: 1px solid #edf0f5;
color: #333c4a;
font-size: 13px;
line-height: 1.57;
vertical-align: middle;
font-variant-numeric: tabular-nums;
white-space: nowrap;
}
.store-listing-table
.ant-table:is(.ant-table-middle, .ant-table-medium)
.ant-table-tbody
> tr:last-child
> td {
border-bottom: 0;
}
.store-listing-table
.ant-table:is(.ant-table-middle, .ant-table-medium)
.ant-table-tbody
> tr:hover
> td,
.store-listing-table
.ant-table:is(.ant-table-middle, .ant-table-medium)
.ant-table-tbody
> tr
> td.ant-table-cell-row-hover {
background: #fbfcfd;
}
.store-listing-table .store-listing-name {
color: #121821;
font-weight: 500;
}
.store-listing-table .store-code {
color: #2b5ce6;
font-family: 'JetBrains Mono', 'SFMono-Regular', Consolas, monospace;
font-size: 12px;
}
.store-listing-table .store-listing-scene {
display: inline-flex;
align-items: center;
height: 20px;
padding: 0 7px;
border: 0;
border-radius: 4px;
background: #e6f7f5;
color: #07796f;
font-size: 11px;
font-weight: 500;
line-height: 1.57;
white-space: nowrap;
}
.store-listing-table .ant-table-tbody > tr > td:last-child .ant-btn-link {
display: inline-flex;
height: auto;
white-space: normal;
text-align: left;
font-weight: 600;
min-width: 0;
padding: 0;
border: 0;
border-radius: 0;
background: transparent;
color: #2b5ce6;
font-size: 13px;
font-weight: 400;
line-height: 1.57;
vertical-align: middle;
box-shadow: none;
}
.store-listing-table .ant-table-tbody > tr > td:last-child .ant-btn-link + .ant-btn-link {
margin-inline-start: 12px;
}
.store-listing-table .ant-table-tbody > tr > td:last-child .ant-btn-link:hover {
color: #2b5ce6;
text-decoration: underline;
}
.store-listing-table.ant-table-wrapper .ant-table-pagination.ant-pagination {
display: flex;
align-items: center;
justify-content: flex-end;
margin: 0;
padding: 13px 20px;
border-top: 1px solid #e1e6ed;
background: #fff;
color: #6b7686;
font-size: 12px;
}
.store-listing-table .ant-pagination .ant-pagination-total-text {
margin-inline-end: auto;
padding-inline-end: 12px;
}
.store-listing-table .ant-pagination .ant-pagination-item,
.store-listing-table .ant-pagination .ant-pagination-prev,
.store-listing-table .ant-pagination .ant-pagination-next {
min-width: 28px;
height: 28px;
margin-inline-end: 5px;
border-radius: 5px;
font-size: 12px;
line-height: 26px;
}
.store-listing-table .ant-pagination .ant-pagination-item-active {
border-color: #2b5ce6;
background: #2b5ce6;
font-weight: 500;
}
.store-listing-table .ant-pagination .ant-pagination-item-active a {
color: #fff;
}
.store-column-options {
......
......@@ -9,7 +9,13 @@ export const COLUMN_LABELS = {
changeCount: '变更次数',
} as const;
export type ListingColumn = keyof typeof COLUMN_LABELS;
export const DEFAULT_COLUMNS = Object.keys(COLUMN_LABELS) as ListingColumn[];
export const DEFAULT_COLUMNS: ListingColumn[] = [
'storeName',
'merchantNo',
'businessScene',
'effectiveTime',
'changeCount',
];
export const INITIAL_PARAMS: ListingPageParams = {
current: 1,
size: DEFAULT_PAGE_SIZE,
......@@ -21,8 +27,9 @@ export function normalizeColumns(columns?: string[] | null): ListingColumn[] {
const valid = (columns ?? []).filter((column): column is ListingColumn =>
Object.hasOwn(COLUMN_LABELS, column),
);
// 保存的配置只决定显隐,字段顺序始终与原型一致。
return valid.length
? ['storeName', ...new Set(valid.filter((column) => column !== 'storeName'))]
? DEFAULT_COLUMNS.filter((column) => column === 'storeName' || valid.includes(column))
: [...DEFAULT_COLUMNS];
}
......
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 '';
import { defineConfig, loadEnv } from 'vite';
import { defineConfig, loadEnv, type ProxyOptions } from 'vite';
import react from '@vitejs/plugin-react';
import { fileURLToPath, URL } from 'node:url';
import fs from 'node:fs';
......@@ -6,6 +6,12 @@ import path from 'node:path';
// 与浏览器侧共用同一份「代理/直连」推导逻辑,避免两侧默认值各自漂移导致错配
import { resolveApiMode } from './src/api/core/api-mode';
const localDevOrigins = new Set([
'http://localhost:5173',
'http://127.0.0.1:5173',
'http://192.168.1.178:5173',
]);
// 密钥材料统一放在 src/api/core/keys/ 目录(与签名代码同层,内聚),不再写进 .env:
// src/api/core/keys/client_private.pem —— 客户端私钥(请求加签)
// src/api/core/keys/server_public.pem —— 服务端公钥(响应验签)
......@@ -125,7 +131,14 @@ export default defineConfig(({ mode }) => {
target: api.target,
changeOrigin: true,
rewrite: (p: string) => p.replace(/^\/api/, ''),
},
configure(proxy) {
proxy.on('proxyReq', (proxyReq, req) => {
if (req.headers.origin && localDevOrigins.has(req.headers.origin)) {
proxyReq.setHeader('origin', api.target);
}
});
},
} satisfies ProxyOptions,
},
}
: null),
......
......@@ -8,6 +8,12 @@ export default defineConfig({
alias: {
'@': fileURLToPath(new URL('./src', 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'] },
......
Markdown is supported
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!