Skip to content

Commit

Permalink
Merge pull request #469 from bcgov/FIX/disable_next_button_while_chec…
Browse files Browse the repository at this point in the history
…king_locations_error

disable next button while checking locations error
  • Loading branch information
chloe-yuu authored Dec 2, 2024
2 parents 28321a6 + 8d2ff87 commit 233d824
Show file tree
Hide file tree
Showing 4 changed files with 195 additions and 162 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ import { Checkbox, FormControlLabel, makeStyles, Typography } from '@mui/materia
import SaveAltIcon from '@mui/icons-material/SaveAlt'
import { StyledButton, StyledTable, StyledConfirmDialog } from 'vaping-regulation-shared-components';
import WarningIcon from '@mui/icons-material/Warning';
import CircularProgress from '@mui/material/CircularProgress';

import { BusinessLocationHeaders } from '@/constants/localEnums';
import { BusinessInfoContext } from '@/contexts/BusinessInfo';
Expand All @@ -17,7 +18,6 @@ import { LocationUtil } from '@/utils/location.util';
import FullScreen from '@/components/generic/FullScreen';
import TableWrapper from '@/components/generic/TableWrapper';
import { getInitialPagination } from '@/utils/util';
import { useAxiosGet } from '@/hooks/axios';

const PREFIX = 'ConfirmLocations';

Expand Down Expand Up @@ -110,7 +110,12 @@ const Root = styled('div')(({ theme }) => ({
},
}));

