Skip to content

Commit

Permalink
Merge pull request #3476 from bcgov/NDT-430-Add-Validations-to-CBC-Ac…
Browse files Browse the repository at this point in the history
…cordion-Edit

chore: add validations to cbc accordian edit
  • Loading branch information
RRanath authored Aug 26, 2024
2 parents e636f09 + 210351f commit 89b0c75
Show file tree
Hide file tree
Showing 8 changed files with 136 additions and 5 deletions.
2 changes: 2 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
## [1.184.1](https://github.com/bcgov/CONN-CCBC-portal/compare/v1.184.0...v1.184.1) (2024-08-26)

# [1.184.0](https://github.com/bcgov/CONN-CCBC-portal/compare/v1.183.0...v1.184.0) (2024-08-26)

### Features
Expand Down
52 changes: 51 additions & 1 deletion app/components/Analyst/Project/fields/ProjectFieldTemplate.tsx
Original file line number Diff line number Diff line change
@@ -1,3 +1,6 @@
import React from 'react';
import { Help } from '@mui/icons-material';
import { Tooltip } from '@mui/material';
import { FieldTemplateProps } from '@rjsf/utils';
import styled from 'styled-components';

Expand Down Expand Up @@ -31,21 +34,68 @@ const StyledContainer = styled.div`
}
`;

const ErrorWrapper = styled.div<{ errorColor?: string }>`
position: relative;
background-color: ${(props) => props.errorColor};
padding: 8px;
margin-bottom: 8px;
max-width: calc(100% - 8px) !important;
.pg-select-wrapper,
.datepicker-widget,
.url-widget-wrapper,
.ccbcid-widget-wrapper {
background-color: white !important;
max-width: calc(340px - 8px) !important;
}
[class*='StyledMessage']:empty {
display: none;
}
`;

const StyledHelp = styled(Help)`
color: ${(props) => props.theme.color.primaryBlue};
cursor: pointer;
position: absolute;
right: 8px;
top: 50%;
transform: translateY(-50%);
`;

