Added downloading back the excel sheet with corrected values

This commit is contained in:
GotthardG
2024-11-08 13:45:23 +01:00
parent dbebfd6d5a
commit 744a365bfc
4 changed files with 1114 additions and 72 deletions

View File

@ -10,13 +10,17 @@ import {
Tooltip,
TextField,
Typography,
Button
Button,
Box
} from '@mui/material';
import { SpreadsheetService } from '../../openapi';
import * as ExcelJS from 'exceljs';
import { saveAs } from 'file-saver';
const SpreadsheetTable = ({ raw_data, errors, headers, setRawData }) => {
const SpreadsheetTable = ({ raw_data, errors, headers, setRawData, onCancel, fileBlob }) => {
const [localErrors, setLocalErrors] = useState(errors || []);
const [editingCell, setEditingCell] = useState({});
const [nonEditableCells, setNonEditableCells] = useState(new Set());
const generateErrorMap = (errorsList) => {
const errorMap = new Map();
@ -31,6 +35,21 @@ const SpreadsheetTable = ({ raw_data, errors, headers, setRawData }) => {
const errorMap = generateErrorMap(localErrors);
useEffect(() => {
const initialNonEditableCells = new Set();
raw_data.forEach((row, rowIndex) => {
headers.forEach((_, colIndex) => {
const key = `${row.row_num}-${headers[colIndex]}`;
if (!errorMap.has(key)) {
initialNonEditableCells.add(`${rowIndex}-${colIndex}`);
}
});
});
setNonEditableCells(initialNonEditableCells);
}, [raw_data, headers, errorMap]);
const handleCellEdit = async (rowIndex, colIndex) => {
const updatedRawData = [...raw_data];
const columnName = headers[colIndex];
@ -39,14 +58,10 @@ const SpreadsheetTable = ({ raw_data, errors, headers, setRawData }) => {
if (newValue === undefined) return;
console.log(`Editing cell at row ${rowIndex}, column ${colIndex}: new value: ${newValue}`);
// Ensure currentRow.data exists before accessing it
if (!currentRow.data) {
currentRow.data = [];
}
// Update the relevant cell value
currentRow.data[colIndex] = newValue;
setEditingCell(prev => {
@ -62,15 +77,13 @@ const SpreadsheetTable = ({ raw_data, errors, headers, setRawData }) => {
value: newValue
});
console.log('Validation response:', response);
if (response.is_valid !== undefined) {
if (response.is_valid) {
// Remove error if it passes validation
const updatedErrors = localErrors.filter(
error => !(error.row === currentRow.row_num && error.cell === colIndex)
);
setLocalErrors(updatedErrors);
setNonEditableCells(prev => new Set([...prev, `${rowIndex}-${colIndex}`]));
} else {
const updatedErrors = [
...localErrors,
@ -78,8 +91,6 @@ const SpreadsheetTable = ({ raw_data, errors, headers, setRawData }) => {
];
setLocalErrors(updatedErrors);
}
} else {
console.error('Unexpected response structure:', response);
}
setRawData(updatedRawData);
} catch (error) {
@ -91,39 +102,33 @@ const SpreadsheetTable = ({ raw_data, errors, headers, setRawData }) => {
handleCellEdit(rowIndex, colIndex);
};
const validateBeforeSubmit = () => {
let isValid = true;
raw_data.forEach((row, rowIndex) => {
headers.forEach((header, colIndex) => {
const key = `${row.row_num}-${header}`;
const newValue = editingCell[`${rowIndex}-${colIndex}`];
if (newValue !== undefined) {
// Perform cell validation on each edit
handleCellEdit(rowIndex, colIndex);
}
const errorMessage = errorMap.get(key);
if (errorMessage) {
isValid = false;
}
});
});
return isValid;
};
const allCellsValid = () => nonEditableCells.size === raw_data.length * headers.length;
const handleSubmit = async () => {
const isValid = validateBeforeSubmit();
if (isValid) {
if (allCellsValid()) {
console.log('All data is valid. Proceeding with submission...');
// Use validated data to populate the database
// You can call a dedicated API endpoint to process the entire dataset as needed
} else {
console.log('There are validation errors in the dataset. Please correct them before submission.');
}
};
const downloadCorrectedSpreadsheet = async () => {
const workbook = new ExcelJS.Workbook();
await workbook.xlsx.load(fileBlob);
const worksheet = workbook.getWorksheet(1);
raw_data.forEach((row, rowIndex) => {
row.data.forEach((value, colIndex) => {
worksheet.getRow(row.row_num).getCell(colIndex + 1).value = value;
});
});
const buffer = await workbook.xlsx.writeBuffer();
const blob = new Blob([buffer], { type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' });
saveAs(blob, 'corrected_data.xlsx');
};
useEffect(() => {
console.log('Raw data:', raw_data);
console.log('Errors:', localErrors);
@ -146,6 +151,17 @@ const SpreadsheetTable = ({ raw_data, errors, headers, setRawData }) => {
))}
</TableRow>
</TableHead>
<Box display="flex" justifyContent="space-between" mt={2}>
<Button variant="contained" color="secondary" onClick={onCancel}>
Cancel
</Button>
<Button variant="contained" color="primary" onClick={handleSubmit} disabled={!allCellsValid()}>
Submit
</Button>
<Button variant="contained" onClick={downloadCorrectedSpreadsheet} disabled={!allCellsValid()}>
Download Corrected Spreadsheet
</Button>
</Box>
<TableBody>
{raw_data.map((row, rowIndex) => (
<TableRow key={rowIndex}>
@ -155,6 +171,7 @@ const SpreadsheetTable = ({ raw_data, errors, headers, setRawData }) => {
const isInvalid = !!errorMessage;
const cellValue = (row.data && row.data[colIndex]) || "";
const editingValue = editingCell[`${rowIndex}-${colIndex}`];
const isReadonly = !isInvalid;
return (
<TableCell key={colIndex} align="center">
@ -172,6 +189,7 @@ const SpreadsheetTable = ({ raw_data, errors, headers, setRawData }) => {
fullWidth
variant="outlined"
size="small"
disabled={isReadonly}
/>
</Tooltip>
</TableCell>
@ -181,9 +199,6 @@ const SpreadsheetTable = ({ raw_data, errors, headers, setRawData }) => {
))}
</TableBody>
</Table>
<Button variant="contained" color="primary" onClick={handleSubmit}>
Submit
</Button>
</TableContainer>
);
};