index.tsx
15 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
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
import { useEffect, useRef, useState } from 'react';
import { useMutation, useQueries, useQuery, useQueryClient } from '@tanstack/react-query';
import { UAlert, UButton, UCard, UResult, UTabs, tabLabel, useUMessage } from '@uj/ui';
import { P, PermButton, useAccess } from '@/access';
import {
DataTable,
DEFAULT_PAGE_SIZE,
PageShell,
SearchForm,
type FieldSchema,
type RowActionSchema,
} from '@/components';
import {
store,
type ApprovalPageParams,
type ApprovalRow,
type ApproveTab,
type StoreListingDetail,
} 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';
import '@/features/store/store.css';
interface DrawerState {
row: ApprovalRow;
audit: boolean;
source: ApproveTab;
}
const cleanText = (value: unknown) =>
typeof value === 'string' && value.trim() ? value.trim() : undefined;
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);
const canAct = (type: ApprovalAction['type']) =>
allowed && (type === 'revoke' ? canRevoke : type === 'reject' ? canReject : canPass);
const message = useUMessage();
const client = useQueryClient();
const [tab, setTab] = useState<ApproveTab>(() =>
new URLSearchParams(window.location.search).get('tab') === 'mine' ? 'mine' : 'todo',
);
const [filters, setFilters] = useState<ApprovalPageParams>({});
const [queryVersion, setQueryVersion] = useState(0);
const [page, setPage] = useState({ current: 1, size: DEFAULT_PAGE_SIZE });
const [selected, setSelected] = useState<ApprovalRow[]>([]);
const [drawer, setDrawer] = useState<DrawerState>();
const [action, setAction] = useState<ApprovalAction>();
const [confirmed, setConfirmed] = useState(false);
const [reason, setReason] = useState('');
const [actionError, setActionError] = useState<string>();
const submissionLock = useRef(false);
const lists = useQueries({
queries: tabDefs.map(({ key }) => {
const params = {
...filters,
current: key === tab ? page.current : 1,
size: key === tab ? page.size : 1,
};
return {
queryKey: ['store', 'approvals', key, params, queryVersion],
queryFn: () => store.listApprovals(key, params),
enabled: allowed,
};
}),
});
const list = lists[tabDefs.findIndex(({ key }) => key === tab)];
const selectedIds = new Set(selected.map((row) => String(row.listingId)));
const selectedCurrent = (list.data?.records ?? []).filter(
(row) =>
selectedIds.has(String(row.listingId)) && row.status === 'PENDING' && row.actionable === true,
);
const detail = useQuery({
queryKey: ['store', 'approval-detail', drawer?.row.listingId],
queryFn: () => store.getApproval(drawer!.row.listingId),
enabled: allowed && !!drawer,
staleTime: 0,
});
// 依赖原始值而不是 page 对象:既满足 exhaustive-deps,也避免 setPage 生成新对象时
// effect 因引用变化被多触发一次。
const currentPage = page.current;
const pageSize = page.size;
useEffect(() => {
if (!list.data) return;
const last = Math.max(1, Math.ceil(list.data.total / pageSize));
if (currentPage > last) setPage((previous) => ({ ...previous, current: last }));
}, [list.data, currentPage, pageSize]);
const refresh = () =>
Promise.all([
client.invalidateQueries({ queryKey: ['store', 'approvals'] }),
client.invalidateQueries({ queryKey: ['store', 'approval-detail'] }),
client.invalidateQueries({ queryKey: ['store', 'listing'] }),
]);
const mutation = useMutation({
retry: false,
mutationFn: async (request: ApprovalAction & { reason: string }) => {
const id = request.records[0].listingId;
switch (request.type) {
case 'pass':
return store.passApproval(id);
case 'reject':
return store.rejectApproval(id, request.reason);
case 'batch':
return store.batchPassApproval(request.records.map((row) => row.listingId));
case 'revoke':
return store.revokeApproval(id);
}
},
onSuccess: async (_, request) => {
setAction(undefined);
setSelected([]);
setDrawer((previous) => (previous ? { ...previous, audit: false } : previous));
await refresh();
const latest = client.getQueryData<StoreListingDetail>([
'store',
'approval-detail',
request.records[0].listingId,
]);
void message.success(
request.type === 'pass'
? latest?.status === 'APPROVED'
? '审批通过,门店已生效'
: '审批通过,已刷新审批进度'
: request.type === 'batch'
? '批量审批请求成功,已刷新列表'
: request.type === 'reject'
? '已打回,审批意见已保存'
: '已撤回',
);
},
onError: async (error) => {
setActionError(errorMessage(error));
await refresh();
},
onSettled: () => {
submissionLock.current = false;
},
});
const openAction = (next: ApprovalAction) => {
if (mutation.isPending || !canAct(next.type)) return;
setAction(next);
setConfirmed(false);
setReason('');
setActionError(undefined);
};
const confirmAction = () => {
if (
!allowed ||
!action ||
!action.records.length ||
mutation.isPending ||
submissionLock.current
)
return;
if ((action.type === 'pass' || action.type === 'batch') && !confirmed) return;
if (action.type === 'reject' && (!reason.trim() || [...reason.trim()].length > 200)) {
setActionError('请填写 1–200 字的打回原因');
return;
}
if (!canAct(action.type)) return;
submissionLock.current = true;
mutation.mutate({ ...action, reason: reason.trim() });
};
const changeQuery = (values: Record<string, unknown>) => {
setQueryVersion((previous) => previous + 1);
setFilters({
keyword: cleanText(values.keyword),
productCategory: cleanText(values.productCategory),
businessScene: cleanText(values.businessScene),
submitUserName: cleanText(values.submitUserName),
});
setPage((previous) => ({ ...previous, current: 1 }));
setSelected([]);
};
const fields: FieldSchema<Record<string, unknown>>[] = [
{
name: 'keyword',
label: '门店名称 / 商户号',
type: 'input',
placeholder: '模糊搜索',
width: '100%',
},
{
name: 'productCategory',
label: '产品分类',
type: 'select',
width: '100%',
options: filterOptions.productCategory.options,
selectProps: filterOptions.productCategory.selectProps,
},
{
name: 'businessScene',
label: '业务场景',
type: 'select',
width: '100%',
options: filterOptions.businessScene.options,
selectProps: filterOptions.businessScene.selectProps,
},
{
name: 'submitUserName',
label: '提交人',
type: 'input',
placeholder: '姓名 / 账号',
width: '100%',
},
];
const rowActions: RowActionSchema<ApprovalRow>[] = [
{
label: '审核',
permission: canPass ? P.STORE_APPROVE_AUDIT : P.STORE_APPROVE_REJECT,
disabled: mutation.isPending,
visible: (row) =>
tab === 'todo' &&
row.status === 'PENDING' &&
row.actionable === true &&
(canPass || canReject),
onClick: (row) => setDrawer({ row, audit: true, source: tab }),
},
{
label: '查看',
permission: P.STORE_APPROVE_VIEW,
onClick: (row) => setDrawer({ row, audit: false, source: tab }),
},
{
label: '撤回',
permission: P.STORE_APPROVE_REVOKE,
disabled: mutation.isPending,
visible: (row) => tab === 'mine' && row.status === 'PENDING',
onClick: (row) => openAction({ type: 'revoke', records: [row] }),
},
];
const drawerRecord =
drawer && detail.data
? {
...drawer.row,
...detail.data,
productCategories:
detail.data.items
?.map((item) => item.productCategory)
.filter((category): category is string => !!category) ?? drawer.row.productCategories,
}
: drawer?.row;
const drawerReady = !!detail.data && !detail.isFetching && !detail.isError;
const canAuditDrawer =
drawerReady &&
drawer?.audit &&
drawer.source === 'todo' &&
drawer.row.actionable === true &&
detail.data?.status === 'PENDING';
if (!allowed)
return (
<UResult status="403" title="无门店审批访问权限" subTitle="请联系管理员确认账号权限。" />
);
return (
<PageShell
fill
title="门店审批"
description="按门店+业务场景审核上架数据,商务经理、财务经理依次审批;全部节点通过后生效。"
>
<UTabs
activeKey={tab}
onChange={(key) => {
setTab(key as ApproveTab);
setPage((previous) => ({ ...previous, current: 1 }));
setSelected([]);
}}
items={tabDefs.map(({ key, label }, index) => ({
key,
label: tabLabel(label, { count: lists[index].data?.total ?? '—' }),
}))}
/>
<UCard className="uj-filter-card" size="small">
<SearchForm
fields={fields}
initialValues={{
keyword: '',
productCategory: '',
businessScene: '',
submitUserName: '',
}}
onSearch={changeQuery}
onReset={() => {
filterOptions.reset();
changeQuery({});
}}
/>
</UCard>
{list.isError ? (
<UAlert
type="error"
showIcon
title="审批列表加载失败"
description={errorMessage(list.error)}
action={
<UButton type="link" onClick={() => void list.refetch()}>
重试
</UButton>
}
/>
) : null}
<UCard size="small" fill>
<DataTable<ApprovalRow>
fillHeight
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.isPending || list.isFetching}
rowActions={rowActions}
toolbarTitle={`共 ${list.data?.total ?? 0} 条记录${
tab === 'todo' ? ` · 已选 ${selectedCurrent.length} 条` : ''
}`}
actions={
tab === 'todo'
? [
{
label: '批量审批',
permission: P.STORE_APPROVE_AUDIT,
disabled: selectedCurrent.length === 0 || mutation.isPending || list.isFetching,
onClick: () => openAction({ type: 'batch', records: selectedCurrent }),
},
]
: []
}
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,
}),
}
: false
}
pagination={{
current: page.current,
pageSize: page.size,
total: list.data?.total ?? 0,
showSizeChanger: true,
pageSizeOptions: [10, 20, 50, 100],
showTotal: (total) => `共 ${total} 条`,
onChange: (current, size) => {
setPage({ current: size === page.size ? current : 1, size });
setSelected([]);
},
}}
/>
</UCard>
<StoreDetailDrawer
open={!!drawer}
detail={detail.data}
loading={detail.isPending || detail.isFetching}
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);
}}
onRetry={() => void detail.refetch()}
footer={
<div className="uj-row-actions" style={{ justifyContent: 'flex-end' }}>
<UButton
type="default"
disabled={mutation.isPending}
onClick={() => setDrawer(undefined)}
>
关闭
</UButton>
{canAuditDrawer && drawerRecord && (
<>
<PermButton
permission={P.STORE_APPROVE_REJECT}
danger
type="default"
disabled={mutation.isPending}
onClick={() => openAction({ type: 'reject', records: [drawerRecord] })}
>
打回
</PermButton>
<PermButton
permission={P.STORE_APPROVE_AUDIT}
disabled={mutation.isPending}
onClick={() => openAction({ type: 'pass', records: [drawerRecord] })}
>
通过
</PermButton>
</>
)}
{drawerReady &&
drawer?.source === 'mine' &&
detail.data?.status === 'PENDING' &&
drawerRecord && (
<PermButton
permission={P.STORE_APPROVE_REVOKE}
disabled={mutation.isPending}
onClick={() => openAction({ type: 'revoke', records: [drawerRecord] })}
>
撤回
</PermButton>
)}
</div>
}
/>
{(!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}
/>
)}
</PageShell>
);
}