-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathCSVImportDialog.tsx
More file actions
313 lines (291 loc) · 10.1 KB
/
CSVImportDialog.tsx
File metadata and controls
313 lines (291 loc) · 10.1 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
import { useState } from 'react';
import {
Dialog,
DialogTitle,
DialogContent,
DialogActions,
Button,
Box,
Typography,
Table,
TableBody,
TableCell,
TableContainer,
TableHead,
TableRow,
Paper,
Alert,
CircularProgress,
Chip,
Stack,
} from '@mui/material';
import { Upload } from '@mui/icons-material';
import {
parseCSVToPVsAsync,
createValidationSummary,
validateCSVTags,
ParsedCSVRow,
ParseProgress,
} from '../utils/csvParser';
interface CSVImportDialogProps {
open: boolean;
onClose: () => void;
onImport: (data: ParsedCSVRow[]) => Promise<void>;
availableTagGroups: Array<{
id: string;
name: string;
tags: Array<{ id: string; name: string }>;
}>;
}
export function CSVImportDialog({
open,
onClose,
onImport,
availableTagGroups,
}: CSVImportDialogProps) {
const [csvData, setCSVData] = useState<ParsedCSVRow[]>([]);
const [parseErrors, setParseErrors] = useState<string[]>([]);
const [validationSummary, setValidationSummary] = useState<string>('');
const [importing, setImporting] = useState(false);
const [fileSelected, setFileSelected] = useState(false);
const [importError, setImportError] = useState<string | null>(null);
const [parsingProgress, setParsingProgress] = useState<ParseProgress | null>(null);
const [parsing, setParsing] = useState(false);
const handleClose = () => {
setCSVData([]);
setParseErrors([]);
setValidationSummary('');
setFileSelected(false);
setImporting(false);
setImportError(null);
onClose();
};
const handleFileSelect = async (event: React.ChangeEvent<HTMLInputElement>) => {
const file = event.target.files?.[0];
const inputElement = event.target;
if (!file) return;
try {
setParsing(true);
setParsingProgress({ processedRows: 0, totalRows: 0, status: 'parsing' });
setParseErrors([]);
setCSVData([]);
setValidationSummary('');
setFileSelected(false);
const content = await file.text();
// Use async parser for better performance with large files
const result = await parseCSVToPVsAsync(content, (progress) => {
setParsingProgress(progress);
});
if (result.errors.length > 0) {
setParseErrors(result.errors);
setCSVData([]);
setValidationSummary('');
setFileSelected(false);
setParsing(false);
setParsingProgress(null);
return;
}
setCSVData(result.data);
setParseErrors([]);
setFileSelected(true);
setParsing(false);
setParsingProgress(null);
// Validate tags with progress feedback
if (result.data.length > 0) {
setParsing(true);
setParsingProgress({
processedRows: 0,
totalRows: result.data.length,
status: 'validating',
});
const validationResults = await validateCSVTags(result.data, availableTagGroups);
const summary = createValidationSummary(
validationResults.rejectedGroups,
validationResults.rejectedValues
);
setValidationSummary(summary);
setParsing(false);
setParsingProgress(null);
}
} catch (error) {
setParseErrors([
`Failed to read CSV file: ${error instanceof Error ? error.message : 'Unknown error'}`,
]);
setCSVData([]);
setValidationSummary('');
setFileSelected(false);
setParsing(false);
setParsingProgress(null);
}
// Reset file input
inputElement.value = '';
};
const handleImport = async () => {
if (csvData.length === 0) return;
setImporting(true);
setImportError(null);
try {
await onImport(csvData);
handleClose();
} catch (error) {
setImportError(`Import failed: ${error instanceof Error ? error.message : 'Unknown error'}`);
} finally {
setImporting(false);
}
};
return (
<Dialog open={open} onClose={handleClose} maxWidth="lg" fullWidth>
<DialogTitle>Import PVs from CSV</DialogTitle>
<DialogContent>
<Stack spacing={2} sx={{ mt: 1 }}>
{/* File Upload Section */}
<Box>
<label htmlFor="csv-file-input">
<input
accept=".csv"
style={{ display: 'none' }}
id="csv-file-input"
type="file"
onChange={handleFileSelect}
/>
<Button
variant="contained"
component="span"
startIcon={<Upload />}
disabled={importing || parsing}
>
Select CSV File
</Button>
</label>
</Box>
{/* Parsing Progress */}
{parsing && parsingProgress && (
<Alert severity="info">
<Box sx={{ display: 'flex', alignItems: 'center', gap: 2 }}>
<CircularProgress size={20} />
<Box sx={{ flex: 1 }}>
<Typography variant="body2" sx={{ fontWeight: 'bold' }}>
{parsingProgress.status === 'parsing'
? 'Parsing CSV file...'
: 'Validating tags...'}
</Typography>
<Typography variant="caption" color="text.secondary">
Processed {parsingProgress.processedRows} of {parsingProgress.totalRows} rows
</Typography>
</Box>
<Typography variant="caption" color="text.secondary">
{Math.round((parsingProgress.processedRows / parsingProgress.totalRows) * 100)}%
</Typography>
</Box>
</Alert>
)}
{/* CSV Format Instructions */}
<Alert severity="info">
<Typography variant="body2" sx={{ mb: 1 }}>
<strong>CSV Format Requirements:</strong>
</Typography>
<Typography variant="body2" component="div">
• Required: At least one column named "Setpoint" or "Readback"
<br />
• Optional: "Device", "Description" columns
<br />
• Tag Groups: Any additional columns will be treated as tag groups
<br />• Tag values can be comma-separated (e.g., "tag1, tag2")
</Typography>
</Alert>
{/* Import Error */}
{importError && (
<Alert severity="error">
<Typography variant="body2">{importError}</Typography>
</Alert>
)}
{/* Parse Errors */}
{parseErrors.length > 0 && (
<Alert severity="error">
{parseErrors.map((error) => (
<Typography key={error} variant="body2">
{error}
</Typography>
))}
</Alert>
)}
{/* Validation Summary */}
{fileSelected && validationSummary && (
<Alert severity={validationSummary.includes('Rejected') ? 'warning' : 'success'}>
<Typography variant="body2">{validationSummary}</Typography>
{validationSummary.includes('Rejected') && (
<Typography variant="caption" sx={{ mt: 1, display: 'block' }}>
Note: Rejected groups/values will be ignored during import.
</Typography>
)}
</Alert>
)}
{/* Preview Table */}
{csvData.length > 0 && (
<Box>
<Typography variant="subtitle2" sx={{ mb: 1 }}>
Preview ({csvData.length} row{csvData.length !== 1 ? 's' : ''})
</Typography>
<TableContainer component={Paper} sx={{ maxHeight: 400 }}>
<Table size="small" stickyHeader>
<TableHead>
<TableRow>
<TableCell>Setpoint</TableCell>
<TableCell>Readback</TableCell>
<TableCell>Device</TableCell>
<TableCell>Description</TableCell>
<TableCell>Tags</TableCell>
</TableRow>
</TableHead>
<TableBody>
{csvData.map((row) => (
<TableRow key={row.Setpoint || row.Readback}>
<TableCell sx={{ fontFamily: 'monospace' }}>{row.Setpoint}</TableCell>
<TableCell sx={{ fontFamily: 'monospace' }}>{row.Readback}</TableCell>
<TableCell>{row.Device}</TableCell>
<TableCell>
<Typography variant="body2" noWrap sx={{ maxWidth: 200 }}>
{row.Description}
</Typography>
</TableCell>
<TableCell>
<Box sx={{ display: 'flex', flexWrap: 'wrap', gap: 0.5 }}>
{Object.entries(row.groups).map(([groupName, values]) =>
values.map((value) => (
<Chip
key={`${groupName}-${value}`}
label={`${groupName}: ${value}`}
size="small"
variant="outlined"
/>
))
)}
</Box>
</TableCell>
</TableRow>
))}
</TableBody>
</Table>
</TableContainer>
</Box>
)}
</Stack>
</DialogContent>
<DialogActions>
<Button onClick={handleClose} disabled={importing}>
Cancel
</Button>
<Button
onClick={handleImport}
variant="contained"
disabled={csvData.length === 0 || importing}
startIcon={importing ? <CircularProgress size={16} /> : undefined}
>
{importing
? 'Importing...'
: `Import ${csvData.length} PV${csvData.length !== 1 ? 's' : ''}`}
</Button>
</DialogActions>
</Dialog>
);
}