Skip to content

Commit

Permalink
Saving changes. Continuing reworking of validation CRUD system and be…
Browse files Browse the repository at this point in the history
…ginning application of feedback changes.
  • Loading branch information
siddheshraze committed Aug 13, 2024
1 parent 555e307 commit cbfd04d
Show file tree
Hide file tree
Showing 16 changed files with 477 additions and 291 deletions.
132 changes: 2 additions & 130 deletions frontend/app/(hub)/measurementshub/summary/page.tsx
Original file line number Diff line number Diff line change
@@ -1,133 +1,5 @@
'use client';
import React, { useState } from 'react';
import { GridRowModes, GridRowModesModel, GridRowsProp } from '@mui/x-data-grid';
import { Alert, AlertProps } from '@mui/material';
import { initialMeasurementsSummaryViewRDSRow } from '@/config/sqlrdsdefinitions/views/measurementssummaryviewrds';
import { Box, Button, Snackbar, Stack, Typography } from '@mui/joy';
import { useOrgCensusContext, usePlotContext } from '@/app/contexts/userselectionprovider';
import { randomId } from '@mui/x-data-grid-generator';
import UploadParentModal from '@/components/uploadsystemhelpers/uploadparentmodal';
import MeasurementSummaryGrid from '@/components/datagrids/msvdatagrid';
import { msvGridColumns } from '@/components/client/datagridcolumns';
import MeasurementsSummaryViewDataGrid from '@/components/datagrids/applications/measurementssummaryviewdatagrid';

export default function SummaryPage() {
const currentPlot = usePlotContext();
const currentCensus = useOrgCensusContext();
const [isUploadModalOpen, setIsUploadModalOpen] = useState(false);
const [triggerGlobalError, setTriggerGlobalError] = useState(false);
const [globalError, setGlobalError] = useState<string | null>(null);

const [rows, setRows] = React.useState([initialMeasurementsSummaryViewRDSRow] as GridRowsProp);
const [rowCount, setRowCount] = useState(0);
const [rowModesModel, setRowModesModel] = React.useState<GridRowModesModel>({});
const [snackbar, setSnackbar] = React.useState<Pick<AlertProps, 'children' | 'severity'> | null>(null);
const [refresh, setRefresh] = useState(false);
const [paginationModel, setPaginationModel] = useState({
page: 0,
pageSize: 10
});
const [isNewRowAdded, setIsNewRowAdded] = useState<boolean>(false);
const [shouldAddRowAfterFetch, setShouldAddRowAfterFetch] = useState(false);

const addNewRowToGrid = () => {
const id = randomId();
// Define new row structure based on MeasurementsSummaryRDS type
const newRow = {
...initialMeasurementsSummaryViewRDSRow,
id: id,
coreMeasurementID: 0,
plotID: currentPlot?.plotID,
plotName: currentPlot?.plotName,
censusID: currentCensus?.dateRanges[0].censusID,
censusStartDate: currentCensus?.dateRanges[0]?.startDate,
censusEndDate: currentCensus?.dateRanges[0]?.endDate,
isNew: true
};
setRows(oldRows => [...oldRows, newRow]);
setRowModesModel(oldModel => ({
...oldModel,
[id]: { mode: GridRowModes.Edit }
}));
};

const handleCloseGlobalError = () => {
setGlobalError(null);
setTriggerGlobalError(false);
};

return (
<>
{globalError && (
<Snackbar open={triggerGlobalError} autoHideDuration={6000} onClose={handleCloseGlobalError}>
<Alert onClose={handleCloseGlobalError} severity="error">
{globalError}
</Alert>
</Snackbar>
)}
<Box sx={{ display: 'flex', alignItems: 'center', mb: 3, width: '100%' }}>
<Box
sx={{
width: '100%',
display: 'flex',
justifyContent: 'space-between',
alignItems: 'center',
backgroundColor: 'warning.main',
borderRadius: '4px',
p: 2
}}
>
<Stack direction="column">
<Box sx={{ display: 'flex', flexDirection: 'column', flexGrow: 1 }}>
<Box
sx={{
flex: 1,
display: 'flex',
justifyContent: 'left',
flexDirection: 'column',
marginTop: 2
}}
>
<Typography level={'title-md'} sx={{ color: '#ffa726' }}>
Note: This plot does not accept subquadrats. <br />
Please ensure that you use quadrat names when submitting new measurements instead of subquadrat names
</Typography>
</Box>
</Box>
</Stack>
<Box sx={{ display: 'flex', alignItems: 'center', gap: 2 }}>
<Button>Upload</Button>
</Box>
</Box>
</Box>
<UploadParentModal
isUploadModalOpen={isUploadModalOpen}
handleCloseUploadModal={() => {
setIsUploadModalOpen(false);
setRefresh(true);
}}
formType={'measurements'}
/>
<MeasurementSummaryGrid
gridType={'measurementssummary'}
gridColumns={msvGridColumns}
rows={rows}
setRows={setRows}
rowCount={rowCount}
setRowCount={setRowCount}
rowModesModel={rowModesModel}
setRowModesModel={setRowModesModel}
snackbar={snackbar}
setSnackbar={setSnackbar}
refresh={refresh}
setRefresh={setRefresh}
paginationModel={paginationModel}
setPaginationModel={setPaginationModel}
isNewRowAdded={isNewRowAdded}
setIsNewRowAdded={setIsNewRowAdded}
shouldAddRowAfterFetch={shouldAddRowAfterFetch}
setShouldAddRowAfterFetch={setShouldAddRowAfterFetch}
addNewRowToGrid={addNewRowToGrid}
/>
</>
);
return <MeasurementsSummaryViewDataGrid />;
}
69 changes: 45 additions & 24 deletions frontend/app/(hub)/measurementshub/validations/page.tsx
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
'use client';

