antd-import-export 1.0.9 → 1.0.12
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +40 -78
- package/README_EN.md +41 -71
- package/dist/components/ImportButton.d.ts +7 -4
- package/dist/core/excel/exportFile.d.ts +1 -1
- package/dist/core/excel/importRow.d.ts +11 -0
- package/dist/core/excel/runtime.d.ts +1 -1
- package/dist/index.cjs +1 -1
- package/dist/index.mjs +280 -260
- package/package.json +1 -1
package/README.md
CHANGED
|
@@ -69,7 +69,6 @@ const fieldSchemas: FieldSchema[] = [
|
|
|
69
69
|
| `single_choice` | required / option_map / default_value | 单元格填文案,接口值取 option_map 里的值 |
|
|
70
70
|
| `multiple_choice` | required / option_map / default_value | 中英文分号分隔,导出统一用英文分号 |
|
|
71
71
|
|
|
72
|
-
|
|
73
72
|
## 逐字段校验
|
|
74
73
|
|
|
75
74
|
```ts
|
|
@@ -88,36 +87,24 @@ const result = validateField("19.99", {
|
|
|
88
87
|
## 组件
|
|
89
88
|
|
|
90
89
|
```tsx
|
|
91
|
-
import {
|
|
90
|
+
import { ExportButton, ImportButton, exportRowsToFile } from "antd-import-export";
|
|
92
91
|
|
|
93
|
-
// 导入:
|
|
92
|
+
// 导入: 模板下载、文件解析、预览编辑、分批提交、行级错误回填
|
|
94
93
|
<ImportButton
|
|
95
94
|
title="供应商"
|
|
96
95
|
fieldSchemas={dataSchema}
|
|
97
96
|
importRows={(rows) => supplierImportData(rows)}
|
|
98
|
-
|
|
99
|
-
|
|
97
|
+
onModalClose={onRefresh}
|
|
98
|
+
/>
|
|
100
99
|
|
|
101
100
|
// 按当前筛选条件导出, 内部用游标分批拉取
|
|
102
101
|
<ExportButton
|
|
103
102
|
title="供应商"
|
|
104
103
|
fieldSchemas={dataSchema}
|
|
105
|
-
// 筛选条件在自己的 exportRows 里合并, 分页参数由包传入
|
|
106
104
|
exportRows={(params) => supplierExportData({ ...queryForm, ...params })}
|
|
107
|
-
|
|
108
|
-
```
|
|
109
|
-
|
|
110
|
-
两个组件都不发请求,只调用你传进来的 `importRows` / `exportRows`。
|
|
111
|
-
|
|
112
|
-
列表为空时用 `disabled` 禁用按钮,或在前置回调里拦截——组件不关心列表条数,也不内置条数上限。
|
|
113
|
-
|
|
114
|
-
退出登录或切换账号时调用 `resetTasks()`,会中止所有在途的导入导出并清空任务。
|
|
115
|
-
|
|
116
|
-
导出已勾选的行这类「数据已经在内存里」的场景,包内只提供函数,按钮由你自己渲染:
|
|
117
|
-
|
|
118
|
-
```tsx
|
|
119
|
-
import { exportRowsToFile } from "antd-import-export";
|
|
105
|
+
/>
|
|
120
106
|
|
|
107
|
+
// 导出已在内存里的行(如勾选的行), 直接下载文件
|
|
121
108
|
await exportRowsToFile({ title: "供应商", fieldSchemas: dataSchema, rows: selectedRows });
|
|
122
109
|
```
|
|
123
110
|
|
|
@@ -130,7 +117,7 @@ await exportRowsToFile({ title: "供应商", fieldSchemas: dataSchema, rows: sel
|
|
|
130
117
|
| `buttonText` | `string` | 导入按钮文案,默认「导入」 |
|
|
131
118
|
| `batchSize` | `number` | 每批提交的行数,默认 20,上限 200(与后端约定);非法值回落到 20 |
|
|
132
119
|
| `importRows` | `(rows) => Promise<Record<string, unknown>[]>` | 一批行提交,返回等长结果;**空对象表示成功** |
|
|
133
|
-
| `beforeImport` | `(rows) => void \| Promise
|
|
120
|
+
| `beforeImport` | `(rows) => void \| ImportRow[] \| Promise<...>` | 解析完成、打开预览前触发;返回数组则替换预览数据并重新校验;抛错即中止 |
|
|
134
121
|
| `afterImport` | `() => void` | 任务结束(成功/失败/取消)时触发一次,通常用来刷新列表;暂停不触发 |
|
|
135
122
|
| `onModalClose` | `() => void` | 弹窗关闭后触发一次,完成、取消、中途关闭都会触发 |
|
|
136
123
|
|
|
@@ -146,8 +133,6 @@ await exportRowsToFile({ title: "供应商", fieldSchemas: dataSchema, rows: sel
|
|
|
146
133
|
| `afterExport` | `() => void` | 任务结束(成功/失败/取消)时触发一次 |
|
|
147
134
|
| `onModalClose` | `() => void` | 弹窗关闭后触发一次,无论任务是否结束 |
|
|
148
135
|
|
|
149
|
-
生成文件期间取消按钮会禁用:ExcelJS 的解析与生成是一整段同步执行,主线程被占满时 abort 只在结束后才生效。
|
|
150
|
-
|
|
151
136
|
### exportRowsToFile
|
|
152
137
|
|
|
153
138
|
| 参数 | 类型 | 说明 |
|
|
@@ -156,17 +141,9 @@ await exportRowsToFile({ title: "供应商", fieldSchemas: dataSchema, rows: sel
|
|
|
156
141
|
| `fieldSchemas` | `FieldSchema[]` | 字段定义 |
|
|
157
142
|
| `rows` | `object[]` | 已在内存中的行 |
|
|
158
143
|
|
|
159
|
-
返回 `Promise<Blob>`。空数组或超过 2 万行时**抛出可直接展示的错误**;不弹提示、不管理 loading,由调用方决定交互。
|
|
160
|
-
|
|
161
|
-
### 导入接口需要幂等
|
|
162
|
-
|
|
163
|
-
一批请求失败时,前端无法确定服务端是否已经写入。任务会把这些行标成「结果未知,重试可能重复」,用户继续任务时会重新提交这一批数据。
|
|
164
|
-
|
|
165
|
-
因此导入接口应按业务唯一键(如编号)做「存在则更新、不存在则新增」,不要在无唯一约束的情况下纯追加。
|
|
166
|
-
|
|
167
144
|
### 导入数据约定
|
|
168
145
|
|
|
169
|
-
`importRows`
|
|
146
|
+
`importRows` 返回这一批每一行的处理结果,顺序与请求行一致:
|
|
170
147
|
|
|
171
148
|
| 返回 | 含义 |
|
|
172
149
|
| --- | --- |
|
|
@@ -174,25 +151,39 @@ await exportRowsToFile({ title: "供应商", fieldSchemas: dataSchema, rows: sel
|
|
|
174
151
|
| `{ "name": ["不能为空"] }` | 该行字段级失败,错误回填到预览表格对应单元格 |
|
|
175
152
|
| `{ "detail": "名称已存在" }` | 该行整体失败 |
|
|
176
153
|
| `{ "warehouse": ["不存在"] }`(键不在字段定义里) | 同样按整体失败处理,提示里保留键名 |
|
|
177
|
-
|
|
|
178
|
-
| HTTP 4xx/5xx
|
|
179
|
-
|
|
180
|
-
除返回数组之外,`importRows` 抛出的任何异常都会暂停整个任务(取消时除外),不区分状态码。提示文案依次取:后端返回的 `detail` → HTTP 状态码对应的可读文案 → `error.message`。
|
|
154
|
+
| 返回条数与请求行数不一致 | 视为接口异常,任务暂停 |
|
|
155
|
+
| 抛出异常(含 HTTP 4xx/5xx、网络异常) | 暂停整个任务,可继续或取消 |
|
|
181
156
|
|
|
182
157
|
### beforeImport 拿到什么
|
|
183
158
|
|
|
184
|
-
`beforeImport(rows)`
|
|
159
|
+
`beforeImport(rows)` 在**解析完成、打开预览之前**触发,`rows` 是解析并逐格校验过的行(只读):
|
|
185
160
|
|
|
186
|
-
|
|
187
|
-
|
|
188
|
-
|
|
189
|
-
|
|
190
|
-
|
|
191
|
-
|
|
161
|
+
```ts
|
|
162
|
+
import type { ImportRow } from "antd-import-export";
|
|
163
|
+
|
|
164
|
+
interface ImportRow {
|
|
165
|
+
key: string; // 行唯一键(解析时按顺序生成); 返回行时无需自己维护, 包会重排
|
|
166
|
+
rowNumber: number; // Excel 里的真实行号, 便于用户对照
|
|
167
|
+
values: Record<string, unknown>; // 编辑器值: 布尔/选项是文案, 列表是分号拼接的字符串
|
|
168
|
+
errors: Record<string, string>; // 字段级校验错误, key 是字段名
|
|
169
|
+
taskIndex?: number; // 内部字段: beforeImport 里恒为 undefined, 不需要处理
|
|
170
|
+
}
|
|
171
|
+
```
|
|
192
172
|
|
|
193
|
-
|
|
173
|
+
| 返回值 | 效果 |
|
|
174
|
+
| --- | --- |
|
|
175
|
+
| 不返回 | 保持原样,直接进入预览 |
|
|
176
|
+
| 返回 `ImportRow[]` | 用它替换预览数据,并重新校验 |
|
|
177
|
+
| 抛错 | 中止,预览不打开 |
|
|
194
178
|
|
|
195
179
|
```tsx
|
|
180
|
+
// 过滤:编号已存在的行不进预览
|
|
181
|
+
beforeImport={(rows) => rows.filter((row) => !existingNumbers.has(String(row.values.number)))}
|
|
182
|
+
|
|
183
|
+
// 截断:超过上限时只保留前 2 万行
|
|
184
|
+
beforeImport={(rows) => rows.slice(0, 20000)}
|
|
185
|
+
|
|
186
|
+
// 中止:不合规就提示用户
|
|
196
187
|
beforeImport={(rows) => {
|
|
197
188
|
if (rows.length > 20000) {
|
|
198
189
|
throw new Error(`导入数据 ${rows.length.toLocaleString()} 条,超过上限 20,000 条,请分批导入`);
|
|
@@ -200,11 +191,9 @@ beforeImport={(rows) => {
|
|
|
200
191
|
}}
|
|
201
192
|
```
|
|
202
193
|
|
|
203
|
-
`rows` 里可能含校验失败的行(`errors` 非空),它们后续提交时会被跳过;如果只想按可提交的行数判断,自行过滤即可。
|
|
204
|
-
|
|
205
194
|
### 导出数据约定
|
|
206
195
|
|
|
207
|
-
`exportRows`
|
|
196
|
+
`exportRows` 每次拉一批数据,返回:
|
|
208
197
|
|
|
209
198
|
| 字段 | 类型 | 说明 |
|
|
210
199
|
| --- | --- | --- |
|
|
@@ -218,42 +207,17 @@ beforeImport={(rows) => {
|
|
|
218
207
|
| 第一页 | `{}` |
|
|
219
208
|
| 后续页 | `{ cursor_id: 上一页最后一条的 id }` |
|
|
220
209
|
|
|
221
|
-
|
|
222
|
-
包只传游标,不传任何分页参数——每次拉多少条由后端决定,或在你的 `exportRows` 里自己加。
|
|
223
|
-
|
|
224
210
|
`results` 返回空数组即视为没有更多数据,任务结束。
|
|
225
211
|
|
|
226
|
-
### 错误状态码的识别
|
|
227
|
-
|
|
228
|
-
包不认请求库,只从你抛出的错误对象上读状态码:
|
|
229
|
-
|
|
230
|
-
| 读取内容 | 顺序 |
|
|
231
|
-
| --- | --- |
|
|
232
|
-
| 状态码 | `error.response.status` → `error.status` → `error.statusCode` |
|
|
233
|
-
| 响应体 | `error.response.data` → `error.data` |
|
|
234
|
-
|
|
235
|
-
axios 的错误天然符合第一种形状。用 fetch 的时候,请把 `Response` 包成上面任一种形状再抛出,否则会被当成普通异常,只显示「导入失败, 任务已暂停」这类通用文案,而不是「登录已过期」这种具体提示。
|
|
236
|
-
|
|
237
212
|
### 取消与暂停的时机
|
|
238
213
|
|
|
239
|
-
|
|
214
|
+
取消和暂停都**不会中断已经发出去的请求**,当前这一步跑完后才生效:
|
|
240
215
|
|
|
241
|
-
|
|
|
216
|
+
| 当前状态 | 点「取消」或「暂停」后的行为 |
|
|
242
217
|
| --- | --- |
|
|
243
|
-
|
|
|
244
|
-
|
|
|
245
|
-
|
|
|
246
|
-
|
|
247
|
-
导入是写操作,中断在途批次后无法确定服务端是否落库,因此两边的取消语义保持一致:**只停止领取新批次**。
|
|
248
|
-
|
|
249
|
-
### 两个使用前提
|
|
250
|
-
|
|
251
|
-
1. 组件用 `App.useApp()` 弹提示,根节点需要包一层 antd 的 `<App>`。
|
|
252
|
-
2. 在 Next.js App Router 里使用时,引入这些组件的文件要加 `"use client"`。
|
|
253
|
-
|
|
254
|
-
## 模块格式
|
|
255
|
-
|
|
256
|
-
同时提供 ESM 与 CJS,类型声明通过 `exports` 分发。
|
|
218
|
+
| 导出的拉取过程中 | 等当前数据返回后进入「已取消」 |
|
|
219
|
+
| 导入的提交过程中 | 等在途数据导入完成后进入「已取消」或「已暂停」 |
|
|
220
|
+
| 导入已暂停 | 取消立即生效 |
|
|
257
221
|
|
|
258
222
|
## 本地开发
|
|
259
223
|
|
|
@@ -264,8 +228,6 @@ npm run preview # 构建后启动示例页
|
|
|
264
228
|
npm run verify # 发布门槛: lint + 测试 + 构建 + 示例页类型检查
|
|
265
229
|
```
|
|
266
230
|
|
|
267
|
-
发布到 npm 的完整流程见 [RELEASING.md](./RELEASING.md)。
|
|
268
|
-
|
|
269
231
|
## 许可证
|
|
270
232
|
|
|
271
233
|
MIT
|
package/README_EN.md
CHANGED
|
@@ -62,7 +62,6 @@ const fieldSchemas: FieldSchema[] = [
|
|
|
62
62
|
| `single_choice` | required / option_map / default_value | label in the cell, mapped value on the wire |
|
|
63
63
|
| `multiple_choice` | required / option_map / default_value | Chinese or English semicolons; exports always use `;` |
|
|
64
64
|
|
|
65
|
-
|
|
66
65
|
## Validation
|
|
67
66
|
|
|
68
67
|
```ts
|
|
@@ -80,34 +79,24 @@ validateField("19.99", {
|
|
|
80
79
|
## Components
|
|
81
80
|
|
|
82
81
|
```tsx
|
|
83
|
-
import {
|
|
82
|
+
import { ExportButton, ImportButton, exportRowsToFile } from "antd-import-export";
|
|
84
83
|
|
|
84
|
+
// import: template download, parsing, editable preview, batched submit, row-level errors
|
|
85
85
|
<ImportButton
|
|
86
86
|
title="Supplier"
|
|
87
87
|
fieldSchemas={fieldSchemas}
|
|
88
88
|
importRows={(rows) => importSuppliers(rows)}
|
|
89
|
-
|
|
90
|
-
|
|
89
|
+
onModalClose={refresh}
|
|
90
|
+
/>
|
|
91
91
|
|
|
92
|
+
// export the current filters, paged with a cursor inside the package
|
|
92
93
|
<ExportButton
|
|
93
94
|
title="Supplier"
|
|
94
95
|
fieldSchemas={fieldSchemas}
|
|
95
|
-
// merge your own filters inside exportRows; paging params come from the package
|
|
96
96
|
exportRows={(params) => exportSuppliers({ ...queryForm, ...params })}
|
|
97
|
-
|
|
98
|
-
```
|
|
99
|
-
|
|
100
|
-
Neither component issues requests: they call the `importRows` / `exportRows` you provide.
|
|
101
|
-
|
|
102
|
-
Disable the button when the list is empty, or reject inside the before callback — the component neither knows nor enforces the row count.
|
|
103
|
-
|
|
104
|
-
Call `resetTasks()` on logout or account switch to abort every in-flight import/export and clear the task list.
|
|
105
|
-
|
|
106
|
-
To export rows that are already in memory, render your own button and call the function:
|
|
107
|
-
|
|
108
|
-
```tsx
|
|
109
|
-
import { exportRowsToFile } from "antd-import-export";
|
|
97
|
+
/>
|
|
110
98
|
|
|
99
|
+
// export rows already in memory (e.g. selected rows); downloads immediately
|
|
111
100
|
await exportRowsToFile({ title: "Supplier", fieldSchemas, rows: selectedRows });
|
|
112
101
|
```
|
|
113
102
|
|
|
@@ -120,7 +109,7 @@ await exportRowsToFile({ title: "Supplier", fieldSchemas, rows: selectedRows });
|
|
|
120
109
|
| `buttonText` | `string` | import button label, defaults to `导入` |
|
|
121
110
|
| `batchSize` | `number` | rows per batch, defaults to 20, capped at 200 (backend contract); invalid values fall back to 20 |
|
|
122
111
|
| `importRows` | `(rows) => Promise<Record<string, unknown>[]>` | submits one batch, returns the same length; **empty object means success** |
|
|
123
|
-
| `beforeImport` | `(rows) => void \| Promise
|
|
112
|
+
| `beforeImport` | `(rows) => void \| ImportRow[] \| Promise<...>` | runs after parsing and before the preview opens; returning an array replaces the preview data (re-validated); throw to abort |
|
|
124
113
|
| `afterImport` | `() => void` | fires once when the task ends (completed / failed / canceled), not on pause |
|
|
125
114
|
| `onModalClose` | `() => void` | fires once after the modal closes, whatever the outcome |
|
|
126
115
|
|
|
@@ -136,8 +125,6 @@ await exportRowsToFile({ title: "Supplier", fieldSchemas, rows: selectedRows });
|
|
|
136
125
|
| `afterExport` | `() => void` | fires once when the task ends (completed / failed / canceled) |
|
|
137
126
|
| `onModalClose` | `() => void` | fires once after the modal closes |
|
|
138
127
|
|
|
139
|
-
The cancel button is disabled while the file is generated: ExcelJS parses and writes in one synchronous block, so an abort only takes effect after it finishes.
|
|
140
|
-
|
|
141
128
|
### exportRowsToFile
|
|
142
129
|
|
|
143
130
|
| option | type | notes |
|
|
@@ -146,11 +133,9 @@ The cancel button is disabled while the file is generated: ExcelJS parses and wr
|
|
|
146
133
|
| `fieldSchemas` | `FieldSchema[]` | field definitions |
|
|
147
134
|
| `rows` | `object[]` | rows already in memory |
|
|
148
135
|
|
|
149
|
-
Returns `Promise<Blob>`. Throws a ready-to-display error when `rows` is empty or exceeds 20,000; it does not show messages or manage loading state.
|
|
150
|
-
|
|
151
136
|
### Import contract
|
|
152
137
|
|
|
153
|
-
`importRows` returns
|
|
138
|
+
`importRows` returns the per-row outcome of the batch, in the same order as the submitted rows:
|
|
154
139
|
|
|
155
140
|
| Response | Meaning |
|
|
156
141
|
| --- | --- |
|
|
@@ -158,25 +143,39 @@ Returns `Promise<Blob>`. Throws a ready-to-display error when `rows` is empty or
|
|
|
158
143
|
| `{ "name": ["required"] }` | field-level failure, mapped back to the preview cell |
|
|
159
144
|
| `{ "detail": "name already exists" }` | the whole row failed |
|
|
160
145
|
| `{ "warehouse": ["not found"] }` (key not in the field schema) | also treated as a whole-row failure, message keeps the key |
|
|
161
|
-
|
|
|
162
|
-
| HTTP 4xx/5xx, network
|
|
163
|
-
|
|
164
|
-
Beyond returning the array, any error thrown by `importRows` pauses the whole task (except when canceled), regardless of the status code. The message is taken from, in order: the backend `detail` → a readable text for the HTTP status → `error.message`.
|
|
146
|
+
| number of results ≠ number of rows | treated as an API error, task pauses |
|
|
147
|
+
| any thrown error (incl. HTTP 4xx/5xx, network) | pauses the whole task, resumable |
|
|
165
148
|
|
|
166
149
|
### What `beforeImport` receives
|
|
167
150
|
|
|
168
|
-
`beforeImport(rows)` runs **after parsing and before the preview opens
|
|
151
|
+
`beforeImport(rows)` runs **after parsing and before the preview opens**; `rows` are the parsed, per-cell validated rows (read-only):
|
|
169
152
|
|
|
170
|
-
|
|
171
|
-
|
|
172
|
-
|
|
173
|
-
|
|
174
|
-
|
|
175
|
-
|
|
153
|
+
```ts
|
|
154
|
+
import type { ImportRow } from "antd-import-export";
|
|
155
|
+
|
|
156
|
+
interface ImportRow {
|
|
157
|
+
key: string; // unique row key (assigned in order while parsing); the package re-numbers it on return
|
|
158
|
+
rowNumber: number; // the real Excel row number
|
|
159
|
+
values: Record<string, unknown>; // editor values: booleans/choices are labels, lists are semicolon-joined
|
|
160
|
+
errors: Record<string, string>; // field-level validation errors
|
|
161
|
+
taskIndex?: number; // internal: always undefined in beforeImport, ignore it
|
|
162
|
+
}
|
|
163
|
+
```
|
|
176
164
|
|
|
177
|
-
|
|
165
|
+
| Returns | Effect |
|
|
166
|
+
| --- | --- |
|
|
167
|
+
| nothing | keep the rows as-is and open the preview |
|
|
168
|
+
| `ImportRow[]` | replace the preview data; rows are re-validated |
|
|
169
|
+
| throws | abort; the preview never opens |
|
|
178
170
|
|
|
179
171
|
```tsx
|
|
172
|
+
// filter: skip rows whose code already exists
|
|
173
|
+
beforeImport={(rows) => rows.filter((row) => !existingNumbers.has(String(row.values.number)))}
|
|
174
|
+
|
|
175
|
+
// truncate: keep only the first 20,000 rows
|
|
176
|
+
beforeImport={(rows) => rows.slice(0, 20000)}
|
|
177
|
+
|
|
178
|
+
// abort with a message
|
|
180
179
|
beforeImport={(rows) => {
|
|
181
180
|
if (rows.length > 20000) {
|
|
182
181
|
throw new Error(`too many rows: ${rows.length}, limit 20,000`);
|
|
@@ -184,11 +183,9 @@ beforeImport={(rows) => {
|
|
|
184
183
|
}}
|
|
185
184
|
```
|
|
186
185
|
|
|
187
|
-
`rows` may still contain failing rows (`errors` non-empty); those are skipped on submit. Filter them if you need the exact submitted count.
|
|
188
|
-
|
|
189
186
|
### Export contract
|
|
190
187
|
|
|
191
|
-
`exportRows` fetches one
|
|
188
|
+
`exportRows` fetches one batch at a time and returns:
|
|
192
189
|
|
|
193
190
|
| Field | Type | Notes |
|
|
194
191
|
| --- | --- | --- |
|
|
@@ -202,42 +199,17 @@ Paging is driven by the package, so `exportRows` only ever receives:
|
|
|
202
199
|
| first page | `{}` |
|
|
203
200
|
| following pages | `{ cursor_id: id of the last row of the previous page }` |
|
|
204
201
|
|
|
205
|
-
|
|
206
|
-
The package only sends the cursor, no paging parameter — the batch size is up to the backend, or add it yourself inside `exportRows`.
|
|
207
|
-
|
|
208
202
|
An empty `results` array ends the task.
|
|
209
203
|
|
|
210
|
-
### How status codes are detected
|
|
211
|
-
|
|
212
|
-
The package does not know your HTTP client; it reads the status from the error you throw:
|
|
213
|
-
|
|
214
|
-
| What | Lookup order |
|
|
215
|
-
| --- | --- |
|
|
216
|
-
| status | `error.response.status` → `error.status` → `error.statusCode` |
|
|
217
|
-
| body | `error.response.data` → `error.data` |
|
|
218
|
-
|
|
219
|
-
axios errors already match the first shape. With fetch, wrap the `Response` into one of these shapes before throwing, otherwise it is treated as a generic error and shows a generic message instead of "session expired".
|
|
220
|
-
|
|
221
204
|
### When cancel and pause take effect
|
|
222
205
|
|
|
223
|
-
Cancel and pause
|
|
206
|
+
Cancel and pause never abort an in-flight request — they take effect once the current step finishes:
|
|
224
207
|
|
|
225
|
-
|
|
|
208
|
+
| Current state | What cancel / pause does |
|
|
226
209
|
| --- | --- |
|
|
227
|
-
| export
|
|
228
|
-
| import canceled
|
|
229
|
-
|
|
|
230
|
-
|
|
231
|
-
Import writes data, and aborting an in-flight batch leaves its server-side outcome unknown. Both directions therefore behave the same: **stop claiming new batches only**.
|
|
232
|
-
|
|
233
|
-
### Two prerequisites
|
|
234
|
-
|
|
235
|
-
1. They use `App.useApp()`, so wrap the root with antd's `<App>`.
|
|
236
|
-
2. In Next.js App Router, add `"use client"` to the file that imports them.
|
|
237
|
-
|
|
238
|
-
## Module format
|
|
239
|
-
|
|
240
|
-
Ships both ESM and CJS, with type declarations resolved through `exports`.
|
|
210
|
+
| export while fetching | enters "canceled" after the current data request completes |
|
|
211
|
+
| import while submitting | enters "canceled" or "paused" after in-flight data finishes importing |
|
|
212
|
+
| import already paused | cancel takes effect immediately |
|
|
241
213
|
|
|
242
214
|
## Development
|
|
243
215
|
|
|
@@ -248,8 +220,6 @@ npm run preview # build, then start the demo
|
|
|
248
220
|
npm run verify # release gate: lint + tests + build + demo type check
|
|
249
221
|
```
|
|
250
222
|
|
|
251
|
-
See [RELEASING.md](./RELEASING.md) for the full npm release process.
|
|
252
|
-
|
|
253
223
|
## License
|
|
254
224
|
|
|
255
225
|
MIT
|
|
@@ -11,10 +11,13 @@ export interface ImportButtonProps {
|
|
|
11
11
|
batchSize?: number;
|
|
12
12
|
/** 提交一批待导入的行, 返回等长的逐行结果; 空对象表示成功 */
|
|
13
13
|
importRows: (rows: Record<string, unknown>[]) => Promise<ImportRowErrorBody[]>;
|
|
14
|
-
/**
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
|
|
14
|
+
/**
|
|
15
|
+
* 解析完成、打开预览前触发, 拿到解析并校验过的行。
|
|
16
|
+
* 抛错即中止; 返回数组则用它替换预览数据(会重新校验), 不返回则保持原样。
|
|
17
|
+
*/
|
|
18
|
+
beforeImport?: (rows: readonly ImportRow[]) => void | ImportRow[] | Promise<void | ImportRow[]>;
|
|
19
|
+
/** 导入任务结束(成功/失败/取消)时回调一次; 用 onModalClose 刷新时可以不传 */
|
|
20
|
+
afterImport?: () => void;
|
|
18
21
|
/** 弹窗关闭后触发, 无论是导入完成、取消还是中途关闭 */
|
|
19
22
|
onModalClose?: () => void;
|
|
20
23
|
}
|
|
@@ -11,4 +11,4 @@ export interface ExportRowsToFileOptions {
|
|
|
11
11
|
* 只负责数据到文件, 不弹提示也不管理 loading;
|
|
12
12
|
* 没有数据时抛出可直接展示的错误, 由调用方决定如何反馈。
|
|
13
13
|
*/
|
|
14
|
-
export declare function exportRowsToFile(options: ExportRowsToFileOptions): Promise<
|
|
14
|
+
export declare function exportRowsToFile(options: ExportRowsToFileOptions): Promise<void>;
|
|
@@ -12,3 +12,14 @@ export interface ImportRow {
|
|
|
12
12
|
}
|
|
13
13
|
/** 从唯一数据源生成接口 payload; 缺列字段跳过, 保持"不修改"语义 */
|
|
14
14
|
export declare function buildImportPayload(row: ImportRow, fieldSchemas: FieldSchema[], includedKeys: string[]): Record<string, unknown>;
|
|
15
|
+
/**
|
|
16
|
+
* 重新校验一批行, 供 beforeImport 返回加工后的数据时使用:
|
|
17
|
+
* values 会按字段规则规范化, errors 与之一致, 不会残留加工前的旧错误.
|
|
18
|
+
*/
|
|
19
|
+
export declare function revalidateImportRows(rows: ImportRow[], fieldSchemas: FieldSchema[], includedKeys: string[]): {
|
|
20
|
+
key: string;
|
|
21
|
+
values: Record<string, unknown>;
|
|
22
|
+
errors: Record<string, string>;
|
|
23
|
+
rowNumber: number;
|
|
24
|
+
taskIndex?: number;
|
|
25
|
+
}[];
|
|
@@ -6,7 +6,7 @@ export declare function saveWorkbook(blob: Blob, fileName: string): void;
|
|
|
6
6
|
/** 导出: 生成 xlsx 内容, 由调用方决定何时下载 */
|
|
7
7
|
export declare function buildExportBlob(data: object[], fieldSchemas: FieldSchema[], signal?: AbortSignal): Promise<Blob>;
|
|
8
8
|
/** 导出: 把列表数据渲染成 Excel 并下载 */
|
|
9
|
-
export declare function exportExcel(data: object[], fieldSchemas: FieldSchema[], fileName: string): Promise<
|
|
9
|
+
export declare function exportExcel(data: object[], fieldSchemas: FieldSchema[], fileName: string): Promise<void>;
|
|
10
10
|
/** 导入模板: 列名与填写要求写在表头单元格里, 不写示例行 */
|
|
11
11
|
export declare function downloadImportTemplate(fieldSchemas: FieldSchema[], fileName: string): Promise<void>;
|
|
12
12
|
/** 导入: 解析并按字段定义校验 Excel, 返回可提交的数据与逐行问题 */
|
package/dist/index.cjs
CHANGED
|
@@ -3,4 +3,4 @@ Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});var e=Object.
|
|
|
3
3
|
`).length))-1)*15,i.eachCell({includeEmpty:!0},e=>{e.font={bold:!0,size:14,color:{argb:`FFFFFFFF`}},e.fill={type:`pattern`,pattern:`solid`,fgColor:{argb:`FF4472C4`}},e.alignment={vertical:`middle`,wrapText:!0}}),t.forEach(t=>{e.addRow(n.map(e=>oe(e,t))).eachCell({includeEmpty:!0},e=>{e.alignment={...e.alignment,wrapText:!0,vertical:`top`}})}),z(e,n),ue(e)}function ce(e){let t=[e.property.required?`必填`:`可选`];switch(e.type){case`text`:t.push(`最长 ${e.property.max_length} 个字符`);break;case`number`:t.push(`最多 ${e.property.precision} 位小数`),e.property.max_digits!==void 0&&t.push(`整数最多 ${e.property.max_digits-e.property.precision} 位`),e.property.min_value!==void 0&&t.push(`最小 ${e.property.min_value}`),e.property.max_value!==void 0&&t.push(`最大 ${e.property.max_value}`);break;case`boolean`:t.push(`填 ${e.property.true_label} 或 ${e.property.false_label}`);break;case`date`:t.push(`格式 YYYY-MM-DD`);break;case`time`:t.push(`格式 HH:mm, 可带秒`);break;case`datetime`:t.push(`格式 YYYY-MM-DD HH:mm, 可带秒`);break;case`list`:t.push(`多个值用分号分隔(中英文均可), 最多 ${e.property.list_max_length} 个`);break;case`single_choice`:t.push(`填其一: ${Object.keys(e.property.option_map).join(` / `)}`);break;case`multiple_choice`:t.push(`可多选, 分号分隔(中英文均可): ${Object.keys(e.property.option_map).join(` / `)}`)}e.key.endsWith(`_name`)?t.push(`填对应记录的名称`):e.key.endsWith(`_number`)&&t.push(`填对应记录的编号`);let n=oe(e,{[e.key]:e.property.default_value});return t.push(`默认值: ${n==null||n===``?`空`:n}`),t.join(`
|
|
4
4
|
`)}function le(e,t){let n=t.map(e=>`${e.title}\n\n${ce(e)}`),r=e.addRow(n);r.height=20+(Math.max(1,...n.map(e=>e.split(`
|
|
5
5
|
`).length))-1)*15,r.eachCell({includeEmpty:!0},e=>{e.font={bold:!0,size:14,color:{argb:`FFFFFFFF`}},e.fill={type:`pattern`,pattern:`solid`,fgColor:{argb:`FF4472C4`}},e.alignment={vertical:`top`,wrapText:!0}}),z(e,t),ue(e)}function ue(e,t=20,n=60){let r=[];e.eachRow({includeEmpty:!1},e=>{e.eachCell({includeEmpty:!1},(e,t)=>{let n=t-1,i=e.text,a=e.font?.size||11,o=.8+a/11*.4,s=i.split(`
|
|
6
|
-
`),c=0;for(let e of s){let t=0;for(let n of e){let e=n.charCodeAt(0);t+=e>255||e>=65280&&e<=65519?2:1}c=Math.max(c,t)}let l=c*7*(a/11)*o;(!r[n]||l>r[n])&&(r[n]=l)})}),r.forEach((r,i)=>{let a=r/7;e.getColumn(i+1).width=Math.min(Math.max(a,t),n)})}var de=`application/vnd.openxmlformats-officedocument.spreadsheetml.sheet`;function B(e,t){(0,d.saveAs)(e,`${t}.xlsx`)}var fe;function pe(){return fe??=import(`exceljs`).then(e=>e.default??e,e=>{throw fe=void 0,e}),fe}function me(){return new Promise(e=>{requestAnimationFrame(()=>setTimeout(e,0))})}function he(e){if(e?.aborted)throw new DOMException(`任务已取消`,`AbortError`)}async function ge(e,t,n){let r=await pe();he(n),await me();let i=new r.Workbook;se(i.addWorksheet(`Sheet`),e,t);let a=await i.xlsx.writeBuffer();return he(n),new Blob([a],{type:de})}async function _e(e,t,n){let r=await ge(e,t);return B(r,n),r}async function V(e,t){let n=await pe();await me();let r=new n.Workbook;le(r.addWorksheet(`导入模板`),e);let i=await r.xlsx.writeBuffer();B(new Blob([i],{type:de}),t)}async function ve(e,t){let n=await pe(),r=await e.arrayBuffer();await me();let i=new n.Workbook;if(await i.xlsx.load(r),i.worksheets.length>1)return{headerMessages:[`文件包含多个工作表, 只支持单个工作表, 请删除其他工作表后再导入`],formulaMessages:[],rows:[],includedKeys:[]};let a=i.worksheets[0];return a?R(a,t):{headerMessages:[`文件里没有工作表`],formulaMessages:[],rows:[],includedKeys:[]}}function H(e){return`${e}_${(0,l.default)().format(`YYYYMMDDHHmmss`)}`}async function ye(e){let{title:t,fieldSchemas:n,rows:r}=e;if(r.length===0)throw Error(`没有可导出的数据`);return _e(r,n,H(t))}function be(e,t){let n=Date.now();return[...e,{time:n,processed:t}].filter(e=>n-e.time<=15e3).slice(-20)}function xe(e){if(e.status!==`running`||e.total<=0)return null;let t=Math.max(0,e.total-(e.validationFailedCount??0)-e.processed);if(t===0)return 0;if(e.samples.length<2)return null;let n=e.samples[0],r=e.samples[e.samples.length-1],i=(r.time-n.time)/1e3,a=r.processed-n.processed;return i<=0||a<=0?null:t/(a/i)}function Se(e){return e.type===`import`?e.successCount===void 0?e.rowStates?.filter(e=>e.status===`completed`).length??e.processed:e.successCount:e.processed}function Ce(e){return e.total<=0?0:Math.min(100,Se(e)/e.total*100)}function we(e){if(e.finalizing)return 100;let t=Ce(e);return t>=100?100:Math.trunc(t*10)/10}function Te(e){return`${(Math.trunc(e*10)/10).toFixed(1)}%`}function Ee(e){if(e===null)return`计算中...`;let t=Math.ceil(e);return t<60?`约 ${t} 秒`:`约 ${Math.floor(t/60)} 分 ${t%60} 秒`}var U={tasks:[]},De=new Set,W=new Map,G=new Map,K=new Map;function Oe(){U={...U},De.forEach(e=>e())}function ke(e){return De.add(e),()=>{De.delete(e)}}function Ae(e){return ke(e)}function je(){return U.tasks}function Me(){return`task-${Date.now()}-${Math.random().toString(36).slice(2,10)}`}function q(e){return U.tasks.find(t=>t.id===e)}function J(e,t){let n=!1,r=U.tasks.map(r=>r.id===e?(n=!0,{...r,...t}):r);n&&(U={...U,tasks:r},Oe())}function Ne(e){U={...U,tasks:[...U.tasks,e]},Oe()}function Pe(e){U={...U,tasks:U.tasks.filter(t=>t.id!==e)},Oe()}function Fe(){K.forEach(e=>e.abort()),K.clear(),W.clear(),G.clear(),U={tasks:[]},Oe()}var Y=class extends Error{constructor(e){super(e),this.name=`ImportPauseError`}},Ie=100,Le=20,Re=200,ze=100,X=new Set,Z=null;function Q(e,t,n){let r=G.get(e);r&&(r.rowStates[t]={...r.rowStates[t],...n},Be(e))}function Be(e){X.add(e),Z===null&&(Z=setTimeout(()=>{Z=null;let e=[...X];X.clear(),e.forEach(We)},ze))}function Ve(e){X.delete(e)}function He(){X.clear(),Z!==null&&(clearTimeout(Z),Z=null)}function Ue(e,t){return{processed:t.processed,total:Ge(t),successCount:t.successCount,failureCount:t.failures.length,validationFailedCount:t.validationFailedCount,failures:t.failures,rowStates:t.rowStates,samples:be(q(e)?.samples??[],t.processed)}}function We(e){let t=G.get(e);t&&q(e)&&J(e,Ue(e,t))}function Ge(e){return e.options.rows.length-e.deletedIndexes.size}function Ke(e){return`成功 ${e.successCount} 条, 失败 ${e.failures.length} 条, 可修正失败行后继续`}function qe(e){if(e===void 0)return Le;let t=Math.floor(e);return!Number.isFinite(t)||t<1?Le:Math.min(t,Re)}async function Je(e,t,n){let r=t.options.rows.length;if(t.controller=n,t.pauseRequested=!1,t.cancelRequested=!1,t.runFailureCount=0,r===0){J(e,{status:`failed`,pausing:!1,errorMessage:`没有可导入的数据`}),t.options.onFinished?.();return}J(e,{...Ue(e,t),status:`running`,samples:[{time:Date.now(),processed:t.processed}]});let i=qe(t.options.batchSize),a=Math.min(Math.max(t.options.concurrency??3,1),5),o=()=>{let e=[];for(;e.length<i;){let n=t.nextIndex;if(t.nextIndex+=1,n>=r)break;t.deletedIndexes.has(n)||t.rowStates[n]?.status!==`completed`&&(t.skippedIndexes.has(n)||e.push(n))}return e},s=async()=>{for(;;){if(n.signal.aborted||t.pauseRequested||t.cancelRequested)return;let r=o();if(r.length===0)return;r.forEach(t=>{Q(e,t,{status:`running`,message:void 0,fieldErrors:void 0})});try{let i=r.map(e=>t.options.rows[e]),a=await t.options.importRows(i);if(n.signal.aborted)return;if(a.length!==r.length)throw new Y(`导入接口返回结果数量不正确, 任务已暂停`);a.forEach((n,i)=>{let a=r[i],o=t.options.rows[a];n.success?(t.successCount+=1,Q(e,a,{status:`completed`,fieldErrors:void 0})):(t.failures.push({index:a,rowNumber:o.rowNumber,message:n.message??`导入失败`,fieldErrors:n.fieldErrors}),Q(e,a,{status:`failed`,message:n.message,fieldErrors:n.fieldErrors}),t.runFailureCount+=1,t.runFailureCount>Ie&&(t.pauseRequested=!0))})}catch(i){if(n.signal.aborted)return;let a=i instanceof Y,o=`${i instanceof Error?i.message:`导入失败`}(该批结果未知,重试可能重复)`;r.forEach(n=>{t.failures.push({index:n,rowNumber:t.options.rows[n].rowNumber,message:o}),Q(e,n,{status:`failed`,message:o}),t.runFailureCount+=1}),a?(t.pauseRequested=!0,n.abort()):t.runFailureCount>Ie&&(t.pauseRequested=!0)}finally{t.processed+=r.length,Be(e)}}},c=Math.min(a,Math.max(1,r));await Promise.all(Array.from({length:c},()=>s())),t.controller=null,q(e)&&Qe(e,t,n)}function Ye(e){e.rowStates=e.rowStates.map(e=>e.status===`queued`||e.status===`running`?{status:`canceled`}:e)}function Xe(e){e.rowStates=e.rowStates.map(e=>e.status===`running`?{status:`queued`,validationErrors:e.validationErrors}:e)}function Ze(e){return e.failures.length>0?`累计失败 ${e.failures.length} 条, 任务已暂停, 可继续导入`:void 0}function $(e,t,n){J(e,{...Ue(e,t),pausing:!1,...n}),n.status!==`paused`&&t.options.onFinished?.()}function Qe(e,t,n){if(Ve(e),t.cancelRequested){Ye(t),$(e,t,{status:`canceled`,canceling:!1});return}if(t.pauseRequested&&n.signal.aborted){Xe(t),$(e,t,{status:`paused`,errorMessage:Ze(t)});return}if(n.signal.aborted){Ye(t),$(e,t,{status:`canceled`,canceling:!1});return}if(t.pauseRequested&&t.nextIndex<t.options.rows.length){$(e,t,{status:`paused`,errorMessage:Ze(t)});return}if(t.failures.length>0){$(e,t,{status:`paused`,errorMessage:Ke(t)});return}let r=[...t.skippedIndexes].filter(e=>!t.deletedIndexes.has(e)).length;r>0?$(e,t,{status:`paused`,errorMessage:`有 ${r} 条校验失败数据待修复`}):$(e,t,{status:`completed`})}function $e(e,t){let n=new AbortController;K.set(e,n),Je(e,t,n).finally(()=>{K.delete(e),X.delete(e),q(e)?.status!==`paused`&&G.delete(e)})}function et(e){let t=Me(),n=e.rows.map(e=>({status:`queued`,validationErrors:Object.keys(e.errors).length>0?e.errors:void 0})),r=new Set(e.rows.flatMap((e,t)=>Object.keys(e.errors).length>0?[t]:[])),i=r.size,a={id:t,type:`import`,title:e.title,status:`running`,total:e.rows.length,processed:0,canceling:!1,successCount:0,failureCount:0,validationFailedCount:i,rowStates:n,failures:[],samples:[]},o={options:e,nextIndex:0,processed:0,successCount:0,failures:[],rowStates:n,validationFailedCount:i,pauseRequested:!1,cancelRequested:!1,deletedIndexes:new Set,skippedIndexes:r,runFailureCount:0,controller:null};return G.set(t,o),Ne(a),$e(t,o),t}function tt(e){let t=q(e);if(!t||t.type!==`import`||t.status!==`paused`)return;let n=G.get(e);if(!n)return;let r=n.rowStates.filter(e=>e.status===`completed`).length,i=n.rowStates.map(e=>e.status===`completed`||e.status===`deleted`?e:{status:`queued`,validationErrors:e.validationErrors}),a=i.filter(e=>e.validationErrors&&Object.keys(e.validationErrors).length>0).length;n.rowStates=i,n.validationFailedCount=a,n.nextIndex=0,n.processed=r,n.successCount=r,n.failures=[],n.pauseRequested=!1,n.cancelRequested=!1,n.runFailureCount=0,J(e,{status:`running`,pausing:!1,canceling:!1,processed:r,successCount:r,failureCount:0,validationFailedCount:a,failures:[],rowStates:i,errorMessage:void 0}),$e(e,n)}function nt(e){let t=q(e);if(!t||t.type!==`import`||t.status!==`running`||t.canceling)return;let n=G.get(e);n&&(n.pauseRequested=!0,J(e,{pausing:!0}))}function rt(e,t,n){let r=q(e),i=G.get(e);if(!r||r.type!==`import`||r.status!==`paused`&&r.status!==`failed`||!i)return;let a=r.rowStates?.[t]?.status;(a===`queued`||a===`failed`)&&(i.options.rows[t]=n)}function it(e,t,n){let r=q(e),i=G.get(e);if(!r||r.type!==`import`||!i||r.status!==`paused`&&r.status!==`failed`)return;let a=Object.keys(n).length>0,o=i.rowStates[t]?.validationErrors,s=!!(o&&Object.keys(o).length>0);a?(i.skippedIndexes.add(t),s||(i.validationFailedCount+=1)):(i.skippedIndexes.delete(t),s&&--i.validationFailedCount),i.rowStates[t]={...i.rowStates[t],validationErrors:a?n:void 0},i.options.rows[t]={...i.options.rows[t],errors:n},J(e,{validationFailedCount:i.validationFailedCount,rowStates:i.rowStates})}function at(e,t){let n=q(e),r=G.get(e);n&&n.type===`import`&&n.status===`paused`&&r&&(t.forEach(e=>{let t=r.rowStates[e];t?.status===`queued`&&(t.validationErrors&&Object.keys(t.validationErrors).length>0&&--r.validationFailedCount,r.deletedIndexes.add(e),r.rowStates[e]={status:`deleted`,fieldErrors:void 0})}),J(e,{total:Ge(r),validationFailedCount:r.validationFailedCount,rowStates:r.rowStates}))}function ot(e,t,n){let r=q(e)?.rowStates?.[t];if(!r?.fieldErrors?.some(e=>n in e))return;let i=r.fieldErrors.filter(e=>!(n in e));Q(e,t,{...r,fieldErrors:i.length>0?i:void 0})}function st(e){if(typeof e!=`object`||!e)return!1;let t=e;return t.isAxiosError===!0||t.response!==void 0||typeof t.status==`number`||typeof t.statusCode==`number`}function ct(e){let t=e,n=t?.response?.status??t?.status??t?.statusCode;return typeof n==`number`?n:void 0}function lt(e){let t=e;return t?.response?.data??t?.data}function ut(e){if(!st(e))return;let t=ct(e);return t===void 0?`network`:t===401?`unauthorized`:t===403?`forbidden`:t===404?`notFound`:t===400?`badRequest`:t>=500?`server`:`unknown`}function dt(e,t,n){let r=ut(e);if(r!==void 0)switch(r){case`network`:return`网络异常, ${n}`;case`unauthorized`:return`登录已过期, ${n}`;case`forbidden`:return`没有${t}权限, ${n}`;case`notFound`:return`${t}接口不存在, ${n}`;case`badRequest`:return`${t}参数错误, ${n}`;case`server`:return`服务器错误, ${n}`;default:return`${t}失败`}}var ft=300;function pt(e){return new Promise(t=>setTimeout(t,e))}async function mt(e,t,n){let{options:r}=t;t.controller=n,t.cancelRequested=!1;try{for(;!t.cancelRequested;){let i=t.cursorId===void 0?{}:{cursor_id:t.cursorId},a=await r.exportRows(i);if(n.signal.aborted)throw new DOMException(`任务已取消`,`AbortError`);if(t.total=a.count,a.results.length===0)break;t.rows=t.rows.concat(a.results);let o=t.rows.length;J(e,{total:t.total,processed:o,samples:be(q(e)?.samples??[],o)});let s=a.results[a.results.length-1]?.id;if(typeof s!=`number`)throw Error(`导出数据缺少 id`);t.cursorId=s}if(t.cancelRequested){J(e,{status:`canceled`,pausing:!1,canceling:!1,finalizing:!1});return}if(t.rows.length===0)throw Error(`没有可导出的数据`);J(e,{finalizing:!0}),await pt(ft);let i=await ge(t.rows,r.fieldSchemas,n.signal);if(n.signal.aborted)throw new DOMException(`任务已取消`,`AbortError`);try{B(i,r.fileName)}catch(e){console.error(`自动下载失败: ${e}`)}J(e,{status:`completed`,pausing:!1,finalizing:!1,canceling:!1,total:t.rows.length,processed:t.rows.length,blob:i})}catch(t){if(n.signal.aborted){J(e,{status:`canceled`,pausing:!1,finalizing:!1,canceling:!1});return}J(e,{status:`failed`,pausing:!1,finalizing:!1,canceling:!1,errorMessage:ht(t)})}finally{t.controller=null,r.onFinished?.()}}function ht(e){return dt(e,`导出`,`导出失败`)??(e instanceof Error&&e.message?e.message:`导出失败`)}function gt(e,t){let n=new AbortController;K.set(e,n),mt(e,t,n).finally(()=>{K.delete(e),W.delete(e)})}function _t(e){let t=Me(),n={id:t,type:`export`,title:e.title,status:`running`,total:0,processed:0,fileName:e.fileName,samples:[]},r={options:e,rows:[],total:0,cancelRequested:!1,controller:null};return W.set(t,r),Ne(n),gt(t,r),t}function vt(e,t){try{return B(e,t),!0}catch(e){return console.error(`下载失败: ${e}`),!1}}function yt(e){let t=q(e);return t?.type!==`export`||!t.blob||!t.fileName?!1:vt(t.blob,t.fileName)}function bt(e){let t=q(e);if(!t)return;if(t.status===`paused`){J(e,{status:`canceled`,pausing:!1,canceling:!1,rowStates:(t.rowStates??[]).map(e=>e.status===`queued`||e.status===`running`?{status:`canceled`}:e)});let n=G.get(e);G.delete(e),Ve(e),n?.options.onFinished?.();return}if(t.status!==`running`)return;if(t.type===`export`){if(t.canceling||t.finalizing)return;let n=W.get(e);if(!n)return;n.cancelRequested=!0,n.controller?.abort(),J(e,{canceling:!0});return}if(t.canceling)return;let n=G.get(e);n&&(n.cancelRequested=!0,J(e,{canceling:!0}))}function xt(e){let t=q(e);t&&(t.status===`running`&&K.get(e)?.abort(),W.delete(e),G.delete(e),Ve(e),Pe(e))}function St(){He(),Fe()}function Ct(e){let t=(0,h.useCallback)(()=>e?je().find(t=>t.id===e):void 0,[e]);return(0,h.useSyncExternalStore)(Ae,t)}function wt(e){if(e.canceling)return`正在取消`;if(e.finalizing)return`正在生成文件`;switch(e.status){case`running`:return`进行中`;case`paused`:return`已暂停`;case`completed`:return`已完成`;case`failed`:return`失败`;case`canceled`:return`已取消`}}function Tt(e){if(e.canceling)return`warning`;if(e.finalizing)return`processing`}function Et(e){switch(e.status){case`failed`:return`exception`;case`completed`:return`success`;default:return`normal`}}var Dt=({taskId:e,onClose:t})=>{let n=Ct(e),{message:r}=m.App.useApp();if(!n)return null;let i=n.status===`completed`||n.status===`failed`||n.status===`canceled`,a=we(n),o=()=>{xt(n.id),t()},s=()=>{yt(n.id)||r.error(`文件不存在`)},c=wt(n);return(0,g.jsx)(m.Modal,{title:n.title,open:!0,maskClosable:!1,closable:i,keyboard:i,onCancel:()=>{i&&o()},footer:i?(0,g.jsxs)(m.Flex,{justify:`flex-end`,gap:8,children:[n.status===`completed`?(0,g.jsx)(m.Button,{onClick:s,children:`重新下载`}):null,(0,g.jsx)(m.Button,{type:`primary`,onClick:o,children:`关闭`})]}):(0,g.jsx)(m.Flex,{justify:`flex-end`,children:(0,g.jsx)(m.Button,{danger:!0,loading:n.canceling,disabled:n.canceling||n.finalizing,onClick:()=>bt(n.id),children:n.canceling?`取消中`:`取消任务`})}),children:(0,g.jsxs)(m.Flex,{vertical:!0,gap:12,children:[(0,g.jsxs)(m.Flex,{justify:`space-between`,align:`center`,gap:12,children:[(0,g.jsxs)(m.Typography.Text,{type:`secondary`,children:[`已导出 `,Se(n).toLocaleString(),` / 总数 `,n.total>0?n.total.toLocaleString():`--`]}),(0,g.jsx)(m.Tag,{color:Tt(n),children:c})]}),(0,g.jsx)(m.Progress,{percent:a,format:()=>Te(a),status:Et(n),size:`small`}),n.errorMessage?(0,g.jsx)(m.Typography.Text,{type:`danger`,children:n.errorMessage}):null]})})};function Ot(){let[e,t]=(0,h.useState)(),n=(0,h.useRef)(void 0);return(0,h.useEffect)(()=>{n.current=e},[e]),(0,h.useEffect)(()=>()=>{n.current&&xt(n.current)},[]),[e,t]}var kt=({title:e,fieldSchemas:t,buttonText:n=`导出`,disabled:r,exportRows:i,beforeExport:a,afterExport:o,onModalClose:s})=>{let{message:c}=m.App.useApp(),[l,u]=Ot();return(0,g.jsxs)(g.Fragment,{children:[(0,g.jsx)(m.Tooltip,{title:`导出 Excel`,children:(0,g.jsx)(m.Button,{type:`default`,icon:(0,g.jsx)(p.DownloadOutlined,{}),disabled:r,onClick:async()=>{try{await a?.()}catch(e){c.error(e instanceof Error?e.message:`导出已取消`);return}u(_t({title:`${e}导出`,fileName:H(e),fieldSchemas:t,exportRows:i,onFinished:o}))},children:n})}),l?(0,g.jsx)(Dt,{taskId:l,onClose:()=>{u(void 0),s?.()}}):null]})},{Text:At}=m.Typography,jt=({missingTitles:e,headerMessages:t})=>(0,g.jsxs)(m.Flex,{vertical:!0,gap:4,children:[e.length>0?(0,g.jsx)(At,{children:`缺少必填列: ${e.join(`, `)}`}):null,t.map((e,t)=>(0,g.jsx)(At,{children:e},t))]});function Mt(e){return e==null||e===``?``:Array.isArray(e)?b(e):String(e)}var Nt=({field:e,record:t,disabled:n,onChange:r,onSave:i})=>{let{token:a}=m.theme.useToken(),[o,s]=(0,h.useState)(!1),[c,l]=(0,h.useState)(!1),u=t.values[e.key];if(o&&!n)return e.type===`boolean`?(0,g.jsx)(m.Select,{autoFocus:!0,open:!0,size:`small`,style:{width:`100%`},value:typeof u==`string`?u:void 0,options:[{value:e.property.true_label,label:e.property.true_label},{value:e.property.false_label,label:e.property.false_label}],onChange:e=>{r(e),i(e),s(!1)},onBlur:()=>s(!1)}):e.type===`single_choice`?(0,g.jsx)(m.Select,{autoFocus:!0,open:!0,size:`small`,style:{width:`100%`},value:typeof u==`string`?u:void 0,options:Object.keys(e.property.option_map).map(e=>({value:e,label:e})),onChange:e=>{r(e),i(e),s(!1)},onBlur:()=>s(!1)}):e.type===`multiple_choice`?(0,g.jsx)(m.Select,{autoFocus:!0,open:!0,mode:`multiple`,size:`small`,style:{width:`100%`},value:Array.isArray(u)?u:[],options:Object.keys(e.property.option_map).map(e=>({value:e,label:e})),onChange:r,onBlur:()=>{s(!1),i(u)}}):e.type===`number`?(0,g.jsx)(m.InputNumber,{autoFocus:!0,size:`small`,style:{width:`100%`},value:typeof u==`number`||typeof u==`string`?u:void 0,onChange:r,onBlur:()=>{s(!1),i(u)},onPressEnter:()=>{s(!1),i(u)}}):(0,g.jsx)(m.Input,{autoFocus:!0,size:`small`,value:typeof u==`string`?u:``,placeholder:e.type===`list`?`多个值用分号分隔(中英文均可)`:void 0,onChange:e=>r(e.target.value),onBlur:()=>{s(!1),i(u)},onPressEnter:()=>{s(!1),i(u)}});let d=Mt(u);return(0,g.jsx)(`div`,{title:d||void 0,style:{height:24,boxSizing:`border-box`,display:`flex`,alignItems:`center`,minWidth:0,padding:`0 7px`,lineHeight:`22px`,whiteSpace:`nowrap`,overflow:`hidden`,border:`1px solid ${c&&!n?a.colorBorder:`transparent`}`,borderRadius:a.borderRadiusSM,cursor:n?`default`:`text`},onMouseEnter:()=>l(!0),onMouseLeave:()=>l(!1),onClick:()=>{n||s(!0)},children:(0,g.jsx)(`span`,{style:{minWidth:0,overflow:`hidden`,textOverflow:`ellipsis`,whiteSpace:`nowrap`},children:d})})};function Pt(e){if(e.canceling)return{label:`正在取消`,color:`warning`};switch(e.status){case`running`:return{label:`进行中`,color:`processing`};case`paused`:return{label:`已暂停`,color:`warning`};case`completed`:return{label:`已完成`,color:`success`};case`failed`:return{label:`失败`,color:`error`};case`canceled`:return{label:`已取消`,color:`warning`}}}function Ft(e,t){if(e.canceling)return`正在取消...`;switch(e.status){case`running`:return`预计剩余 ${Ee(t)}`;default:return null}}function It(e){switch(e.status){case`failed`:return`exception`;case`completed`:return`success`;default:return`normal`}}var Lt={valid:{label:`已校验`,color:`success`},invalid:{label:`校验失败`,color:`error`}},Rt={pending:{label:`待导入`,color:`default`},running:{label:`进行中`,color:`processing`},completed:{label:`已完成`,color:`success`},failed:{label:`导入失败`,color:`error`},canceled:{label:`已取消`,color:`warning`}};function zt(e){return Object.keys(e.errors).length>0?`invalid`:`valid`}function Bt(e,t,n){if(!t||e.taskIndex===void 0)return`pending`;switch(n?.rowStates?.[e.taskIndex]?.status){case`running`:return`running`;case`completed`:return`completed`;case`failed`:return`failed`;case`canceled`:return`canceled`;default:return`pending`}}function Vt(e,t){let[n,r]=(0,h.useState)(e);return(0,h.useEffect)(()=>{let n=setTimeout(()=>r(e),t);return()=>clearTimeout(n)},[e,t]),n}function Ht(e,t){let[n,r]=(0,h.useState)(e),i=(0,h.useRef)(e),a=(0,h.useRef)(0),o=(0,h.useRef)(null);return(0,h.useEffect)(()=>{i.current=e;let n=Date.now()-a.current;n>=t?(a.current=Date.now(),r(e)):o.current===null&&(o.current=setTimeout(()=>{o.current=null,a.current=Date.now(),r(i.current)},t-n))},[e,t]),(0,h.useEffect)(()=>()=>{o.current!==null&&clearTimeout(o.current)},[]),n}var Ut=({open:e,title:t,fieldSchemas:n,rows:r,taskId:i,includedKeys:a,onChangeCell:o,onSaveCell:s,onDelete:c,onConfirm:l,onClose:u})=>{let[d,f]=(0,h.useState)(`all`),[_,v]=(0,h.useState)(`all`),[y,b]=(0,h.useState)(``),x=Vt(y,300),S=()=>{f(`all`),v(`all`),b(``)},C=Ct(i),w=(0,h.useRef)(void 0);(0,h.useEffect)(()=>{C&&(w.current=C)},[C]);let T=(0,h.useMemo)(()=>new Set(a),[a]),E=n.filter(e=>T.has(e.key)),D=w.current,O=C??(D?.id===i?D:void 0),k=O?Pt(O):void 0,A=!!(O&&O.status!==`completed`&&O.status!==`failed`&&O.status!==`canceled`),ee=Ht(O?.status===`running`?xe(O):null,1e3),j=O?Ft(O,ee):null,M=e=>e.taskIndex===void 0?void 0:O?.rowStates?.[e.taskIndex],N=!(!C||C.status!==`failed`&&C.status!==`paused`),te=e=>{if(!i)return!0;let t=M(e)?.status;return N&&(t===`queued`||t===`failed`)?!0:N&&e.taskIndex===void 0&&Object.keys(e.errors).length>0},ne=e=>!i||C?.status===`paused`&&M(e)?.status===`queued`,P=(0,h.useMemo)(()=>[`valid`,`invalid`].map(e=>({value:e,label:Lt[e].label})),[]),re=(0,h.useMemo)(()=>[`pending`,`running`,`completed`,`failed`,`canceled`].map(e=>({value:e,label:Rt[e].label})),[]),F=O?.status===`running`,ie=F?``:x,I=!F&&d!==`all`&&P.some(e=>e.value===d)?d:`all`,L=!F&&_!==`all`&&re.some(e=>e.value===_)?_:`all`,ae=I!==`all`||ie.trim()!==``,R=L!==`all`,oe=ae||R,z=(0,h.useMemo)(()=>{if(!ae)return r;let e=ie.trim().toLowerCase();return r.filter(t=>I!==`all`&&zt(t)!==I?!1:!e||Object.values(t.values).some(t=>(Array.isArray(t)?t.join(` `):String(t??``)).toLowerCase().includes(e)))},[r,I,ie,ae]),se=Ht(O,300),ce=R?se:void 0,le=(0,h.useMemo)(()=>R?z.filter(e=>Bt(e,i,ce)===L):i&&O?z.slice():z,[z,L,R,ce,O,i]),ue=e=>{let t=Object.entries(e.errors);return(0,g.jsx)(m.Flex,{vertical:!0,gap:4,style:{maxWidth:320},children:t.map(([e,t])=>{let r=n.find(t=>t.key===e)?.title??e;return(0,g.jsxs)(m.Typography.Text,{children:[(0,g.jsx)(m.Typography.Text,{strong:!0,children:r}),`: `,t]},e)})})},de=e=>{let t=zt(e),n=Lt[t];return t===`invalid`?(0,g.jsx)(m.Popover,{trigger:`hover`,placement:`topRight`,title:`错误信息`,content:ue(e),children:(0,g.jsx)(m.Tag,{color:n.color,children:n.label})}):(0,g.jsx)(m.Tag,{color:n.color,children:n.label})},B=e=>{let t=M(e),r=t?.fieldErrors??[],i=t?.message;if(r.length===0)return(0,g.jsx)(m.Typography.Text,{children:i??`导入失败`});let a=new Map;r.forEach(e=>{let[t,r]=Object.entries(e)[0]??[],i=t===`detail`||t===`non_field_errors`?`错误`:n.find(e=>e.key===t)?.title??`数据`,o=a.get(i)??[];o.push(r),a.set(i,o)});let o=[...a.entries()],s=o.slice(0,3),c=o.length-s.length;return(0,g.jsxs)(m.Flex,{vertical:!0,gap:8,style:{maxWidth:360},children:[i?(0,g.jsx)(m.Typography.Text,{children:i}):null,s.map(([e,t])=>(0,g.jsxs)(m.Flex,{vertical:!0,gap:2,children:[(0,g.jsx)(m.Typography.Text,{strong:!0,children:e}),t.map((e,t)=>(0,g.jsxs)(m.Typography.Text,{children:[`• `,e]},t))]},e)),c>0?(0,g.jsxs)(m.Typography.Text,{type:`secondary`,children:[`还有 `,c,` 个字段错误`]}):null]})},fe=e=>{let t=Bt(e,i,O),n=Rt[t];if(t===`failed`){let t=M(e),r=(t?.fieldErrors?.length??0)+ +!!t?.message,i=r>0?`导入失败(${r})`:n.label;return(0,g.jsx)(m.Popover,{trigger:`hover`,placement:`topRight`,title:`错误信息`,content:B(e),children:(0,g.jsx)(m.Tag,{color:n.color,children:i})})}return(0,g.jsx)(m.Tag,{color:n.color,children:n.label})},pe=e=>(0,g.jsx)(m.Button,{type:`primary`,danger:!0,size:`small`,disabled:!ne(e),icon:(0,g.jsx)(p.DeleteOutlined,{}),onClick:()=>{c(e),C&&e.taskIndex!==void 0&&at(C.id,[e.taskIndex])},children:`删除`}),me=[{key:`rowNumber`,title:`行号`,dataIndex:`rowNumber`,width:60,fixed:`left`},...E.map(e=>({key:e.key,title:e.title,dataIndex:e.key,width:160,render:(t,n)=>(0,g.jsx)(Nt,{field:e,record:n,disabled:!te(n),onChange:t=>o(n,e,t),onSave:t=>s(n,e,t)})})),{key:`dataStatus`,title:`数据状态`,width:100,fixed:`right`,render:(e,t)=>de(t)},{key:`importStatus`,title:`导入状态`,width:110,fixed:`right`,render:(e,t)=>fe(t)},{key:`action`,title:`操作`,width:80,fixed:`right`,render:(e,t)=>pe(t)}],he=Math.max(1200,60+E.length*160+100+110+80),ge=O&&O.total>0?we(O):0,_e=O?.failureCount??O?.failures?.length??0,V=O?.validationFailedCount??r.filter(e=>Object.keys(e.errors).length>0).length,ve=r.filter(e=>Object.keys(e.errors).length>0).length,H=r.length>0&&ve===r.length;return(0,g.jsx)(g.Fragment,{children:(0,g.jsxs)(m.Modal,{title:i?`${t}导入`:`${t}导入预览`,open:e,width:`min(1400px, 96vw)`,maskClosable:!1,closable:!1,keyboard:!1,onCancel:()=>{A||u()},footer:(()=>{if(!i)return(0,g.jsxs)(m.Flex,{justify:`space-between`,align:`center`,gap:8,wrap:!0,children:[(0,g.jsx)(`span`,{children:r.length>0&&ve>0?(0,g.jsx)(m.Typography.Text,{type:H?`danger`:`secondary`,children:H?`全部行校验失败, 请先修正后再导入`:`有 ${ve} 行校验失败, 不会导入`}):null}),(0,g.jsxs)(m.Flex,{gap:8,children:[(0,g.jsx)(m.Button,{onClick:u,children:`取消`}),(0,g.jsx)(m.Button,{type:`primary`,disabled:r.length===0||H,onClick:()=>{S(),l()},children:`开始导入`})]})]});if(!C||!O)return(0,g.jsx)(m.Flex,{justify:`flex-end`,children:(0,g.jsx)(m.Button,{onClick:u,children:`关闭`})});let e=O.status===`running`,t=O.status===`paused`;return(0,g.jsxs)(m.Flex,{justify:`flex-end`,gap:8,children:[e?(0,g.jsxs)(g.Fragment,{children:[(0,g.jsx)(m.Button,{danger:!0,loading:O.canceling,disabled:O.canceling,onClick:()=>bt(O.id),children:O.canceling?`取消中`:`取消任务`}),(0,g.jsx)(m.Button,{loading:O.pausing,disabled:O.canceling,onClick:()=>nt(O.id),children:`暂停`})]}):null,t?(0,g.jsxs)(g.Fragment,{children:[(0,g.jsx)(m.Button,{danger:!0,onClick:()=>bt(O.id),children:`取消任务`}),(0,g.jsx)(m.Button,{type:`primary`,onClick:()=>{S(),tt(O.id)},children:`继续导入`})]}):null,!e&&!t?(0,g.jsx)(m.Button,{type:`primary`,onClick:u,children:`关闭`}):null]})})(),children:[O&&k?(0,g.jsxs)(m.Flex,{vertical:!0,gap:4,style:{marginBottom:12},children:[(0,g.jsxs)(m.Flex,{justify:`space-between`,align:`center`,children:[(0,g.jsxs)(m.Typography.Text,{type:`secondary`,children:[`已导入 `,Se(O).toLocaleString(),` / 总数 `,O.total.toLocaleString()]}),(0,g.jsxs)(m.Flex,{align:`center`,gap:8,children:[j?(0,g.jsx)(m.Typography.Text,{type:`secondary`,children:j}):null,V>0?(0,g.jsxs)(m.Tag,{color:`error`,children:[`校验失败 `,V,` 条`]}):null,_e>0?(0,g.jsxs)(m.Tag,{color:`error`,children:[`导入失败 `,_e,` 条`]}):null,(0,g.jsx)(m.Tag,{color:k.color,children:k.label})]})]}),(0,g.jsx)(m.Progress,{percent:ge,format:()=>Te(ge),status:It(O),size:`small`})]}):i?null:(0,g.jsxs)(m.Flex,{vertical:!0,gap:4,style:{marginBottom:12},children:[(0,g.jsxs)(m.Flex,{justify:`space-between`,align:`center`,children:[(0,g.jsxs)(m.Typography.Text,{type:`secondary`,children:[`总数 `,r.length.toLocaleString()]}),(0,g.jsxs)(m.Flex,{align:`center`,gap:8,children:[V>0?(0,g.jsxs)(m.Tag,{color:`error`,children:[`校验失败 `,V,` 条`]}):null,(0,g.jsx)(m.Tag,{children:`待导入`})]})]}),(0,g.jsx)(m.Progress,{percent:0,format:()=>`0.0%`,size:`small`})]}),(0,g.jsxs)(m.Flex,{justify:`space-between`,align:`center`,gap:8,wrap:!0,style:{marginBottom:8},children:[(0,g.jsxs)(m.Flex,{align:`center`,gap:8,wrap:!0,children:[(0,g.jsx)(m.Input,{allowClear:!0,disabled:F,placeholder:`搜索所有字段`,value:F?``:y,style:{width:260},onChange:e=>{b(e.target.value)}}),(0,g.jsx)(m.Select,{allowClear:!0,disabled:F,placeholder:`数据状态`,value:I===`all`?void 0:I,options:P,style:{width:140},onChange:e=>{f(e??`all`)}}),(0,g.jsx)(m.Select,{allowClear:!0,disabled:F,placeholder:`导入状态`,value:L===`all`?void 0:L,options:re,style:{width:140},onChange:e=>{v(e??`all`)}})]}),oe?(0,g.jsxs)(m.Typography.Text,{type:`secondary`,children:[`筛选出 `,le.length,` 条`]}):null]}),(0,g.jsx)(m.Table,{rowKey:`key`,size:`middle`,tableLayout:`fixed`,virtual:!0,columns:me,dataSource:le,pagination:!1,scroll:{x:he,y:520},locale:{emptyText:oe?`没有符合条件的行`:void 0}})]})})},Wt=[/期望为一个包含物件的列表/,/expected a list/i,/得到的类型是/,/not a list/i];function Gt(e){return Wt.some(t=>t.test(e))?`数据格式不正确, 请检查导入内容`:e}function Kt(e,t){if(Object.keys(e).length===0)return{success:!0};let n=[],r;return Object.entries(e).forEach(([e,i])=>{let a=Array.isArray(i)?i:[i];if(e===`detail`||e===`non_field_errors`||!t.has(e)){let t=a.map(e=>Gt(String(e))).join(`; `);r=e===`detail`||e===`non_field_errors`?t:`${e}: ${t}`}else a.forEach(t=>n.push({[e]:Gt(String(t))}))}),{success:!1,...r?{message:r}:{},...n.length>0?{fieldErrors:n}:{}}}function qt(e,t,n){let r={};return t.forEach(t=>{if(!n.includes(t.key))return;let i=P(t,e.values[t.key]),a=j(i.trim()===``?null:i,t);if(!a.validateSuccess)throw Error(a.validateMessage);r[t.key]=a.validateValue??null}),r}var Jt=`缺少列: `;function Yt(e){let t=lt(e);if(t&&typeof t==`object`){let e=t;if(typeof e.detail==`string`)return e.detail;let n=Object.entries(e)[0];if(n){let[e,t]=n,r=Array.isArray(t)?t[0]:t;return`${e}: ${String(r)}`}}return dt(e,`导入`,`任务已暂停`)??(e instanceof Error&&e.message?e.message:`导入失败, 任务已暂停`)}var Xt=({title:e,fieldSchemas:t,buttonText:n=`导入`,batchSize:r=20,importRows:i,beforeImport:a,afterImport:o,onModalClose:s})=>{let[c,l]=(0,h.useState)(!1),[u,d]=(0,h.useState)([]),[f,v]=Ot(),[y,b]=(0,h.useState)(`empty`),[x,S]=(0,h.useState)(!1),[C,w]=(0,h.useState)(!1),[T,E]=(0,h.useState)([]),{modal:D,message:O}=m.App.useApp(),k=(0,h.useRef)(null),A=(0,h.useMemo)(()=>_(t),[t]),ee=(0,h.useMemo)(()=>new Set([...T].filter(e=>A.some(t=>t.key===e))),[A,T]),M=()=>k.current?.click(),N=(e,t)=>{D.warning({title:t??(e.missingTitles.length>0?`文件表头不完整`:`文件检查未通过`),width:480,content:(0,g.jsx)(jt,{...e}),okCancel:!0,okText:`重新选择文件`,cancelText:`关闭`,closable:!0,onOk:M})},te=async e=>{if(e.size>20971520)O.error(`文件大小超过 20MB, 请拆分后再导入`);else{v(void 0),E([]),S(!0);try{let{headerMessages:t,formulaMessages:n,rows:r,includedKeys:i}=await ve(e,A);if(n.length>0){N({missingTitles:[],headerMessages:n},`文件里的公式还没有计算结果`);return}if(t.length>0){N({missingTitles:t.filter(e=>e.startsWith(Jt)).map(e=>e.slice(5)),headerMessages:t.filter(e=>!e.startsWith(Jt))});return}if(r.length===0){O.error(`文件里没有数据行`);return}try{await a?.(r)}catch(e){O.error(e instanceof Error?e.message:`导入已取消`);return}E(i),b(`${e.name}-${Date.now()}`),d(r),l(!0)}catch(e){console.error(`导入文件解析失败: ${e}`),O.error(`导入文件解析失败, 请确认上传的是 Excel 文件`)}finally{S(!1)}}};return(0,g.jsxs)(g.Fragment,{children:[(0,g.jsxs)(m.Space.Compact,{block:!0,children:[(0,g.jsx)(m.Tooltip,{title:`Excel 导入`,children:(0,g.jsx)(m.Button,{type:`default`,icon:(0,g.jsx)(p.UploadOutlined,{}),loading:x,disabled:x,onClick:M,children:n})}),(0,g.jsx)(m.Tooltip,{title:`Excel 导入模板`,children:(0,g.jsx)(m.Button,{type:`default`,icon:(0,g.jsx)(p.FileOutlined,{}),loading:C,onClick:async()=>{w(!0);try{await V(A,`${e}导入模板`)}catch(e){console.error(`模板下载失败: ${e}`),O.error(`模板下载失败`)}finally{w(!1)}},children:`下载模板`})})]}),(0,g.jsx)(`input`,{ref:k,type:`file`,accept:`.xlsx`,style:{display:`none`},onChange:e=>{let t=e.target.files?.[0];e.target.value=``,t&&te(t)}}),(0,g.jsx)(Ut,{open:c,title:e,fieldSchemas:A,rows:u,taskId:f,includedKeys:T,onChangeCell:(e,t,n)=>{if(!T.includes(t.key))return;let r=P(t,n),i=j(r.trim()===``?null:r,t);d(r=>r.map(r=>{if(r.key!==e.key)return r;let a={...r.errors};return i.validateSuccess?delete a[t.key]:a[t.key]=i.validateMessage,{...r,values:{...r.values,[t.key]:n},errors:a}}))},onSaveCell:(e,t,n)=>{if(!T.includes(t.key))return;let r={...e.values,[t.key]:n},i={};A.forEach(e=>{if(!T.includes(e.key))return;let t=P(e,r[e.key]),n=j(t.trim()===``?null:t,e);n.validateSuccess||(i[e.key]=n.validateMessage)});let a={...e,values:r,errors:i};d(t=>t.map(t=>t.key===e.key?a:t)),f&&e.taskIndex!==void 0&&(ot(f,e.taskIndex,t.key),it(f,e.taskIndex,i),rt(f,e.taskIndex,a))},onDelete:e=>{d(t=>t.filter(t=>t.key!==e.key))},onConfirm:async()=>{let t=u;if(t.length===0){O.error(`没有可导入的数据`);return}if(t.every(e=>Object.keys(e.errors).length>0)){O.error(`所有行都有校验错误, 请先修正后再导入`);return}let n=t.map((e,t)=>({...e,taskIndex:t}));d(n);let a=et({title:`${e}导入`,rows:n,fieldSchemas:A,includedKeys:T,batchSize:r,importRows:async e=>{try{let t=await i(e.map(e=>qt(e,A,T)));if(t.length!==e.length)throw new Y(`导入接口返回结果数量不正确, 任务已暂停`);return t.map(e=>Kt(e,ee))}catch(e){throw e instanceof Y?e:new Y(Yt(e))}},onFinished:o});v(a)},onClose:()=>{f&&xt(f),l(!1),v(void 0),d([]),E([]),s?.()}},y)]})};exports.ExportButton=kt,exports.ImportButton=Xt,exports.MAX_IMPORT_FILE_SIZE=M,exports.MULTI_VALUE_SEPARATOR=v,exports.exportRowsToFile=ye,exports.importableFields=_,exports.joinMultiValues=b,exports.resetTasks=St,exports.splitMultiValues=x,exports.validateBooleanField=T,exports.validateDateField=E,exports.validateDateTimeField=O,exports.validateField=j,exports.validateListField=k,exports.validateMultipleChoiceField=ee,exports.validateNumberField=w,exports.validateSingleChoiceField=A,exports.validateTextField=C,exports.validateTimeField=D;
|
|
6
|
+
`),c=0;for(let e of s){let t=0;for(let n of e){let e=n.charCodeAt(0);t+=e>255||e>=65280&&e<=65519?2:1}c=Math.max(c,t)}let l=c*7*(a/11)*o;(!r[n]||l>r[n])&&(r[n]=l)})}),r.forEach((r,i)=>{let a=r/7;e.getColumn(i+1).width=Math.min(Math.max(a,t),n)})}var de=`application/vnd.openxmlformats-officedocument.spreadsheetml.sheet`;function B(e,t){(0,d.saveAs)(e,`${t}.xlsx`)}var fe;function pe(){return fe??=import(`exceljs`).then(e=>e.default??e,e=>{throw fe=void 0,e}),fe}function me(){return new Promise(e=>{requestAnimationFrame(()=>setTimeout(e,0))})}function he(e){if(e?.aborted)throw new DOMException(`任务已取消`,`AbortError`)}async function ge(e,t,n){let r=await pe();he(n),await me();let i=new r.Workbook;se(i.addWorksheet(`Sheet`),e,t);let a=await i.xlsx.writeBuffer();return he(n),new Blob([a],{type:de})}async function _e(e,t,n){B(await ge(e,t),n)}async function V(e,t){let n=await pe();await me();let r=new n.Workbook;le(r.addWorksheet(`导入模板`),e);let i=await r.xlsx.writeBuffer();B(new Blob([i],{type:de}),t)}async function ve(e,t){let n=await pe(),r=await e.arrayBuffer();await me();let i=new n.Workbook;if(await i.xlsx.load(r),i.worksheets.length>1)return{headerMessages:[`文件包含多个工作表, 只支持单个工作表, 请删除其他工作表后再导入`],formulaMessages:[],rows:[],includedKeys:[]};let a=i.worksheets[0];return a?R(a,t):{headerMessages:[`文件里没有工作表`],formulaMessages:[],rows:[],includedKeys:[]}}function H(e){return`${e}_${(0,l.default)().format(`YYYYMMDDHHmmss`)}`}async function ye(e){let{title:t,fieldSchemas:n,rows:r}=e;if(r.length===0)throw Error(`没有可导出的数据`);await _e(r,n,H(t))}function be(e,t){let n=Date.now();return[...e,{time:n,processed:t}].filter(e=>n-e.time<=15e3).slice(-20)}function xe(e){if(e.status!==`running`||e.total<=0)return null;let t=Math.max(0,e.total-(e.validationFailedCount??0)-e.processed);if(t===0)return 0;if(e.samples.length<2)return null;let n=e.samples[0],r=e.samples[e.samples.length-1],i=(r.time-n.time)/1e3,a=r.processed-n.processed;return i<=0||a<=0?null:t/(a/i)}function Se(e){return e.type===`import`?e.successCount===void 0?e.rowStates?.filter(e=>e.status===`completed`).length??e.processed:e.successCount:e.processed}function Ce(e){return e.total<=0?0:Math.min(100,Se(e)/e.total*100)}function we(e){if(e.finalizing)return 100;let t=Ce(e);return t>=100?100:Math.trunc(t*10)/10}function Te(e){return`${(Math.trunc(e*10)/10).toFixed(1)}%`}function Ee(e){if(e===null)return`计算中...`;let t=Math.ceil(e);return t<60?`约 ${t} 秒`:`约 ${Math.floor(t/60)} 分 ${t%60} 秒`}var U={tasks:[]},De=new Set,W=new Map,G=new Map,K=new Map;function Oe(){U={...U},De.forEach(e=>e())}function ke(e){return De.add(e),()=>{De.delete(e)}}function Ae(e){return ke(e)}function je(){return U.tasks}function Me(){return`task-${Date.now()}-${Math.random().toString(36).slice(2,10)}`}function q(e){return U.tasks.find(t=>t.id===e)}function J(e,t){let n=!1,r=U.tasks.map(r=>r.id===e?(n=!0,{...r,...t}):r);n&&(U={...U,tasks:r},Oe())}function Ne(e){U={...U,tasks:[...U.tasks,e]},Oe()}function Pe(e){U={...U,tasks:U.tasks.filter(t=>t.id!==e)},Oe()}function Fe(){K.forEach(e=>e.abort()),K.clear(),W.clear(),G.clear(),U={tasks:[]},Oe()}var Y=class extends Error{constructor(e){super(e),this.name=`ImportPauseError`}},Ie=100,Le=20,Re=200,ze=100,X=new Set,Z=null;function Q(e,t,n){let r=G.get(e);r&&(r.rowStates[t]={...r.rowStates[t],...n},Be(e))}function Be(e){X.add(e),Z===null&&(Z=setTimeout(()=>{Z=null;let e=[...X];X.clear(),e.forEach(We)},ze))}function Ve(e){X.delete(e)}function He(){X.clear(),Z!==null&&(clearTimeout(Z),Z=null)}function Ue(e,t){return{processed:t.processed,total:Ge(t),successCount:t.successCount,failureCount:t.failures.length,validationFailedCount:t.validationFailedCount,failures:t.failures,rowStates:t.rowStates,samples:be(q(e)?.samples??[],t.processed)}}function We(e){let t=G.get(e);t&&q(e)&&J(e,Ue(e,t))}function Ge(e){return e.options.rows.length-e.deletedIndexes.size}function Ke(e){return`成功 ${e.successCount} 条, 失败 ${e.failures.length} 条, 可修正失败行后继续`}function qe(e){if(e===void 0)return Le;let t=Math.floor(e);return!Number.isFinite(t)||t<1?Le:Math.min(t,Re)}async function Je(e,t,n){let r=t.options.rows.length;if(t.controller=n,t.pauseRequested=!1,t.cancelRequested=!1,t.runFailureCount=0,r===0){J(e,{status:`failed`,pausing:!1,errorMessage:`没有可导入的数据`}),t.options.onFinished?.();return}J(e,{...Ue(e,t),status:`running`,samples:[{time:Date.now(),processed:t.processed}]});let i=qe(t.options.batchSize),a=Math.min(Math.max(t.options.concurrency??3,1),5),o=()=>{let e=[];for(;e.length<i;){let n=t.nextIndex;if(t.nextIndex+=1,n>=r)break;t.deletedIndexes.has(n)||t.rowStates[n]?.status!==`completed`&&(t.skippedIndexes.has(n)||e.push(n))}return e},s=async()=>{for(;;){if(n.signal.aborted||t.pauseRequested||t.cancelRequested)return;let r=o();if(r.length===0)return;r.forEach(t=>{Q(e,t,{status:`running`,message:void 0,fieldErrors:void 0})});try{let i=r.map(e=>t.options.rows[e]),a=await t.options.importRows(i);if(n.signal.aborted)return;if(a.length!==r.length)throw new Y(`导入接口返回结果数量不正确, 任务已暂停`);a.forEach((n,i)=>{let a=r[i],o=t.options.rows[a];n.success?(t.successCount+=1,Q(e,a,{status:`completed`,fieldErrors:void 0})):(t.failures.push({index:a,rowNumber:o.rowNumber,message:n.message??`导入失败`,fieldErrors:n.fieldErrors}),Q(e,a,{status:`failed`,message:n.message,fieldErrors:n.fieldErrors}),t.runFailureCount+=1,t.runFailureCount>Ie&&(t.pauseRequested=!0))})}catch(i){if(n.signal.aborted)return;let a=i instanceof Y,o=`${i instanceof Error?i.message:`导入失败`}(该批结果未知,重试可能重复)`;r.forEach(n=>{t.failures.push({index:n,rowNumber:t.options.rows[n].rowNumber,message:o}),Q(e,n,{status:`failed`,message:o}),t.runFailureCount+=1}),a?(t.pauseRequested=!0,n.abort()):t.runFailureCount>Ie&&(t.pauseRequested=!0)}finally{t.processed+=r.length,Be(e)}}},c=Math.min(a,Math.max(1,r));await Promise.all(Array.from({length:c},()=>s())),t.controller=null,q(e)&&Qe(e,t,n)}function Ye(e){e.rowStates=e.rowStates.map(e=>e.status===`queued`||e.status===`running`?{status:`canceled`}:e)}function Xe(e){e.rowStates=e.rowStates.map(e=>e.status===`running`?{status:`queued`,validationErrors:e.validationErrors}:e)}function Ze(e){return e.failures.length>0?`累计失败 ${e.failures.length} 条, 任务已暂停, 可继续导入`:void 0}function $(e,t,n){J(e,{...Ue(e,t),pausing:!1,...n}),n.status!==`paused`&&t.options.onFinished?.()}function Qe(e,t,n){if(Ve(e),t.cancelRequested){Ye(t),$(e,t,{status:`canceled`,canceling:!1});return}if(t.pauseRequested&&n.signal.aborted){Xe(t),$(e,t,{status:`paused`,errorMessage:Ze(t)});return}if(n.signal.aborted){Ye(t),$(e,t,{status:`canceled`,canceling:!1});return}if(t.pauseRequested&&t.nextIndex<t.options.rows.length){$(e,t,{status:`paused`,errorMessage:Ze(t)});return}if(t.failures.length>0){$(e,t,{status:`paused`,errorMessage:Ke(t)});return}let r=[...t.skippedIndexes].filter(e=>!t.deletedIndexes.has(e)).length;r>0?$(e,t,{status:`paused`,errorMessage:`有 ${r} 条校验失败数据待修复`}):$(e,t,{status:`completed`})}function $e(e,t){let n=new AbortController;K.set(e,n),Je(e,t,n).finally(()=>{K.delete(e),X.delete(e),q(e)?.status!==`paused`&&G.delete(e)})}function et(e){let t=Me(),n=e.rows.map(e=>({status:`queued`,validationErrors:Object.keys(e.errors).length>0?e.errors:void 0})),r=new Set(e.rows.flatMap((e,t)=>Object.keys(e.errors).length>0?[t]:[])),i=r.size,a={id:t,type:`import`,title:e.title,status:`running`,total:e.rows.length,processed:0,canceling:!1,successCount:0,failureCount:0,validationFailedCount:i,rowStates:n,failures:[],samples:[]},o={options:e,nextIndex:0,processed:0,successCount:0,failures:[],rowStates:n,validationFailedCount:i,pauseRequested:!1,cancelRequested:!1,deletedIndexes:new Set,skippedIndexes:r,runFailureCount:0,controller:null};return G.set(t,o),Ne(a),$e(t,o),t}function tt(e){let t=q(e);if(!t||t.type!==`import`||t.status!==`paused`)return;let n=G.get(e);if(!n)return;let r=n.rowStates.filter(e=>e.status===`completed`).length,i=n.rowStates.map(e=>e.status===`completed`||e.status===`deleted`?e:{status:`queued`,validationErrors:e.validationErrors}),a=i.filter(e=>e.validationErrors&&Object.keys(e.validationErrors).length>0).length;n.rowStates=i,n.validationFailedCount=a,n.nextIndex=0,n.processed=r,n.successCount=r,n.failures=[],n.pauseRequested=!1,n.cancelRequested=!1,n.runFailureCount=0,J(e,{status:`running`,pausing:!1,canceling:!1,processed:r,successCount:r,failureCount:0,validationFailedCount:a,failures:[],rowStates:i,errorMessage:void 0}),$e(e,n)}function nt(e){let t=q(e);if(!t||t.type!==`import`||t.status!==`running`||t.canceling)return;let n=G.get(e);n&&(n.pauseRequested=!0,J(e,{pausing:!0}))}function rt(e,t,n){let r=q(e),i=G.get(e);if(!r||r.type!==`import`||r.status!==`paused`&&r.status!==`failed`||!i)return;let a=r.rowStates?.[t]?.status;(a===`queued`||a===`failed`)&&(i.options.rows[t]=n)}function it(e,t,n){let r=q(e),i=G.get(e);if(!r||r.type!==`import`||!i||r.status!==`paused`&&r.status!==`failed`)return;let a=Object.keys(n).length>0,o=i.rowStates[t]?.validationErrors,s=!!(o&&Object.keys(o).length>0);a?(i.skippedIndexes.add(t),s||(i.validationFailedCount+=1)):(i.skippedIndexes.delete(t),s&&--i.validationFailedCount),i.rowStates[t]={...i.rowStates[t],validationErrors:a?n:void 0},i.options.rows[t]={...i.options.rows[t],errors:n},J(e,{validationFailedCount:i.validationFailedCount,rowStates:i.rowStates})}function at(e,t){let n=q(e),r=G.get(e);n&&n.type===`import`&&n.status===`paused`&&r&&(t.forEach(e=>{let t=r.rowStates[e];t?.status===`queued`&&(t.validationErrors&&Object.keys(t.validationErrors).length>0&&--r.validationFailedCount,r.deletedIndexes.add(e),r.rowStates[e]={status:`deleted`,fieldErrors:void 0})}),J(e,{total:Ge(r),validationFailedCount:r.validationFailedCount,rowStates:r.rowStates}))}function ot(e,t,n){let r=q(e)?.rowStates?.[t];if(!r?.fieldErrors?.some(e=>n in e))return;let i=r.fieldErrors.filter(e=>!(n in e));Q(e,t,{...r,fieldErrors:i.length>0?i:void 0})}function st(e){if(typeof e!=`object`||!e)return!1;let t=e;return t.isAxiosError===!0||t.response!==void 0||typeof t.status==`number`||typeof t.statusCode==`number`}function ct(e){let t=e,n=t?.response?.status??t?.status??t?.statusCode;return typeof n==`number`?n:void 0}function lt(e){let t=e;return t?.response?.data??t?.data}function ut(e){if(!st(e))return;let t=ct(e);return t===void 0?`network`:t===401?`unauthorized`:t===403?`forbidden`:t===404?`notFound`:t===400?`badRequest`:t>=500?`server`:`unknown`}function dt(e,t,n){let r=ut(e);if(r!==void 0)switch(r){case`network`:return`网络异常, ${n}`;case`unauthorized`:return`登录已过期, ${n}`;case`forbidden`:return`没有${t}权限, ${n}`;case`notFound`:return`${t}接口不存在, ${n}`;case`badRequest`:return`${t}参数错误, ${n}`;case`server`:return`服务器错误, ${n}`;default:return`${t}失败`}}var ft=300;function pt(e){return new Promise(t=>setTimeout(t,e))}async function mt(e,t,n){let{options:r}=t;t.controller=n,t.cancelRequested=!1;try{for(;!t.cancelRequested;){let i=t.cursorId===void 0?{}:{cursor_id:t.cursorId},a=await r.exportRows(i);if(n.signal.aborted)throw new DOMException(`任务已取消`,`AbortError`);if(t.total=a.count,a.results.length===0)break;t.rows=t.rows.concat(a.results);let o=t.rows.length;J(e,{total:t.total,processed:o,samples:be(q(e)?.samples??[],o)});let s=a.results[a.results.length-1]?.id;if(typeof s!=`number`)throw Error(`导出数据缺少 id`);t.cursorId=s}if(t.cancelRequested){J(e,{status:`canceled`,pausing:!1,canceling:!1,finalizing:!1});return}if(t.rows.length===0)throw Error(`没有可导出的数据`);J(e,{finalizing:!0}),await pt(ft);let i=await ge(t.rows,r.fieldSchemas,n.signal);if(n.signal.aborted)throw new DOMException(`任务已取消`,`AbortError`);try{B(i,r.fileName)}catch(e){console.error(`自动下载失败: ${e}`)}J(e,{status:`completed`,pausing:!1,finalizing:!1,canceling:!1,total:t.rows.length,processed:t.rows.length,blob:i})}catch(t){if(n.signal.aborted){J(e,{status:`canceled`,pausing:!1,finalizing:!1,canceling:!1});return}J(e,{status:`failed`,pausing:!1,finalizing:!1,canceling:!1,errorMessage:ht(t)})}finally{t.controller=null,r.onFinished?.()}}function ht(e){return dt(e,`导出`,`导出失败`)??(e instanceof Error&&e.message?e.message:`导出失败`)}function gt(e,t){let n=new AbortController;K.set(e,n),mt(e,t,n).finally(()=>{K.delete(e),W.delete(e)})}function _t(e){let t=Me(),n={id:t,type:`export`,title:e.title,status:`running`,total:0,processed:0,fileName:e.fileName,samples:[]},r={options:e,rows:[],total:0,cancelRequested:!1,controller:null};return W.set(t,r),Ne(n),gt(t,r),t}function vt(e,t){try{return B(e,t),!0}catch(e){return console.error(`下载失败: ${e}`),!1}}function yt(e){let t=q(e);return t?.type!==`export`||!t.blob||!t.fileName?!1:vt(t.blob,t.fileName)}function bt(e){let t=q(e);if(!t)return;if(t.status===`paused`){J(e,{status:`canceled`,pausing:!1,canceling:!1,rowStates:(t.rowStates??[]).map(e=>e.status===`queued`||e.status===`running`?{status:`canceled`}:e)});let n=G.get(e);G.delete(e),Ve(e),n?.options.onFinished?.();return}if(t.status!==`running`)return;if(t.type===`export`){if(t.canceling||t.finalizing)return;let n=W.get(e);if(!n)return;n.cancelRequested=!0,n.controller?.abort(),J(e,{canceling:!0});return}if(t.canceling)return;let n=G.get(e);n&&(n.cancelRequested=!0,J(e,{canceling:!0}))}function xt(e){let t=q(e);t&&(t.status===`running`&&K.get(e)?.abort(),W.delete(e),G.delete(e),Ve(e),Pe(e))}function St(){He(),Fe()}function Ct(e){let t=(0,h.useCallback)(()=>e?je().find(t=>t.id===e):void 0,[e]);return(0,h.useSyncExternalStore)(Ae,t)}function wt(e){if(e.canceling)return`正在取消`;if(e.finalizing)return`正在生成文件`;switch(e.status){case`running`:return`进行中`;case`paused`:return`已暂停`;case`completed`:return`已完成`;case`failed`:return`失败`;case`canceled`:return`已取消`}}function Tt(e){if(e.canceling)return`warning`;if(e.finalizing)return`processing`}function Et(e){switch(e.status){case`failed`:return`exception`;case`completed`:return`success`;default:return`normal`}}var Dt=({taskId:e,onClose:t})=>{let n=Ct(e),{message:r}=m.App.useApp();if(!n)return null;let i=n.status===`completed`||n.status===`failed`||n.status===`canceled`,a=we(n),o=()=>{xt(n.id),t()},s=()=>{yt(n.id)||r.error(`文件不存在`)},c=wt(n);return(0,g.jsx)(m.Modal,{title:n.title,open:!0,maskClosable:!1,closable:i,keyboard:i,onCancel:()=>{i&&o()},footer:i?(0,g.jsxs)(m.Flex,{justify:`flex-end`,gap:8,children:[n.status===`completed`?(0,g.jsx)(m.Button,{onClick:s,children:`重新下载`}):null,(0,g.jsx)(m.Button,{type:`primary`,onClick:o,children:`关闭`})]}):(0,g.jsx)(m.Flex,{justify:`flex-end`,children:(0,g.jsx)(m.Button,{danger:!0,loading:n.canceling,disabled:n.canceling||n.finalizing,onClick:()=>bt(n.id),children:n.canceling?`取消中`:`取消任务`})}),children:(0,g.jsxs)(m.Flex,{vertical:!0,gap:12,children:[(0,g.jsxs)(m.Flex,{justify:`space-between`,align:`center`,gap:12,children:[(0,g.jsxs)(m.Typography.Text,{type:`secondary`,children:[`已导出 `,Se(n).toLocaleString(),` / 总数 `,n.total>0?n.total.toLocaleString():`--`]}),(0,g.jsx)(m.Tag,{color:Tt(n),children:c})]}),(0,g.jsx)(m.Progress,{percent:a,format:()=>Te(a),status:Et(n),size:`small`}),n.errorMessage?(0,g.jsx)(m.Typography.Text,{type:`danger`,children:n.errorMessage}):null]})})};function Ot(){let[e,t]=(0,h.useState)(),n=(0,h.useRef)(void 0);return(0,h.useEffect)(()=>{n.current=e},[e]),(0,h.useEffect)(()=>()=>{n.current&&xt(n.current)},[]),[e,t]}var kt=({title:e,fieldSchemas:t,buttonText:n=`导出`,disabled:r,exportRows:i,beforeExport:a,afterExport:o,onModalClose:s})=>{let{message:c}=m.App.useApp(),[l,u]=Ot();return(0,g.jsxs)(g.Fragment,{children:[(0,g.jsx)(m.Tooltip,{title:`导出 Excel`,children:(0,g.jsx)(m.Button,{type:`default`,icon:(0,g.jsx)(p.DownloadOutlined,{}),disabled:r,onClick:async()=>{try{await a?.()}catch(e){c.error(e instanceof Error?e.message:`导出已取消`);return}u(_t({title:`${e}导出`,fileName:H(e),fieldSchemas:t,exportRows:i,onFinished:o}))},children:n})}),l?(0,g.jsx)(Dt,{taskId:l,onClose:()=>{u(void 0),s?.()}}):null]})},{Text:At}=m.Typography,jt=({missingTitles:e,headerMessages:t})=>(0,g.jsxs)(m.Flex,{vertical:!0,gap:4,children:[e.length>0?(0,g.jsx)(At,{children:`缺少必填列: ${e.join(`, `)}`}):null,t.map((e,t)=>(0,g.jsx)(At,{children:e},t))]});function Mt(e){return e==null||e===``?``:Array.isArray(e)?b(e):String(e)}var Nt=({field:e,record:t,disabled:n,onChange:r,onSave:i})=>{let{token:a}=m.theme.useToken(),[o,s]=(0,h.useState)(!1),[c,l]=(0,h.useState)(!1),u=t.values[e.key];if(o&&!n)return e.type===`boolean`?(0,g.jsx)(m.Select,{autoFocus:!0,open:!0,size:`small`,style:{width:`100%`},value:typeof u==`string`?u:void 0,options:[{value:e.property.true_label,label:e.property.true_label},{value:e.property.false_label,label:e.property.false_label}],onChange:e=>{r(e),i(e),s(!1)},onBlur:()=>s(!1)}):e.type===`single_choice`?(0,g.jsx)(m.Select,{autoFocus:!0,open:!0,size:`small`,style:{width:`100%`},value:typeof u==`string`?u:void 0,options:Object.keys(e.property.option_map).map(e=>({value:e,label:e})),onChange:e=>{r(e),i(e),s(!1)},onBlur:()=>s(!1)}):e.type===`multiple_choice`?(0,g.jsx)(m.Select,{autoFocus:!0,open:!0,mode:`multiple`,size:`small`,style:{width:`100%`},value:Array.isArray(u)?u:[],options:Object.keys(e.property.option_map).map(e=>({value:e,label:e})),onChange:r,onBlur:()=>{s(!1),i(u)}}):e.type===`number`?(0,g.jsx)(m.InputNumber,{autoFocus:!0,size:`small`,style:{width:`100%`},value:typeof u==`number`||typeof u==`string`?u:void 0,onChange:r,onBlur:()=>{s(!1),i(u)},onPressEnter:()=>{s(!1),i(u)}}):(0,g.jsx)(m.Input,{autoFocus:!0,size:`small`,value:typeof u==`string`?u:``,placeholder:e.type===`list`?`多个值用分号分隔(中英文均可)`:void 0,onChange:e=>r(e.target.value),onBlur:()=>{s(!1),i(u)},onPressEnter:()=>{s(!1),i(u)}});let d=Mt(u);return(0,g.jsx)(`div`,{title:d||void 0,style:{height:24,boxSizing:`border-box`,display:`flex`,alignItems:`center`,minWidth:0,padding:`0 7px`,lineHeight:`22px`,whiteSpace:`nowrap`,overflow:`hidden`,border:`1px solid ${c&&!n?a.colorBorder:`transparent`}`,borderRadius:a.borderRadiusSM,cursor:n?`default`:`text`},onMouseEnter:()=>l(!0),onMouseLeave:()=>l(!1),onClick:()=>{n||s(!0)},children:(0,g.jsx)(`span`,{style:{minWidth:0,overflow:`hidden`,textOverflow:`ellipsis`,whiteSpace:`nowrap`},children:d})})};function Pt(e){if(e.canceling)return{label:`正在取消`,color:`warning`};switch(e.status){case`running`:return{label:`进行中`,color:`processing`};case`paused`:return{label:`已暂停`,color:`warning`};case`completed`:return{label:`已完成`,color:`success`};case`failed`:return{label:`失败`,color:`error`};case`canceled`:return{label:`已取消`,color:`warning`}}}function Ft(e,t){if(e.canceling)return`正在取消...`;switch(e.status){case`running`:return`预计剩余 ${Ee(t)}`;default:return null}}function It(e){switch(e.status){case`failed`:return`exception`;case`completed`:return`success`;default:return`normal`}}var Lt={valid:{label:`已校验`,color:`success`},invalid:{label:`校验失败`,color:`error`}},Rt={pending:{label:`待导入`,color:`default`},running:{label:`进行中`,color:`processing`},completed:{label:`已完成`,color:`success`},failed:{label:`导入失败`,color:`error`},canceled:{label:`已取消`,color:`warning`}};function zt(e){return Object.keys(e.errors).length>0?`invalid`:`valid`}function Bt(e,t,n){if(!t||e.taskIndex===void 0)return`pending`;switch(n?.rowStates?.[e.taskIndex]?.status){case`running`:return`running`;case`completed`:return`completed`;case`failed`:return`failed`;case`canceled`:return`canceled`;default:return`pending`}}function Vt(e,t){let[n,r]=(0,h.useState)(e);return(0,h.useEffect)(()=>{let n=setTimeout(()=>r(e),t);return()=>clearTimeout(n)},[e,t]),n}function Ht(e,t){let[n,r]=(0,h.useState)(e),i=(0,h.useRef)(e),a=(0,h.useRef)(0),o=(0,h.useRef)(null);return(0,h.useEffect)(()=>{i.current=e;let n=Date.now()-a.current;n>=t?(a.current=Date.now(),r(e)):o.current===null&&(o.current=setTimeout(()=>{o.current=null,a.current=Date.now(),r(i.current)},t-n))},[e,t]),(0,h.useEffect)(()=>()=>{o.current!==null&&clearTimeout(o.current)},[]),n}var Ut=({open:e,title:t,fieldSchemas:n,rows:r,taskId:i,includedKeys:a,onChangeCell:o,onSaveCell:s,onDelete:c,onConfirm:l,onClose:u})=>{let[d,f]=(0,h.useState)(`all`),[_,v]=(0,h.useState)(`all`),[y,b]=(0,h.useState)(``),x=Vt(y,300),S=()=>{f(`all`),v(`all`),b(``)},C=Ct(i),w=(0,h.useRef)(void 0);(0,h.useEffect)(()=>{C&&(w.current=C)},[C]);let T=(0,h.useMemo)(()=>new Set(a),[a]),E=n.filter(e=>T.has(e.key)),D=w.current,O=C??(D?.id===i?D:void 0),k=O?Pt(O):void 0,A=!!(O&&O.status!==`completed`&&O.status!==`failed`&&O.status!==`canceled`),ee=Ht(O?.status===`running`?xe(O):null,1e3),j=O?Ft(O,ee):null,M=e=>e.taskIndex===void 0?void 0:O?.rowStates?.[e.taskIndex],N=!(!C||C.status!==`failed`&&C.status!==`paused`),te=e=>{if(!i)return!0;let t=M(e)?.status;return N&&(t===`queued`||t===`failed`)?!0:N&&e.taskIndex===void 0&&Object.keys(e.errors).length>0},ne=e=>!i||C?.status===`paused`&&M(e)?.status===`queued`,P=(0,h.useMemo)(()=>[`valid`,`invalid`].map(e=>({value:e,label:Lt[e].label})),[]),re=(0,h.useMemo)(()=>[`pending`,`running`,`completed`,`failed`,`canceled`].map(e=>({value:e,label:Rt[e].label})),[]),F=O?.status===`running`,ie=F?``:x,I=!F&&d!==`all`&&P.some(e=>e.value===d)?d:`all`,L=!F&&_!==`all`&&re.some(e=>e.value===_)?_:`all`,ae=I!==`all`||ie.trim()!==``,R=L!==`all`,oe=ae||R,z=(0,h.useMemo)(()=>{if(!ae)return r;let e=ie.trim().toLowerCase();return r.filter(t=>I!==`all`&&zt(t)!==I?!1:!e||Object.values(t.values).some(t=>(Array.isArray(t)?t.join(` `):String(t??``)).toLowerCase().includes(e)))},[r,I,ie,ae]),se=Ht(O,300),ce=R?se:void 0,le=(0,h.useMemo)(()=>R?z.filter(e=>Bt(e,i,ce)===L):i&&O?z.slice():z,[z,L,R,ce,O,i]),ue=e=>{let t=Object.entries(e.errors);return(0,g.jsx)(m.Flex,{vertical:!0,gap:4,style:{maxWidth:320},children:t.map(([e,t])=>{let r=n.find(t=>t.key===e)?.title??e;return(0,g.jsxs)(m.Typography.Text,{children:[(0,g.jsx)(m.Typography.Text,{strong:!0,children:r}),`: `,t]},e)})})},de=e=>{let t=zt(e),n=Lt[t];return t===`invalid`?(0,g.jsx)(m.Popover,{trigger:`hover`,placement:`topRight`,title:`错误信息`,content:ue(e),children:(0,g.jsx)(m.Tag,{color:n.color,children:n.label})}):(0,g.jsx)(m.Tag,{color:n.color,children:n.label})},B=e=>{let t=M(e),r=t?.fieldErrors??[],i=t?.message;if(r.length===0)return(0,g.jsx)(m.Typography.Text,{children:i??`导入失败`});let a=new Map;r.forEach(e=>{let[t,r]=Object.entries(e)[0]??[],i=t===`detail`||t===`non_field_errors`?`错误`:n.find(e=>e.key===t)?.title??`数据`,o=a.get(i)??[];o.push(r),a.set(i,o)});let o=[...a.entries()],s=o.slice(0,3),c=o.length-s.length;return(0,g.jsxs)(m.Flex,{vertical:!0,gap:8,style:{maxWidth:360},children:[i?(0,g.jsx)(m.Typography.Text,{children:i}):null,s.map(([e,t])=>(0,g.jsxs)(m.Flex,{vertical:!0,gap:2,children:[(0,g.jsx)(m.Typography.Text,{strong:!0,children:e}),t.map((e,t)=>(0,g.jsxs)(m.Typography.Text,{children:[`• `,e]},t))]},e)),c>0?(0,g.jsxs)(m.Typography.Text,{type:`secondary`,children:[`还有 `,c,` 个字段错误`]}):null]})},fe=e=>{let t=Bt(e,i,O),n=Rt[t];if(t===`failed`){let t=M(e),r=(t?.fieldErrors?.length??0)+ +!!t?.message,i=r>0?`导入失败(${r})`:n.label;return(0,g.jsx)(m.Popover,{trigger:`hover`,placement:`topRight`,title:`错误信息`,content:B(e),children:(0,g.jsx)(m.Tag,{color:n.color,children:i})})}return(0,g.jsx)(m.Tag,{color:n.color,children:n.label})},pe=e=>(0,g.jsx)(m.Button,{type:`primary`,danger:!0,size:`small`,disabled:!ne(e),icon:(0,g.jsx)(p.DeleteOutlined,{}),onClick:()=>{c(e),C&&e.taskIndex!==void 0&&at(C.id,[e.taskIndex])},children:`删除`}),me=[{key:`rowNumber`,title:`行号`,dataIndex:`rowNumber`,width:60,fixed:`left`},...E.map(e=>({key:e.key,title:e.title,dataIndex:e.key,width:160,render:(t,n)=>(0,g.jsx)(Nt,{field:e,record:n,disabled:!te(n),onChange:t=>o(n,e,t),onSave:t=>s(n,e,t)})})),{key:`dataStatus`,title:`数据状态`,width:100,fixed:`right`,render:(e,t)=>de(t)},{key:`importStatus`,title:`导入状态`,width:110,fixed:`right`,render:(e,t)=>fe(t)},{key:`action`,title:`操作`,width:80,fixed:`right`,render:(e,t)=>pe(t)}],he=Math.max(1200,60+E.length*160+100+110+80),ge=O&&O.total>0?we(O):0,_e=O?.failureCount??O?.failures?.length??0,V=O?.validationFailedCount??r.filter(e=>Object.keys(e.errors).length>0).length,ve=r.filter(e=>Object.keys(e.errors).length>0).length,H=r.length>0&&ve===r.length;return(0,g.jsx)(g.Fragment,{children:(0,g.jsxs)(m.Modal,{title:i?`${t}导入`:`${t}导入预览`,open:e,width:`min(1400px, 96vw)`,maskClosable:!1,closable:!1,keyboard:!1,onCancel:()=>{A||u()},footer:(()=>{if(!i)return(0,g.jsxs)(m.Flex,{justify:`space-between`,align:`center`,gap:8,wrap:!0,children:[(0,g.jsx)(`span`,{children:r.length>0&&ve>0?(0,g.jsx)(m.Typography.Text,{type:H?`danger`:`secondary`,children:H?`全部行校验失败, 请先修正后再导入`:`有 ${ve} 行校验失败, 不会导入`}):null}),(0,g.jsxs)(m.Flex,{gap:8,children:[(0,g.jsx)(m.Button,{onClick:u,children:`取消`}),(0,g.jsx)(m.Button,{type:`primary`,disabled:r.length===0||H,onClick:()=>{S(),l()},children:`开始导入`})]})]});if(!C||!O)return(0,g.jsx)(m.Flex,{justify:`flex-end`,children:(0,g.jsx)(m.Button,{onClick:u,children:`关闭`})});let e=O.status===`running`,t=O.status===`paused`;return(0,g.jsxs)(m.Flex,{justify:`flex-end`,gap:8,children:[e?(0,g.jsxs)(g.Fragment,{children:[(0,g.jsx)(m.Button,{danger:!0,loading:O.canceling,disabled:O.canceling,onClick:()=>bt(O.id),children:O.canceling?`取消中`:`取消任务`}),(0,g.jsx)(m.Button,{loading:O.pausing,disabled:O.canceling,onClick:()=>nt(O.id),children:`暂停`})]}):null,t?(0,g.jsxs)(g.Fragment,{children:[(0,g.jsx)(m.Button,{danger:!0,onClick:()=>bt(O.id),children:`取消任务`}),(0,g.jsx)(m.Button,{type:`primary`,onClick:()=>{S(),tt(O.id)},children:`继续导入`})]}):null,!e&&!t?(0,g.jsx)(m.Button,{type:`primary`,onClick:u,children:`关闭`}):null]})})(),children:[O&&k?(0,g.jsxs)(m.Flex,{vertical:!0,gap:4,style:{marginBottom:12},children:[(0,g.jsxs)(m.Flex,{justify:`space-between`,align:`center`,children:[(0,g.jsxs)(m.Typography.Text,{type:`secondary`,children:[`已导入 `,Se(O).toLocaleString(),` / 总数 `,O.total.toLocaleString()]}),(0,g.jsxs)(m.Flex,{align:`center`,gap:8,children:[j?(0,g.jsx)(m.Typography.Text,{type:`secondary`,children:j}):null,V>0?(0,g.jsxs)(m.Tag,{color:`error`,children:[`校验失败 `,V,` 条`]}):null,_e>0?(0,g.jsxs)(m.Tag,{color:`error`,children:[`导入失败 `,_e,` 条`]}):null,(0,g.jsx)(m.Tag,{color:k.color,children:k.label})]})]}),(0,g.jsx)(m.Progress,{percent:ge,format:()=>Te(ge),status:It(O),size:`small`})]}):i?null:(0,g.jsxs)(m.Flex,{vertical:!0,gap:4,style:{marginBottom:12},children:[(0,g.jsxs)(m.Flex,{justify:`space-between`,align:`center`,children:[(0,g.jsxs)(m.Typography.Text,{type:`secondary`,children:[`总数 `,r.length.toLocaleString()]}),(0,g.jsxs)(m.Flex,{align:`center`,gap:8,children:[V>0?(0,g.jsxs)(m.Tag,{color:`error`,children:[`校验失败 `,V,` 条`]}):null,(0,g.jsx)(m.Tag,{children:`待导入`})]})]}),(0,g.jsx)(m.Progress,{percent:0,format:()=>`0.0%`,size:`small`})]}),(0,g.jsxs)(m.Flex,{justify:`space-between`,align:`center`,gap:8,wrap:!0,style:{marginBottom:8},children:[(0,g.jsxs)(m.Flex,{align:`center`,gap:8,wrap:!0,children:[(0,g.jsx)(m.Input,{allowClear:!0,disabled:F,placeholder:`搜索所有字段`,value:F?``:y,style:{width:260},onChange:e=>{b(e.target.value)}}),(0,g.jsx)(m.Select,{allowClear:!0,disabled:F,placeholder:`数据状态`,value:I===`all`?void 0:I,options:P,style:{width:140},onChange:e=>{f(e??`all`)}}),(0,g.jsx)(m.Select,{allowClear:!0,disabled:F,placeholder:`导入状态`,value:L===`all`?void 0:L,options:re,style:{width:140},onChange:e=>{v(e??`all`)}})]}),oe?(0,g.jsxs)(m.Typography.Text,{type:`secondary`,children:[`筛选出 `,le.length,` 条`]}):null]}),(0,g.jsx)(m.Table,{rowKey:`key`,size:`middle`,tableLayout:`fixed`,virtual:!0,columns:me,dataSource:le,pagination:!1,scroll:{x:he,y:520},locale:{emptyText:oe?`没有符合条件的行`:void 0}})]})})},Wt=[/期望为一个包含物件的列表/,/expected a list/i,/得到的类型是/,/not a list/i];function Gt(e){return Wt.some(t=>t.test(e))?`数据格式不正确, 请检查导入内容`:e}function Kt(e,t){if(Object.keys(e).length===0)return{success:!0};let n=[],r;return Object.entries(e).forEach(([e,i])=>{let a=Array.isArray(i)?i:[i];if(e===`detail`||e===`non_field_errors`||!t.has(e)){let t=a.map(e=>Gt(String(e))).join(`; `);r=e===`detail`||e===`non_field_errors`?t:`${e}: ${t}`}else a.forEach(t=>n.push({[e]:Gt(String(t))}))}),{success:!1,...r?{message:r}:{},...n.length>0?{fieldErrors:n}:{}}}function qt(e,t,n){let r={};return t.forEach(t=>{if(!n.includes(t.key))return;let i=P(t,e.values[t.key]),a=j(i.trim()===``?null:i,t);if(!a.validateSuccess)throw Error(a.validateMessage);r[t.key]=a.validateValue??null}),r}function Jt(e,t,n){return e.map((e,r)=>{let i={},a={};return t.forEach(t=>{if(!n.includes(t.key))return;let r=P(t,e.values[t.key]),o=j(r.trim()===``?null:r,t);o.validateSuccess?i[t.key]=te(t,o.validateValue??null):(i[t.key]=e.values[t.key],a[t.key]=o.validateMessage)}),{...e,key:String(r),values:i,errors:a}})}var Yt=`缺少列: `;function Xt(e){let t=lt(e);if(t&&typeof t==`object`){let e=t;if(typeof e.detail==`string`)return e.detail;let n=Object.entries(e)[0];if(n){let[e,t]=n,r=Array.isArray(t)?t[0]:t;return`${e}: ${String(r)}`}}return dt(e,`导入`,`任务已暂停`)??(e instanceof Error&&e.message?e.message:`导入失败, 任务已暂停`)}var Zt=({title:e,fieldSchemas:t,buttonText:n=`导入`,batchSize:r=20,importRows:i,beforeImport:a,afterImport:o,onModalClose:s})=>{let[c,l]=(0,h.useState)(!1),[u,d]=(0,h.useState)([]),[f,v]=Ot(),[y,b]=(0,h.useState)(`empty`),[x,S]=(0,h.useState)(!1),[C,w]=(0,h.useState)(!1),[T,E]=(0,h.useState)([]),{modal:D,message:O}=m.App.useApp(),k=(0,h.useRef)(null),A=(0,h.useMemo)(()=>_(t),[t]),ee=(0,h.useMemo)(()=>new Set([...T].filter(e=>A.some(t=>t.key===e))),[A,T]),M=()=>k.current?.click(),N=(e,t)=>{D.warning({title:t??(e.missingTitles.length>0?`文件表头不完整`:`文件检查未通过`),width:480,content:(0,g.jsx)(jt,{...e}),okCancel:!0,okText:`重新选择文件`,cancelText:`关闭`,closable:!0,onOk:M})},te=async e=>{if(e.size>20971520)O.error(`文件大小超过 20MB, 请拆分后再导入`);else{v(void 0),E([]),S(!0);try{let{headerMessages:t,formulaMessages:n,rows:r,includedKeys:i}=await ve(e,A);if(n.length>0){N({missingTitles:[],headerMessages:n},`文件里的公式还没有计算结果`);return}if(t.length>0){N({missingTitles:t.filter(e=>e.startsWith(Yt)).map(e=>e.slice(5)),headerMessages:t.filter(e=>!e.startsWith(Yt))});return}if(r.length===0){O.error(`文件里没有数据行`);return}let o=r;try{let e=await a?.(r);e&&(o=Jt(e,A,i))}catch(e){O.error(e instanceof Error?e.message:`导入已取消`);return}if(o.length===0){O.error(`没有可导入的数据`);return}E(i),b(`${e.name}-${Date.now()}`),d(o),l(!0)}catch(e){console.error(`导入文件解析失败: ${e}`),O.error(`导入文件解析失败, 请确认上传的是 Excel 文件`)}finally{S(!1)}}};return(0,g.jsxs)(g.Fragment,{children:[(0,g.jsxs)(m.Space.Compact,{block:!0,children:[(0,g.jsx)(m.Tooltip,{title:`Excel 导入`,children:(0,g.jsx)(m.Button,{type:`default`,icon:(0,g.jsx)(p.UploadOutlined,{}),loading:x,disabled:x,onClick:M,children:n})}),(0,g.jsx)(m.Tooltip,{title:`Excel 导入模板`,children:(0,g.jsx)(m.Button,{type:`default`,icon:(0,g.jsx)(p.FileOutlined,{}),loading:C,onClick:async()=>{w(!0);try{await V(A,`${e}导入模板`)}catch(e){console.error(`模板下载失败: ${e}`),O.error(`模板下载失败`)}finally{w(!1)}},children:`下载模板`})})]}),(0,g.jsx)(`input`,{ref:k,type:`file`,accept:`.xlsx`,style:{display:`none`},onChange:e=>{let t=e.target.files?.[0];e.target.value=``,t&&te(t)}}),(0,g.jsx)(Ut,{open:c,title:e,fieldSchemas:A,rows:u,taskId:f,includedKeys:T,onChangeCell:(e,t,n)=>{if(!T.includes(t.key))return;let r=P(t,n),i=j(r.trim()===``?null:r,t);d(r=>r.map(r=>{if(r.key!==e.key)return r;let a={...r.errors};return i.validateSuccess?delete a[t.key]:a[t.key]=i.validateMessage,{...r,values:{...r.values,[t.key]:n},errors:a}}))},onSaveCell:(e,t,n)=>{if(!T.includes(t.key))return;let r={...e.values,[t.key]:n},i={};A.forEach(e=>{if(!T.includes(e.key))return;let t=P(e,r[e.key]),n=j(t.trim()===``?null:t,e);n.validateSuccess||(i[e.key]=n.validateMessage)});let a={...e,values:r,errors:i};d(t=>t.map(t=>t.key===e.key?a:t)),f&&e.taskIndex!==void 0&&(ot(f,e.taskIndex,t.key),it(f,e.taskIndex,i),rt(f,e.taskIndex,a))},onDelete:e=>{d(t=>t.filter(t=>t.key!==e.key))},onConfirm:async()=>{let t=u;if(t.length===0){O.error(`没有可导入的数据`);return}if(t.every(e=>Object.keys(e.errors).length>0)){O.error(`所有行都有校验错误, 请先修正后再导入`);return}let n=t.map((e,t)=>({...e,taskIndex:t}));d(n);let a=et({title:`${e}导入`,rows:n,fieldSchemas:A,includedKeys:T,batchSize:r,importRows:async e=>{try{let t=await i(e.map(e=>qt(e,A,T)));if(t.length!==e.length)throw new Y(`导入接口返回结果数量不正确, 任务已暂停`);return t.map(e=>Kt(e,ee))}catch(e){throw e instanceof Y?e:new Y(Xt(e))}},onFinished:o});v(a)},onClose:()=>{f&&xt(f),l(!1),v(void 0),d([]),E([]),s?.()}},y)]})};exports.ExportButton=kt,exports.ImportButton=Zt,exports.MAX_IMPORT_FILE_SIZE=M,exports.MULTI_VALUE_SEPARATOR=v,exports.exportRowsToFile=ye,exports.importableFields=_,exports.joinMultiValues=b,exports.resetTasks=St,exports.splitMultiValues=x,exports.validateBooleanField=T,exports.validateDateField=E,exports.validateDateTimeField=O,exports.validateField=j,exports.validateListField=k,exports.validateMultipleChoiceField=ee,exports.validateNumberField=w,exports.validateSingleChoiceField=A,exports.validateTextField=C,exports.validateTimeField=D;
|