const ProjectFieldTemplate: React.FC<FieldTemplateProps> = ({
children,
uiSchema,
formContext,
id,
}) => {
const uiTitle =
uiSchema?.['ui:label'] || uiSchema?.['ui:title']
? `${uiSchema?.['ui:label'] ?? uiSchema?.['ui:title']}`
: null;
const fieldName = id?.split('_')?.[1];
const hidden = uiSchema?.['ui:widget'] === 'HiddenWidget' || false;

const showErrorHint = formContext?.showErrorHint ?? false;
const { errorColor, __errors: formContextErrors } =
formContext?.errors?.[fieldName] || {};
const hasFormContextError = formContextErrors?.length > 0;

return (
<>
{!hidden && (
<StyledContainer>
{uiTitle && <StyledH4>{uiTitle}</StyledH4>}
{children}
{showErrorHint && hasFormContextError ? (
<ErrorWrapper errorColor={errorColor}>
<div>{children}</div>
<Tooltip title={formContextErrors?.join()}>
<StyledHelp />
</Tooltip>
</ErrorWrapper>
) : (
children
)}
</StyledContainer>
)}
</>
Expand Down
1 change: 1 addition & 0 deletions app/formSchema/uiSchema/cbc/projectTypeUiSchema.ts
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@ const projectTypeUiSchema = {
highwayProjectType: {
'ui:widget': 'SelectWidget',
'ui:placeholder': 'Highway project type',
'ui:label': 'Highway Project Type',
},
lastMileProjectType: {
'ui:widget': 'SelectWidget',
Expand Down
35 changes: 33 additions & 2 deletions app/pages/analyst/cbc/[cbcId]/edit/[section].tsx
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ import { RelayProps, withRelay } from 'relay-nextjs';
import { graphql } from 'relay-runtime';
import review from 'formSchema/analyst/cbc/review';
import { ProjectTheme } from 'components/Analyst/Project';
import { useState } from 'react';
import { useCallback, useMemo, useState } from 'react';
import { useRouter } from 'next/router';
import editUiSchema from 'formSchema/uiSchema/cbc/editUiSchema';
import { FormBase } from 'components/Form';
Expand All @@ -17,6 +17,7 @@ import useModal from 'lib/helpers/useModal';
import { ChangeModal } from 'components/Analyst';
import { useUpdateCbcDataAndInsertChangeRequest } from 'schema/mutations/cbc/updateCbcDataAndInsertChangeReason';
import { createCbcSchemaData } from 'utils/schemaUtils';
import customValidate, { CBC_WARN_COLOR } from 'utils/cbcCustomValidator';

const getCbcSectionQuery = graphql`
query SectionCbcDataQuery($rowId: Int!) {
Expand Down Expand Up @@ -122,18 +123,48 @@ const EditCbcSection = ({
});
};

const validateSection = useCallback(
(data, schema) => {
const sectionErrors: any = {};
if (!schema?.properties) return sectionErrors;

Object.keys(schema.properties).forEach((fieldKey) => {
const fieldErrorList = customValidate(data, section, fieldKey);
if (fieldErrorList.length > 0) {
sectionErrors[fieldKey] = {
__errors: fieldErrorList,
errorColor: CBC_WARN_COLOR,
};
}
});

return sectionErrors;
},
[section]
);

const formErrors = useMemo(
() =>
validateSection(formData || dataBySection, review.properties[section]),
[dataBySection, formData, section, validateSection]
);

return (
<Layout title="Edit CBC Section" session={session}>
<CbcAnalystLayout query={query} isFormEditable>
<FormBase
formData={dataBySection[section]}
formData={formData?.[section] || dataBySection[section]}
schema={review.properties[section] as RJSFSchema}
theme={ProjectTheme}
uiSchema={editUiSchema[section]}
onSubmit={handleChangeRequestModal}
noValidate
noHtml5Validate
omitExtraData={false}
formContext={{ errors: formErrors, showErrorHint: true }}
onChange={(e) => {
setFormData({ ...dataBySection, [section]: e.formData });
}}
>
<Button>Save</Button>
<Button
Expand Down
46 changes: 46 additions & 0 deletions app/tests/pages/analyst/cbc/[cbcId]/[section].test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -53,6 +53,7 @@ const mockQueryPayload = {
transportProjectType: 'Fibre',
indigenousCommunities: 5,
proposedCompletionDate: '2023-03-31T00:00:00.000Z',
projectMilestoneCompleted: 0.75,
},
},
},
Expand Down Expand Up @@ -229,6 +230,7 @@ describe('EditCbcSection', () => {
'https://www.somethingmadeup.ca/en/innovation-science-economic-development/internet.html',
lastReviewed: '2023-07-11T00:00:00.000Z',
reviewNotes: 'Qtrly Report: Progress 0.39 -> 0.38',
projectMilestoneCompleted: 0.75,
},
},
},
Expand All @@ -241,4 +243,48 @@ describe('EditCbcSection', () => {
}
);
});

it('should have the correct validation errors for tombstone projectStatus', async () => {
pageTestingHelper.loadQuery();
pageTestingHelper.renderPage();

const projectStatusElement = screen.getByTestId(
'root_federalProjectNumber'
);
const parentElement = projectStatusElement.closest(
'[class^="ProjectFieldTemplate__ErrorWrapper"]'
);

expect(parentElement).toHaveStyle({
backgroundColor: 'rgb(248, 231, 143)',
});
const helpIcon = parentElement.querySelector('[data-testid="HelpIcon"]');
expect(helpIcon).toBeInTheDocument();

fireEvent.mouseOver(helpIcon);
const tooltip = await screen.findByText(/Missing Federal project number/);
expect(tooltip).toBeInTheDocument();
});

it('should have the correct validation errors for accordion', async () => {
pageTestingHelper.loadQuery();
pageTestingHelper.renderPage();

const projectStatusElement = screen.getByTestId(
'root_federalProjectNumber'
);
const parentElement = projectStatusElement.closest(
'[class^="ProjectFieldTemplate__ErrorWrapper"]'
);

expect(parentElement).toHaveStyle({
backgroundColor: 'rgb(248, 231, 143)',
});
const helpIcon = parentElement.querySelector('[data-testid="HelpIcon"]');
expect(helpIcon).toBeInTheDocument();

fireEvent.mouseOver(helpIcon);
const tooltip = await screen.findByText(/Missing Federal project number/);
expect(tooltip).toBeInTheDocument();
});
});
2 changes: 1 addition & 1 deletion app/utils/cbcCustomValidator.ts
Original file line number Diff line number Diff line change
Expand Up @@ -58,7 +58,7 @@ const CBC_VALIDATIONS = {
rules: [
{
condition: (data) =>
data.miscellaneous?.projectMilestoneCompleted === 1 &&
data.miscellaneous?.projectMilestoneCompleted === 100 &&
!data.miscellaneous?.constructionCompletedOn,
error: 'Missing date',
},
Expand Down
1 change: 1 addition & 0 deletions db/sqitch.plan
Original file line number Diff line number Diff line change
Expand Up @@ -643,3 +643,4 @@ tables/cbc_add_fk_update_constraint 2024-07-11T20:32:11Z Rafael Solorzano <61289
@1.182.2 2024-08-22T17:54:31Z CCBC Service Account <[email protected]> # release v1.182.2
@1.183.0 2024-08-22T18:35:35Z CCBC Service Account <[email protected]> # release v1.183.0
@1.184.0 2024-08-26T16:51:24Z CCBC Service Account <[email protected]> # release v1.184.0
@1.184.1 2024-08-26T19:57:58Z CCBC Service Account <[email protected]> # release v1.184.1
2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "CONN-CCBC-portal",
"version": "1.184.0",
"version": "1.184.1",
"main": "index.js",
"repository": "https://github.com/bcgov/CONN-CCBC-portal.git",
"author": "Romer, Meherzad CITZ:EX <[email protected]>",
Expand Down

0 comments on commit 89b0c75

Please sign in to comment.