store.test.ts
12.3 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
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';
// 业务路径契约独立于本机 .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',
storeName: '测试门店',
merchantNo: 'M-001',
productCategories: ['FILM_ORIGINAL'],
categoryCount: 1,
businessScene: 'AFTER_SALE_MEMBER',
costTotal: '90071992547409.91',
currentLevel: 1,
totalLevel: 2,
submitUserName: '运营人员',
submitTime: '2026-10-09T09:00:00',
pendingHours: 1,
timeoutLevel: 'NORMAL',
status: 'PENDING',
statusLabel: '待审批',
rejectReason: null,
myAction: null,
myActionLabel: null,
handleTime: null,
handleOpinion: null,
actionable: true,
};
const page = { records: [approvalRecord], total: 41, current: 2, size: 20, pages: 3 };
function serve(
handler: (config: InternalAxiosRequestConfig) => {
data: unknown;
headers?: Record<string, string>;
},
) {
const adapter: AxiosAdapter = async (config) => {
const result = handler(config);
return {
config,
data: result.data,
headers: result.headers ?? { 'content-type': 'application/json' },
status: 200,
statusText: 'OK',
};
};
http.defaults.adapter = adapter;
}
function result(data: unknown) {
return JSON.stringify({
code: 200,
message: '操作成功',
data,
timestamp: 1791514515716,
success: true,
});
}
beforeEach(() => {
localStorage.clear();
vi.spyOn(console, 'log').mockImplementation(() => undefined);
});
afterEach(() => {
http.defaults.adapter = originalAdapter;
vi.restoreAllMocks();
vi.unstubAllGlobals();
vi.useRealTimers();
});
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'],
['mine', '/store/approval/mine'],
] as const)('loads %s with server pagination and untouched monetary values', async (tab, url) => {
serve((config) => {
expect(config.method).toBe('get');
expect(config.url).toBe(url);
expect(config.params).toEqual({ current: 2, size: 20, keyword: 'M-001' });
return { data: result(page) };
});
expect(await store.listApprovals(tab, { current: 2, size: 20, keyword: 'M-001' })).toEqual(
page,
);
});
it('defaults approvals to the pending endpoint', async () => {
serve((config) => {
expect(config.url).toBe('/store/approval/pending');
return { data: result({ records: [], total: 0, current: 1, size: 20, pages: 0 }) };
});
expect((await store.listApprovals()).records).toEqual([]);
});
it('forwards listing filters and server sort keys without adding status or region', async () => {
const params = {
current: 3,
size: 10,
storeName: '门店',
merchantNo: 'M',
businessScene: 'AFTER_SALE_MEMBER',
startDate: '2026-10-01',
endDate: '2026-10-09',
sortField: 'effectiveDate' as const,
sortOrder: 'desc' as const,
};
serve((config) => {
expect(config.url).toBe('/store/listing/page');
expect(config.params).toEqual(params);
return { data: result({ records: [], total: 0, current: 3, size: 10, pages: 0 }) };
});
expect((await store.listStores(params)).current).toBe(3);
});
it('uses listing IDs for detail and history and unwraps column responses', async () => {
const responses: Record<string, unknown> = {
'/store/approval/9007199254740993': {
...approvalRecord,
items: [],
approvalLogs: [],
changeHistory: [],
},
'/store/listing/9007199254740993': {
...approvalRecord,
items: [],
approvalLogs: [],
changeHistory: [],
},
'/store/listing/9007199254740993/changes': [
{ changeId: 4, beforeValue: '0', afterValue: '5' },
],
'/store/listing/column-config': { columns: ['storeName', 'businessScene'] },
};
serve((config) => {
expect(config.method).toBe('get');
expect(responses).toHaveProperty(config.url!);
return { data: result(responses[config.url!]) };
});
expect((await store.getApproval('9007199254740993')).listingId).toBe('9007199254740993');
expect((await store.getStore('9007199254740993')).costTotal).toBe('90071992547409.91');
expect(await store.getChanges('9007199254740993')).toEqual([
{ changeId: '4', beforeValue: '0', afterValue: '5' },
]);
expect(await store.getColumnConfig()).toEqual({ columns: ['storeName', 'businessScene'] });
});
it('sends exact approval action bodies and revokes the record without a body', async () => {
const requests: { url: string; data: unknown }[] = [];
serve((config) => {
expect(config.method).toBe('post');
requests.push({ url: config.url!, data: config.data ? JSON.parse(config.data) : undefined });
return { data: result(null) };
});
await store.passApproval('9007199254740993');
await store.rejectApproval(21, '政策有误');
await store.batchPassApproval([21, 22]);
await store.revokeApproval(21);
await store.saveColumnConfig(['merchantNo', 'storeName']);
expect(requests).toEqual([
{ url: '/store/approval/pass', data: { listingId: '9007199254740993' } },
{ url: '/store/approval/reject', data: { listingId: 21, reason: '政策有误' } },
{ url: '/store/approval/batch-pass', data: { listingIds: [21, 22] } },
{ url: '/store/approval/21/revoke', data: undefined },
{ url: '/store/listing/column-config', data: { columns: ['merchantNo', 'storeName'] } },
]);
});
it('does not submit an empty batch and exposes backend business failures', async () => {
let calls = 0;
serve(() => {
calls += 1;
return { data: JSON.stringify({ code: 10003, message: '无审批权限', data: null }) };
});
await expect(store.batchPassApproval([])).rejects.toThrow();
expect(calls).toBe(0);
await expect(store.passApproval(21)).rejects.toMatchObject({
message: '无审批权限',
code: 10003,
});
});
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', () => {
function watchDownloads() {
const createObjectURL = vi.fn((_blob: Blob) => 'blob:store-export');
const revokeObjectURL = vi.fn();
vi.stubGlobal(
'URL',
class extends URL {
static createObjectURL = createObjectURL;
static revokeObjectURL = revokeObjectURL;
},
);
const downloads: { filename: string; href: string }[] = [];
vi.spyOn(HTMLAnchorElement.prototype, 'click').mockImplementation(function (
this: HTMLAnchorElement,
) {
downloads.push({ filename: this.download, href: this.href });
});
return { downloads, createObjectURL, revokeObjectURL };
}
it('downloads with the current token, filters and UTF-8 filename even when signing is unavailable', async () => {
vi.useFakeTimers();
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',
});
return {
data: new Uint8Array([80, 75, 3, 4]).buffer,
headers: {
'content-type': 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
'content-disposition':
"attachment; filename*=UTF-8''%E9%97%A8%E5%BA%97%E6%98%8E%E7%BB%86.xlsx",
},
};
});
await store.exportStores({ businessScene: 'AFTER_SALE_MEMBER', startDate: '2026-10-01' });
expect(watched.downloads).toEqual([{ filename: '门店明细.xlsx', href: 'blob:store-export' }]);
expect(watched.createObjectURL.mock.calls[0][0]).toBeInstanceOf(Blob);
expect(watched.createObjectURL.mock.calls[0][0].size).toBe(4);
expect(document.querySelector('a[download]')).toBeNull();
await vi.runAllTimersAsync();
expect(watched.revokeObjectURL).toHaveBeenCalledWith('blob:store-export');
});
it('rejects JSON business errors received as arraybuffer without downloading them', async () => {
const watched = watchDownloads();
serve(() => ({
data: new TextEncoder().encode(
JSON.stringify({ code: 10003, message: '无导出权限', data: null }),
).buffer,
headers: { 'content-type': 'application/json;charset=UTF-8' },
}));
await expect(store.exportStores({})).rejects.toMatchObject({
message: '无导出权限',
code: 10003,
});
expect(watched.downloads).toEqual([]);
expect(watched.createObjectURL).not.toHaveBeenCalled();
});
});