import { Box, Card, CardContent, Typography } from '@mui/joy';
import { Box, Card, CardContent, Stack, Typography } from '@mui/joy';
import React, { useEffect, useState } from 'react';
import { useSiteContext } from '@/app/contexts/userselectionprovider';
import { ValidationProceduresRDS } from '@/config/sqlrdsdefinitions/tables/validationproceduresrds';
Expand All @@ -9,6 +9,7 @@ import { CMVErrorGridColumns, ValidationProceduresGridColumns } from '@/componen
import { GridToolbar } from '@mui/x-data-grid';
import Divider from '@mui/joy/Divider';
import { CMVErrorRDS } from '@/config/sqlrdsdefinitions/tables/cmrds';
import MeasurementsSummaryViewDataGrid from '@/components/datagrids/applications/measurementssummaryviewdatagrid';

export default function ValidationsPage() {
const currentSite = useSiteContext();
Expand Down Expand Up @@ -43,47 +44,67 @@ export default function ValidationsPage() {
Review Validations
</Typography>
<StyledDataGrid
isCellEditable={() => false}
slots={{ toolbar: GridToolbar }}
loading={loading}
disableColumnSelector
sx={{ width: '100%' }}
sx={{
width: '100%',
'& .MuiDataGrid-cell': {
whiteSpace: 'normal',
wordWrap: 'break-word',
lineHeight: '1.2'
}
}}
columns={ValidationProceduresGridColumns}
rows={validationProcedures}
initialState={{
columns: {
columnVisibilityModel: {
id: false,
validationID: false,
updatedAt: false
updatedAt: false,
createdAt: false
}
}
}}
/>
</CardContent>
</Card>
<Divider orientation={'vertical'} sx={{ mx: 1 }} />
<Card variant="plain" sx={{ width: '50%' }}>
<CardContent>
<Typography level={'title-lg'} fontWeight={'bold'}>
Rows Failing Validation
</Typography>
<StyledDataGrid
slots={{ toolbar: GridToolbar }}
loading={loading}
disableColumnSelector
sx={{ width: '100%' }}
columns={CMVErrorGridColumns}
rows={currentErrors}
initialState={{
columns: {
columnVisibilityModel: {
id: false
<Stack direction={'column'} sx={{ width: '50%' }}>
<Card variant={'plain'}>
<CardContent>
<Typography level={'title-lg'} fontWeight={'bold'}>
Rows Pending Validation
</Typography>
<MeasurementsSummaryViewDataGrid filterPending={true} />
</CardContent>
</Card>
<Card variant="plain">
<CardContent>
<Typography level={'title-lg'} fontWeight={'bold'}>
Rows Failing Validation
</Typography>
<StyledDataGrid
isCellEditable={() => false}
slots={{ toolbar: GridToolbar }}
loading={loading}
disableColumnSelector
sx={{ width: '100%' }}
columns={CMVErrorGridColumns}
rows={currentErrors}
initialState={{
columns: {
columnVisibilityModel: {
id: false
}
}
}
}}
/>
</CardContent>
</Card>
}}
/>
</CardContent>
</Card>
</Stack>
</Box>
);
}
39 changes: 39 additions & 0 deletions frontend/app/api/fetchrowspendingvalidation/route.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
import { NextRequest, NextResponse } from 'next/server';
import { PoolConnection } from 'mysql2/promise';
import { getConn, runQuery } from '@/components/processors/processormacros';
import MapperFactory from '@/config/datamapper';

export async function GET(request: NextRequest) {
const schema = request.nextUrl.searchParams.get('schema');
if (!schema) throw new Error('no schema variable provided!');
const plotIDParam = request.nextUrl.searchParams.get('plotID');
const censusIDParam = request.nextUrl.searchParams.get('censusID');
const plotID = plotIDParam ? parseInt(plotIDParam) : null;
const censusID = censusIDParam ? parseInt(censusIDParam) : null;
const query = `
SELECT
cm.*
FROM
${schema}.coremeasurements cm
JOIN
${schema}.stems s ON cm.StemID = s.StemID
JOIN
${schema}.quadrats q ON s.QuadratID = q.QuadratID
WHERE
cm.IsValidated IS NULL
${plotID !== null ? `AND q.PlotID = ${plotID}` : ''}
${censusID !== null ? `AND cm.CensusID = ${censusID}` : ''} ORDER BY MeasurementDate LIMIT 10;`;
let conn: PoolConnection | null = null;
try {
conn = await getConn();
const results = await runQuery(conn, query);
return new NextResponse(JSON.stringify(MapperFactory.getMapper<any, any>('coremeasurements').mapData(results)), {
status: 200
});
} catch (error: any) {
console.error('Error in update operation:', error.message);
return new NextResponse(JSON.stringify({ error: error.message }), {
status: 500
});
}
}
14 changes: 7 additions & 7 deletions frontend/app/api/fixeddata/[dataType]/[[...slugs]]/route.ts
Original file line number Diff line number Diff line change
Expand Up @@ -24,11 +24,12 @@ export async function GET(
const [schema, pageParam, pageSizeParam, plotIDParam, plotCensusNumberParam, quadratIDParam] = params.slugs;
if (!schema || schema === 'undefined' || !pageParam || pageParam === 'undefined' || !pageSizeParam || pageSizeParam === 'undefined')
throw new Error('core slugs schema/page/pageSize not correctly received');
const page = parseInt(pageParam);
const pageSize = parseInt(pageSizeParam);

if (!plotIDParam || plotIDParam === '0' || !plotCensusNumberParam || plotCensusNumberParam === '0')
throw new Error('Core plot/census information not received');
// optional pending parameter to filter only pending rows:
const pending = request.nextUrl.searchParams.get('pending') === 'true';
const page = parseInt(pageParam);
const pageSize = parseInt(pageSizeParam);
const plotID = parseInt(plotIDParam);
const plotCensusNumber = parseInt(plotCensusNumberParam);
const quadratID = quadratIDParam ? parseInt(quadratIDParam) : undefined;
Expand Down Expand Up @@ -126,12 +127,10 @@ export async function GET(
paginatedQuery = `
SELECT SQL_CALC_FOUND_ROWS pdt.*
FROM ${schema}.${params.dataType} pdt
JOIN ${schema}.stems s ON pdt.StemID = s.StemID
JOIN ${schema}.trees t ON s.TreeID = t.TreeID
JOIN ${schema}.species sp ON t.SpeciesID = sp.SpeciesID
JOIN ${schema}.census c ON sp.CensusID = c.CensusID
JOIN ${schema}.census c ON pdt.CensusID = c.CensusID
WHERE c.PlotID = ?
AND c.PlotCensusNumber = ?
${pending ? ` AND pdt.IsValidated IS NULL` : ''}
ORDER BY pdt.MeasurementDate LIMIT ?, ?`;
queryParams.push(plotID, plotCensusNumber, page * pageSize, pageSize);
break;
Expand All @@ -150,6 +149,7 @@ export async function GET(
JOIN ${schema}.census c ON sp.CensusID = c.CensusID
WHERE c.PlotID = ?
AND c.CensusID IN (${censusIDs.map(() => '?').join(', ')})
${pending ? ` AND pdt.IsValidated IS NULL` : ''}
ORDER BY pdt.MeasurementDate ASC LIMIT ?, ?`;
queryParams.push(plotID, ...censusIDs, page * pageSize, pageSize);
break;
Expand Down
Loading

0 comments on commit cbfd04d

Please sign in to comment.