@firecms/data_import_export 3.0.0-canary.19 → 3.0.0-canary.191

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.
Files changed (45) hide show
  1. package/LICENSE +114 -21
  2. package/README.md +1 -4
  3. package/dist/index.d.ts +2 -4
  4. package/dist/index.es.js +12 -994
  5. package/dist/index.es.js.map +1 -1
  6. package/dist/index.umd.js +29 -2
  7. package/dist/index.umd.js.map +1 -1
  8. package/dist/useImportExportPlugin.d.ts +6 -4
  9. package/package.json +17 -34
  10. package/src/index.ts +2 -4
  11. package/src/useImportExportPlugin.tsx +10 -6
  12. package/dist/components/DataNewPropertiesMapping.d.ts +0 -15
  13. package/dist/components/ImportFileUpload.d.ts +0 -3
  14. package/dist/components/ImportNewPropertyFieldPreview.d.ts +0 -10
  15. package/dist/components/ImportSaveInProgress.d.ts +0 -8
  16. package/dist/components/index.d.ts +0 -4
  17. package/dist/export_import/ExportCollectionAction.d.ts +0 -11
  18. package/dist/export_import/ImportCollectionAction.d.ts +0 -15
  19. package/dist/export_import/export.d.ts +0 -10
  20. package/dist/hooks/index.d.ts +0 -1
  21. package/dist/hooks/useImportConfig.d.ts +0 -2
  22. package/dist/types/column_mapping.d.ts +0 -22
  23. package/dist/types/index.d.ts +0 -1
  24. package/dist/utils/data.d.ts +0 -11
  25. package/dist/utils/file_to_json.d.ts +0 -11
  26. package/dist/utils/get_import_inference_type.d.ts +0 -2
  27. package/dist/utils/get_properties_mapping.d.ts +0 -3
  28. package/dist/utils/index.d.ts +0 -4
  29. package/src/components/DataNewPropertiesMapping.tsx +0 -128
  30. package/src/components/ImportFileUpload.tsx +0 -34
  31. package/src/components/ImportNewPropertyFieldPreview.tsx +0 -55
  32. package/src/components/ImportSaveInProgress.tsx +0 -122
  33. package/src/components/index.ts +0 -4
  34. package/src/export_import/ExportCollectionAction.tsx +0 -252
  35. package/src/export_import/ImportCollectionAction.tsx +0 -442
  36. package/src/export_import/export.ts +0 -200
  37. package/src/hooks/index.ts +0 -1
  38. package/src/hooks/useImportConfig.tsx +0 -28
  39. package/src/types/column_mapping.ts +0 -32
  40. package/src/types/index.ts +0 -1
  41. package/src/utils/data.ts +0 -223
  42. package/src/utils/file_to_json.ts +0 -88
  43. package/src/utils/get_import_inference_type.ts +0 -27
  44. package/src/utils/get_properties_mapping.ts +0 -59
  45. package/src/utils/index.ts +0 -4
