index.tsx
9.66 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
import { useEffect, useMemo, useState } from 'react';
import { keepPreviousData, useMutation, useQuery, useQueryClient } from '@tanstack/react-query';
import { App } from 'antd';
import { DownloadOutlined, SettingOutlined } from '@ant-design/icons';
import { Skeleton, UAlert, UButton, UCard, UResult, UText, UTitle } from '@uj/ui';
import { P, useAccess } from '@/access';
import { store, type ListingPageParams, type StoreId, type StoreListingRow } from '@/api';
import {
DataTable,
DEFAULT_PAGE_SIZE,
SearchForm,
type ActionSchema,
type FieldSchema,
type RowActionSchema,
} 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 {
errorText,
exportParams,
filterParams,
INITIAL_PARAMS,
normalizeColumns,
type ListingFilters,
} from './tools/listing';
import '@/features/store/store.css';
import './listing.css';
const CONFIG_KEY = ['store', 'listing', 'columns'] as const;
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);
const [selected, setSelected] = useState<{ id: StoreId; tab: string } | null>(null);
const [configOpen, setConfigOpen] = useState(false);
const listing = useQuery({
queryKey: ['store', 'listing', 'page', params, queryVersion],
queryFn: () => store.listStores(params),
placeholderData: keepPreviousData,
enabled: allowed,
});
const config = useQuery({
queryKey: CONFIG_KEY,
queryFn: () => store.getColumnConfig(),
enabled: allowed,
});
const configuredColumns = useMemo(() => normalizeColumns(config.data?.columns), [config.data]);
const detail = useQuery({
queryKey: ['store', 'listing', 'detail', selected?.id],
enabled: allowed && selected !== null,
queryFn: async () => {
const id = selected!.id;
const [data, changes] = await Promise.all([store.getStore(id), store.getChanges(id)]);
return { ...data, changeHistory: changes };
},
});
useEffect(() => {
if (!allowed || !listing.data || listing.isPlaceholderData) return;
const lastPage = Math.max(1, Math.ceil(listing.data.total / (params.size ?? 20)));
if ((params.current ?? 1) > lastPage) {
setParams((previous) => ({ ...previous, current: lastPage }));
setQueryVersion((version) => version + 1);
}
}, [allowed, listing.data, listing.isPlaceholderData, params.current, params.size]);
const saveConfig = useMutation({
mutationFn: async (columns: string[]) => {
await store.saveColumnConfig(columns);
return store.getColumnConfig();
},
onSuccess: (result) => {
queryClient.setQueryData(CONFIG_KEY, result);
setConfigOpen(false);
message.success('列配置已保存');
},
});
const exportFile = useMutation({
mutationFn: () => store.exportStores(exportParams(params)),
onSuccess: () => {
message.success('导出文件已下载');
},
});
const total = listing.data?.total ?? 0;
const overExportLimit = total > 50_000;
const openDetail = (row: StoreListingRow, tab = 'info') =>
setSelected({ id: row.listingId, tab });
const fields: FieldSchema<ListingFilters>[] = [
{ name: 'storeName', label: '门店名称', type: 'input', placeholder: '模糊搜索', width: '100%' },
{
name: 'merchantNo',
label: '门店商户号',
type: 'input',
placeholder: '模糊搜索',
width: '100%',
},
{
name: 'businessScene',
label: '业务场景',
type: 'select',
width: '100%',
options: filterOptions.businessScene.options,
selectProps: filterOptions.businessScene.selectProps,
},
{ name: 'effectiveRange', label: '上架时间', type: 'dateRange', width: '100%' },
];
const columns = buildColumns({
visible: configuredColumns,
spec: STORE_DICTIONARIES,
});
const rowActions: RowActionSchema<StoreListingRow>[] = [
{ label: '查看详情', permission: P.STORE_LISTING_VIEW, onClick: (row) => openDetail(row) },
{
label: '变更历史',
permission: P.STORE_LISTING_VIEW,
onClick: (row) => openDetail(row, 'history'),
},
];
const actions: ActionSchema[] = [
{
label: (
<>
<SettingOutlined aria-hidden /> 列配置
</>
),
type: 'default',
permission: P.STORE_LISTING_VIEW,
onClick: () => {
saveConfig.reset();
setConfigOpen(true);
},
},
{
label: (
<>
<DownloadOutlined aria-hidden /> {exportFile.isPending ? '正在导出…' : '导出'}
</>
),
type: 'default',
permission: P.STORE_LISTING_EXPORT,
disabled:
overExportLimit || listing.isFetching || Boolean(listing.error) || exportFile.isPending,
onClick: () => {
if (!overExportLimit && !exportFile.isPending) exportFile.mutate();
},
},
];
if (!allowed)
return (
<UResult status="403" title="无门店列表访问权限" subTitle="请联系管理员开通访问权限。" />
);
if (listing.isPending) return <Skeleton variant="table" />;
return (
<div className="store-page">
<div className="store-page-header">
<div>
<UTitle level={3} style={{ margin: 0 }}>
门店列表
</UTitle>
<UText type="secondary">
仅展示审批通过的数据。一行对应一个门店与一个业务场景,门店名称相同、业务场景不同的记录分别展示。
</UText>
</div>
</div>
<UCard className="store-filter-card" size="small">
<SearchForm<ListingFilters>
fields={fields}
layout="vertical"
className="store-search-form"
initialValues={{ businessScene: '' }}
onSearch={(values) => {
const next = {
...filterParams(values),
current: 1,
size: params.size,
sortField: params.sortField,
sortOrder: params.sortOrder,
};
setParams(next);
setQueryVersion((version) => version + 1);
if (!exportFile.isPending) exportFile.reset();
}}
onReset={() => {
filterOptions.reset();
setParams({ ...INITIAL_PARAMS, size: params.size });
setQueryVersion((version) => version + 1);
if (!exportFile.isPending) exportFile.reset();
}}
/>
</UCard>
{listing.error ? (
<UAlert
type="error"
showIcon
title={errorText(listing.error, '门店列表加载失败')}
action={
<UButton type="link" onClick={() => void listing.refetch()}>
重新加载列表
</UButton>
}
/>
) : null}
{exportFile.error ? (
<UAlert type="error" showIcon title={errorText(exportFile.error, '导出失败,请重试')} />
) : null}
{overExportLimit ? (
<UAlert type="warning" showIcon title="筛选结果超过 50,000 条,请缩小范围后导出。" />
) : null}
<div className="store-listing-section">
<DataTable<StoreListingRow>
className="store-listing-table"
rowKey="listingId"
columns={columns}
rowActions={rowActions}
actionColumnWidth={150}
actionColumnFixed="right"
toolbarTitle={
<UText strong>
已生效门店 <UText type="secondary">{total} 条</UText>
</UText>
}
toolbarClassName="store-listing-toolbar"
actions={actions}
dataSource={listing.data?.records ?? []}
loading={listing.isFetching}
scroll={{ x: 950 }}
pagination={{
current: params.current ?? 1,
pageSize: params.size ?? DEFAULT_PAGE_SIZE,
total,
showSizeChanger: false,
pageSizeOptions: [10, 20, 50, 100],
showTotal: (count) =>
`共 ${count.toLocaleString('zh-CN')} 条记录 · 每页 ${params.size ?? DEFAULT_PAGE_SIZE} 条`,
onChange: (current, size) =>
setParams((previous) => ({
...previous,
current: size !== previous.size ? 1 : current,
size,
})),
}}
/>
</div>
<ColumnConfigModal
open={configOpen}
columns={configuredColumns}
loading={config.isFetching}
error={config.error}
saving={saveConfig.isPending}
saveError={saveConfig.error}
onClose={() => setConfigOpen(false)}
onRetry={() => void config.refetch()}
onSave={(next) => {
if (!config.isFetching && !config.error && !saveConfig.isPending) saveConfig.mutate(next);
}}
/>
<StoreDetailDrawer
key={selected ? `${selected.id}:${selected.tab}` : 'closed'}
open={selected !== null}
detail={detail.data}
spec={STORE_DICTIONARIES}
loading={detail.isPending && selected !== null}
error={detail.error}
mode="listing"
initialTab={selected?.tab}
onClose={() => setSelected(null)}
onRetry={() => void detail.refetch()}
/>
</div>
);
}