export default function ConfirmLocations () {
interface ConfirmLocationsProps {
isLoading: boolean;
setIsLoading: (loading: boolean) => void;
}

export default function ConfirmLocations({ isLoading, setIsLoading }: ConfirmLocationsProps) {

const [businessInfo, setBusinessInfo] = useContext(BusinessInfoContext);
const [targetRow, setTargetRow] = useState<IBusinessLocationValues>();
Expand All @@ -119,18 +124,19 @@ export default function ConfirmLocations () {
const [filterTable, setFilterTable] = useState<boolean>(false);
const viewFullscreenTable = useState<boolean>(false);
const [newLocations, setNewLocations] = useState<Array<IBusinessLocationValues>>([]);
const {errors: uploadErrors, validatedData, validateCSV} = useCsvValidator();
const [{ data: addressExistsData }, checkAddressExists] = useAxiosGet('', { manual: true });
const [duplicateWarning, setDuplicateWarning] = useState<String>("");
const [duplicateCount, setDuplicateCount] = useState<number>(0);
const { errors: uploadErrors, validatedData, validateCSV, duplicateWarning, duplicateCount } = useCsvValidator();

useEffect(() => {
setNewLocations(businessInfo.locations.filter((l: any) => !l.id)); //reset newLocations
setNewLocations(businessInfo.locations.filter((l: any) => !l.id)); //locations without id are new
}, [businessInfo.locations])

useEffect(() => {
validateCSV(BusinessCsvValidation, newLocations)
verifyDuplicates();
const validateAndCheckDuplicates = async () => {
setIsLoading(true);
await validateCSV(BusinessCsvValidation, newLocations);
setIsLoading(false);
};
validateAndCheckDuplicates();
}, [newLocations]);

useEffect(() => {
Expand Down Expand Up @@ -158,42 +164,14 @@ export default function ConfirmLocations () {
setOpenEdit(true);
}

const docheckAddressExists = async(fullAddress: string) => {
const response = await checkAddressExists({ url: `/location/check-address-exists?address=${fullAddress}` });
return response.data;
if (isLoading) {
return (
<div style={{ display: 'flex', justifyContent: 'center', alignItems: 'center', height: '100vh' }}>
<CircularProgress />
</div>
);
}

const verifyDuplicates = async () => {
if (newLocations.length === 0) return;

const updatedLocations = [...newLocations];
let duplicateWarnings = "";
let duplicateCount = 0;
let hasChanges = false;

for (let i = 0; i < newLocations.length; i++) {
const location = newLocations[i];
if (!location.tableData) location.tableData = { id: i };
if (location.addressLine1) {
const addressExists = await docheckAddressExists(location.addressLine1);
if (addressExists) {
duplicateWarnings = duplicateWarnings + location.addressLine1 + '; ';
duplicateCount++;
}
if (updatedLocations[i].addressExists !== addressExists) {
updatedLocations[i] = { ...location, addressExists: addressExists };
hasChanges = true;
}
}
}
if (hasChanges) {// Update the businessInfo state with the new locations only if there are changes
const existingLocations = businessInfo.locations.filter((l: any) => !!l.id);
setBusinessInfo({ ...businessInfo, locations: [...existingLocations, ...updatedLocations] });
}
setDuplicateWarning(duplicateWarnings);
setDuplicateCount(duplicateCount);
};

return (
(<Root>
<div className={classes.subHeader} >
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -54,77 +54,78 @@ const StyledChatBubbleOutlineIcon = styled(ChatBubbleOutlineIcon)({
paddingRight: '25px',
});

// NB: move steps to their own file
// the presence/logic of execIf should be revisited
const steps = [
{
icon: WorkOutlineIcon,
label: 'Business Details',
title: 'Confirm Your Business Details',
path: '/business/details',
component: <BusinessDetails />,
helpText: <p>Please confirm the business details that were entered when registering for your BCeID.
If you sell e-substances from this location, please add it as a location in the <b>"Add Business Locations"</b> section.
You must also add any additional locations from which you sell e-substances.</p>,
showSubscription: true,
canAdvanceChecks: [
{
property: 'locations',
validate: (val: Array<any>) => val.length,
},
{
property: 'detailsComplete',
validate: (val: boolean) => val,
}
],
onAdvance: [{
endpoint: process.env.BASE_URL + '/submission',
method: 'PATCH' as Method,
execIf: { validate: () => true }
}]
},
{
icon: MapOutlinedIcon,
label: 'Confirm Locations',
title: 'Confirm New Business Locations',
path: '/business/map',
component: <ConfirmLocations/>,
helpText: 'Confirm the details of the business locations that you have added on the previous page. You will be able to update this information at any time. Upon completion of this section you will be able to complete a Notice of Intent to sell E-substances and submit Product and Manufacturing Reports for each location you have listed.',
canAdvanceChecks: [
{
property: 'uploadErrors',
validate: (val: Array<any>) => val?.length === 0,
}
],
onAdvance: [{
endpoint: process.env.BASE_URL + '/submission',
method: 'PATCH' as Method,
execIf: {
property: 'entry',
validate: (val?: string) => val === 'upload',
},
}]
},
{
icon: AssignmentTurnedInOutlinedIcon,
label: 'Confirm Business Details and Submit',
title: 'Confirm Business Details and Submit',
path: '/business/confirm',
component: <ConfirmAndSubmit/>,
helpText: '',
onAdvance: [{
datakey: 'submissionId',
endpoint: process.env.BASE_URL + '/submission/save',
method: 'POST' as Method,
execIf: { validate: () => true }
}]
},
]

export default function MyBusinessNav () {

const [appGlobal, setAppGlobal] = useContext(AppGlobalContext);
const { pathname } = useLocation();
const [isLoading, setIsLoading] = useState<boolean>(false); //A loading state for the stepper Next button

// NB: move steps to their own file
// the presence/logic of execIf should be revisited
const steps = [
{
icon: WorkOutlineIcon,
label: 'Business Details',
title: 'Confirm Your Business Details',
path: '/business/details',
component: <BusinessDetails />,
helpText: <p>Please confirm the business details that were entered when registering for your BCeID.
If you sell e-substances from this location, please add it as a location in the <b>"Add Business Locations"</b> section.
You must also add any additional locations from which you sell e-substances.</p>,
showSubscription: true,
canAdvanceChecks: [
{
property: 'locations',
validate: (val: Array<any>) => val.length,
},
{
property: 'detailsComplete',
validate: (val: boolean) => val,
}
],
onAdvance: [{
endpoint: process.env.BASE_URL + '/submission',
method: 'PATCH' as Method,
execIf: { validate: () => true }
}]
},
{
icon: MapOutlinedIcon,
label: 'Confirm Locations',
title: 'Confirm New Business Locations',
path: '/business/map',
component: <ConfirmLocations isLoading={isLoading} setIsLoading={setIsLoading}/>,
helpText: 'Confirm the details of the business locations that you have added on the previous page. You will be able to update this information at any time. Upon completion of this section you will be able to complete a Notice of Intent to sell E-substances and submit Product and Manufacturing Reports for each location you have listed.',
canAdvanceChecks: [
{
property: 'uploadErrors',
validate: (val: Array<any>) => val?.length === 0,
}
],
onAdvance: [{
endpoint: process.env.BASE_URL + '/submission',
method: 'PATCH' as Method,
execIf: {
property: 'entry',
validate: (val?: string) => val === 'upload',
},
}]
},
{
icon: AssignmentTurnedInOutlinedIcon,
label: 'Confirm Business Details and Submit',
title: 'Confirm Business Details and Submit',
path: '/business/confirm',
component: <ConfirmAndSubmit/>,
helpText: '',
onAdvance: [{
datakey: 'submissionId',
endpoint: process.env.BASE_URL + '/submission/save',
method: 'POST' as Method,
execIf: { validate: () => true }
}]
},
]

// Fetch initial business details from local storage
const initialBusinessDetails = JSON.parse(localStorage.getItem('BusinessDetailesValues') || '{}');
Expand All @@ -144,12 +145,11 @@ export default function MyBusinessNav () {
uploadErrors: []
})

const stepperOptions = steps.map(element => ({ path: element.path, icon: element.icon, label: element.label }))

const [{ data: profile, error: profileError }] = useAxiosPost('/users/profile');
const [{ loading, error, response, data: submission }, get] = useAxiosGet('/submission', { manual: true });
const [{ loading: postLoading, error: postError, data: newSubmission }, post] = useAxiosPost('/submission', { manual: true });

const stepperOptions = steps.map(element => ({ path: element.path, icon: element.icon, label: element.label }))

// Fetch initial data
useEffect(() => {
Expand Down Expand Up @@ -297,6 +297,7 @@ export default function MyBusinessNav () {
dataForContext={businessInfo}
steps={steps.map(step => ({ path: step.path }))}
currentStep={currentStep}
isLoading={isLoading}
{...steps[currentStep]}
/>
)}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -44,6 +44,7 @@ type BottomStepperProps = {
steps: Array<{ path: string }>;
currentStep: number;
onAdvance?: OnAdvance[];
isLoading?: boolean;
}

export default function Bottom ({
Expand All @@ -55,6 +56,7 @@ export default function Bottom ({
onAdvance,
steps,
currentStep,
isLoading,
}: BottomStepperProps) {


Expand Down Expand Up @@ -155,7 +157,7 @@ export default function Bottom ({
) : (
<StyledButton
variant='contained'
disabled={!canAdvance || loading}
disabled={!canAdvance || loading || isLoading}
onClick={stepAction}
>
{'Next'}
Expand Down
Loading

0 comments on commit 233d824

Please sign in to comment.