Commit 60524b02 by liimin

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

2 parents 5a98823f 788f01c2
Pipeline #351 for 60524b02 failed in 0 seconds
Showing 36 changed files with 969 additions and 190 deletions
......@@ -91,6 +91,6 @@ Windows 荳玖凶 `nvm use` 謠千、コ邉サ扈滄得謗・隶ソ髣ョ陲ォ諡堤サ晢シ悟庄蝨ィ邂。逅遭扈育
开发代理:`/api` → `http://192.168.3.197:8788`,配置位于 `vite.config.ts`。需处于可访问后端的内网;生产环境应配置对应网关代理。
门店审批与门店列表已连接 `/store/approval/*`、`/store/listing/*`。筛选和详情共用 `src/features/store/dictionaries.ts` 本地字典,查询提交中文业务值,未知回显值原样展示;新增业务场景或产品分类在此维护。查看权限及按钮权限取登录接口的 `permCodes`;审批状态和层级以后端返回为准。详情按一条「门店+业务场景」记录展示,批量审批使用后端批量接口,重新提交入口及对接已屏蔽,导出直接下载当前筛选结果。
门店审批与门店列表已连接 `/store/approval/*`、`/store/listing/*`。业务场景和产品分类筛选使用后端分类查询接口;产品分类支持远程搜索和下拉滚动分页加载,不预先拉取全部选项,查询仍提交中文名称。详情保留 `src/features/store/dictionaries.ts` 的显示映射,未知回显值原样展示,不调用 `/store/import/spec`。查看权限及按钮权限取登录接口的 `permCodes`;审批状态和层级以后端返回为准。详情按一条「门店+业务场景」记录展示,批量审批使用后端批量接口,重新提交入口及对接已屏蔽,导出直接下载当前筛选结果。
审批和列表接口通过 `lossless-json` 保留长 ID、金额及比例原文;运营成本合计直接展示 `costTotal`,不从已格式化单价或分类明细重新计算。真实页面联调记录位于 `artifacts/store-ui-selftest-2026-10-09/`。
......@@ -22,7 +22,14 @@ export const PermButton = forwardRef<HTMLButtonElement, PermButtonProps>(
if (!ok && fallback === 'hide') return null;
const btn = <UButton ref={ref} {...rest} disabled={!ok || rest.disabled} />;
const btn = (
<UButton
ref={ref}
{...rest}
disabled={!ok || rest.disabled}
style={rest.type === 'text' ? { ...rest.style, paddingInline: 0 } : rest.style}
/>
);
if (!ok && fallback === 'disabled' && unauthorizedTip) {
return <UTooltip title={unauthorizedTip}>{btn}</UTooltip>;
......
......@@ -5,6 +5,12 @@ import { setToken } from '../../core/token';
import * as signing from '../../core/sign';
import { store } from '../store';
// 业务路径契约独立于本机 .env 的部署前缀;公共 /youjia 前缀由 HTTP 层统一添加。
vi.mock('../../core/config', async (importOriginal) => ({
...(await importOriginal<typeof import('../../core/config')>()),
API_CONTEXT_PATH: '',
}));
const originalAdapter = http.defaults.adapter;
const approvalRecord = {
listingId: '9007199254740993',
......@@ -73,6 +79,69 @@ afterEach(() => {
});
describe('store API contract', () => {
it('loads scene options with flat paging and search parameters and preserves scene names', async () => {
serve((config) => {
expect(config.method).toBe('get');
expect(config.url).toBe('/store/category/scenes');
expect(config.params).toEqual({ current: 2, size: 20, name: '售后', status: 1 });
return {
data: result([
{ id: 201, name: '售后会员权益升级', baseSceneCode: '110102', status: 1 },
{ id: 202, name: '售后众筹', baseSceneCode: '110103', status: 1 },
]),
};
});
expect(await store.listScenes({ current: 2, size: 20, name: '售后', status: 1 })).toEqual([
{ id: 201, name: '售后会员权益升级', baseSceneCode: '110102', status: 1 },
{ id: 202, name: '售后众筹', baseSceneCode: '110103', status: 1 },
]);
});
it('loads only the requested goods category page and preserves its category hierarchy', async () => {
let requestCount = 0;
serve((config) => {
requestCount += 1;
expect(config.method).toBe('get');
expect(config.url).toBe('/store/category/goods/page');
expect(config.params).toEqual({ current: 3, size: 20, categoryName: '太阳膜' });
return {
data: result({
records: [
{
id: 51,
categoryType: 6,
categoryName: '太阳膜',
children: [{ id: 52, categoryType: 7, categoryName: '原厂', children: [] }],
},
],
current: 3,
size: 20,
total: 81,
pages: 5,
}),
};
});
expect(
await store.listGoodsCategories({ current: 3, size: 20, categoryName: '太阳膜' }),
).toEqual({
records: [
{
id: 51,
categoryType: 6,
categoryName: '太阳膜',
children: [{ id: 52, categoryType: 7, categoryName: '原厂', children: [] }],
},
],
current: 3,
size: 20,
total: 81,
pages: 5,
});
expect(requestCount).toBe(1);
});
it.each([
['todo', '/store/approval/pending'],
['done', '/store/approval/done'],
......
......@@ -8,10 +8,14 @@ import type {
ListingPageParams,
StoreChangeLog,
StoreColumnConfig,
StoreGoodsCategory,
StoreGoodsCategoryQuery,
StoreId,
StoreListingDetail,
StoreListingRow,
StorePage,
StoreScene,
StoreSceneQuery,
} from './storeTypes';
export * from './storeTypes';
......@@ -149,6 +153,17 @@ const APPROVAL_PATHS: Record<ApproveTab, string> = {
};
class Store extends ApiClient {
listScenes(params: StoreSceneQuery = {}) {
return this.get<StoreScene[]>('/store/category/scenes', params as Record<string, unknown>);
}
listGoodsCategories(params: StoreGoodsCategoryQuery = {}) {
return this.get<StorePage<StoreGoodsCategory>>(
'/store/category/goods/page',
params as Record<string, unknown>,
);
}
listStores(params: ListingPageParams = {}) {
return this.get<StorePage<StoreListingRow>>(
'/store/listing/page',
......
......@@ -11,6 +11,65 @@ export interface StorePage<T> {
pages: number;
}
/** GET /store/category/scenes 的扁平查询参数。 */
export interface StoreSceneQuery {
current?: number;
size?: number;
name?: string;
bizTypeCode?: string;
subTypeCode?: string;
sceneType?: number;
businessType?: number;
status?: number;
baseSceneCode?: string;
}
export interface StoreScene {
id?: StoreId | null;
num?: string | null;
name?: string | null;
baseSceneCode?: string | null;
bizTypeCode?: string | null;
bizTypeName?: string | null;
subTypeCode?: string | null;
subTypeName?: string | null;
description?: string | null;
sceneType?: number | null;
businessType?: number | null;
status?: number | null;
statusName?: string | null;
tagIds?: StoreId[] | null;
tagNames?: string[] | null;
createdBy?: string | null;
createdDate?: string | null;
updatedBy?: string | null;
updatedDate?: string | null;
}
/** GET /store/category/goods/page;分类名称由后端模糊匹配。 */
export interface StoreGoodsCategoryQuery {
current?: number;
size?: number;
categoryName?: string;
}
export interface StoreGoodsCategory {
id?: StoreId | null;
categoryType?: number | null;
categoryName?: string | null;
sceneType?: string | null;
sceneName?: string | null;
createdBy?: string | null;
createdDate?: string | null;
updatedBy?: string | null;
updatedDate?: string | null;
goodsSource?: string | null;
parentId?: StoreId | null;
level?: string | null;
systemCategory?: string | null;
children?: StoreGoodsCategory[] | null;
}
export interface ApprovalPageParams {
current?: number;
size?: number;
......
......@@ -126,12 +126,21 @@ export function DataTable<T extends object>({
onClick: () => void,
key: string,
isRowAction = false,
style?: CSSProperties,
) => {
const type = action.type ?? (isRowAction ? ('text' as const) : undefined);
const buttonProps = {
danger: action.danger,
disabled: action.disabled,
onClick,
type: action.type ?? (isRowAction ? ('link' as const) : undefined),
type,
style:
isRowAction && type === 'text'
? {
color: action.danger ? 'var(--ant-color-error)' : 'var(--ant-color-primary)',
...style,
}
: style,
};
return action.permission ? (
......@@ -150,21 +159,27 @@ export function DataTable<T extends object>({
key: '__actions',
width: actionColumnWidth,
fixed: actionColumnFixed,
render: (_: unknown, record: T) =>
rowActions
.filter((action) => action.visible?.(record) ?? true)
.map((action, index) => {
const label =
typeof action.label === 'function' ? action.label(record) : action.label;
const danger =
typeof action.danger === 'function' ? action.danger(record) : action.danger;
return renderActionButton(
{ ...action, danger, label },
() => action.onClick(record),
`row-action-${index}`,
true,
);
}),
render: (_: unknown, record: T) => {
const visibleActions = rowActions.filter((action) => action.visible?.(record) ?? true);
const lastPermissionActionIndex = visibleActions.reduce(
(lastIndex, action, index) => (action.permission ? index : lastIndex),
-1,
);
return visibleActions.map((action, index) => {
const label = typeof action.label === 'function' ? action.label(record) : action.label;
const danger =
typeof action.danger === 'function' ? action.danger(record) : action.danger;
return renderActionButton(
{ ...action, danger, label },
() => action.onClick(record),
`row-action-${index}`,
true,
action.permission && index < lastPermissionActionIndex
? { marginRight: 8 }
: undefined,
);
});
},
}
: undefined;
const sourceColumns: DataTableColumnsType<T> = showIndex
......@@ -211,6 +226,10 @@ export function DataTable<T extends object>({
columns={tableColumns}
tableLayout={hasLineLimit ? 'fixed' : undefined}
rowSelection={resolvedSelection}
styles={{
header: { cell: { paddingLeft: 20 } },
body: { cell: { paddingLeft: 20 } },
}}
pagination={
resolvedPagination === false
? false
......
......@@ -45,6 +45,7 @@ export function SearchForm<T extends Record<string, unknown>>({
style={{ width }}
options={field.options}
mode={field.type === 'selectMultiple' ? 'multiple' : undefined}
{...field.selectProps}
/>
);
if (field.type === 'cascader')
......
......@@ -2,10 +2,10 @@
// 共五个状态覆盖全部生命周期,其中仅「已生效」可对外展示(门店列表只展示已生效数据)。
export type StoreStatus = 'PENDING' | 'APPROVED' | 'REJECTED' | 'REVOKED' | 'VOID';
// 状态徽标配色规范(待审批黄 / 已生效绿 / 已打回红 / 已撤回灰 / 已作废灰)
// 状态徽标配色规范(待审批黄 / 已生效蓝 / 已打回红 / 已撤回灰 / 已作废灰)
export const STORE_STATUS: Record<StoreStatus, { label: string; color: string }> = {
PENDING: { label: '待审批', color: 'gold' },
APPROVED: { label: '已生效', color: 'green' },
APPROVED: { label: '已生效', color: 'blue' },
REJECTED: { label: '已打回', color: 'red' },
REVOKED: { label: '已撤回', color: '#8A94A6' },
VOID: { label: '已作废', color: '#C9CED6' },
......
......@@ -32,7 +32,7 @@ interface FlowStage {
key: string;
title: string;
state: StageState;
number?: number;
number: number;
actor?: string | null;
time?: string | null;
caption?: string;
......@@ -101,10 +101,10 @@ function ApprovalStatus({ detail }: { detail: StoreListingDetail }) {
}
function StageIcon({ state, number }: { state: StageState; number?: number }) {
if (number !== undefined) return <>{number}</>;
if (state === 'rejected') return <CloseOutlined />;
if (state === 'stopped') return <MinusOutlined />;
if (state === 'done' || number === undefined) return <CheckOutlined />;
return <>{number}</>;
return <CheckOutlined />;
}
export function ApprovalDetailHeader({
......@@ -174,6 +174,7 @@ export function ApprovalStages({ detail }: { detail: StoreListingDetail }) {
{
key: 'submit',
title: '提交',
number: 1,
state: 'done',
actor: detail.submitUserName || EMPTY,
time: detail.submitTime,
......@@ -198,7 +199,7 @@ export function ApprovalStages({ detail }: { detail: StoreListingDetail }) {
return {
key: title,
title,
number: index + 1,
number: index + 2,
state,
actor: done ? passedLog?.operatorName : undefined,
time: done ? passedLog?.operateTime : undefined,
......@@ -215,6 +216,7 @@ export function ApprovalStages({ detail }: { detail: StoreListingDetail }) {
{
key: 'effective',
title: '生效',
number: roles.length + 2,
state: approved ? 'done' : stopped ? 'stopped' : 'waiting',
time: approved ? (detail.effectiveTime ?? detail.approveTime) : undefined,
caption: approved ? undefined : stopped || rejected ? '未生效' : '写入门店列表',
......
......@@ -66,9 +66,11 @@ function ListingStatus({ detail }: { detail: StoreListingDetail }) {
export function ListingDetailHeader({
detail,
spec,
onClose,
}: {
detail: StoreListingDetail;
spec?: StoreDictionaries;
onClose: () => void;
}) {
return (
......@@ -93,7 +95,7 @@ export function ListingDetailHeader({
</div>
<div>
<dt>业务场景</dt>
<dd>{detail.businessScene?.trim() ? '1 个' : EMPTY}</dd>
<dd>{dictionaryLabel(spec?.businessScenes, detail.businessScene?.trim())}</dd>
</div>
<div>
<dt>产品分类</dt>
......
......@@ -150,7 +150,7 @@ describe('store detail presentation', () => {
});
const overview = within(screen.getByLabelText('门店概览'));
expect(overview.getByRole('heading', { name: '当前门店' })).toBeInTheDocument();
for (const text of ['SQ001', '1 个', '6 个', '2026-10-09', 'v3', '已生效']) {
for (const text of ['SQ001', '售后会员权益升级', '6 个', '2026-10-09', 'v3', '已生效']) {
expect(overview.getByText(text)).toBeInTheDocument();
}
expect(overview.queryByText('提交人')).not.toBeInTheDocument();
......@@ -166,7 +166,7 @@ describe('store detail presentation', () => {
expect(onClose).toHaveBeenCalledOnce();
});
it('does not invent a version or scene count when listing fields are missing', () => {
it('does not invent a version or scene when listing fields are missing', () => {
show({
mode: 'listing',
detail: {
......@@ -179,6 +179,7 @@ describe('store detail presentation', () => {
});
const overview = within(screen.getByLabelText('门店概览'));
expect(overview.getByText('当前版本')).toBeInTheDocument();
expect(overview.getByText('业务场景').nextElementSibling).toHaveTextContent('—');
expect(overview.queryByText(/^v\d/)).not.toBeInTheDocument();
expect(overview.queryByText('1 个')).not.toBeInTheDocument();
expect(overview.queryByText('0 个')).not.toBeInTheDocument();
......@@ -272,8 +273,47 @@ describe('store detail presentation', () => {
const flow = within(screen.getByLabelText('审批流程'));
expect(flow.queryByText('优加商务经理')).not.toBeInTheDocument();
expect(flow.getByText('优加财务经理')).toBeInTheDocument();
for (const [title, number] of [
['提交', '1'],
['优加财务经理', '2'],
['生效', '3'],
]) {
const stage = flow.getByText(title).closest('li')!;
expect(within(stage).getByText(number)).toBeInTheDocument();
}
});
it.each(['PENDING', 'APPROVED', 'REJECTED', 'REVOKED'] as const)(
'keeps all flow nodes continuously numbered after the flow advances to %s',
(status) => {
show({
detail: {
...detail,
status,
currentLevel: 2,
approvalLogs: [
{
action: 'PASS',
operatorRole: 'YJ_BUSINESS_MGR',
operatorName: '商务甲',
operateTime: '2026-10-09T11:00:00',
},
],
},
});
const flow = within(screen.getByLabelText('审批流程'));
for (const [title, number] of [
['提交', '1'],
['优加商务经理', '2'],
['优加财务经理', '3'],
['生效', '4'],
]) {
const stage = flow.getByText(title).closest('li')!;
expect(within(stage).getByText(number)).toBeInTheDocument();
}
},
);
it('does not describe a rejected record as awaiting approval and preserves the audit reason', () => {
show({ detail: { ...detail, status: 'REJECTED', rejectReason: '请核对政策' } });
expect(
......
......@@ -200,7 +200,7 @@ export function StoreDetailDrawer({
title={
showCustomHeader ? (
mode === 'listing' ? (
<ListingDetailHeader detail={detail!} onClose={onClose} />
<ListingDetailHeader detail={detail!} spec={spec} onClose={onClose} />
) : (
<ApprovalDetailHeader detail={detail!} spec={spec} onClose={onClose} />
)
......
......@@ -72,8 +72,8 @@
}
.approval-detail-status--approved {
background: #e6f5ee;
color: #087b54;
background: var(--ant-color-primary-bg, #eef3ff);
color: var(--uj-primary, #2b5ce6);
}
.approval-detail-status--rejected {
......@@ -141,8 +141,8 @@
.approval-detail-flow__heading > span {
padding: 1px 8px;
border-radius: 4px;
background: #e4f5f4;
color: #008f88;
background: var(--ant-color-primary-bg, #eef3ff);
color: var(--uj-primary, #2b5ce6);
font-size: 13px;
line-height: 22px;
}
......@@ -176,7 +176,7 @@
}
.approval-detail-flow__node--done:not(:last-child)::after {
background: #0da370;
background: var(--uj-primary, #2b5ce6);
}
.approval-detail-flow__icon {
......@@ -197,8 +197,8 @@
.approval-detail-flow__node--done .approval-detail-flow__icon,
.approval-detail-chaincard__icon--done {
border-color: #0da370;
background: #0da370;
border-color: var(--uj-primary, #2b5ce6);
background: var(--uj-primary, #2b5ce6);
color: #fff;
}
......
......@@ -47,8 +47,8 @@
max-width: 280px;
padding: 1px 7px;
border-radius: 4px;
background: #e4f5f4;
color: #07796f;
background: var(--ant-color-primary-bg, #eef3ff);
color: var(--uj-primary, #2b5ce6);
font-size: 12px;
font-weight: 500;
line-height: 20px;
......
......@@ -12,9 +12,9 @@ const textOptions = (values: string[]): DictOption[] =>
values.map((value) => ({ value, label: value }));
/**
* 门店筛选和详情共用的本地字典;查询接口接收中文业务值。
* 详情展示所用的本地映射和计算规则字典;未知业务名称原样回显。
* 来源:2026-10-09 导入模板的计算/是否取值、模板示例及已返回的门店记录。
* 模板未提供完整场景/分类目录;新增业务值在此维护,未知回显值仍原样展示。
* 场景/分类目录仅含历史示例,不用于筛选;筛选选项由分类查询接口提供。
*/
export const STORE_DICTIONARIES: StoreDictionaries = {
businessScenes: textOptions(['售后众筹', '精品升级', '售后会员权益升级', '售前延保']),
......
......@@ -93,8 +93,8 @@
}
.listing-detail-status--approved {
background: #e6f5ee;
color: #087b54;
background: var(--ant-color-primary-bg, #eef3ff);
color: var(--uj-primary, #2b5ce6);
}
.listing-detail-status--pending {
......@@ -198,8 +198,8 @@
max-width: 100%;
padding: 1px 8px;
border-radius: 4px;
background: #e4f5f4;
color: #008f88;
background: var(--ant-color-primary-bg, #eef3ff);
color: var(--uj-primary, #2b5ce6);
font-size: 13px;
line-height: 22px;
}
......
import type { PropsWithChildren } from 'react';
import { QueryClient, QueryClientProvider } from '@tanstack/react-query';
import {
act,
cleanup,
fireEvent,
render,
renderHook,
screen,
waitFor,
} from '@testing-library/react';
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import { useStoreFilterOptions } from './useStoreFilterOptions';
const api = vi.hoisted(() => ({ listScenes: vi.fn(), listGoodsCategories: vi.fn() }));
vi.mock('@/api', () => ({ store: api }));
const clients: QueryClient[] = [];
function setup(enabled = true, includeProducts = true) {
const client = new QueryClient({ defaultOptions: { queries: { retry: false } } });
clients.push(client);
const wrapper = ({ children }: PropsWithChildren) => (
<QueryClientProvider client={client}>{children}</QueryClientProvider>
);
return renderHook(() => useStoreFilterOptions({ enabled, includeProducts }), { wrapper });
}
const bottomScroll = {
currentTarget: { scrollHeight: 320, scrollTop: 280, clientHeight: 40 },
} as React.UIEvent<HTMLDivElement>;
beforeEach(() => {
vi.resetAllMocks();
api.listScenes.mockResolvedValue([{ name: '接口新增场景' }]);
api.listGoodsCategories.mockResolvedValue({
records: [{ categoryName: '接口新增分类' }],
current: 1,
size: 20,
total: 1,
pages: 1,
});
});
afterEach(() => {
cleanup();
clients.forEach((client) => client.clear());
clients.length = 0;
});
describe('store remote filter options', () => {
it('loads only one page, appends on scroll, and stops at the last page', async () => {
api.listGoodsCategories.mockImplementation(async ({ current }) => ({
records:
current === 1
? [
{
categoryName: '车辆美容',
children: [
{
categoryName: '车辆美容2级',
children: [{ categoryName: '车辆美容3级(集采)' }],
},
],
},
]
: [{ categoryName: '车辆美容' }, { categoryName: '第二页分类' }],
current,
size: 20,
total: 21,
pages: 2,
}));
const { result } = setup();
await waitFor(() =>
expect(result.current.productCategory.options).toContainEqual({
value: '车辆美容-车辆美容2级',
label: '车辆美容-车辆美容2级',
}),
);
expect(api.listGoodsCategories).toHaveBeenCalledTimes(1);
expect(api.listGoodsCategories).toHaveBeenCalledWith({
current: 1,
size: 20,
categoryName: undefined,
});
act(() => {
result.current.productCategory.selectProps.onPopupScroll?.(bottomScroll);
result.current.productCategory.selectProps.onPopupScroll?.(bottomScroll);
});
await waitFor(() =>
expect(result.current.productCategory.options.map((option) => option.value)).toEqual([
'',
'车辆美容',
'车辆美容-车辆美容2级',
'车辆美容-车辆美容2级-车辆美容3级(集采)',
'第二页分类',
]),
);
act(() => result.current.productCategory.selectProps.onPopupScroll?.(bottomScroll));
expect(api.listGoodsCategories).toHaveBeenCalledTimes(2);
});
it('debounces remote search, resets pagination, and ignores an older search response', async () => {
let resolveOld!: (value: unknown) => void;
const response = (name: string) => ({
records: [{ categoryName: name }],
current: 1,
size: 20,
total: 1,
pages: 1,
});
api.listGoodsCategories.mockImplementation(({ categoryName }) =>
categoryName === '旧搜索'
? new Promise((resolve) => {
resolveOld = resolve;
})
: Promise.resolve(response(categoryName || '初始分类')),
);
const { result } = setup();
await waitFor(() => expect(result.current.productCategory.options).toHaveLength(2));
const search = (text: string) => {
const config = result.current.productCategory.selectProps.showSearch;
if (typeof config === 'object') config.onSearch?.(text);
};
act(() => {
search('旧');
search('旧搜索');
});
expect(api.listGoodsCategories).toHaveBeenCalledTimes(1);
await waitFor(() =>
expect(api.listGoodsCategories).toHaveBeenCalledWith({
current: 1,
size: 20,
categoryName: '旧搜索',
}),
);
act(() => search('新搜索'));
await waitFor(() =>
expect(result.current.productCategory.options).toContainEqual({
value: '新搜索',
label: '新搜索',
}),
);
await act(async () => resolveOld(response('旧搜索结果')));
expect(result.current.productCategory.options.map((option) => option.value)).toEqual([
'',
'新搜索',
]);
act(() => result.current.reset());
await waitFor(() =>
expect(result.current.productCategory.options.map((option) => option.value)).toEqual([
'',
'初始分类',
]),
);
});
it('uses scene names from the endpoint and skips product calls on the listing page', async () => {
const { result } = setup(true, false);
await waitFor(() =>
expect(result.current.businessScene.options).toContainEqual({
value: '接口新增场景',
label: '接口新增场景',
}),
);
expect(api.listGoodsCategories).not.toHaveBeenCalled();
});
it('can paginate a new keyword while an older keyword page is still loading', async () => {
let resolveOld!: (value: unknown) => void;
const page = (current: number, name: string) => ({
records: [{ categoryName: name }],
current,
size: 20,
total: 21,
pages: 2,
});
api.listGoodsCategories.mockImplementation(({ current, categoryName }) =>
!categoryName && current === 2
? new Promise((resolve) => {
resolveOld = resolve;
})
: Promise.resolve(page(current, `${categoryName || '初始'}${current}`)),
);
const { result } = setup();
await waitFor(() => expect(result.current.productCategory.options).toHaveLength(2));
act(() => result.current.productCategory.selectProps.onPopupScroll?.(bottomScroll));
act(() => {
const config = result.current.productCategory.selectProps.showSearch;
if (typeof config === 'object') config.onSearch?.('新词');
});
await waitFor(() =>
expect(result.current.productCategory.options).toContainEqual({
value: '新词1',
label: '新词1',
}),
);
act(() => result.current.productCategory.selectProps.onPopupScroll?.(bottomScroll));
await waitFor(() =>
expect(result.current.productCategory.options).toContainEqual({
value: '新词2',
label: '新词2',
}),
);
await act(async () => resolveOld(page(2, '旧页')));
expect(result.current.productCategory.options.map((option) => option.value)).toEqual([
'',
'新词1',
'新词2',
]);
});
it('preserves loaded options when loading more fails and retries the same page', async () => {
api.listGoodsCategories
.mockResolvedValueOnce({
records: [{ categoryName: '第一页' }],
current: 1,
size: 20,
total: 21,
pages: 2,
})
.mockRejectedValueOnce(new Error('网络异常'))
.mockResolvedValueOnce({
records: [{ categoryName: '第二页' }],
current: 2,
size: 20,
total: 21,
pages: 2,
});
const { result } = setup();
await waitFor(() => expect(result.current.productCategory.options).toHaveLength(2));
act(() => result.current.productCategory.selectProps.onPopupScroll?.(bottomScroll));
await waitFor(() => expect(api.listGoodsCategories).toHaveBeenCalledTimes(2));
await waitFor(() => expect(result.current.productCategory.selectProps.loading).toBe(false));
expect(result.current.productCategory.options[1].value).toBe('第一页');
render(<>{result.current.productCategory.selectProps.popupRender?.(<div />)}</>);
fireEvent.click(screen.getByRole('button', { name: '加载失败,点击重试' }));
await waitFor(() =>
expect(result.current.productCategory.options.map((option) => option.value)).toEqual([
'',
'第一页',
'第二页',
]),
);
expect(api.listGoodsCategories).toHaveBeenLastCalledWith({
current: 2,
size: 20,
categoryName: undefined,
});
});
it('does not load dictionaries without view permission', async () => {
setup(false);
await act(async () => {});
expect(api.listScenes).not.toHaveBeenCalled();
expect(api.listGoodsCategories).not.toHaveBeenCalled();
});
});
import { useEffect, useRef, useState } from 'react';
import { useInfiniteQuery } from '@tanstack/react-query';
import type { SelectProps } from 'antd';
import { UButton } from '@uj/ui';
import { store, type StoreGoodsCategory } from '@/api';
import type { FieldOption } from '@/components/formSchema';
const PAGE_SIZE = 20;
const ALL: FieldOption = { value: '', label: '全部' };
type OptionKind = 'scenes' | 'goods';
interface OptionPage {
options: FieldOption[];
next?: number;
}
function nameOptions(names: (string | null | undefined)[]): FieldOption[] {
return [
...new Set(names.map((name) => name?.trim()).filter((name): name is string => !!name)),
].map((name) => ({ value: name, label: name }));
}
function categoryNames(categories: StoreGoodsCategory[], ancestors: string[] = []): string[] {
return categories.flatMap((category) => {
const name = category.categoryName?.trim();
const path = name ? [...ancestors, name] : ancestors;
// 门店导入/审批记录存的是以“-”连接的完整分类路径,而字典 children 是分层名称。
return [...(name ? [path.join('-')] : []), ...categoryNames(category.children ?? [], path)];
});
}
/** 筛选接口仍接收名称;字典 ID 只属于字典接口,不能代替查询值。 */
async function loadOptions(
kind: OptionKind,
current: number,
keyword: string,
): Promise<OptionPage> {
if (kind === 'goods') {
const page = await store.listGoodsCategories({
current,
size: PAGE_SIZE,
categoryName: keyword || undefined,
});
return {
options: nameOptions(categoryNames(page.records ?? [])),
next: page.records?.length && page.current < page.pages ? page.current + 1 : undefined,
};
}
const scenes = await store.listScenes({ current, size: PAGE_SIZE, name: keyword || undefined });
return {
options: nameOptions((scenes ?? []).map((scene) => scene.name)),
// 场景接口返回数组,没有 total/pages;不足一页表示已加载完。
next: scenes?.length >= PAGE_SIZE ? current + 1 : undefined,
};
}
function useRemoteOptions(kind: OptionKind, enabled: boolean) {
const [search, setSearch] = useState('');
const [keyword, setKeyword] = useState('');
const fetchingNext = useRef<string | undefined>(undefined);
useEffect(() => {
const timer = window.setTimeout(() => setKeyword(search.trim()), 300);
return () => window.clearTimeout(timer);
}, [search]);
const query = useInfiniteQuery({
queryKey: ['store', 'filter-options', kind, keyword],
queryFn: ({ pageParam }) => loadOptions(kind, pageParam, keyword),
initialPageParam: 1,
getNextPageParam: (last, pages) => {
if (kind === 'scenes' && pages.length > 1) {
const previous = new Set(
pages.slice(0, -1).flatMap((page) => page.options.map((option) => option.value)),
);
// 兼容返回全量数组的场景服务,避免一直请求相同数据。
if (last.options.every((option) => previous.has(option.value))) return undefined;
}
return last.next;
},
enabled,
staleTime: 5 * 60_000,
retry: false,
});
const searching = search.trim() !== keyword;
const options = [ALL];
const seen = new Set<string | number>(['']);
for (const page of searching ? [] : (query.data?.pages ?? [])) {
for (const option of page.options) {
if (!seen.has(option.value)) {
seen.add(option.value);
options.push(option);
}
}
}
const reset = () => {
setSearch('');
setKeyword('');
};
const loadMore = () => {
if (
!enabled ||
searching ||
!query.hasNextPage ||
query.isFetching ||
fetchingNext.current === keyword
)
return;
fetchingNext.current = keyword;
void query.fetchNextPage({ cancelRefetch: false }).finally(() => {
if (fetchingNext.current === keyword) fetchingNext.current = undefined;
});
};
const loading = enabled && (searching || query.isFetching);
const selectProps: SelectProps = {
showSearch: { searchValue: search, onSearch: setSearch, filterOption: false },
loading,
onChange: reset,
onOpenChange: (open) => {
if (!open) reset();
},
onPopupScroll: (event) => {
const target = event.currentTarget;
if (target.scrollHeight - target.scrollTop - target.clientHeight < 32) loadMore();
},
popupRender: (menu) => (
<>
{menu}
<div
style={{ padding: '6px 12px', color: 'var(--uj-text-3)', fontSize: 12 }}
aria-live="polite"
>
{loading ? (
'加载中…'
) : query.isError ? (
<UButton
type="link"
size="small"
onMouseDown={(event) => event.preventDefault()}
onClick={() => {
if (query.isFetchNextPageError) loadMore();
else void query.refetch();
}}
>
加载失败,点击重试
</UButton>
) : options.length === 1 ? (
'暂无匹配选项'
) : query.hasNextPage ? (
'向下滚动加载更多'
) : (
'已加载全部'
)}
</div>
</>
),
};
return { options, selectProps, reset };
}
export function useStoreFilterOptions({
enabled,
includeProducts = false,
}: {
enabled: boolean;
includeProducts?: boolean;
}) {
const productCategory = useRemoteOptions('goods', enabled && includeProducts);
const businessScene = useRemoteOptions('scenes', enabled);
return {
productCategory,
businessScene,
reset: () => {
productCategory.reset();
businessScene.reset();
},
};
}
......@@ -129,13 +129,13 @@ export default function AccountManage() {
<UText style={{ color: '#315ce8', fontFamily: 'monospace' }}>{value}</UText>
),
},
{ title: '姓名', dataIndex: 'name', width: 110, line: 1 },
{ title: '姓名', dataIndex: 'name', width: 130, line: 1 },
{ title: '手机号', dataIndex: 'mobile', width: 120 },
{ title: '所属组织', dataIndex: 'orgPath', width: 230, line: 1 },
{
title: '角色',
dataIndex: 'roleNames',
width: 280,
width: 290,
render: (names: string[]) =>
names.length
? names.map((name, index) => (
......@@ -149,7 +149,7 @@ export default function AccountManage() {
))
: '—',
},
{ title: '数据域', dataIndex: 'dataScopeLabel', width: 140 },
{ title: '数据域', dataIndex: 'dataScopeLabel' },
{
title: '状态',
width: 90,
......
......@@ -114,13 +114,13 @@ export default function RoleManage() {
{
title: '角色编码',
dataIndex: 'code',
width: 150,
width: 200,
line: 1,
render: (v) => <UText style={{ color: '#315ce8', fontFamily: 'monospace' }}>{v}</UText>,
},
{ title: '默认数据域', dataIndex: 'scope', width: 130 },
{ title: '默认数据域', dataIndex: 'scope' },
{ title: '账号数', dataIndex: 'userCount', width: 90 },
{ title: '角色描述', dataIndex: 'description', width: 380, line: 1 },
{ title: '角色描述', dataIndex: 'description', width: 400, line: 1 },
{
title: '类型',
dataIndex: 'type',
......
......@@ -7,6 +7,8 @@ import type { ApprovalRow } from '@/api';
import StoreApprove from '../index';
const api = vi.hoisted(() => ({
listScenes: vi.fn(),
listGoodsCategories: vi.fn(),
listApprovals: vi.fn(),
getApproval: vi.fn(),
passApproval: vi.fn(),
......@@ -50,6 +52,14 @@ let detail = {
beforeEach(() => {
vi.resetAllMocks();
api.listScenes.mockResolvedValue([]);
api.listGoodsCategories.mockResolvedValue({
records: [],
total: 0,
current: 1,
size: 20,
pages: 0,
});
pending = [{ ...row }];
mine = [
{ ...row, listingId: '202', status: 'REJECTED', statusLabel: '已打回', actionable: false },
......@@ -121,22 +131,42 @@ describe('门店审批页面', () => {
expect(screen.getByText('49 小时')).toBeInTheDocument();
});
it('使用本地字典按实际中文业务场景和产品分类筛选', async () => {
it('使用接口新增的业务场景和产品分类选项,查询提交中文名称', async () => {
api.listScenes.mockResolvedValue([{ id: 11, name: '新能源车交付' }]);
api.listGoodsCategories.mockImplementation(async ({ categoryName }) => ({
records:
categoryName === '汽车精品'
? [{ id: 91, categoryType: 91, categoryName: '汽车精品专属服务', children: [] }]
: [],
total: categoryName === '汽车精品' ? 1 : 0,
current: 1,
size: 20,
pages: categoryName === '汽车精品' ? 1 : 0,
}));
mount();
await screen.findByText('测试门店');
fireEvent.mouseDown(screen.getByLabelText('业务场景'));
fireEvent.click(
await screen.findByText('精品升级', { selector: '.ant-select-item-option-content' }),
await screen.findByText('新能源车交付', { selector: '.ant-select-item-option-content' }),
);
fireEvent.mouseDown(screen.getByLabelText('产品分类'));
fireEvent.change(screen.getByLabelText('产品分类'), { target: { value: '汽车精品' } });
fireEvent.click(
await screen.findByText('车辆美容', { selector: '.ant-select-item-option-content' }),
await screen.findByText('汽车精品专属服务', { selector: '.ant-select-item-option-content' }),
);
expect(api.listGoodsCategories).toHaveBeenCalledWith({
current: 1,
size: 20,
categoryName: '汽车精品',
});
fireEvent.click(screen.getByRole('button', { name: '查询' }));
await waitFor(() =>
expect(api.listApprovals).toHaveBeenCalledWith(
'todo',
expect.objectContaining({ businessScene: '精品升级', productCategory: '车辆美容' }),
expect.objectContaining({
businessScene: '新能源车交付',
productCategory: '汽车精品专属服务',
}),
),
);
expect(screen.queryByText('筛选字典加载失败')).not.toBeInTheDocument();
......@@ -325,6 +355,8 @@ describe('门店审批页面', () => {
mount([]);
expect(screen.getByText('无门店审批访问权限')).toBeInTheDocument();
expect(api.listApprovals).not.toHaveBeenCalled();
expect(api.listScenes).not.toHaveBeenCalled();
expect(api.listGoodsCategories).not.toHaveBeenCalled();
});
it('仅有通过权限不能替代页面查看权限,也不加载审批详情', () => {
......
......@@ -37,14 +37,31 @@
white-space: nowrap;
}
.store-approve-categories[tabindex] {
cursor: help;
}
.store-approve-category-list {
max-height: 320px;
margin: 0;
padding: 0 0 0 18px;
overflow-y: auto;
overflow-wrap: anywhere;
white-space: normal;
}
.store-approve-category-list > li + li {
margin-top: 4px;
}
.store-approve-tag {
display: inline-flex;
align-items: center;
height: 20px;
padding: 0 7px;
border-radius: 4px;
background: #e6f7f5;
color: #07796f;
background: var(--ant-color-primary-bg, #eef3ff);
color: var(--uj-primary, #2b5ce6);
font-size: 11px;
font-weight: 500;
white-space: nowrap;
......@@ -89,8 +106,8 @@
}
.store-approve-stay--normal {
background: #e8f7f0;
color: #0b6b47;
background: var(--ant-color-primary-bg, #eef3ff);
color: var(--uj-primary, #2b5ce6);
}
.store-approve-stay--warning {
......
......@@ -19,6 +19,7 @@ import {
} from '@/api';
import { StoreDetailDrawer } from '@/features/store/StoreDetailDrawer';
import { STORE_DICTIONARIES } from '@/features/store/dictionaries';
import { useStoreFilterOptions } from '@/features/store/useStoreFilterOptions';
import { buildApproveColumns } from './tools/columns';
import { ApprovalActionModal, type ApprovalAction } from './components/ApprovalActionModal';
import { errorMessage, tabDefs } from './tools/consts';
......@@ -35,6 +36,7 @@ const cleanText = (value: unknown) =>
export default function StoreApprove() {
const { canPoint } = useAccess();
const allowed = canPoint(P.STORE_APPROVE_VIEW);
const filterOptions = useStoreFilterOptions({ enabled: allowed, includeProducts: true });
const canPass = canPoint(P.STORE_APPROVE_AUDIT);
const canReject = canPoint(P.STORE_APPROVE_REJECT);
const canRevoke = canPoint(P.STORE_APPROVE_REVOKE);
......@@ -186,14 +188,16 @@ export default function StoreApprove() {
label: '产品分类',
type: 'select',
width: '100%',
options: [{ value: '', label: '全部' }, ...STORE_DICTIONARIES.productCategories],
options: filterOptions.productCategory.options,
selectProps: filterOptions.productCategory.selectProps,
},
{
name: 'businessScene',
label: '业务场景',
type: 'select',
width: '100%',
options: [{ value: '', label: '全部' }, ...STORE_DICTIONARIES.businessScenes],
options: filterOptions.businessScene.options,
selectProps: filterOptions.businessScene.selectProps,
},
{
name: 'submitUserName',
......@@ -288,7 +292,10 @@ export default function StoreApprove() {
submitUserName: '',
}}
onSearch={changeQuery}
onReset={() => changeQuery({})}
onReset={() => {
filterOptions.reset();
changeQuery({});
}}
/>
</UCard>
{list.isError ? (
......
import type { ColumnsType } from 'antd/es/table';
import { UTag } from '@uj/ui';
import { UTag, UTooltip } from '@uj/ui';
import { StatusTag } from '@/components/StatusTag';
import type { ApprovalRow, ApproveTab } from '@/api';
import type { StoreDictionaries } from '@/features/store/dictionaries';
......@@ -38,17 +38,34 @@ export function buildApproveColumns(
render: (_, row) => {
const categories = row.productCategories ?? [];
const count = row.categoryCount ?? categories.length;
const categoryNames = categories
.filter((category) => category.trim())
.map((category) => dictionaryLabel(spec?.productCategories, category));
return (
<span className="store-approve-categories">
{categories[0] ? (
<span className="store-approve-tag">
{dictionaryLabel(spec?.productCategories, categories[0])}
</span>
) : (
'—'
)}
{count > 1 && <span className="store-approve-category-count">等 {count} 个分类</span>}
</span>
<UTooltip
trigger={['hover', 'focus']}
title={
categoryNames.length ? (
<ul className="store-approve-category-list" aria-label="全部产品分类">
{categoryNames.map((name, index) => (
<li key={`${name}-${index}`}>{name}</li>
))}
</ul>
) : undefined
}
>
<span
className="store-approve-categories"
tabIndex={categoryNames.length ? 0 : undefined}
>
{categoryNames[0] ? (
<span className="store-approve-tag">{categoryNames[0]}</span>
) : (
'—'
)}
{count > 1 && <span className="store-approve-category-count">等 {count} 个分类</span>}
</span>
</UTooltip>
);
},
},
......@@ -113,9 +130,7 @@ export function buildApproveColumns(
width: 110,
render: (_, row) => (
<UTag
color={
row.myAction === 'PASS' ? 'green' : row.myAction === 'REJECT' ? 'red' : undefined
}
color={row.myAction === 'PASS' ? 'blue' : row.myAction === 'REJECT' ? 'red' : undefined}
>
{row.myActionLabel ||
({ PASS: '通过', REJECT: '打回' }[row.myAction ?? ''] ?? row.myAction ?? '—')}
......
......@@ -7,6 +7,8 @@ import { AccessTestProvider } from '@/test/AccessTestProvider';
import StoreListing from './index';
const api = vi.hoisted(() => ({
listScenes: vi.fn(),
listGoodsCategories: vi.fn(),
listStores: vi.fn(),
getStore: vi.fn(),
getChanges: vi.fn(),
......@@ -60,6 +62,14 @@ function renderPage(permissions = ['store:list:view', 'store:list:export']) {
beforeEach(() => {
vi.clearAllMocks();
api.listScenes.mockResolvedValue([]);
api.listGoodsCategories.mockResolvedValue({
records: [],
total: 0,
current: 1,
size: 20,
pages: 0,
});
api.listStores.mockImplementation(async (params) => ({
records: rows,
total: 42,
......@@ -99,16 +109,17 @@ afterEach(() => {
});
describe('门店列表', () => {
it('本地业务场景可筛选且导出沿用同一实际中文值', async () => {
it('接口新增的业务场景可筛选且导出沿用同一实际中文值', async () => {
api.listScenes.mockResolvedValue([{ id: 11, name: '新能源车交付' }]);
renderPage();
fireEvent.mouseDown(await screen.findByLabelText('业务场景'));
fireEvent.click(
await screen.findByText('售后众筹', { selector: '.ant-select-item-option-content' }),
await screen.findByText('新能源车交付', { selector: '.ant-select-item-option-content' }),
);
fireEvent.click(screen.getByRole('button', { name: /查\s*询/ }));
await waitFor(() =>
expect(api.listStores).toHaveBeenLastCalledWith(
expect.objectContaining({ businessScene: '售后众筹', current: 1 }),
expect.objectContaining({ businessScene: '新能源车交付', current: 1 }),
),
);
const exportButton = screen.getByRole('button', { name: /导\s*出/ });
......@@ -116,10 +127,11 @@ describe('门店列表', () => {
fireEvent.click(exportButton);
await waitFor(() =>
expect(api.exportStores).toHaveBeenCalledWith(
expect.objectContaining({ businessScene: '售后众筹' }),
expect.objectContaining({ businessScene: '新能源车交付' }),
),
);
expect(screen.queryByText('业务场景加载失败')).not.toBeInTheDocument();
expect(api.listGoodsCategories).not.toHaveBeenCalled();
});
it('提交真实筛选参数,翻页保留筛选,重置同时清空表单与请求', async () => {
......@@ -379,6 +391,8 @@ describe('门店列表', () => {
expect(api.listStores).not.toHaveBeenCalled();
expect(api.getColumnConfig).not.toHaveBeenCalled();
expect(api.getStore).not.toHaveBeenCalled();
expect(api.listScenes).not.toHaveBeenCalled();
expect(api.listGoodsCategories).not.toHaveBeenCalled();
});
it('仅有导出权限不能替代列表查看权限,也不显示导出操作', async () => {
......
......@@ -15,6 +15,7 @@ import {
} from '@/components';
import { StoreDetailDrawer } from '@/features/store/StoreDetailDrawer';
import { STORE_DICTIONARIES } from '@/features/store/dictionaries';
import { useStoreFilterOptions } from '@/features/store/useStoreFilterOptions';
import { buildColumns } from './components/columns';
import { ColumnConfigModal } from './components/ColumnConfigModal';
import {
......@@ -34,6 +35,7 @@ export default function StoreListing() {
const { message } = App.useApp();
const { canPoint } = useAccess();
const allowed = canPoint(P.STORE_LISTING_VIEW);
const filterOptions = useStoreFilterOptions({ enabled: allowed, includeProducts: false });
const queryClient = useQueryClient();
const [params, setParams] = useState<ListingPageParams>(INITIAL_PARAMS);
const [queryVersion, setQueryVersion] = useState(0);
......@@ -103,7 +105,8 @@ export default function StoreListing() {
label: '业务场景',
type: 'select',
width: '100%',
options: [{ value: '', label: '全部' }, ...STORE_DICTIONARIES.businessScenes],
options: filterOptions.businessScene.options,
selectProps: filterOptions.businessScene.selectProps,
},
{ name: 'effectiveRange', label: '上架时间', type: 'dateRange', width: '100%' },
];
......@@ -186,6 +189,7 @@ export default function StoreListing() {
if (!exportFile.isPending) exportFile.reset();
}}
onReset={() => {
filterOptions.reset();
setParams({ ...INITIAL_PARAMS, size: params.size });
setQueryVersion((version) => version + 1);
if (!exportFile.isPending) exportFile.reset();
......
......@@ -96,8 +96,8 @@
padding: 0 7px;
border: 0;
border-radius: 4px;
background: #e6f7f5;
color: #07796f;
background: var(--ant-color-primary-bg, #eef3ff);
color: var(--uj-primary, #2b5ce6);
font-size: 11px;
font-weight: 500;
line-height: 1.57;
......
......@@ -7,7 +7,7 @@ export interface ConfirmActionBarProps {
onSubmit?: () => void;
}
export function ConfirmActionBar({ passCount = 12, onBack, onSubmit }: ConfirmActionBarProps) {
export function ConfirmActionBar({ onBack, onSubmit }: ConfirmActionBarProps) {
return (
<div
style={{
......@@ -27,7 +27,7 @@ export function ConfirmActionBar({ passCount = 12, onBack, onSubmit }: ConfirmAc
icon={<ArrowRightOutlined />}
onClick={onSubmit ?? (() => console.log('下一步:提交审批'))}
>
下一步:提交审批({passCount})
下一步:提交审批
</UButton>
</div>
</div>
......
import { useMemo } from 'react';
import { InfoCircleFilled, UploadOutlined, DownloadOutlined } from '@ant-design/icons';
import { UCard, UButton, UTag } from '@uj/ui';
import { UCard, UButton } from '@uj/ui';
import type { StoreImportFailVO, StoreImportCheckVO } from '@/api/modules/store';
export interface FailDetailCardProps {
checkResult?: StoreImportCheckVO;
/** 上传文件的字节数(兜底:后端可能不返回 fileSize,用 File 对象的 size 字段) */
fileSize?: number;
/** 点击「重新上传」时触发(通常回到 Step 0 并清空文件) */
onReUpload?: () => void;
}
......@@ -13,7 +15,6 @@ const FAIL_COL_LABELS = [
{ key: 'rowIndex' as const, label: '行号', width: 92 },
{ key: 'storeName' as const, label: '门店名称', width: 300 },
{ key: 'merchantNo' as const, label: '门店商户号', width: 160 },
{ key: 'levelLabel' as const, label: '校验层级', width: 130 },
{ key: 'reason' as const, label: '失败原因', width: undefined },
] as const;
......@@ -33,7 +34,7 @@ function triggerDownloadFailFile(url: string) {
}
}
export function FailDetailCard({ checkResult, onReUpload }: FailDetailCardProps) {
export function FailDetailCard({ checkResult, fileSize, onReUpload }: FailDetailCardProps) {
const failRows = (checkResult?.failRows ?? 0) as number;
const failFileUrl = checkResult?.failFileUrl ?? null;
const failures = (checkResult?.failures ?? []) as StoreImportFailVO[];
......@@ -49,11 +50,13 @@ export function FailDetailCard({ checkResult, onReUpload }: FailDetailCardProps)
* 底部 L1 / L2 通过校验文字(复用 checkResult 的字段,无则从 failures.length 推断)
*/
const l1 = useMemo(() => {
// 文件大小:优先后端 fileSize,兜底用传入的 File.size(字节)
const rawSize = typeof checkResult?.fileSize === 'number' ? checkResult.fileSize : fileSize;
const size =
typeof checkResult?.fileSize === 'number'
? checkResult.fileSize === 0
typeof rawSize === 'number'
? rawSize === 0
? '0'
: `${Math.max(1, Math.round(checkResult.fileSize / 1024))}KB`
: `${Math.max(1, Math.round(rawSize / 1024))}KB`
: '';
const total = typeof checkResult?.totalRows === 'number' ? `${checkResult.totalRows} 行` : '';
const version = checkResult?.templateVersion ? `模板版本${checkResult.templateVersion}` : '';
......@@ -63,7 +66,7 @@ export function FailDetailCard({ checkResult, onReUpload }: FailDetailCardProps)
: `格式 .xlsx / ${size}${total ? ' / ' + total : ''}${version ? ' / ' + version : ''}`,
];
return parts.filter(Boolean).join(' · ');
}, [checkResult]);
}, [checkResult, fileSize]);
const l2 = useMemo(() => {
const template = checkResult?.templateVersion
......@@ -208,29 +211,6 @@ export function FailDetailCard({ checkResult, onReUpload }: FailDetailCardProps)
>
{f.merchantNo ?? '-'}
</td>
{/* 校验层级(浅黄 Tag,与截图 L4 业务级 一致) */}
<td
style={{
padding: '14px 8px',
borderBottom: '1px solid #F3F4F6',
whiteSpace: 'nowrap',
}}
>
<UTag
color="default"
bordered={false}
style={{
background: '#FEF3C7',
color: '#92400E',
padding: '3px 10px',
borderRadius: 6,
fontSize: 13,
lineHeight: 1.4,
}}
>
{f.levelLabel ?? `L${f.levelCode ?? '?'} 校验级`}
</UTag>
</td>
{/* 失败原因(红 #991B1B) */}
<td
style={{
......
......@@ -6,9 +6,9 @@ import type { USelectProps } from '@uj/ui';
import type { StoreImportCheckVO } from '@/api/modules/store';
export interface ImportInfoValues {
org: string;
scene: string;
categories: string[];
org?: string;
scene?: string;
categories?: string[];
remark?: string;
}
......
......@@ -3,8 +3,8 @@ import type { TableProps } from 'antd';
import type { PolicyConfirmRow } from '../../tools/policyTableData';
const storeInfoHeaderStyle: React.CSSProperties = {
background: '#EEF2FF',
color: '#3730A3',
background: '#EFF4FF',
color: '#2B5CE6',
fontWeight: 600,
fontSize: 13,
};
......@@ -51,7 +51,7 @@ function SceneTag({ text }: { text: string }) {
function CategoryTag({ text }: { text: string }) {
return (
<UTag
color="success"
color="processing"
bordered={false}
title={text}
style={{
......@@ -77,7 +77,27 @@ function FeeValueCell({ value }: { value: string }) {
return <span style={{ fontWeight: 600, color: '#1F2937' }}>{value}</span>;
}
export function buildPolicyColumns(): TableProps<PolicyConfirmRow>['columns'] {
export function buildPolicyColumns(
rows: PolicyConfirmRow[] = [],
): TableProps<PolicyConfirmRow>['columns'] {
/**
* 计算当前行某列的 rowSpan(同门店 / 同业务场景合并单元格):
* - keyFn:对每行提取分组 key(如门店名、或「门店名|业务场景」复合键)
* - 当前行与上一行 key 相同 → rowSpan = 0(被合并)
* - 否则向下统计连续相同 key 的行数作为 rowSpan
*/
const getRowSpan = (index: number, keyFn: (r: PolicyConfirmRow) => string): number => {
if (index < 0 || index >= rows.length) return 1;
const cur = keyFn(rows[index]);
if (index > 0 && keyFn(rows[index - 1]) === cur) return 0;
let span = 1;
for (let i = index + 1; i < rows.length; i++) {
if (keyFn(rows[i]) === cur) span++;
else break;
}
return span;
};
return [
// ------------- 第一组:门店信息(4 列) -------------
{
......@@ -90,7 +110,10 @@ export function buildPolicyColumns(): TableProps<PolicyConfirmRow>['columns'] {
key: 'storeName',
width: 200,
onHeaderCell: () => ({ style: storeInfoHeaderStyle }),
onCell: () => ({ style: cellStyle }),
onCell: (_r, index) => ({
rowSpan: getRowSpan(index ?? 0, (r) => r.storeName),
style: cellStyle,
}),
render: (v) => <span style={{ color: '#1A202C', fontWeight: 500 }}>{v}</span>,
},
{
......@@ -100,7 +123,11 @@ export function buildPolicyColumns(): TableProps<PolicyConfirmRow>['columns'] {
width: 130,
align: 'center',
onHeaderCell: () => ({ style: storeInfoHeaderStyle }),
onCell: () => ({ style: cellStyle }),
onCell: (_r, index) => ({
// 同门店的商户号必然相同,按「门店名 + 商户号」复合键合并
rowSpan: getRowSpan(index ?? 0, (r) => `${r.storeName}|${r.storeMerchantNo}`),
style: cellStyle,
}),
render: (v) => <a style={{ color: '#2563EB', fontSize: 12.5 }}>{v}</a>,
},
{
......@@ -110,16 +137,27 @@ export function buildPolicyColumns(): TableProps<PolicyConfirmRow>['columns'] {
width: 130,
align: 'center',
onHeaderCell: () => ({ style: storeInfoHeaderStyle }),
onCell: () => ({ style: cellStyle }),
onCell: (_r, index) => ({
// 同门店下相同业务场景才合并(不同门店同名场景不合并)
rowSpan: getRowSpan(index ?? 0, (r) => `${r.storeName}|${r.businessScene}`),
style: cellStyle,
}),
render: (v: string) => <SceneTag text={v} />,
},
],
},
// ------------- 第二组:商务政策(14 列) -------------
{
title: '商务政策',
align: 'center',
children: [
{
title: '产品分类',
dataIndex: 'productCategory',
key: 'productCategory',
width: 280,
align: 'center',
onHeaderCell: () => ({ style: storeInfoHeaderStyle }),
onHeaderCell: () => ({ style: bizPolicyHeaderStyle }),
onCell: () => ({
style: {
...cellStyle,
......@@ -130,13 +168,6 @@ export function buildPolicyColumns(): TableProps<PolicyConfirmRow>['columns'] {
}),
render: (v: string) => <CategoryTag text={v} />,
},
],
},
// ------------- 第二组:商务政策(14 列) -------------
{
title: '商务政策',
align: 'center',
children: [
// 管理层市场费 1
{
title: '管理层市场费1计算模式',
......@@ -203,7 +234,11 @@ export function buildPolicyColumns(): TableProps<PolicyConfirmRow>['columns'] {
width: 170,
align: 'center',
onHeaderCell: () => ({ style: bizPolicyHeaderStyle }),
onCell: () => ({ style: cellStyle }),
onCell: (_r, index) => ({
// 同门店同业务场景合并(与「业务场景」列合并粒度一致)
rowSpan: getRowSpan(index ?? 0, (r) => `${r.storeName}|${r.businessScene}`),
style: cellStyle,
}),
},
{
title: '一线阳光计算模式',
......@@ -241,7 +276,11 @@ export function buildPolicyColumns(): TableProps<PolicyConfirmRow>['columns'] {
width: 180,
align: 'center',
onHeaderCell: () => ({ style: bizPolicyHeaderStyle }),
onCell: () => ({ style: cellStyle }),
onCell: (_r, index) => ({
// 同门店同业务场景合并(与「业务场景」列合并粒度一致)
rowSpan: getRowSpan(index ?? 0, (r) => `${r.storeName}|${r.businessScene}`),
style: cellStyle,
}),
},
{
title: '一线阳光2计算模式',
......@@ -285,7 +324,11 @@ export function buildPolicyColumns(): TableProps<PolicyConfirmRow>['columns'] {
width: 160,
align: 'center',
onHeaderCell: () => ({ style: costHeaderStyle }),
onCell: () => ({ style: cellStyle }),
onCell: (_r, index) => ({
// 运营成本按「门店 + 业务场景」维度合并(同一门店下不同业务场景的运营成本不同)
rowSpan: getRowSpan(index ?? 0, (r) => `${r.storeName}|${r.businessScene}`),
style: cellStyle,
}),
render: (v) => <MoneyCell value={v as string} />,
},
{
......@@ -295,7 +338,10 @@ export function buildPolicyColumns(): TableProps<PolicyConfirmRow>['columns'] {
width: 220,
align: 'center',
onHeaderCell: () => ({ style: costHeaderStyle }),
onCell: () => ({ style: cellStyle }),
onCell: (_r, index) => ({
rowSpan: getRowSpan(index ?? 0, (r) => `${r.storeName}|${r.businessScene}`),
style: cellStyle,
}),
render: (v) => <MoneyCell value={v as string} />,
},
{
......@@ -305,7 +351,10 @@ export function buildPolicyColumns(): TableProps<PolicyConfirmRow>['columns'] {
width: 140,
align: 'center',
onHeaderCell: () => ({ style: costHeaderStyle }),
onCell: () => ({ style: cellStyle }),
onCell: (_r, index) => ({
rowSpan: getRowSpan(index ?? 0, (r) => `${r.storeName}|${r.businessScene}`),
style: cellStyle,
}),
render: (v) => <MoneyCell value={v as string} />,
},
],
......
......@@ -24,7 +24,21 @@ export function PolicyConfirmTable({
ruleCategoryCount,
ruleTotalRows,
}: PolicyConfirmTableProps) {
const columns = useMemo(() => buildPolicyColumns() as any[], []);
/**
* 数据源优先级:previewRows(接口真实数据) > dataSource > mock 兜底
* 放在 columns 之前,因为 buildPolicyColumns 需要 rows 来计算同门店 / 同场景的合并单元格 rowSpan
*/
const rows: PolicyConfirmRow[] = useMemo(() => {
if (Array.isArray(previewRows) && previewRows.length > 0) {
return convertPreviewRows(previewRows);
}
if (Array.isArray(dataSource) && dataSource.length > 0) {
return dataSource;
}
return mockPolicyRows;
}, [dataSource, previewRows]);
const columns = useMemo(() => buildPolicyColumns(rows) as any[], [rows]);
/**
* 动态拼接 footer 文字:优先用外部传入的通过行统计,
......@@ -71,17 +85,6 @@ export function PolicyConfirmTable({
return colWidths.reduce((a, b) => a + b, 0) + 40; // 加 40px 冗余
}, [columns]);
const rows: PolicyConfirmRow[] = useMemo(() => {
// 优先级:previewRows(接口真实数据) > dataSource > mock 兜底
if (Array.isArray(previewRows) && previewRows.length > 0) {
return convertPreviewRows(previewRows);
}
if (Array.isArray(dataSource) && dataSource.length > 0) {
return dataSource;
}
return mockPolicyRows;
}, [dataSource, previewRows]);
// 显式标注 TableProps:否则 pagination:false 会被推断成 boolean,赋给 UTable 时类型不兼容
const tableProps: TableProps<PolicyConfirmRow> = {
rowKey: (r: PolicyConfirmRow) => `${r.storeMerchantNo}-${r.businessScene}-${r.productCategory}`,
......
......@@ -10,7 +10,6 @@ export interface SubmitActionBarProps {
}
export function SubmitActionBar({
totalRows = 12,
loading = false,
disabled = false,
onBack,
......@@ -40,7 +39,7 @@ export function SubmitActionBar({
disabled={disabled || loading}
onClick={onSubmit ?? (() => console.log('确认提交并推送审批'))}
>
确认提交并推送审批({totalRows})
确认提交并推送审批
</UButton>
</div>
);
......
import { useState, useCallback, useEffect } from 'react';
import { useState, useCallback, useEffect, useRef } from 'react';
import { App } from 'antd';
import {
InfoCircleFilled,
......@@ -40,6 +40,10 @@ export function UploadCard({
const [uploading, setUploading] = useState(false);
const [downloading, setDownloading] = useState(false);
const [fileList, setFileList] = useState<UploadFile[]>([]);
// antd Upload 实例,用于编程式打开文件选择框
const uploadRef = useRef<any>(null);
// 记录上一次已处理的 reUploadTrigger,防止 effect 因其它依赖变化而重复触发
const processedTriggerRef = useRef(0);
/** 从 checkResult + 文件名推导要显示的统计文案:共 N 行(X 家门店 × Y 场景 × Z 分类)· 模板版本 vX.X.X */
const statLineText = (() => {
......@@ -100,18 +104,6 @@ export function UploadCard({
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [file]);
/**
* Step 2 → 点击失败明细里的【重新上传】:
* 父组件 handleReUpload = 切 Step0 + 清空 checkResult + reUploadCounter++
* 本 useEffect 监听 reUploadTrigger(>0 表示被触发过)+ 有 file + 非 uploading → 自动 runUpload
*/
useEffect(() => {
if (reUploadTrigger > 0 && file && !uploading) {
void runUpload(file);
}
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [reUploadTrigger]);
const clearFileState = useCallback(() => {
setFileList([]);
onFileChange?.(null);
......@@ -191,6 +183,38 @@ export function UploadCard({
fileList,
};
/**
* Step 2 → 点击失败明细里的【重新上传】:
* 父组件 handleReUpload = 切 Step0 + 清空 checkResult + reUploadCounter++
* 本 effect 监听 reUploadTrigger 变化,清空已选文件并编程式打开文件选择对话框,
* 让用户重新选择文件(选完文件后走正常 customRequest → runUpload → check 接口链路)。
* 注意:不再自动用原文件调用 check 接口,必须由用户重新选文件。
*/
useEffect(() => {
if (reUploadTrigger <= 0) return;
if (reUploadTrigger === processedTriggerRef.current) return;
processedTriggerRef.current = reUploadTrigger;
// 清空文件状态
setFileList([]);
onFileChange?.(null);
// 等 DOM 更新后再打开文件选择框:兼容 antd Upload ref 可能不暴露 upload() 的情况,
// 优先用 ref.upload(),兜底通过 DOM 查找隐藏的 input[type=file] 触发 click
setTimeout(() => {
const inst = uploadRef.current;
if (inst && typeof inst.upload === 'function') {
inst.upload();
return;
}
const input = document.querySelector<HTMLInputElement>(
'.uj-upload-dragger input[type="file"], .ant-upload input[type="file"]',
);
if (input) {
input.value = '';
input.click();
}
}, 0);
}, [reUploadTrigger, onFileChange]);
return (
<UCard
styles={{ body: { padding: 20 } }}
......@@ -209,7 +233,7 @@ export function UploadCard({
}
>
<div style={{ position: 'relative' }}>
<UUpload.Dragger {...uploadProps}>
<UUpload.Dragger ref={uploadRef} {...uploadProps}>
<div style={{ padding: '30px 0' }}>
<div
style={{
......
......@@ -82,22 +82,10 @@ export interface ValidationStatsProps {
checkResult?: StoreImportCheckVO;
}
function calcOperatingCost(vo: StoreImportCheckVO): number {
const rows = vo.previewRows ?? [];
if (rows.length === 0) return 0;
const first = rows[0];
return (
Math.round(first.costDecoration ?? 0) +
Math.round(first.costMonthly ?? 0) +
Math.round(first.costLabor ?? 0)
);
}
function buildStatsFromCheckResult(vo: StoreImportCheckVO): StatItem[] {
const rows = vo.productCategoryRowCount ?? vo.totalRows;
const storeCount = 1;
const sceneCount = vo.distinctBusinessSceneCount;
const operating = calcOperatingCost(vo);
const items: StatItem[] = [
{
......@@ -123,13 +111,6 @@ function buildStatsFromCheckResult(vo: StoreImportCheckVO): StatItem[] {
});
}
items.push({
label: '运营成本合计',
value: operating > 0 ? `¥ ${operating.toLocaleString('en-US')}` : '-',
desc: '门店维度(装修设备 + 当月产生 + 人工成本)',
tone: 'default',
});
return items;
}
......@@ -151,11 +132,13 @@ const defaultStats: StatItem[] = [
export function ValidationStats({ stats, checkResult }: ValidationStatsProps) {
const finalStats: StatItem[] =
stats ?? (checkResult ? buildStatsFromCheckResult(checkResult) : defaultStats);
// 按实际卡片数量平分整行宽度
const colCount = Math.max(1, finalStats.length);
return (
<div
style={{
display: 'grid',
gridTemplateColumns: 'repeat(4, minmax(0, 1fr))',
gridTemplateColumns: `repeat(${colCount}, minmax(0, 1fr))`,
gap: 16,
marginBottom: 20,
}}
......
......@@ -45,12 +45,13 @@ export default function TemplateImport() {
const handleFileChange = (f: File | null) => {
setSelectedFile(f);
// 移除文件时,同步清空校验结果 + 导入信息里的 3 个回显字段(保留 remark)
// 注意:org/scene 用 undefined 而非 '',否则 antd Select 会把 '' 当成选中值,placeholder 不显示
if (f === null) {
setCheckResult(null);
setImportInfo((prev) => ({
org: prev?.org ?? '',
scene: prev?.scene ?? '',
categories: prev?.categories ?? [],
org: undefined,
scene: undefined,
categories: [],
remark: prev?.remark,
}));
}
......@@ -76,7 +77,9 @@ export default function TemplateImport() {
};
const handleReUpload = () => {
// Step 2 重新上传:不清空文件,回到 Step0 后由 UploadCard.useEffect 监听 trigger 自动重跑上传
// Step 2 重新上传:清空文件 + checkResult,回到 Step0 后由 UploadCard 打开文件选择对话框,
// 用户重新选择文件后走正常 customRequest → runUpload → check 接口链路
setSelectedFile(null);
setCheckResult(null);
setSubmitChecked(true);
setCurrentStep(0);
......@@ -96,7 +99,7 @@ export default function TemplateImport() {
setCheckResult(result);
modal.success({
title: '提交审批成功',
content: `已提交 ${result.passRows ?? 0} 行 / 涉及 ${listingIds.length} 条上架记录,请在「门店审批」中跟踪进度。`,
content: `涉及 ${listingIds.length} 条上架记录,请在「门店审批」中跟踪进度。`,
okText: '前往门店审批',
okButtonProps: { type: 'primary' },
cancelText: '知道了',
......@@ -143,7 +146,11 @@ export default function TemplateImport() {
{currentStep === 1 && (
<>
<ValidationStats checkResult={checkResult ?? undefined} />
<FailDetailCard checkResult={checkResult ?? undefined} onReUpload={handleReUpload} />
<FailDetailCard
checkResult={checkResult ?? undefined}
fileSize={selectedFile?.size}
onReUpload={handleReUpload}
/>
<ValidationActionBar nextDisabled={failCount > 0} onBack={goPrev} onNextStep={goNext} />
</>
)}
......
Markdown is supported
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!