store.test.ts
9.54 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
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import type { AxiosAdapter, InternalAxiosRequestConfig } from 'axios';
import { http } from '../../core/http';
import { store } from '../store';
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.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('retains existing import upload and submission behavior', async () => {
const file = new File(['example'], 'import.xlsx');
const payload = { taskId: 'task-1', storeName: '门店', businessScene: 'AFTER_SALE_MEMBER' };
serve((config) => {
if (config.url === '/store/import/check') {
expect(config.data.get('file')).toBe(file);
expect(config.data.get('templateVersion')).toBe('V1.0.1');
return { data: result({ taskId: 'task-1' }) };
}
expect(config.url).toBe('/store/import/submit');
expect(JSON.parse(config.data)).toEqual(payload);
return { data: result({ approveId: 'approval-1' }) };
});
expect(await store.uploadImport(file)).toEqual({ taskId: 'task-1' });
expect(await store.submitImport(payload)).toEqual({ approveId: 'approval-1' });
});
});
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 the binary response with authorization, filters and UTF-8 filename', async () => {
vi.useFakeTimers();
localStorage.setItem('session', JSON.stringify({ token: 'test-token', tokenType: 'Bearer' }));
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.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();
});
});