options.ts
11.7 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
import { useMemo } from 'react';
import { useQuery, type UseQueryResult } from '@tanstack/react-query';
import type { FieldOption } from '@/components';
import {
pointsApi,
withdrawApi,
type ChannelNode,
type DictOption,
type LegacyOption,
type TagNode,
} from '@/api';
import { errorMessage } from './format';
/**
* 远程筛选项。
*
* 老系统每个页面在 mounted 里各拉一遍、各自往 baseData 里塞,
* 这里按「一份数据一个 hook」重做:同一次会话里同一份选项只发一次请求,
* 换页不再重复拉;字段名差别(confId / id / code / nameWithId)在各自 hook 里抹平。
*/
/** 老接口有三种返回:数组、{ data: 数组 }、null。 */
function asArray(value: unknown): LegacyOption[] {
if (Array.isArray(value)) return value as LegacyOption[];
if (value && typeof value === 'object' && Array.isArray((value as { data?: unknown }).data)) {
return (value as { data: LegacyOption[] }).data;
}
return [];
}
function options(
items: LegacyOption[],
valueKey: keyof LegacyOption,
labelKey: keyof LegacyOption,
): DictOption[] {
return items
.map((item) => ({
value: String(item[valueKey] ?? item.id ?? item.code ?? item.confId ?? ''),
label: String(item[labelKey] ?? item.name ?? item.confLabel ?? item.label ?? ''),
}))
.filter((option) => option.value);
}
/** 一次查询的公共形状:页面只需要 options 与 loading/error。 */
export interface OptionQuery {
options: DictOption[];
isLoading: boolean;
error?: string;
query: UseQueryResult<unknown, Error>;
}
function useOptionQuery(
scope: string,
key: unknown[],
fetcher: () => Promise<unknown>,
enabled: boolean,
pick: (raw: unknown) => DictOption[],
): OptionQuery {
const query = useQuery({
queryKey: ['points', scope, ...key],
queryFn: fetcher,
enabled,
staleTime: 5 * 60 * 1000,
});
return {
options: useMemo(() => (query.data ? pick(query.data) : []), [query.data, pick]),
isLoading: enabled && query.isPending,
error: query.error ? errorMessage(query.error) : undefined,
query,
};
}
/** 去掉老渠道树里的空 child,否则级联框会出现一层空白板。 */
export function pruneChannelTree(nodes: unknown): ChannelNode[] {
if (!Array.isArray(nodes)) return [];
return (nodes as ChannelNode[]).map((node) => {
const child = Array.isArray(node.child) ? pruneChannelTree(node.child) : [];
const next: ChannelNode = { ...node };
if (child.length) next.child = child;
else delete next.child;
return next;
});
}
function toCascader(nodes: ChannelNode[]): FieldOption[] {
return nodes.map((node) => ({
value: String(node.code ?? node.id ?? ''),
label: String(node.name ?? node.code ?? ''),
children: Array.isArray(node.child) && node.child.length ? toCascader(node.child) : undefined,
}));
}
/**
* 付款渠道树(搜索用)。同一份树还派生出「付款主体」下拉:
* 老系统的付款主体不是独立接口,而是所选渠道下的子节点去重(见 entityOptions)。
*/
export function useChannelTree(enabled = true) {
const result = useOptionQuery(
'channel-tree',
[],
() => withdrawApi.channelTree({}),
enabled,
(raw) => options(asArray(raw), 'code', 'name'),
);
const nodes = useMemo(
() => pruneChannelTree(result.query.data) as ChannelNode[],
[result.query.data],
);
return { ...result, nodes, cascader: toCascader(nodes) };
}
/** 渠道树里选中渠道(或未选)之后的付款主体候选,按 code 去重。 */
export function entityOptions(nodes: ChannelNode[], channelCode?: string): DictOption[] {
const children = nodes
.filter((node) => !channelCode || node.code === channelCode)
.flatMap((node) => (Array.isArray(node.child) ? node.child : []));
const seen = new Set<string>();
const unique: ChannelNode[] = [];
for (const child of children) {
const code = String(child.code ?? '');
if (!code || seen.has(code)) continue;
seen.add(code);
unique.push(child);
}
return options(unique, 'code', 'name');
}
/** 付款弹窗的渠道级联:候选随提现类型与提现方式变化(老 getChannel)。 */
export function usePayChannelTree(
params: { transferType?: string; mode?: string },
enabled: boolean,
) {
const query = useQuery({
queryKey: ['points', 'pay-channel-tree', params.transferType ?? '', params.mode ?? ''],
queryFn: () => withdrawApi.channelTree({ ...params }),
enabled,
staleTime: 0,
});
const nodes = useMemo(() => pruneChannelTree(query.data) as ChannelNode[], [query.data]);
return { nodes, cascader: toCascader(nodes), isLoading: query.isPending };
}
/** 所属门店(提现域接口,展示「名称(编号)」,提交 id)。 */
export function useWithdrawMerchants(enabled = true) {
return useOptionQuery(
'merchants',
[],
() => withdrawApi.merchantOptions({}),
enabled,
(raw) =>
asArray(raw).map((item) => ({
value: String(item.id ?? ''),
label: String(item.nameWithId ?? `${item.name ?? ''}(${item.id ?? ''})`),
})),
);
}
/** 门店列表(dj 网关,用户积分明细用:提交 merchantId,显示 merchantName)。 */
export function useShopMerchants(enabled = true) {
return useOptionQuery(
'shop-merchants',
[],
() => pointsApi.merchantOptions({}),
enabled,
(raw) => options(asArray(raw), 'merchantId', 'merchantName'),
);
}
/** 主营品牌(提交 id)。 */
export function useBrands(enabled = true) {
return useOptionQuery(
'brands',
[],
() => withdrawApi.brandOptions({}),
enabled,
(raw) => options(asArray(raw), 'id', 'name'),
);
}
/** 省份(提交 code)。 */
export function useProvinces(enabled = true) {
return useOptionQuery(
'provinces',
[],
() => withdrawApi.provinceOptions({}),
enabled,
(raw) => options(asArray(raw), 'code', 'name'),
);
}
/** 代征主体(付款弹窗)。 */
export function usePayLevies(enabled = true) {
return useOptionQuery(
'pay-levies',
[],
() => withdrawApi.payLevyList({}),
enabled,
(raw) => options(asArray(raw), 'code', 'name'),
);
}
/** 审批侧付款主体(付款审核弹窗)。 */
export function useApprovalPaymentEntities(enabled = true) {
return useOptionQuery(
'approval-payment-entities',
[],
() => withdrawApi.approvalPaymentEntityList({}),
enabled,
(raw) => options(asArray(raw), 'code', 'name'),
);
}
/**
* 提现标签树。
* 一份数据三种用法:抽屉按层级渲染并就地增删改(nodes)、
* 批量标注弹窗要求选到已补全的末级(cascader + onlyComplete)、
* 筛选项则摊平成「一级 / 二级」路径文案,选任意层级都能筛(paths)。
*/
export function useTagTree(enabled = true, onlyComplete = false) {
const query = useQuery({
queryKey: ['points', 'tag-tree', onlyComplete],
queryFn: () => withdrawApi.tagTree(onlyComplete ? { onlyComplete: true } : {}),
enabled,
staleTime: onlyComplete ? 0 : 5 * 60 * 1000,
});
const nodes = useMemo(() => toTagNodes(query.data), [query.data]);
return {
nodes,
cascader: toTagCascader(nodes),
paths: flattenTagPaths(nodes),
isLoading: query.isPending,
error: query.error ? errorMessage(query.error) : undefined,
refetch: query.refetch,
};
}
/** 老接口三种名字写法(name / label / tagName)都出现过,子节点字段也是 children 与 child 并存。 */
function toTagNodes(raw: unknown): TagNode[] {
const nodes: TagNode[] = [];
for (const item of asArray(raw)) {
const id = String(item.id ?? '');
if (!id) continue;
nodes.push({
id,
name: String(item.name ?? item.label ?? item.tagName ?? id),
parentId: item.parentId === undefined || item.parentId === null ? '' : String(item.parentId),
children: toTagNodes(item.children ?? item.child ?? []),
});
}
return nodes;
}
function toTagCascader(nodes: TagNode[]): FieldOption[] {
return nodes.map((node) => ({
value: node.id,
label: String(node.name ?? node.id),
children: node.children && node.children.length ? toTagCascader(node.children) : undefined,
}));
}
/** 摊平成带路径前缀的平铺候选:老系统的级联框可以只选到一级,平铺之后这一层能力不丢。 */
function flattenTagPaths(nodes: TagNode[], parent = ''): DictOption[] {
const flat: DictOption[] = [];
for (const node of nodes) {
const path = parent ? `${parent} / ${node.name ?? node.id}` : String(node.name ?? node.id);
flat.push({ value: node.id, label: path });
if (node.children?.length) flat.push(...flattenTagPaths(node.children, path));
}
return flat;
}
/** 渠道管理员(付款验证码发给谁)。 */
export function useChannelAdmins(channel: string | undefined, enabled: boolean) {
const query = useQuery({
queryKey: ['points', 'channel-admins', channel ?? ''],
queryFn: () => withdrawApi.channelConfig(channel ? { channel } : {}),
enabled,
staleTime: 5 * 60 * 1000,
});
const admins = useMemo(() => asArray(query.data), [query.data]);
return { admins, isLoading: query.isPending };
}
/**
* 审批侧的「付款渠道 → 付款主体 → 代征主体」。
*
* 老系统这三层是级联框的懒加载(approve.vue 与 payApproval.vue 各抄了一份同样的三个方法),
* 提交的是 paymentSubjectId(主体 id)与 paymentChannelId(代征主体 id,字段名是历史遗留)。
* 取数与候选派生放在这里一次,级联框与筛选区的下拉都用它。
*/
export interface ApprovalLevy {
value: string;
label: string;
/** 税点;付款审批弹窗按它重算付款总额。 */
tax: string;
}
function toFieldOptions(items: LegacyOption[], valueKey: string, labelKey: string): DictOption[] {
return items
.map((item) => ({ value: String(item[valueKey] ?? ''), label: String(item[labelKey] ?? '') }))
.filter((option) => option.value);
}
export async function loadApprovalChannels(): Promise<DictOption[]> {
return toFieldOptions(asArray(await withdrawApi.channelList({})), 'channel', 'channelName');
}
export async function loadApprovalEntities(channel: string): Promise<DictOption[]> {
if (!channel) return [];
return toFieldOptions(
asArray(await withdrawApi.paymentEntityList({ channel })),
'paymentEntityId',
'paymentEntityName',
);
}
export async function loadApprovalLevies(
channel: string,
paymentEntityId: string,
): Promise<ApprovalLevy[]> {
if (!channel || !paymentEntityId) return [];
return asArray(await withdrawApi.payLevyList({ channel, paymentEntityId }))
.map((item) => ({
value: String(item.id ?? ''),
label: String(item.levyName ?? ''),
tax: String(item.tax ?? ''),
}))
.filter((item) => item.value);
}
/** 筛选区用的三层候选:选了上一层才发下一层的请求(与老系统懒加载的时机一致)。 */
export function useApprovalChannelOptions(channel: string | undefined, entity: string | undefined) {
const channels = useQuery({
queryKey: ['points', 'approval-channels'],
queryFn: loadApprovalChannels,
staleTime: 5 * 60 * 1000,
});
const entities = useQuery({
queryKey: ['points', 'approval-entities', channel ?? ''],
queryFn: () => loadApprovalEntities(channel ?? ''),
enabled: !!channel,
staleTime: 5 * 60 * 1000,
});
const levies = useQuery({
queryKey: ['points', 'approval-levies', channel ?? '', entity ?? ''],
queryFn: () => loadApprovalLevies(channel ?? '', entity ?? ''),
enabled: !!channel && !!entity,
staleTime: 5 * 60 * 1000,
});
return {
channels: channels.data ?? [],
entities: entities.data ?? [],
levies: levies.data ?? [],
isLoading: channels.isPending || entities.isPending || levies.isPending,
};
}