antd-import-export 1.0.10 → 1.0.13
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 +141 -77
- package/README_EN.md +142 -70
- package/dist/components/EditableImportCell.d.cts +12 -0
- package/dist/components/EditableImportCell.d.ts +2 -2
- package/dist/components/ExportButton.d.cts +20 -0
- package/dist/components/ExportButton.d.ts +2 -2
- package/dist/components/ExportTaskModal.d.cts +7 -0
- package/dist/components/ImportButton.d.cts +25 -0
- package/dist/components/ImportButton.d.ts +8 -5
- package/dist/components/ImportCheckContent.d.cts +10 -0
- package/dist/components/ImportPreviewModal.d.cts +19 -0
- package/dist/components/ImportPreviewModal.d.ts +2 -2
- package/dist/components/importBatchResult.d.cts +7 -0
- package/dist/components/importBatchResult.d.ts +4 -6
- package/dist/components/importPreviewStatus.d.cts +20 -0
- package/dist/components/importPreviewStatus.d.ts +2 -2
- package/dist/core/dateTime.d.cts +56 -0
- package/dist/core/dateTime.d.ts +56 -0
- package/dist/core/excel/exportFile.d.cts +14 -0
- package/dist/core/excel/exportFile.d.ts +2 -2
- package/dist/core/excel/importEditor.d.cts +7 -0
- package/dist/core/excel/importEditor.d.ts +2 -2
- package/dist/core/excel/importRow.d.cts +28 -0
- package/dist/core/excel/importRow.d.ts +15 -1
- package/dist/core/excel/parseSheet.d.cts +31 -0
- package/dist/core/excel/parseSheet.d.ts +18 -5
- package/dist/core/excel/runtime.d.cts +18 -0
- package/dist/core/excel/runtime.d.ts +9 -4
- package/dist/core/excel/worksheet.d.cts +8 -0
- package/dist/core/excel/worksheet.d.ts +2 -7
- package/dist/core/httpError.d.cts +34 -0
- package/dist/core/limits.d.cts +2 -0
- package/dist/core/schema/defaultValue.d.cts +17 -0
- package/dist/core/schema/defaultValue.d.ts +17 -0
- package/dist/core/schema/index.d.cts +91 -0
- package/dist/core/schema/index.d.ts +4 -1
- package/dist/core/schema/multiValue.d.cts +4 -0
- package/dist/core/schema/optionMap.d.cts +10 -0
- package/dist/core/schema/optionMap.d.ts +10 -0
- package/dist/core/schema/validate.d.cts +21 -0
- package/dist/core/schema/validate.d.ts +2 -2
- package/dist/core/task/exportRunner.d.cts +4 -0
- package/dist/core/task/exportRunner.d.ts +1 -1
- package/dist/core/task/importRunner.d.cts +21 -0
- package/dist/core/task/importRunner.d.ts +4 -4
- package/dist/core/task/index.d.cts +12 -0
- package/dist/core/task/index.d.ts +6 -6
- package/dist/core/task/stats.d.cts +16 -0
- package/dist/core/task/stats.d.ts +3 -3
- package/dist/core/task/store.d.cts +17 -0
- package/dist/core/task/store.d.ts +1 -1
- package/dist/core/task/types.d.cts +106 -0
- package/dist/core/task/types.d.ts +10 -5
- package/dist/core/types.d.cts +16 -0
- package/dist/index.cjs +9 -6
- package/dist/index.d.cts +15 -0
- package/dist/index.d.ts +15 -14
- package/dist/index.mjs +1134 -1004
- package/dist/react/useActiveTask.d.cts +5 -0
- package/dist/react/useActiveTask.d.ts +1 -1
- package/dist/react/useDebouncedValue.d.cts +2 -0
- package/dist/react/useTaskDetail.d.cts +2 -0
- package/dist/react/useTaskDetail.d.ts +1 -1
- package/dist/react/useThrottledValue.d.cts +2 -0
- package/package.json +18 -8
package/README_EN.md
CHANGED
|
@@ -23,10 +23,31 @@
|
|
|
23
23
|
| antd | >=6.0.0 |
|
|
24
24
|
| @ant-design/icons | >=5.0.0 |
|
|
25
25
|
|
|
26
|
+
## Installation
|
|
27
|
+
|
|
28
|
+
```bash
|
|
29
|
+
npm i antd-import-export
|
|
30
|
+
```
|
|
31
|
+
|
|
32
|
+
React / react-dom / antd / @ant-design/icons are provided by the host app (versions above).
|
|
33
|
+
|
|
34
|
+
`message` / `modal` inside the components use antd's `App` context, so **wrap them in `<App>`**:
|
|
35
|
+
|
|
36
|
+
```tsx
|
|
37
|
+
import { App } from "antd";
|
|
38
|
+
import { ImportButton } from "antd-import-export";
|
|
39
|
+
|
|
40
|
+
<App>
|
|
41
|
+
<ImportButton title="Supplier" fieldSchemas={fieldSchemas} importRows={importSuppliers} />
|
|
42
|
+
</App>
|
|
43
|
+
```
|
|
44
|
+
|
|
26
45
|
## Field schema
|
|
27
46
|
|
|
28
47
|
Everything is driven by `FieldSchema[]`: export headers, template hints and cell-level validation. **The array order is the column order.**
|
|
29
48
|
|
|
49
|
+
Field `key`s and `title`s must be unique and clean (field definitions are not validated at runtime); `title` is used verbatim as the Excel header, so avoid leading/trailing spaces or newlines.
|
|
50
|
+
|
|
30
51
|
Each field is the common part plus a type-specific `property`:
|
|
31
52
|
|
|
32
53
|
| Field | Required | Notes |
|
|
@@ -35,7 +56,7 @@ Each field is the common part plus a type-specific `property`:
|
|
|
35
56
|
| `title` | yes | Column name: export header, template hint and preview column all use it |
|
|
36
57
|
| `type` | yes | One of nine types; decides the shape of `property` and the validation rules |
|
|
37
58
|
| `property` | yes | Type-specific config, see the table below |
|
|
38
|
-
| `importable` | no | Defaults to `true`. `false` means **export only**: excluded from the template and parsing, and the export header is marked "(仅导出)" |
|
|
59
|
+
| `importable` | no | Defaults to `true`. `false` means **export only**: excluded from the template and parsing, and the export header is marked "(仅导出)". On re-import, columns are matched by `title` against the field definitions, and columns whose field has `importable: false` are ignored; the marker text is only a hint and is not used for matching |
|
|
39
60
|
|
|
40
61
|
```ts
|
|
41
62
|
import type { FieldSchema } from "antd-import-export";
|
|
@@ -53,15 +74,38 @@ const fieldSchemas: FieldSchema[] = [
|
|
|
53
74
|
| type | property | notes |
|
|
54
75
|
| --- | --- | --- |
|
|
55
76
|
| `text` | required / max_length / default_value | length checked in characters |
|
|
56
|
-
| `number` | required / precision / max_digits? / min_value? / max_value? / default_value | precision judged on decimal places |
|
|
77
|
+
| `number` | required / precision / max_digits? / min_value? / max_value? / default_value | precision judged on decimal places; only decimal literals are accepted (exponent notation like `1e3` is allowed, `0x`/binary/underscores are not); template and export columns use text format so long numbers keep full precision in Excel |
|
|
57
78
|
| `boolean` | required / true_label / false_label / default_value | labels in the cell, boolean on the wire |
|
|
58
79
|
| `date` | required / default_value | strict `YYYY-MM-DD` |
|
|
59
|
-
| `time` | required / default_value |
|
|
60
|
-
| `datetime` | required / default_value | strict `YYYY-MM-DD
|
|
80
|
+
| `time` | required / default_value | accepts `H:mm` / `HH:mm` (optionally `:ss`); output is zero-padded to `HH:mm` or `HH:mm:ss`; seconds are dropped when zero |
|
|
81
|
+
| `datetime` | required / default_value | date part is strict `YYYY-MM-DD`, time part follows `time`; seconds are dropped when zero |
|
|
61
82
|
| `list` | required / list_max_length / text_max_length / item_key? / default_value | Chinese or English semicolons; exports always use `;` |
|
|
62
|
-
| `single_choice` | required / option_map / default_value | label in the cell,
|
|
83
|
+
| `single_choice` | required / option_map / default_value | label in the cell, `option_map` key on the wire |
|
|
63
84
|
| `multiple_choice` | required / option_map / default_value | Chinese or English semicolons; exports always use `;` |
|
|
64
85
|
|
|
86
|
+
`option_map` maps **API value → display label**: the **key is the internal API value** (must be unique), while the **value is the label** shown in Excel/UI (**and labels must be unique too**; duplicates resolve to the first one by object property order). For example `{ "ON_SALE": "On sale", "OFF_SALE": "Off sale" }`: the Excel cell contains `On sale` and the API receives `"ON_SALE"`. (Older versions used the opposite direction: `{ "On sale": "ON_SALE" }` must become `{ "ON_SALE": "On sale" }` when upgrading, see RELEASING.)
|
|
87
|
+
|
|
88
|
+
### Date and time input/export
|
|
89
|
+
|
|
90
|
+
- Import: `date` is strict `YYYY-MM-DD` (4-2-2 and a real calendar date); `time` / `datetime` accept a 1-digit hour, minutes/seconds must have 2 digits; multiple spaces between date and time are allowed, and surrounding whitespace is ignored.
|
|
91
|
+
- Output is zero-padded: `9:05` → `09:05`, `2026-11-22 9:05` → `2026-11-22 09:05`; seconds are dropped when zero (`09:05:00` → `09:05`).
|
|
92
|
+
- Use these canonical strings for interface values and `default_value`. On export a `Date` is read as UTC and an ISO-8601 string by its literal wall clock, with no timezone conversion; other formats (e.g. `2026/11/22`, `20261122`, dayjs-like objects) are no longer guessed and are written as-is.
|
|
93
|
+
|
|
94
|
+
### `default_value`
|
|
95
|
+
|
|
96
|
+
`default_value` always uses the field's **API value** (the same type as the payload), never the display label:
|
|
97
|
+
|
|
98
|
+
| type | default_value | example |
|
|
99
|
+
| --- | --- | --- |
|
|
100
|
+
| text | string | `"N/A"` |
|
|
101
|
+
| number | number | `0` |
|
|
102
|
+
| boolean | boolean | `false` (not `"No"`) |
|
|
103
|
+
| date / time / datetime | string | `"2026-01-01"` / `"09:00"` / `"2026-01-01 09:00"` |
|
|
104
|
+
| list | string[] | `["A", "B"]` |
|
|
105
|
+
| single_choice | a key of `option_map` | `"ON_SALE"` (not `"On sale"`) |
|
|
106
|
+
| multiple_choice | array of `option_map` keys | `["ONLINE"]` |
|
|
107
|
+
|
|
108
|
+
Empty cells fall back to the configured default. `null` / `undefined` (or not configured) means no default: a `required` field then fails with `不能为空`, and an optional field submits `null` (clears the field). Any other configured value — including an empty string `""`, an empty array `[]`, or whitespace-only text — is submitted as-is, and a `required` field with a default no longer fails; configuring an empty default on a required field effectively allows empty values, so make sure this matches your business semantics. The template renders labels automatically (e.g. `ON_SALE` → `On sale`).
|
|
65
109
|
|
|
66
110
|
## Validation
|
|
67
111
|
|
|
@@ -74,40 +118,30 @@ validateField("19.99", {
|
|
|
74
118
|
type: "number",
|
|
75
119
|
property: { required: false, precision: 2 },
|
|
76
120
|
});
|
|
77
|
-
// { validateSuccess: true, validateValue: 19.99 }
|
|
121
|
+
// { validateSuccess: true, validateValue: "19.99" }
|
|
78
122
|
```
|
|
79
123
|
|
|
80
124
|
## Components
|
|
81
125
|
|
|
82
126
|
```tsx
|
|
83
|
-
import {
|
|
127
|
+
import { ExportButton, ImportButton, exportRowsToFile } from "antd-import-export";
|
|
84
128
|
|
|
129
|
+
// import: template download, parsing, editable preview, batched submit, row-level errors
|
|
85
130
|
<ImportButton
|
|
86
131
|
title="Supplier"
|
|
87
132
|
fieldSchemas={fieldSchemas}
|
|
88
133
|
importRows={(rows) => importSuppliers(rows)}
|
|
89
|
-
|
|
90
|
-
|
|
134
|
+
onModalClose={refresh}
|
|
135
|
+
/>
|
|
91
136
|
|
|
137
|
+
// export the current filters, paged with a cursor inside the package
|
|
92
138
|
<ExportButton
|
|
93
139
|
title="Supplier"
|
|
94
140
|
fieldSchemas={fieldSchemas}
|
|
95
|
-
// merge your own filters inside exportRows; paging params come from the package
|
|
96
141
|
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";
|
|
142
|
+
/>
|
|
110
143
|
|
|
144
|
+
// export rows already in memory (e.g. selected rows); downloads immediately
|
|
111
145
|
await exportRowsToFile({ title: "Supplier", fieldSchemas, rows: selectedRows });
|
|
112
146
|
```
|
|
113
147
|
|
|
@@ -120,7 +154,7 @@ await exportRowsToFile({ title: "Supplier", fieldSchemas, rows: selectedRows });
|
|
|
120
154
|
| `buttonText` | `string` | import button label, defaults to `导入` |
|
|
121
155
|
| `batchSize` | `number` | rows per batch, defaults to 20, capped at 200 (backend contract); invalid values fall back to 20 |
|
|
122
156
|
| `importRows` | `(rows) => Promise<Record<string, unknown>[]>` | submits one batch, returns the same length; **empty object means success** |
|
|
123
|
-
| `beforeImport` | `(rows) => void \| Promise<void>` | runs after parsing and before the preview opens
|
|
157
|
+
| `beforeImport` | `(rows) => void \| Promise<void>` | runs after parsing and before the preview opens (rows are read-only); throw to abort, return values are ignored |
|
|
124
158
|
| `afterImport` | `() => void` | fires once when the task ends (completed / failed / canceled), not on pause |
|
|
125
159
|
| `onModalClose` | `() => void` | fires once after the modal closes, whatever the outcome |
|
|
126
160
|
|
|
@@ -131,13 +165,11 @@ await exportRowsToFile({ title: "Supplier", fieldSchemas, rows: selectedRows });
|
|
|
131
165
|
| `title` | `string` | file name and task title |
|
|
132
166
|
| `fieldSchemas` | `FieldSchema[]` | field definitions |
|
|
133
167
|
| `buttonText` | `string` | button label, defaults to `导出` |
|
|
134
|
-
| `exportRows` | `(params) => Promise<{ count, results }>` | cursor paging; **every row needs a numeric `id
|
|
168
|
+
| `exportRows` | `(params) => Promise<{ count, results }>` | cursor paging; **every row needs a numeric `id` and rows must be `id`-ascending** |
|
|
135
169
|
| `beforeExport` | `() => void \| Promise<void>` | runs before the task is created; throw to abort |
|
|
136
170
|
| `afterExport` | `() => void` | fires once when the task ends (completed / failed / canceled) |
|
|
137
171
|
| `onModalClose` | `() => void` | fires once after the modal closes |
|
|
138
172
|
|
|
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
173
|
### exportRowsToFile
|
|
142
174
|
|
|
143
175
|
| option | type | notes |
|
|
@@ -146,37 +178,52 @@ The cancel button is disabled while the file is generated: ExcelJS parses and wr
|
|
|
146
178
|
| `fieldSchemas` | `FieldSchema[]` | field definitions |
|
|
147
179
|
| `rows` | `object[]` | rows already in memory |
|
|
148
180
|
|
|
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
181
|
### Import contract
|
|
152
182
|
|
|
153
|
-
`importRows` returns
|
|
183
|
+
`importRows` returns the per-row outcome of the batch, in the same order as the submitted rows:
|
|
154
184
|
|
|
155
185
|
| Response | Meaning |
|
|
156
186
|
| --- | --- |
|
|
157
187
|
| `{}` | the row succeeded |
|
|
158
188
|
| `{ "name": ["required"] }` | field-level failure, mapped back to the preview cell |
|
|
159
|
-
| `{ "
|
|
160
|
-
| `{ "warehouse": ["not found"] }` (key not in the field schema) | also treated as a whole-row failure
|
|
161
|
-
|
|
|
162
|
-
| HTTP 4xx/5xx, network
|
|
189
|
+
| `{ "message": "name already exists" }` (key not in the field schema) | the whole row failed; the message is shown as `name already exists` |
|
|
190
|
+
| `{ "warehouse": ["not found"] }` (key not in the field schema) | also treated as a whole-row failure; the message is shown as `not found` |
|
|
191
|
+
| number of results ≠ number of rows | treated as an API error, task pauses |
|
|
192
|
+
| any thrown error (incl. HTTP 4xx/5xx, network) | pauses the whole task, resumable |
|
|
193
|
+
|
|
194
|
+
Whether an error body key is in the `FieldSchema` decides the error type: **key in the field schema → field-level error** (mapped back to the preview cell); **key not in the field schema → whole-row error**, showing the raw message only (no key). The package does not rely on `detail` / `non_field_errors` or any other backend convention — any backend can adapt its response to this shape inside `importRows`.
|
|
195
|
+
|
|
196
|
+
Merged cells are not supported: if the file contains any merged cell the whole file is **rejected** with the affected ranges shown (first 3 plus the total count); unmerge the cells and re-import.
|
|
163
197
|
|
|
164
|
-
|
|
198
|
+
Duplicate header names are not supported: if the same header appears in multiple columns the whole file is **rejected** with the affected columns shown (e.g. `Name (A, C)`); the package cannot tell which column to use. Export-only columns are identified by their field definition (`importable: false`), not by the `(仅导出)` marker text; they are ignored and do not participate in duplicate detection.
|
|
199
|
+
|
|
200
|
+
A single import file is limited to **20MB** (public constant `MAX_IMPORT_FILE_SIZE`); larger files are rejected up front. The package does not limit the number of rows — the 20,000-row check in the example is a business rule of the host app.
|
|
165
201
|
|
|
166
202
|
### What `beforeImport` receives
|
|
167
203
|
|
|
168
|
-
`beforeImport(rows)` runs **after parsing and before the preview opens
|
|
204
|
+
`beforeImport(rows)` runs **after parsing and before the preview opens**; `rows` are the parsed, per-cell validated rows (read-only), useful for validation and telemetry. **Replacing or filtering the preview data via the return value is not supported**: the return value is ignored and the preview always shows every parsed data row.
|
|
169
205
|
|
|
170
|
-
|
|
206
|
+
```ts
|
|
207
|
+
import type { ImportRow } from "antd-import-export";
|
|
208
|
+
|
|
209
|
+
interface ImportRow {
|
|
210
|
+
key: string; // unique row key (assigned in order while parsing)
|
|
211
|
+
rowNumber: number; // the real Excel row number
|
|
212
|
+
values: Record<string, unknown>; // editor values: booleans/single choices are labels, multiple choices are label arrays, lists are semicolon-joined
|
|
213
|
+
errors: Record<string, string>; // field-level validation errors
|
|
214
|
+
taskIndex?: number; // internal: always undefined in beforeImport, ignore it
|
|
215
|
+
}
|
|
216
|
+
```
|
|
217
|
+
|
|
218
|
+
| Behavior | Effect |
|
|
171
219
|
| --- | --- |
|
|
172
|
-
|
|
|
173
|
-
|
|
|
174
|
-
| user edits | ❌ the preview has not opened yet |
|
|
175
|
-
| rows the user deleted | ❌ same reason |
|
|
220
|
+
| returns nothing (`void` / `Promise<void>`) | ignored; the preview opens |
|
|
221
|
+
| throws | abort; the preview never opens |
|
|
176
222
|
|
|
177
|
-
|
|
223
|
+
> In TypeScript, returning any other value is a compile error (the old `ImportRow[]` return is a breaking change); in plain JS the return value is ignored and a single `console.warn` is printed.
|
|
178
224
|
|
|
179
225
|
```tsx
|
|
226
|
+
// abort with a message
|
|
180
227
|
beforeImport={(rows) => {
|
|
181
228
|
if (rows.length > 20000) {
|
|
182
229
|
throw new Error(`too many rows: ${rows.length}, limit 20,000`);
|
|
@@ -184,16 +231,14 @@ beforeImport={(rows) => {
|
|
|
184
231
|
}}
|
|
185
232
|
```
|
|
186
233
|
|
|
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
234
|
### Export contract
|
|
190
235
|
|
|
191
|
-
`exportRows` fetches one
|
|
236
|
+
`exportRows` fetches one batch at a time and returns:
|
|
192
237
|
|
|
193
238
|
| Field | Type | Notes |
|
|
194
239
|
| --- | --- | --- |
|
|
195
240
|
| `count` | `number` | total rows under the current filters, used for progress |
|
|
196
|
-
| `results` | `object[]` | rows of this page; **every row needs a numeric `id
|
|
241
|
+
| `results` | `object[]` | rows of this page; **every row needs a numeric `id`**, and **rows must be sorted by `id` ascending** for the cursor |
|
|
197
242
|
|
|
198
243
|
Paging is driven by the package, so `exportRows` only ever receives:
|
|
199
244
|
|
|
@@ -202,42 +247,71 @@ Paging is driven by the package, so `exportRows` only ever receives:
|
|
|
202
247
|
| first page | `{}` |
|
|
203
248
|
| following pages | `{ cursor_id: id of the last row of the previous page }` |
|
|
204
249
|
|
|
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
250
|
An empty `results` array ends the task.
|
|
209
251
|
|
|
210
|
-
|
|
252
|
+
`results` must be returned with `id` **ascending**; the package uses the last `id` of the page as the next `cursor_id`. Pages must not overlap (the first `id` of the next page must be greater than the last `id` of the previous page). If the next page's `id` does not strictly increase (e.g. the API ignores the cursor and repeats the same page), the task fails with a hint to check `cursor_id` paging.
|
|
253
|
+
|
|
254
|
+
### When cancel and pause take effect
|
|
211
255
|
|
|
212
|
-
|
|
256
|
+
Cancel and pause never abort an in-flight request — they take effect once the current step finishes:
|
|
213
257
|
|
|
214
|
-
|
|
|
258
|
+
| Current state | What cancel / pause does |
|
|
215
259
|
| --- | --- |
|
|
216
|
-
|
|
|
217
|
-
|
|
|
260
|
+
| export while fetching | enters "canceled" after the current data request completes |
|
|
261
|
+
| import while submitting | enters "canceled" or "paused" after in-flight data finishes importing |
|
|
262
|
+
| import already paused | cancel takes effect immediately |
|
|
218
263
|
|
|
219
|
-
|
|
264
|
+
## Backend adaptation
|
|
220
265
|
|
|
221
|
-
|
|
266
|
+
The package does not bind to a request library or backend framework. The host app only needs to adapt its responses to these minimal contracts inside the callbacks.
|
|
222
267
|
|
|
223
|
-
|
|
268
|
+
### `importRows`
|
|
224
269
|
|
|
225
|
-
|
|
226
|
-
|
|
227
|
-
|
|
228
|
-
|
|
229
|
-
|
|
270
|
+
- Input: a batch of validated row payloads;
|
|
271
|
+
- Output: an array with the **same length**; `{}` means the row succeeded;
|
|
272
|
+
- Error-body key in the `FieldSchema` → field-level error; key not in the schema → whole-row error (message shown).
|
|
273
|
+
|
|
274
|
+
```ts
|
|
275
|
+
// any backend response -> generic error body
|
|
276
|
+
importRows: async (rows) => {
|
|
277
|
+
const result = await api.importRows(rows);
|
|
278
|
+
return result.items.map((item) => (item.ok ? {} : { message: item.errorMessage }));
|
|
279
|
+
};
|
|
280
|
+
```
|
|
281
|
+
|
|
282
|
+
If the request library throws, just `throw`; the task pauses (HTTP status codes are recognized when available).
|
|
230
283
|
|
|
231
|
-
|
|
284
|
+
### `exportRows`
|
|
232
285
|
|
|
233
|
-
|
|
286
|
+
- Input: `{}` for the first page, `{ cursor_id: number }` for following pages;
|
|
287
|
+
- Output: `{ count, results }`; every row in `results` must have a **numeric `id`**, returned in ascending `id` order;
|
|
288
|
+
- The cursor is driven by the package: `cursor_id` is the last `id` of the previous page, and pages must not overlap.
|
|
234
289
|
|
|
235
|
-
|
|
236
|
-
2. In Next.js App Router, add `"use client"` to the file that imports them.
|
|
290
|
+
Other paging styles need adaptation. Example with offset paging:
|
|
237
291
|
|
|
238
|
-
|
|
292
|
+
```ts
|
|
293
|
+
exportRows: async ({ cursor_id }) => {
|
|
294
|
+
const offset = typeof cursor_id === "number" ? cursor_id : 0;
|
|
295
|
+
const page = await api.list({ offset, limit: 20 });
|
|
296
|
+
return {
|
|
297
|
+
count: page.total,
|
|
298
|
+
// add a monotonically increasing numeric id used as the cursor
|
|
299
|
+
results: page.list.map((row, index) => ({ ...row, id: offset + index + 1 })),
|
|
300
|
+
};
|
|
301
|
+
};
|
|
302
|
+
```
|
|
303
|
+
|
|
304
|
+
### Request error objects
|
|
239
305
|
|
|
240
|
-
|
|
306
|
+
If your request library throws errors that are not shaped like `{ status, data }` / `{ response: { status, data } }`, wrap them into that shape for better messages; otherwise the package falls back to `error.message`.
|
|
307
|
+
|
|
308
|
+
## Public API
|
|
309
|
+
|
|
310
|
+
- Components: `ImportButton`, `ExportButton`
|
|
311
|
+
- Functions: `exportRowsToFile`, `validateField`, single-type validators (`validateTextField` / `validateNumberField` / `validateBooleanField` / `validateDateField` / `validateTimeField` / `validateDateTimeField` / `validateListField` / `validateSingleChoiceField` / `validateMultipleChoiceField`), `resetTasks`
|
|
312
|
+
- Constants: `MAX_IMPORT_FILE_SIZE`, `MULTI_VALUE_SEPARATOR`
|
|
313
|
+
- Utilities: `importableFields`, `joinMultiValues`, `splitMultiValues`
|
|
314
|
+
- Types: `FieldSchema` and its per-type variants, `ImportRow`, `ImportRowResult`, `ImportRowErrorBody`, `ImportRowFieldError`, `PagedData`, `ExportRowsToFileOptions`, `ImportButtonProps`, `ExportButtonProps`, `ValidateResult`
|
|
241
315
|
|
|
242
316
|
## Development
|
|
243
317
|
|
|
@@ -248,8 +322,6 @@ npm run preview # build, then start the demo
|
|
|
248
322
|
npm run verify # release gate: lint + tests + build + demo type check
|
|
249
323
|
```
|
|
250
324
|
|
|
251
|
-
See [RELEASING.md](./RELEASING.md) for the full npm release process.
|
|
252
|
-
|
|
253
325
|
## License
|
|
254
326
|
|
|
255
327
|
MIT
|
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
import React from "react";
|
|
2
|
+
import type { ImportRow } from "../core/excel/importRow.cjs";
|
|
3
|
+
import type { FieldSchema } from "../core/schema/index.cjs";
|
|
4
|
+
interface EditableImportCellProps {
|
|
5
|
+
field: FieldSchema;
|
|
6
|
+
record: ImportRow;
|
|
7
|
+
disabled: boolean;
|
|
8
|
+
onChange: (value: unknown) => void;
|
|
9
|
+
onSave: (value: unknown) => void;
|
|
10
|
+
}
|
|
11
|
+
declare const EditableImportCell: React.FC<EditableImportCellProps>;
|
|
12
|
+
export default EditableImportCell;
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import React from "react";
|
|
2
|
-
import type { ImportRow } from "../core/excel/importRow";
|
|
3
|
-
import type { FieldSchema } from "../core/schema";
|
|
2
|
+
import type { ImportRow } from "../core/excel/importRow.js";
|
|
3
|
+
import type { FieldSchema } from "../core/schema/index.js";
|
|
4
4
|
interface EditableImportCellProps {
|
|
5
5
|
field: FieldSchema;
|
|
6
6
|
record: ImportRow;
|
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
import React from "react";
|
|
2
|
+
import type { FieldSchema } from "../core/schema/index.cjs";
|
|
3
|
+
import type { PagedData } from "../core/types.cjs";
|
|
4
|
+
export interface ExportButtonProps {
|
|
5
|
+
title: string;
|
|
6
|
+
fieldSchemas: FieldSchema[];
|
|
7
|
+
/** 按钮文案, 默认「导出」 */
|
|
8
|
+
buttonText?: string;
|
|
9
|
+
disabled?: boolean;
|
|
10
|
+
/** 拉取一页待导出的数据; 分页参数由包传入, 筛选条件在这里合并 */
|
|
11
|
+
exportRows: (params: Record<string, unknown>) => Promise<PagedData<object>>;
|
|
12
|
+
/** 创建任务前触发, 可做二次确认或自定义校验; 抛错则中止, 不创建任务 */
|
|
13
|
+
beforeExport?: () => void | Promise<void>;
|
|
14
|
+
/** 导出任务结束(成功/失败/取消)时回调一次 */
|
|
15
|
+
afterExport?: () => void;
|
|
16
|
+
/** 弹窗关闭后触发, 无论任务是否结束 */
|
|
17
|
+
onModalClose?: () => void;
|
|
18
|
+
}
|
|
19
|
+
declare const ExportButton: React.FC<ExportButtonProps>;
|
|
20
|
+
export default ExportButton;
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import React from "react";
|
|
2
|
-
import type { FieldSchema } from "../core/schema";
|
|
3
|
-
import type { PagedData } from "../core/types";
|
|
2
|
+
import type { FieldSchema } from "../core/schema/index.js";
|
|
3
|
+
import type { PagedData } from "../core/types.js";
|
|
4
4
|
export interface ExportButtonProps {
|
|
5
5
|
title: string;
|
|
6
6
|
fieldSchemas: FieldSchema[];
|
|
@@ -0,0 +1,25 @@
|
|
|
1
|
+
import React from "react";
|
|
2
|
+
import type { ImportRowErrorBody } from "../core/types.cjs";
|
|
3
|
+
import type { ImportRow } from "../core/excel/importRow.cjs";
|
|
4
|
+
import type { FieldSchema } from "../core/schema/index.cjs";
|
|
5
|
+
export interface ImportButtonProps {
|
|
6
|
+
title: string;
|
|
7
|
+
fieldSchemas: FieldSchema[];
|
|
8
|
+
/** 导入按钮文案, 默认「导入」; 模板按钮文案固定 */
|
|
9
|
+
buttonText?: string;
|
|
10
|
+
/** 每批提交的行数, 默认 20, 范围 1-200 */
|
|
11
|
+
batchSize?: number;
|
|
12
|
+
/** 提交一批待导入的行, 返回等长的逐行结果; 空对象表示成功 */
|
|
13
|
+
importRows: (rows: Record<string, unknown>[]) => Promise<ImportRowErrorBody[]>;
|
|
14
|
+
/**
|
|
15
|
+
* 解析完成、打开预览前触发, 拿到解析并校验过的只读行, 可用于校验/埋点。
|
|
16
|
+
* 抛错即中止; 返回值会被忽略, 不支持通过返回值替换或过滤预览数据。
|
|
17
|
+
*/
|
|
18
|
+
beforeImport?: (rows: readonly ImportRow[]) => void | Promise<void>;
|
|
19
|
+
/** 导入任务结束(成功/失败/取消)时回调一次; 用 onModalClose 刷新时可以不传 */
|
|
20
|
+
afterImport?: () => void;
|
|
21
|
+
/** 弹窗关闭后触发, 无论是导入完成、取消还是中途关闭 */
|
|
22
|
+
onModalClose?: () => void;
|
|
23
|
+
}
|
|
24
|
+
declare const ImportButton: React.FC<ImportButtonProps>;
|
|
25
|
+
export default ImportButton;
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import React from "react";
|
|
2
|
-
import type { ImportRowErrorBody } from "../core/types";
|
|
3
|
-
import type { ImportRow } from "../core/excel/importRow";
|
|
4
|
-
import type { FieldSchema } from "../core/schema";
|
|
2
|
+
import type { ImportRowErrorBody } from "../core/types.js";
|
|
3
|
+
import type { ImportRow } from "../core/excel/importRow.js";
|
|
4
|
+
import type { FieldSchema } from "../core/schema/index.js";
|
|
5
5
|
export interface ImportButtonProps {
|
|
6
6
|
title: string;
|
|
7
7
|
fieldSchemas: FieldSchema[];
|
|
@@ -11,8 +11,11 @@ export interface ImportButtonProps {
|
|
|
11
11
|
batchSize?: number;
|
|
12
12
|
/** 提交一批待导入的行, 返回等长的逐行结果; 空对象表示成功 */
|
|
13
13
|
importRows: (rows: Record<string, unknown>[]) => Promise<ImportRowErrorBody[]>;
|
|
14
|
-
/**
|
|
15
|
-
|
|
14
|
+
/**
|
|
15
|
+
* 解析完成、打开预览前触发, 拿到解析并校验过的只读行, 可用于校验/埋点。
|
|
16
|
+
* 抛错即中止; 返回值会被忽略, 不支持通过返回值替换或过滤预览数据。
|
|
17
|
+
*/
|
|
18
|
+
beforeImport?: (rows: readonly ImportRow[]) => void | Promise<void>;
|
|
16
19
|
/** 导入任务结束(成功/失败/取消)时回调一次; 用 onModalClose 刷新时可以不传 */
|
|
17
20
|
afterImport?: () => void;
|
|
18
21
|
/** 弹窗关闭后触发, 无论是导入完成、取消还是中途关闭 */
|
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
import React from "react";
|
|
2
|
+
export interface ImportCheckMessages {
|
|
3
|
+
/** 没有对上的必填列名 */
|
|
4
|
+
missingTitles: string[];
|
|
5
|
+
/** 表头级问题: 文件打不开、没有工作表等 */
|
|
6
|
+
headerMessages: string[];
|
|
7
|
+
}
|
|
8
|
+
/** 导入校验的明细内容, 使用普通正文样式, 不再叠加图标和强调色 */
|
|
9
|
+
declare const ImportCheckContent: React.FC<ImportCheckMessages>;
|
|
10
|
+
export default ImportCheckContent;
|
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
import React from "react";
|
|
2
|
+
import type { ImportRow } from "../core/excel/importRow.cjs";
|
|
3
|
+
import type { FieldSchema } from "../core/schema/index.cjs";
|
|
4
|
+
interface ImportPreviewModalProps {
|
|
5
|
+
open: boolean;
|
|
6
|
+
title: string;
|
|
7
|
+
fieldSchemas: FieldSchema[];
|
|
8
|
+
rows: ImportRow[];
|
|
9
|
+
taskId?: string;
|
|
10
|
+
/** 文件里实际存在的列; 预览只展示这些列, 缺列不渲染也不提交 */
|
|
11
|
+
includedKeys: string[];
|
|
12
|
+
onChangeCell: (row: ImportRow, field: FieldSchema, value: unknown) => void;
|
|
13
|
+
onSaveCell: (row: ImportRow, field: FieldSchema, value: unknown) => void;
|
|
14
|
+
onDelete: (row: ImportRow) => void;
|
|
15
|
+
onConfirm: () => void;
|
|
16
|
+
onClose: () => void;
|
|
17
|
+
}
|
|
18
|
+
declare const ImportPreviewModal: React.FC<ImportPreviewModalProps>;
|
|
19
|
+
export default ImportPreviewModal;
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import React from "react";
|
|
2
|
-
import type { ImportRow } from "../core/excel/importRow";
|
|
3
|
-
import type { FieldSchema } from "../core/schema";
|
|
2
|
+
import type { ImportRow } from "../core/excel/importRow.js";
|
|
3
|
+
import type { FieldSchema } from "../core/schema/index.js";
|
|
4
4
|
interface ImportPreviewModalProps {
|
|
5
5
|
open: boolean;
|
|
6
6
|
title: string;
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
import type { ImportRowErrorBody, ImportRowResult } from "../core/types.cjs";
|
|
2
|
+
/**
|
|
3
|
+
* 把接口返回的单行错误体转成任务行结果。
|
|
4
|
+
* 错误体 key 在 FieldSchema 中 = 字段错误; 不在 = 整行错误(消息保留 key, 便于排查)。
|
|
5
|
+
* 不依赖 detail / non_field_errors 等具体后端约定, 任意后端在 importRows 里转换成这个形状即可。
|
|
6
|
+
*/
|
|
7
|
+
export declare function parseImportBatchResult(result: ImportRowErrorBody, fieldKeys: ReadonlySet<string>): ImportRowResult;
|
|
@@ -1,9 +1,7 @@
|
|
|
1
|
-
import type { ImportRowErrorBody, ImportRowResult } from "../core/types";
|
|
2
|
-
/** DRF 的列表类型技术错误对用户没有意义, 统一成可读提示 */
|
|
3
|
-
export declare function normalizeImportErrorMessage(message: string): string;
|
|
1
|
+
import type { ImportRowErrorBody, ImportRowResult } from "../core/types.js";
|
|
4
2
|
/**
|
|
5
3
|
* 把接口返回的单行错误体转成任务行结果。
|
|
6
|
-
*
|
|
7
|
-
*
|
|
4
|
+
* 错误体 key 在 FieldSchema 中 = 字段错误; 不在 = 整行错误(消息保留 key, 便于排查)。
|
|
5
|
+
* 不依赖 detail / non_field_errors 等具体后端约定, 任意后端在 importRows 里转换成这个形状即可。
|
|
8
6
|
*/
|
|
9
|
-
export declare function parseImportBatchResult(result: ImportRowErrorBody, fieldKeys:
|
|
7
|
+
export declare function parseImportBatchResult(result: ImportRowErrorBody, fieldKeys: ReadonlySet<string>): ImportRowResult;
|
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
import type { ImportRow } from "../core/excel/importRow.cjs";
|
|
2
|
+
import type { TaskItem } from "../core/task/index.cjs";
|
|
3
|
+
export type DataStatusKey = "valid" | "invalid";
|
|
4
|
+
export type ImportStatusKey = "pending" | "running" | "completed" | "failed" | "canceled";
|
|
5
|
+
export declare function getTaskMeta(task: TaskItem): {
|
|
6
|
+
label: string;
|
|
7
|
+
color: string;
|
|
8
|
+
};
|
|
9
|
+
export declare function getRemainingTimeText(task: TaskItem, remainingSeconds: number | null): string | null;
|
|
10
|
+
export declare function getTaskProgressStatus(task: TaskItem): "exception" | "success" | "normal";
|
|
11
|
+
export declare const dataStatusMeta: Record<DataStatusKey, {
|
|
12
|
+
label: string;
|
|
13
|
+
color: string;
|
|
14
|
+
}>;
|
|
15
|
+
export declare const importStatusMeta: Record<ImportStatusKey, {
|
|
16
|
+
label: string;
|
|
17
|
+
color: string;
|
|
18
|
+
}>;
|
|
19
|
+
export declare function getDataStatusKey(record: ImportRow): DataStatusKey;
|
|
20
|
+
export declare function getImportStatusKey(record: ImportRow, taskId: string | undefined, task: TaskItem | undefined): ImportStatusKey;
|
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import type { ImportRow } from "../core/excel/importRow";
|
|
2
|
-
import type { TaskItem } from "../core/task";
|
|
1
|
+
import type { ImportRow } from "../core/excel/importRow.js";
|
|
2
|
+
import type { TaskItem } from "../core/task/index.js";
|
|
3
3
|
export type DataStatusKey = "valid" | "invalid";
|
|
4
4
|
export type ImportStatusKey = "pending" | "running" | "completed" | "failed" | "canceled";
|
|
5
5
|
export declare function getTaskMeta(task: TaskItem): {
|
|
@@ -0,0 +1,56 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* 日期与时间的唯一实现: 输入解析、真实日期校验、规范化输出、ExcelJS Date 转换与导出展示都在这里。
|
|
3
|
+
* 校验(validate)、导入解析(parseSheet)、导出展示(worksheet)必须复用本模块, 不要另写格式化规则。
|
|
4
|
+
*
|
|
5
|
+
* 约定:
|
|
6
|
+
* - date: 严格 YYYY-MM-DD (4-2-2), 且必须是真实存在的日期
|
|
7
|
+
* - time: H:mm / HH:mm / H:mm:ss / HH:mm:ss, 小时可 1 位, 分秒必须 2 位
|
|
8
|
+
* - datetime: YYYY-MM-DD 后接空白和 time
|
|
9
|
+
* - 输出统一补零; 秒为 0 时不带秒
|
|
10
|
+
* - ExcelJS 的日期单元格按 UTC 还原; 导出侧的 Date 也按 UTC 解释, 保证导入导出与浏览器时区无关
|
|
11
|
+
*/
|
|
12
|
+
export interface DateParts {
|
|
13
|
+
year: number;
|
|
14
|
+
month: number;
|
|
15
|
+
day: number;
|
|
16
|
+
}
|
|
17
|
+
export interface TimeParts {
|
|
18
|
+
hour: number;
|
|
19
|
+
minute: number;
|
|
20
|
+
second: number;
|
|
21
|
+
}
|
|
22
|
+
/** 两位补零: 日期/时间的年月日时分秒在拼文本时都必须补齐 */
|
|
23
|
+
export declare function pad2(value: number): string;
|
|
24
|
+
/** 解析日期文本; 非法或非字符串返回 null。只接受 4-2-2 且真实存在的日期 */
|
|
25
|
+
export declare function parseDateText(text: unknown): DateParts | null;
|
|
26
|
+
/** 解析时间文本; 非法或非字符串返回 null。小时可 1 位, 分秒必须 2 位, 缺秒按 0 处理 */
|
|
27
|
+
export declare function parseTimeText(text: unknown): TimeParts | null;
|
|
28
|
+
/** 解析日期时间文本; 日期与时间之间允许任意空白, 非法或非字符串返回 null */
|
|
29
|
+
export declare function parseDateTimeText(text: unknown): {
|
|
30
|
+
date: DateParts;
|
|
31
|
+
time: TimeParts;
|
|
32
|
+
} | null;
|
|
33
|
+
export declare function formatDateParts({ year, month, day }: DateParts): string;
|
|
34
|
+
/** 时间统一补零; 秒为 0 时不带秒 */
|
|
35
|
+
export declare function formatTimeParts({ hour, minute, second }: TimeParts): string;
|
|
36
|
+
export declare function formatDateTimeParts(date: DateParts, time: TimeParts): string;
|
|
37
|
+
/** ExcelJS 的日期单元格按 UTC 还原, 这里使用 UTC getter 与之保持一致 */
|
|
38
|
+
export declare function datePartsFromDate(date: Date): DateParts;
|
|
39
|
+
export declare function timePartsFromDate(date: Date): TimeParts;
|
|
40
|
+
export declare function formatDateFromDate(date: Date): string;
|
|
41
|
+
export declare function formatTimeFromDate(date: Date): string;
|
|
42
|
+
export declare function formatDateTimeFromDate(date: Date): string;
|
|
43
|
+
/**
|
|
44
|
+
* Excel 日期序列号(1900 系统) 转 Date; 只在日期/时间字段上使用。
|
|
45
|
+
* 25569 是 1970-01-01 的 Excel 序列号; ExcelJS 也按 UTC 还原日期。
|
|
46
|
+
*/
|
|
47
|
+
export declare function excelSerialToDate(serial: number): Date | null;
|
|
48
|
+
/** 导出展示: 接口值 -> date 文本; 无法识别返回 null, 由调用方原样输出 */
|
|
49
|
+
export declare function normalizeExportDate(value: unknown): string | null;
|
|
50
|
+
/** 导出展示: 接口值 -> time 文本; 无法识别返回 null, 由调用方原样输出 */
|
|
51
|
+
export declare function normalizeExportTime(value: unknown): string | null;
|
|
52
|
+
/**
|
|
53
|
+
* 导出展示: 接口值 -> datetime 文本; 无法识别返回 null, 由调用方原样输出。
|
|
54
|
+
* 纯日期字符串按当天 00:00 展示, 与历史行为一致。
|
|
55
|
+
*/
|
|
56
|
+
export declare function normalizeExportDateTime(value: unknown): string | null;
|