@@ -1,128 +0,0 @@
1
- import { getPropertyInPath, Property, } from "@firecms/core";
2
- import {
3
- ChevronRightIcon,
4
- Select,
5
- SelectItem,
6
- Table,
7
- TableBody,
8
- TableCell,
9
- TableHeader,
10
- TableRow,
11
- Typography
12
- } from "@firecms/ui";
13
-
14
- export interface DataPropertyMappingProps {
15
- idColumn?: string;
16
- headersMapping: Record<string, string | null>;
17
- originProperties: Record<string, Property>;
18
- destinationProperties: Record<string, Property>;
19
- onIdPropertyChanged: (value: string | null) => void;
20
- buildPropertyView?: (props: {
21
- isIdColumn: boolean,
22
- property: Property | null,
23
- propertyKey: string | null,
24
- importKey: string
25
- }) => React.ReactNode;
26
- }
27
-
28
- export function DataNewPropertiesMapping({
29
- idColumn,
30
- headersMapping,
31
- originProperties,
32
- destinationProperties,
33
- onIdPropertyChanged,
34
- buildPropertyView,
35
- }: DataPropertyMappingProps) {
36
-
37
- return (
38
- <>
39
-
40
- <IdSelectField idColumn={idColumn}
41
- headersMapping={headersMapping}
42
- onChange={onIdPropertyChanged}/>
43
-
44
- <Table style={{
45
- tableLayout: "fixed"
46
- }}>
47
- <TableHeader>
48
- <TableCell header={true} style={{ width: "20%" }}>
49
- Column in file
50
- </TableCell>
51
- <TableCell header={true}>
52
- </TableCell>
53
- <TableCell header={true} style={{ width: "75%" }}>
54
- Property
55
- </TableCell>
56
- </TableHeader>
57
- <TableBody>
58
- {destinationProperties &&
59
- Object.entries(headersMapping)
60
- .map(([importKey, mappedKey]) => {
61
- const propertyKey = headersMapping[importKey];
62
- const property = mappedKey ? getPropertyInPath(destinationProperties, mappedKey) as Property : null;
63
-
64
- const originProperty = getPropertyInPath(originProperties, importKey) as Property | undefined;
65
- const originDataType = originProperty ? (originProperty.dataType === "array" && typeof originProperty.of === "object"
66
- ? `${originProperty.dataType} - ${(originProperty.of as Property).dataType}`
67
- : originProperty.dataType)
68
- : undefined;
69
- return <TableRow key={importKey} style={{ height: "90px" }}>
70
- <TableCell style={{ width: "20%" }}>
71
- <Typography variant={"body2"}>{importKey}</Typography>
72
- {originProperty && <Typography
73
- variant={"caption"}
74
- color={"secondary"}
75
- >{originDataType}</Typography>}
76
- </TableCell>
77
- <TableCell>
78
- <ChevronRightIcon/>
79
- </TableCell>
80
- <TableCell className={importKey === idColumn ? "text-center" : undefined}
81
- style={{ width: "75%" }}>
82
- {buildPropertyView?.({
83
- isIdColumn: importKey === idColumn,
84
- property,
85
- propertyKey,
86
- importKey
87
- })
88
- }
89
- </TableCell>
90
- </TableRow>;
91
- }
92
- )}
93
- </TableBody>
94
- </Table>
95
- </>
96
- );
97
- }
98
-
99
- function IdSelectField({
100
- idColumn,
101
- headersMapping,
102
- onChange
103
- }: {
104
- idColumn?: string,
105
- headersMapping: Record<string, string | null>;
106
- onChange: (value: string | null) => void
107
- }) {
108
- return <div>
109
- <Select
110
- size={"small"}
111
- value={idColumn ?? ""}
112
- onChange={(event) => {
113
- const value = event.target.value;
114
- onChange(value === "none" ? null : value);
115
- }}
116
- renderValue={(value) => {
117
- return <Typography variant={"body2"}>
118
- {value !== "" ? value : "Autogenerate ID"}
119
- </Typography>;
120
- }}
121
- label={"Column that will be used as ID for each document"}>
122
- <SelectItem value={"none"}>Autogenerate ID</SelectItem>
123
- {Object.entries(headersMapping).map(([key, value]) => {
124
- return <SelectItem key={key} value={key}>{key}</SelectItem>;
125
- })}
126
- </Select>
127
- </div>;
128
- }
@@ -1,34 +0,0 @@
1
- import { FileUpload, UploadIcon } from "@firecms/ui";
2
- import { convertFileToJson } from "../utils/file_to_json";
3
- import { useSnackbarController } from "@firecms/core";
4
-
5
- export function ImportFileUpload({ onDataAdded }: { onDataAdded: (data: object[]) => void }) {
6
- const snackbarController = useSnackbarController();
7
- return <FileUpload
8
- accept={{
9
- "text/*": [".csv", ".xls", ".xlsx"],
10
- "application/vnd.ms-excel": [".xls", ".xlsx"],
11
- "application/msexcel": [".xls", ".xlsx"],
12
- "application/vnd.ms-office": [".xls", ".xlsx"],
13
- "application/xls": [".xls", ".xlsx"],
14
- "application/x-xls": [".xls", ".xlsx"],
15
- "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet": [".xls", ".xlsx"],
16
- "application/json": [".json"],
17
- }}
18
- preventDropOnDocument={true}
19
- size={"small"}
20
- maxFiles={1}
21
- uploadDescription={<><UploadIcon/>Drag and drop a file here or click to upload</>}
22
- onFilesAdded={(files: File[]) => {
23
- if (files.length > 0) {
24
- convertFileToJson(files[0])
25
- .then((jsonData) => {
26
- onDataAdded(jsonData);
27
- })
28
- .catch((error) => {
29
- console.error("Error parsing file", error);
30
- snackbarController.open({ type: "error", message: error.message });
31
- });
32
- }
33
- }}/>
34
- }
@@ -1,55 +0,0 @@
1
- import React from "react";
2
- import { ErrorBoundary, PropertyConfigBadge, getFieldConfig, Property, useCustomizationController } from "@firecms/core";
3
- import { EditIcon, IconButton, TextField, } from "@firecms/ui";
4
-
5
- export function ImportNewPropertyFieldPreview({
6
- propertyKey,
7
- property,
8
- onEditClick,
9
- includeName = true,
10
- onPropertyNameChanged,
11
- propertyTypeView
12
- }: {
13
- propertyKey: string | null,
14
- property: Property | null
15
- includeName?: boolean,
16
- onEditClick?: () => void,
17
- onPropertyNameChanged?: (propertyKey: string, value: string) => void,
18
- propertyTypeView?: React.ReactNode
19
- }) {
20
-
21
- const { propertyConfigs } = useCustomizationController();
22
- const widget = property ? getFieldConfig(property, propertyConfigs) : null;
23
-
24
- return <ErrorBoundary>
25
- <div
26
- className="flex flex-row w-full items-center">
27
-
28
- <div className={"mx-4"}>
29
- {propertyTypeView ?? <PropertyConfigBadge propertyConfig={widget ?? undefined}/>}
30
- </div>
31
-
32
- <div className="w-full flex flex-col grow">
33
-
34
- <div className={"flex flex-row items-center gap-2"}>
35
- {includeName &&
36
- <TextField
37
- size={"small"}
38
- className={"text-base grow"}
39
- value={property?.name ?? ""}
40
- onChange={(e) => {
41
- if (onPropertyNameChanged && propertyKey)
42
- onPropertyNameChanged(propertyKey, e.target.value);
43
- }}/>}
44
-
45
- <IconButton onClick={onEditClick} size={"small"}>
46
- <EditIcon size={"small"}/>
47
- </IconButton>
48
- </div>
49
-
50
- </div>
51
-
52
-
53
- </div>
54
- </ErrorBoundary>
55
- }
@@ -1,122 +0,0 @@
1
- import { DataSource, Entity, EntityCollection, useDataSource } from "@firecms/core";
2
- import { Button, CenteredView, CircularProgress, Typography, } from "@firecms/ui";
3
- import { useEffect, useRef, useState } from "react";
4
- import { ImportConfig } from "../types";
5
-
6
- export function ImportSaveInProgress<C extends EntityCollection>
7
- ({
8
- path,
9
- importConfig,
10
- collection,
11
- onImportSuccess
12
- }:
13
- {
14
- path: string,
15
- importConfig: ImportConfig,
16
- collection: C,
17
- onImportSuccess: (collection: C) => void
18
- }) {
19
-
20
- const [errorSaving, setErrorSaving] = useState<Error | undefined>(undefined);
21
- const dataSource = useDataSource();
22
-
23
- const savingRef = useRef<boolean>(false);
24
-
25
- const [processedEntities, setProcessedEntities] = useState<number>(0);
26
-
27
- function save() {
28
-
29
- if (savingRef.current)
30
- return;
31
-
32
- savingRef.current = true;
33
-
34
- saveDataBatch(
35
- dataSource,
36
- collection,
37
- path,
38
- importConfig.entities,
39
- 0,
40
- 25,
41
- setProcessedEntities
42
- ).then(() => {
43
- onImportSuccess(collection);
44
- savingRef.current = false;
45
- }).catch((e) => {
46
- setErrorSaving(e);
47
- savingRef.current = false;
48
- });
49
- }
50
-
51
- useEffect(() => {
52
- save();
53
- }, []);
54
-
55
- if (errorSaving) {
56
- return (
57
- <CenteredView className={"flex flex-col gap-4 items-center"}>
58
- <Typography variant={"h6"}>
59
- Error saving data
60
- </Typography>
61
-
62
- <Typography variant={"body2"} color={"error"}>
63
- {errorSaving.message}
64
- </Typography>
65
- <Button
66
- onClick={save}
67
- variant={"outlined"}>
68
- Retry
69
- </Button>
70
- </CenteredView>
71
- );
72
- }
73
-
74
- return (
75
- <CenteredView className={"flex flex-col gap-4 items-center"}>
76
- <CircularProgress/>
77
-
78
- <Typography variant={"h6"}>
79
- Saving data
80
- </Typography>
81
-
82
- <Typography variant={"body2"}>
83
- {processedEntities}/{importConfig.entities.length} entities saved
84
- </Typography>
85
-
86
- <Typography variant={"caption"}>
87
- Do not close this tab or the import will be interrupted.
88
- </Typography>
89
-
90
- </CenteredView>
91
- );
92
-
93
- }
94
-
95
- function saveDataBatch(dataSource: DataSource,
96
- collection: EntityCollection,
97
- path: string,
98
- data: Partial<Entity<any>>[],
99
- offset = 0,
100
- batchSize = 25,
101
- onProgressUpdate: (progress: number) => void): Promise<void> {
102
-
103
- console.debug("Saving imported data", offset, batchSize);
104
-
105
- const batch = data.slice(offset, offset + batchSize);
106
- return Promise.all(batch.map(d =>
107
- dataSource.saveEntity({
108
- path,
109
- values: d.values,
110
- entityId: d.id,
111
- collection,
112
- status: "new"
113
- })))
114
- .then(() => {
115
- if (offset + batchSize < data.length) {
116
- onProgressUpdate(offset + batchSize);
117
- return saveDataBatch(dataSource, collection, path, data, offset + batchSize, batchSize, onProgressUpdate);
118
- }
119
- onProgressUpdate(data.length);
120
- return Promise.resolve();
121
- });
122
- }
@@ -1,4 +0,0 @@
1
- export * from "./DataNewPropertiesMapping";
2
- export * from "./ImportFileUpload";
3
- export * from "./ImportNewPropertyFieldPreview";
4
- export * from "./ImportSaveInProgress";
@@ -1,252 +0,0 @@
1
- import React, { useCallback } from "react";
2
-
3
- import {
4
- CollectionActionsProps,
5
- Entity,
6
- EntityCollection,
7
- ExportConfig,
8
- resolveCollection,
9
- ResolvedEntityCollection,
10
- useCustomizationController,
11
- useDataSource,
12
- useFireCMSContext,
13
- useNavigationController,
14
- User
15
- } from "@firecms/core";
16
- import {
17
- Alert,
18
- BooleanSwitchWithLabel,
19
- Button,
20
- CircularProgress,
21
- cn,
22
- Dialog,
23
- DialogActions,
24
- DialogContent,
25
- focusedMixin,
26
- GetAppIcon,
27
- IconButton,
28
- Tooltip,
29
- Typography,
30
- } from "@firecms/ui";
31
- import { downloadExport } from "./export";
32
-
33
- const DOCS_LIMIT = 500;
34
-
35
- export function ExportCollectionAction<M extends Record<string, any>, UserType extends User>({
36
- collection: inputCollection,
37
- path: inputPath,
38
- collectionEntitiesCount,
39
- exportAllowed,
40
- notAllowedView
41
- }: CollectionActionsProps<M, UserType, EntityCollection<M, any>> & {
42
- exportAllowed?: (props: { collectionEntitiesCount: number, path: string, collection: EntityCollection }) => boolean;
43
- notAllowedView?: React.ReactNode;
44
- onAnalyticsEvent?: (event: string, params?: any) => void;
45
- }) {
46
-
47
- const customizationController = useCustomizationController();
48
-
49
- const exportConfig = typeof inputCollection.exportable === "object" ? inputCollection.exportable : undefined;
50
-
51
- const dateRef = React.useRef<Date>(new Date());
52
- const [flattenArrays, setFlattenArrays] = React.useState<boolean>(true);
53
- const [exportType, setExportType] = React.useState<"csv" | "json">("csv");
54
- const [dateExportType, setDateExportType] = React.useState<"timestamp" | "string">("string");
55
-
56
- const context = useFireCMSContext<UserType>();
57
- const dataSource = useDataSource();
58
- const navigationController = useNavigationController();
59
-
60
- const path = navigationController.resolveAliasesFrom(inputPath);
61
-
62
- const canExport = !exportAllowed || exportAllowed({
63
- collectionEntitiesCount,
64
- path,
65
- collection: inputCollection
66
- });
67
-
68
- const collection: ResolvedEntityCollection<M> = React.useMemo(() => resolveCollection({
69
- collection: inputCollection,
70
- path,
71
- fields: customizationController.propertyConfigs
72
- }), [inputCollection, path]);
73
-
74
- const [dataLoading, setDataLoading] = React.useState<boolean>(false);
75
- const [dataLoadingError, setDataLoadingError] = React.useState<Error | undefined>();
76
-
77
- const [open, setOpen] = React.useState(false);
78
-
79
- const handleClickOpen = useCallback(() => {
80
- setOpen(true);
81
- }, [setOpen]);
82
-
83
- const handleClose = useCallback(() => {
84
- setOpen(false);
85
- }, [setOpen]);
86
-
87
- const fetchAdditionalFields = useCallback(async (entities: Entity<M>[]) => {
88
-
89
- const additionalExportFields = exportConfig?.additionalFields;
90
- const additionalFields = collection.additionalFields;
91
-
92
- const resolvedExportColumnsValues: Record<string, any>[] = additionalExportFields
93
- ? await Promise.all(entities.map(async (entity) => {
94
- return (await Promise.all(additionalExportFields.map(async (column) => {
95
- return {
96
- [column.key]: await column.builder({
97
- entity,
98
- context
99
- })
100
- };
101
- }))).reduce((a, b) => ({ ...a, ...b }), {});
102
- }))
103
- : [];
104
-
105
- const resolvedColumnsValues: Record<string, any>[] = additionalFields
106
- ? await Promise.all(entities.map(async (entity) => {
107
- return (await Promise.all(additionalFields
108
- .map(async (field) => {
109
- if (!field.value)
110
- return {};
111
- return {
112
- [field.key]: await field.value({
113
- entity,
114
- context
115
- })
116
- };
117
- }))).reduce((a, b) => ({ ...a, ...b }), {});
118
- }))
119
- : [];
120
- return [...resolvedExportColumnsValues, ...resolvedColumnsValues];
121
- }, [exportConfig?.additionalFields]);
122
-
123
- const doDownload = useCallback(async (collection: ResolvedEntityCollection<M>,
124
- exportConfig: ExportConfig<any> | undefined) => {
125
-
126
- setDataLoading(true);
127
- dataSource.fetchCollection<M>({
128
- path,
129
- collection
130
- })
131
- .then(async (data) => {
132
- setDataLoadingError(undefined);
133
- const additionalData = await fetchAdditionalFields(data);
134
- const additionalHeaders = [
135
- ...exportConfig?.additionalFields?.map(column => column.key) ?? [],
136
- ...collection.additionalFields?.map(field => field.key) ?? []
137
- ];
138
- downloadExport(data, additionalData, collection, flattenArrays, additionalHeaders, exportType, dateExportType);
139
- })
140
- .catch((e) => {
141
- console.error("Error loading export data", e);
142
- setDataLoadingError(e);
143
- })
144
- .finally(() => setDataLoading(false));
145
-
146
- }, [dataSource, path, fetchAdditionalFields, flattenArrays, exportType, dateExportType]);
147
-
148
- const onOkClicked = useCallback(() => {
149
- doDownload(collection, exportConfig);
150
- handleClose();
151
- }, [doDownload, collection, exportConfig, handleClose]);
152
-
153
- return <>
154
-
155
- <Tooltip title={"Export"}>
156
- <IconButton color={"primary"} onClick={handleClickOpen}>
157
- <GetAppIcon/>
158
- </IconButton>
159
- </Tooltip>
160
-
161
- <Dialog
162
- open={open}
163
- onOpenChange={setOpen}
164
- maxWidth={"xl"}>
165
- <DialogContent className={"flex flex-col gap-4 my-4"}>
166
-
167
- <Typography variant={"h6"}>Export data</Typography>
168
-
169
- <div>Download the the content of this table as a CSV</div>
170
-
171
- {collectionEntitiesCount > DOCS_LIMIT &&
172
- <Alert color={"warning"}>
173
- <div>
174
- This collections has a large number
175
- of documents ({collectionEntitiesCount}).
176
- </div>
177
- </Alert>}
178
-
179
- <div className={"flex flex-row gap-4"}>
180
- <div className={"p-4 flex flex-col"}>
181
- <div className="flex items-center">
182
- <input id="radio-csv" type="radio" value="csv" name="exportType"
183
- checked={exportType === "csv"}
184
- onChange={() => setExportType("csv")}
185
- className={cn(focusedMixin, "w-4 text-primary-dark bg-gray-100 border-gray-300 dark:bg-gray-700 dark:border-gray-600")}/>
186
- <label htmlFor="radio-csv"
187
- className="p-2 text-sm font-medium text-gray-900 dark:text-slate-300">CSV</label>
188
- </div>
189
- <div className="flex items-center">
190
- <input id="radio-json" type="radio" value="json" name="exportType"
191
- checked={exportType === "json"}
192
- onChange={() => setExportType("json")}
193
- className={cn(focusedMixin, "w-4 text-primary-dark bg-gray-100 border-gray-300 dark:bg-gray-700 dark:border-gray-600")}/>
194
- <label htmlFor="radio-json"
195
- className="p-2 text-sm font-medium text-gray-900 dark:text-slate-300">JSON</label>
196
- </div>
197
- </div>
198
-
199
- <div className={"p-4 flex flex-col"}>
200
- <div className="flex items-center">
201
- <input id="radio-timestamp" type="radio" value="timestamp" name="dateExportType"
202
- checked={dateExportType === "timestamp"}
203
- onChange={() => setDateExportType("timestamp")}
204
- className={cn(focusedMixin, "w-4 text-primary-dark bg-gray-100 border-gray-300 dark:bg-gray-700 dark:border-gray-600")}/>
205
- <label htmlFor="radio-timestamp"
206
- className="p-2 text-sm font-medium text-gray-900 dark:text-slate-300">Dates as
207
- timestamps ({dateRef.current.getTime()})</label>
208
- </div>
209
- <div className="flex items-center">
210
- <input id="radio-string" type="radio" value="string" name="dateExportType"
211
- checked={dateExportType === "string"}
212
- onChange={() => setDateExportType("string")}
213
- className={cn(focusedMixin, "w-4 text-primary-dark bg-gray-100 border-gray-300 dark:bg-gray-700 dark:border-gray-600")}/>
214
- <label htmlFor="radio-string"
215
- className="p-2 text-sm font-medium text-gray-900 dark:text-slate-300">Dates as
216
- strings ({dateRef.current.toISOString()})</label>
217
- </div>
218
- </div>
219
- </div>
220
-
221
- <BooleanSwitchWithLabel
222
- size={"small"}
223
- disabled={exportType !== "csv"}
224
- value={flattenArrays}
225
- onValueChange={setFlattenArrays}
226
- label={"Flatten arrays"}/>
227
-
228
- {!canExport && notAllowedView}
229
-
230
- </DialogContent>
231
-
232
- <DialogActions>
233
-
234
- {dataLoading && <CircularProgress size={"small"}/>}
235
-
236
- <Button onClick={handleClose}
237
- variant={"text"}>
238
- Cancel
239
- </Button>
240
-
241
- <Button variant="filled"
242
- onClick={onOkClicked}
243
- disabled={dataLoading || !canExport}>
244
- Download
245
- </Button>
246
-
247
- </DialogActions>
248
-
249
- </Dialog>
250
-
251
- </>;
252
- }