Skip to content

Commit

Permalink
missed some sections that needed to be updated (interacting with quad…
Browse files Browse the repository at this point in the history
…rats --> census). resolved some additional errors that were occurring at various interaction points and repaired some functionality issues
  • Loading branch information
siddheshraze committed Oct 21, 2024
1 parent 68496ee commit 491ff63
Show file tree
Hide file tree
Showing 9 changed files with 93 additions and 55 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -65,7 +65,7 @@ export async function GET(
case 'personnel':
paginatedQuery = `
SELECT SQL_CALC_FOUND_ROWS p.*
FROM ${schema}.${params.dataType} q
FROM ${schema}.${params.dataType} p
JOIN ${schema}.census c ON p.CensusID = c.CensusID
WHERE c.PlotID = ?
AND c.PlotCensusNumber = ? LIMIT ?, ?;`;
Expand Down
69 changes: 35 additions & 34 deletions frontend/components/client/formcolumns.tsx
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
'use client';

import { GridColDef, GridRenderEditCellParams, useGridApiContext, useGridApiRef } from '@mui/x-data-grid';
import { GridColDef, GridRenderEditCellParams, useGridApiContext } from '@mui/x-data-grid';
import { areaSelectionOptions, unitSelectionOptions } from '@/config/macros';
import { formatHeader } from '@/components/client/datagridcolumns';
import moment from 'moment/moment';
Expand All @@ -12,25 +12,44 @@ import { AttributeStatusOptions } from '@/config/sqlrdsdefinitions/core';
import { styled } from '@mui/joy/styles';
import { CheckCircleOutlined } from '@mui/icons-material';

const renderDatePicker = (params: GridRenderEditCellParams) => {
export const renderDatePicker = (params: GridRenderEditCellParams) => {
const convertedValue = params.row.date ? moment(params.row.date, 'YYYY-MM-DD') : null;
if (!convertedValue) return <></>;

return (
<Box sx={{ display: 'flex', flexDirection: 'row', gap: '0.5em', alignItems: 'center' }}>
<DatePicker label={'Recorded Date'} value={convertedValue} disabled />
<Box
sx={{
display: 'flex',
alignItems: 'center',
justifyContent: 'center',
width: '100%',
height: '100%',
padding: '0'
}}
>
<Input
size={'lg'}
value={convertedValue.format('MM-DD-YYYY')}
disabled
sx={{
textAlign: 'center',
width: '100%',
overflow: 'hidden'
}}
/>
</Box>
);
};

const renderEditDatePicker = (params: GridRenderEditCellParams) => {
const apiRef = useGridApiRef();
export const renderEditDatePicker = (params: GridRenderEditCellParams) => {
const apiRef = useGridApiContext();
const { id, row } = params;

return (
<Box sx={{ display: 'flex', flexDirection: 'row', gap: '0.5em', alignItems: 'center' }}>
<Box sx={{ display: 'flex', flexDirection: 'row', gap: '0.5em', alignItems: 'center', marginY: 1 }}>
<DatePicker
label={'Recorded Date'}
slotProps={{ textField: { size: 'small' } }}
value={moment(row.date, 'YYYY-MM-DD')}
onChange={newValue => {
apiRef.current.setEditCellValue({ id, field: 'date', value: newValue ? newValue.format('YYYY-MM-DD') : null });
Expand Down Expand Up @@ -666,10 +685,10 @@ export const MeasurementsFormGridColumns: GridColDef[] = [
},
{
field: 'coordinateunit',
headerName: 'Coordinate Units',
headerName: '<= Units',
headerClassName: 'header',
renderHeader: () => formatHeader('Coordinate', 'Units'),
flex: 1.5,
// renderHeader: () => formatHeader('Coordinate', 'Units'),
flex: 0.5,
align: 'center',
editable: true,
renderEditCell: params => <EditUnitsCell {...params} fieldName={'coordinateunit'} isArea={false} />
Expand All @@ -685,10 +704,10 @@ export const MeasurementsFormGridColumns: GridColDef[] = [
},
{
field: 'dbhunit',
headerName: 'DBH Units',
headerName: '<= Units',
headerClassName: 'header',
renderHeader: () => formatHeader('DBH', 'Units'),
flex: 1.5,
// renderHeader: () => formatHeader('DBH', 'Units'),
flex: 0.5,
align: 'center',
editable: true,
renderEditCell: params => <EditUnitsCell {...params} fieldName={'dbhunit'} isArea={false} />
Expand All @@ -704,30 +723,12 @@ export const MeasurementsFormGridColumns: GridColDef[] = [
},
{
field: 'homunit',
headerName: 'HOM Units',
headerName: '<= Units',
headerClassName: 'header',
renderHeader: () => formatHeader('HOM', 'Units'),
flex: 1.5,
// renderHeader: () => formatHeader('HOM', 'Units'),
flex: 0.5,
align: 'center',
editable: true,
renderEditCell: params => <EditUnitsCell {...params} fieldName={'homunit'} isArea={false} />
},
{
field: 'date',
headerName: 'Date',
headerClassName: 'header',
flex: 1,
align: 'center',
editable: true,
renderCell: renderDatePicker,
renderEditCell: renderEditDatePicker
},
{
field: 'codes',
headerName: 'Codes',
headerClassName: 'header',
flex: 1,
align: 'center',
editable: true
}
];
21 changes: 18 additions & 3 deletions frontend/components/datagrids/applications/msvdatagrid.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,6 @@
import { useOrgCensusContext, usePlotContext, useSiteContext } from '@/app/contexts/userselectionprovider';
import React, { useEffect, useState } from 'react';
import { GridRowModes, GridRowModesModel, GridRowsProp } from '@mui/x-data-grid';
import { Alert, AlertProps } from '@mui/material';
import { randomId } from '@mui/x-data-grid-generator';
import { Box, Button, Snackbar, Stack, Typography } from '@mui/joy';
import UploadParentModal from '@/components/uploadsystemhelpers/uploadparentmodal';
Expand All @@ -13,6 +12,7 @@ import { FormType } from '@/config/macros/formdetails';
import { MeasurementsSummaryRDS } from '@/config/sqlrdsdefinitions/views';
import MultilineModal from '@/components/datagrids/applications/multiline/multilinemodal';
import { useLoading } from '@/app/contexts/loadingprovider';
import { Alert, AlertProps, AlertTitle, Collapse } from '@mui/material';

const initialMeasurementsSummaryViewRDSRow: MeasurementsSummaryRDS = {
id: 0,
Expand Down Expand Up @@ -50,6 +50,7 @@ export default function MeasurementsSummaryViewDataGrid() {
const [isManualEntryFormOpen, setIsManualEntryFormOpen] = useState(false);
const [triggerGlobalError, setTriggerGlobalError] = useState(false);
const [globalError, setGlobalError] = useState<string | null>(null);
const [openAlert, setOpenAlert] = useState(false);

const [rows, setRows] = React.useState([initialMeasurementsSummaryViewRDSRow] as GridRowsProp);
const [rowCount, setRowCount] = useState(0);
Expand Down Expand Up @@ -156,15 +157,15 @@ export default function MeasurementsSummaryViewDataGrid() {
isUploadModalOpen={isUploadModalOpen}
handleCloseUploadModal={() => {
setIsUploadModalOpen(false);
setRefresh(true);
setOpenAlert(true);
}}
formType={FormType.measurements}
/>
<MultilineModal
isManualEntryFormOpen={isManualEntryFormOpen}
handleCloseManualEntryForm={() => {
setIsManualEntryFormOpen(false);
setRefresh(true);
setOpenAlert(true);
}}
formType={'measurements'}
/>
Expand All @@ -190,6 +191,20 @@ export default function MeasurementsSummaryViewDataGrid() {
setShouldAddRowAfterFetch={setShouldAddRowAfterFetch}
addNewRowToGrid={addNewRowToGrid}
/>
<Collapse in={openAlert} sx={{ width: '100%' }}>
<Snackbar
anchorOrigin={{ vertical: 'top', horizontal: 'center' }}
open={openAlert}
autoHideDuration={6000}
onClose={() => setOpenAlert(false)}
sx={{ display: 'flex', flex: 1, alignSelf: 'center', justifySelf: 'center', alignItems: 'center', justifyContent: 'center' }}
>
<Alert variant={'outlined'} onClose={() => setOpenAlert(false)} severity="warning">
<AlertTitle>Changes detected!</AlertTitle>
Please press the refresh button to update the grid.
</Alert>
</Snackbar>
</Collapse>
</>
);
}
Original file line number Diff line number Diff line change
Expand Up @@ -147,7 +147,9 @@ export default function ViewFullTableDataGrid() {
}

useEffect(() => {
reloadVFT().catch(console.error).then(setLoading(false));
reloadVFT()
.catch(console.error)
.then(() => setLoading(false));
}, []);

return (
Expand Down
24 changes: 20 additions & 4 deletions frontend/components/datagrids/isolatedmultilinedatagridcommons.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@ import { getColumnVisibilityModel } from '@/config/datagridhelpers';
import { useOrgCensusContext, usePlotContext, useSiteContext } from '@/app/contexts/userselectionprovider';
import { FileRow, FileRowSet } from '@/config/macros/formdetails';
import { AttributeStatusOptions } from '@/config/sqlrdsdefinitions/core';
import { renderDatePicker, renderEditDatePicker } from '@/components/client/formcolumns';

export interface IsolatedDataGridCommonProps {
gridType: string;
Expand Down Expand Up @@ -85,7 +86,24 @@ export default function IsolatedMultilineDataGridCommons(props: Readonly<Isolate
];
}
},
...gridColumns
...gridColumns,
{
field: 'date',
headerName: 'Date',
headerClassName: 'header',
flex: 1,
editable: true,
renderCell: renderDatePicker,
renderEditCell: renderEditDatePicker
},
{
field: 'codes',
headerName: 'Codes',
headerClassName: 'header',
flex: 1,
align: 'center',
editable: true
}
],
[gridColumns, unsavedChangesRef, apiRef, setRows]
);
Expand Down Expand Up @@ -119,7 +137,6 @@ export default function IsolatedMultilineDataGridCommons(props: Readonly<Isolate
try {
setIsSaving(true);

// After saving, process both edited and deleted rows
const rowsToDelete = Object.values(unsavedChangesRef.current.unsavedRows).filter(row => row._action === 'delete');
const rowsToSave = Object.values(unsavedChangesRef.current.unsavedRows).filter(row => row._action !== 'delete');

Expand All @@ -134,7 +151,6 @@ export default function IsolatedMultilineDataGridCommons(props: Readonly<Isolate
});
});

// Clear unsaved changes
unsavedChangesRef.current.unsavedRows = {};
unsavedChangesRef.current.rowsBeforeChange = {};

Expand Down Expand Up @@ -294,7 +310,7 @@ export default function IsolatedMultilineDataGridCommons(props: Readonly<Isolate
}}
loading={isSaving}
getRowClassName={getRowClassName}
autoHeight
getRowHeight={() => 'auto'}
/>
</Box>
<Button sx={{ marginTop: 8 }} onClick={submitChanges} color={'primary'} size={'lg'}>
Expand Down
19 changes: 11 additions & 8 deletions frontend/components/datagrids/measurementscommons.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -211,19 +211,20 @@ export default function MeasurementsCommons(props: Readonly<MeasurementsCommonsP
const errorFields = error.validationErrorIDs.flatMap(id => errorMapping[id.toString()] || []);
return errorFields.includes(colField);
};

const rowHasError = (rowId: GridRowId) => {
if (!rows || rows.length === 0) return false;
return gridColumns.some(column => cellHasError(column.field, rowId));
};

const fetchErrorRows = async () => {
if (!rows || rows.length === 0) return [];
return rows.filter(row => rowHasError(row.id));
};

const getRowErrorDescriptions = (rowId: GridRowId): string[] => {
const row = rows.find(row => rowId === row.id);
const error = validationErrors[row?.coreMeasurementID];
console.log('error: ', error);
console.log('validationerrorids: ', validationErrors);
return error.validationErrorIDs.map(id => {
const index = error.validationErrorIDs.indexOf(id);
return error.descriptions[index]; // Assumes that descriptions are stored in the CMError object
Expand Down Expand Up @@ -510,7 +511,7 @@ export default function MeasurementsCommons(props: Readonly<MeasurementsCommonsP
setRefresh(true);
await fetchPaginatedData(paginationModel.page);
setRefresh(false);
}, [fetchPaginatedData, paginationModel.page]);
}, [fetchPaginatedData, paginationModel.page, refresh]);

const processRowUpdate = useCallback(
(newRow: GridRowModel, oldRow: GridRowModel) =>
Expand Down Expand Up @@ -631,8 +632,6 @@ export default function MeasurementsCommons(props: Readonly<MeasurementsCommonsP
: {};

// Only update state if there is a difference
console.log('existing valerrors: ', validationErrors);
console.log('new valerrors: ', errorMap);
if (JSON.stringify(validationErrors) !== JSON.stringify(errorMap)) {
setValidationErrors(errorMap);
}
Expand Down Expand Up @@ -683,10 +682,16 @@ export default function MeasurementsCommons(props: Readonly<MeasurementsCommonsP
align: 'center',
width: 50,
renderCell: (params: GridCellParams) => {
const rowId = params.row.coremeasurementID;
console.log('val stat rendercell');
console.log('val stat params: ', params);
const rowId = params.row.coreMeasurementID;
console.log('rowId located: ', rowId);
const validationError = validationErrors[Number(rowId)];
console.log('searched for val error: ', validationError);
const isPendingValidation = rows.find(row => row.coreMeasurementID === rowId)?.isValidated && !validationError;
console.log('pending validation? ', isPendingValidation);
const isValidated = params.row.isValidated;
console.log('is validated?', isValidated);

if (validationError) {
return (
Expand Down Expand Up @@ -782,7 +787,6 @@ export default function MeasurementsCommons(props: Readonly<MeasurementsCommonsP
// }
// };
});
console.log('common columns', commonColumns);
if (locked) {
return [validationStatusColumn, measurementDateColumn, ...commonColumns];
}
Expand Down Expand Up @@ -931,7 +935,6 @@ export default function MeasurementsCommons(props: Readonly<MeasurementsCommonsP
handleExportErrors: handleExportErrors
}
}}
autoHeight
getRowHeight={() => 'auto'}
getRowClassName={getRowClassName}
isCellEditable={() => !locked}
Expand Down
5 changes: 3 additions & 2 deletions frontend/components/processors/processorhelperfunctions.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -482,7 +482,7 @@ export async function updateValidatedRows(schema: string, params: { p_CensusID?:
FROM ${schema}.coremeasurements cm
LEFT JOIN ${schema}.cmverrors cme ON cm.CoreMeasurementID = cme.CoreMeasurementID
JOIN ${schema}.census c ON cm.CensusID = c.CensusID
WHERE cm.IsValidated IS NULLa
WHERE cm.IsValidated IS NULL
AND (@p_CensusID IS NULL OR c.CensusID = @p_CensusID)
AND (@p_PlotID IS NULL OR c.PlotID = @p_PlotID);`;
const query = `
Expand All @@ -500,9 +500,10 @@ export async function updateValidatedRows(schema: string, params: { p_CensusID?:
SELECT cm.*
FROM ${schema}.coremeasurements cm
JOIN UpdatedRows ur ON cm.CoreMeasurementID = ur.CoreMeasurementID;`;
const dropTemp = `DROP TEMPORARY TABLE UpdatedRows;`;
const dropTemp = `DROP TEMPORARY TABLE IF EXISTS UpdatedRows;`;
try {
await conn.beginTransaction();
await runQuery(conn, dropTemp); // just in case
await runQuery(conn, setVariables, [params.p_CensusID || null, params.p_PlotID || null]);
await runQuery(conn, tempTable);
await runQuery(conn, insertTemp);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -155,7 +155,7 @@ const UploadFireSQL: React.FC<UploadFireProps> = ({
useEffect(() => {
if (!loading && completedOperations === totalOperations) {
if (uploadForm === FormType.measurements)
setReviewState(ReviewStates.UPLOAD_AZURE); // temporary shift to upload a draft
setReviewState(ReviewStates.VALIDATE); // because 2x entry is site-dependent, default behavior should be to trigger validations
else setReviewState(ReviewStates.UPLOAD_AZURE);
}
}, [loading, completedOperations, totalOperations]);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -82,7 +82,7 @@ export default function UploadParseFiles(props: Readonly<UploadParseFilesProps>)
{uploadForm === 'measurements' && (
<>
<Alert startDecorator={<WarningIcon fontSize="large" />} variant="soft" color="danger" sx={{ mb: 2 }}>
<Typography>
<Typography component={'div'}>
Please note: For date fields, accepted formats are
<List marker="decimal">
<ListItem>
Expand Down

0 comments on commit 491ff63

Please sign in to comment.