diff --git a/frontend/src/common/apiManager/httpRequestHandler.ts b/frontend/src/common/apiManager/httpRequestHandler.ts index 0fae7ad6e..73865a141 100644 --- a/frontend/src/common/apiManager/httpRequestHandler.ts +++ b/frontend/src/common/apiManager/httpRequestHandler.ts @@ -28,13 +28,13 @@ const getUserStorage = () => { const getAccessToken = () => { const parsedSessionObject = getDefaultRequiredVal( { token_type: "", access_token: "" }, - getUserStorage() + getUserStorage(), ); const tokenType = String( - getDefaultRequiredVal("", parsedSessionObject["token_type"]) + getDefaultRequiredVal("", parsedSessionObject["token_type"]), ); const accessToken = String( - getDefaultRequiredVal("", parsedSessionObject["access_token"]) + getDefaultRequiredVal("", parsedSessionObject["access_token"]), ); return tokenType.trim() !== "" && accessToken.trim() !== "" ? `${parsedSessionObject["token_type"]} ${parsedSessionObject["access_token"]}` @@ -64,7 +64,7 @@ export const getCompanyIdFromSession = (): string | null => { export const getUserGuidFromSession = (): string | null => { const parsedSessionObject = getDefaultRequiredVal( { profile: { bceid_user_guid: "" } }, - getUserStorage() + getUserStorage(), ); return parsedSessionObject.profile?.bceid_user_guid ?? null; @@ -77,11 +77,11 @@ export const getUserGuidFromSession = (): string | null => { export const getCompanyNameFromSession = (): string | undefined => { const parsedSessionObject = getDefaultRequiredVal( { profile: { bceid_business_name: "" } }, - getUserStorage() + getUserStorage(), ); return getDefaultNullableVal( - parsedSessionObject.profile?.bceid_business_name + parsedSessionObject.profile?.bceid_business_name, ); }; @@ -93,7 +93,7 @@ export const getLoginUsernameFromSession = (): string => { const parsedSessionObject = getUserStorage(); if (!parsedSessionObject) return ""; return getDefaultRequiredVal( - "", + "", parsedSessionObject.profile?.bceid_username, parsedSessionObject.profile?.idir_username, ); @@ -106,12 +106,10 @@ export const getLoginUsernameFromSession = (): string => { export const getCompanyEmailFromSession = (): string | undefined => { const parsedSessionObject = getDefaultRequiredVal( { profile: { email: "" } }, - getUserStorage() + getUserStorage(), ); - return getDefaultNullableVal( - parsedSessionObject.profile?.email - ); + return getDefaultNullableVal(parsedSessionObject.profile?.email); }; /** @@ -135,7 +133,7 @@ export const httpGETRequest = (url: string) => { export const httpGETRequestStream = (url: string) => { return fetch(url, { headers: { - "Authorization": getAccessToken(), + Authorization: getAccessToken(), }, }); }; diff --git a/frontend/src/common/authentication/LoginRedirect.tsx b/frontend/src/common/authentication/LoginRedirect.tsx index 3d9665576..2fc140b8a 100644 --- a/frontend/src/common/authentication/LoginRedirect.tsx +++ b/frontend/src/common/authentication/LoginRedirect.tsx @@ -66,7 +66,5 @@ export const LoginRedirect = () => { return ; } - return ( - <> - ) + return <>; }; diff --git a/frontend/src/common/authentication/OnRouteBCContext.tsx b/frontend/src/common/authentication/OnRouteBCContext.tsx index 38ebdf254..dbbbba32c 100644 --- a/frontend/src/common/authentication/OnRouteBCContext.tsx +++ b/frontend/src/common/authentication/OnRouteBCContext.tsx @@ -42,7 +42,9 @@ export type OnRouteBCContextType = { setCompanyLegalName?: Dispatch>; companyLegalName?: string; idirUserDetails?: IDIRUserDetailContext; - setIDIRUserDetails?: Dispatch>; + setIDIRUserDetails?: Dispatch< + SetStateAction + >; }; const defaultBehaviour: OnRouteBCContextType = {}; diff --git a/frontend/src/common/authentication/util.ts b/frontend/src/common/authentication/util.ts index 95632775a..55ab5f8f1 100644 --- a/frontend/src/common/authentication/util.ts +++ b/frontend/src/common/authentication/util.ts @@ -17,7 +17,7 @@ import OnRouteBCContext from "./OnRouteBCContext"; */ export const DoesUserHaveRole = ( userRoles: string[] | null | undefined, - requiredRole: string | undefined + requiredRole: string | undefined, ) => { return ( requiredRole && @@ -34,7 +34,7 @@ export const DoesUserHaveRole = ( * @returns A boolean indicating if the user has the role to access a page or feature. */ export const DoesUserHaveRoleWithContext = ( - requiredRole: string | undefined + requiredRole: string | undefined, ) => { const { userRoles } = useContext(OnRouteBCContext); return ( diff --git a/frontend/src/common/components/banners/AlertBanners.tsx b/frontend/src/common/components/banners/AlertBanners.tsx index 37fc08fc4..7b07bb393 100644 --- a/frontend/src/common/components/banners/AlertBanners.tsx +++ b/frontend/src/common/components/banners/AlertBanners.tsx @@ -1,9 +1,9 @@ import { FontAwesomeIcon } from "@fortawesome/react-fontawesome"; -import { - faExclamationCircle, - faExclamationTriangle, - faInfoCircle, - faCheckCircle, +import { + faExclamationCircle, + faExclamationTriangle, + faInfoCircle, + faCheckCircle, } from "@fortawesome/free-solid-svg-icons"; import "./AlertBanners.scss"; diff --git a/frontend/src/common/components/banners/CompanyBanner.tsx b/frontend/src/common/components/banners/CompanyBanner.tsx index fc69d22c2..c90693ad6 100644 --- a/frontend/src/common/components/banners/CompanyBanner.tsx +++ b/frontend/src/common/components/banners/CompanyBanner.tsx @@ -13,30 +13,18 @@ export const CompanyBanner = ({ return (
- + COMPANY NAME - + {getDefaultRequiredVal("", companyName)}
- + onRouteBC CLIENT NUMBER - + {getDefaultRequiredVal("", clientNumber)}
diff --git a/frontend/src/common/components/banners/PermitExpiryDateBanner.tsx b/frontend/src/common/components/banners/PermitExpiryDateBanner.tsx index cc86383a4..3f975e607 100644 --- a/frontend/src/common/components/banners/PermitExpiryDateBanner.tsx +++ b/frontend/src/common/components/banners/PermitExpiryDateBanner.tsx @@ -11,10 +11,7 @@ export const PermitExpiryDateBanner = ({
PERMIT EXPIRY DATE - + {expiryDate}
diff --git a/frontend/src/common/components/banners/UserInfoBanner.tsx b/frontend/src/common/components/banners/UserInfoBanner.tsx index 4fd6d1487..1332960a6 100644 --- a/frontend/src/common/components/banners/UserInfoBanner.tsx +++ b/frontend/src/common/components/banners/UserInfoBanner.tsx @@ -4,32 +4,28 @@ import { Box, Typography } from "@mui/material"; import { UserInformation } from "../../../features/manageProfile/types/manageProfile"; import { BC_COLOURS } from "../../../themes/bcGovStyles"; -export const UserInfoBanner = memo(({ - userInfo -}: { - userInfo?: UserInformation; -}) => { - return userInfo ? ( - -
- USER GROUP - - {userInfo.userAuthGroup} - -
-
- ) : null; -}); +export const UserInfoBanner = memo( + ({ userInfo }: { userInfo?: UserInformation }) => { + return userInfo ? ( + +
+ USER GROUP + {userInfo.userAuthGroup} +
+
+ ) : null; + }, +); UserInfoBanner.displayName = "UserInfoBanner"; diff --git a/frontend/src/common/components/banners/tests/CompanyBanner.test.tsx b/frontend/src/common/components/banners/tests/CompanyBanner.test.tsx index 6666e597e..625e5f0b8 100644 --- a/frontend/src/common/components/banners/tests/CompanyBanner.test.tsx +++ b/frontend/src/common/components/banners/tests/CompanyBanner.test.tsx @@ -1,8 +1,11 @@ -import { defaultCompanyInfo, renderTestComponent } from "./helpers/CompanyBanner/prepare"; -import { - companyClientLabel, - companyClientNumber, - companyName, +import { + defaultCompanyInfo, + renderTestComponent, +} from "./helpers/CompanyBanner/prepare"; +import { + companyClientLabel, + companyClientNumber, + companyName, companyNameLabel, } from "./helpers/CompanyBanner/access"; @@ -14,7 +17,9 @@ describe("CompanyBanner display", () => { // Assert expect(await companyNameLabel()).toHaveTextContent("COMPANY NAME"); expect(await companyName()).toHaveTextContent(""); - expect(await companyClientLabel()).toHaveTextContent("onRouteBC CLIENT NUMBER"); + expect(await companyClientLabel()).toHaveTextContent( + "onRouteBC CLIENT NUMBER", + ); expect(await companyClientNumber()).toHaveTextContent(""); }); @@ -26,7 +31,9 @@ describe("CompanyBanner display", () => { const { legalName, clientNumber } = defaultCompanyInfo; expect(await companyNameLabel()).toHaveTextContent("COMPANY NAME"); expect(await companyName()).toHaveTextContent(legalName); - expect(await companyClientLabel()).toHaveTextContent("onRouteBC CLIENT NUMBER"); + expect(await companyClientLabel()).toHaveTextContent( + "onRouteBC CLIENT NUMBER", + ); expect(await companyClientNumber()).toHaveTextContent(clientNumber); }); -}); \ No newline at end of file +}); diff --git a/frontend/src/common/components/banners/tests/helpers/CompanyBanner/prepare.tsx b/frontend/src/common/components/banners/tests/helpers/CompanyBanner/prepare.tsx index 7fb22bd21..f3a86511e 100644 --- a/frontend/src/common/components/banners/tests/helpers/CompanyBanner/prepare.tsx +++ b/frontend/src/common/components/banners/tests/helpers/CompanyBanner/prepare.tsx @@ -32,6 +32,6 @@ export const renderTestComponent = (companyInfo?: CompanyProfile) => { + />, ); }; diff --git a/frontend/src/common/components/breadcrumb/Breadcrumb.tsx b/frontend/src/common/components/breadcrumb/Breadcrumb.tsx index e3a5cdc21..140d48d5f 100644 --- a/frontend/src/common/components/breadcrumb/Breadcrumb.tsx +++ b/frontend/src/common/components/breadcrumb/Breadcrumb.tsx @@ -16,7 +16,7 @@ export const Breadcrumb = ({ return ( {links.map((link, i) => { - const isCurrent = i === (links.length - 1); + const isCurrent = i === links.length - 1; return isCurrent ? ( ); -}; \ No newline at end of file +}; diff --git a/frontend/src/common/components/dashboard/Banner.tsx b/frontend/src/common/components/dashboard/Banner.tsx index 5066fd5fe..f002e6d10 100644 --- a/frontend/src/common/components/dashboard/Banner.tsx +++ b/frontend/src/common/components/dashboard/Banner.tsx @@ -27,11 +27,7 @@ export const Banner = ({ className={`layout-banner ${extendHeight ? "layout-banner--extend" : ""}`} > - +

{bannerText}

{bannerButton ? bannerButton : null} diff --git a/frontend/src/common/components/dashboard/TabLayout.tsx b/frontend/src/common/components/dashboard/TabLayout.tsx index ca8f67e9e..dfe22171a 100644 --- a/frontend/src/common/components/dashboard/TabLayout.tsx +++ b/frontend/src/common/components/dashboard/TabLayout.tsx @@ -70,19 +70,12 @@ const DisplayTabs = ({ -
- {label} -
- {count ? ( - - ) : null} +
{label}
+ {count ? : null}
- )} + } {...TabProps(index)} /> ); @@ -156,7 +149,7 @@ export const TabLayout = React.memo( ); - } + }, ); TabLayout.displayName = "TabLayout"; diff --git a/frontend/src/common/components/dialog/DeleteConfirmationDialog.tsx b/frontend/src/common/components/dialog/DeleteConfirmationDialog.tsx index 697138b02..f65fac8ed 100644 --- a/frontend/src/common/components/dialog/DeleteConfirmationDialog.tsx +++ b/frontend/src/common/components/dialog/DeleteConfirmationDialog.tsx @@ -37,7 +37,7 @@ export const DeleteConfirmationDialog = ({ * A caption string showing on title of the Dialog box. * @returns string */ - caption: string + caption: string; }) => { const title = caption; @@ -49,23 +49,16 @@ export const DeleteConfirmationDialog = ({ aria-labelledby="confirmation-dialog-title" open={isOpen} > - + -   + {" "} +   Delete {title}(s)? - - + + Are you sure you want to delete this? This action cannot be undone. @@ -73,8 +66,8 @@ export const DeleteConfirmationDialog = ({ ); diff --git a/frontend/src/common/components/header/components/SearchFilter.tsx b/frontend/src/common/components/header/components/SearchFilter.tsx index 4b7ebb8cf..b3f3855b0 100644 --- a/frontend/src/common/components/header/components/SearchFilter.tsx +++ b/frontend/src/common/components/header/components/SearchFilter.tsx @@ -1,7 +1,7 @@ import { useState } from "react"; -import { - RadioGroup, - FormControlLabel, +import { + RadioGroup, + FormControlLabel, Radio, MenuItem, Select, @@ -11,15 +11,24 @@ import { } from "@mui/material"; import "./SearchFilter.scss"; -import { Controller, FieldValues, FormProvider, useForm } from "react-hook-form"; +import { + Controller, + FieldValues, + FormProvider, + useForm, +} from "react-hook-form"; import { CustomSelectDisplayProps } from "../../../types/formElements"; import { useNavigate, useSearchParams } from "react-router-dom"; import { getDefaultRequiredVal } from "../../../helpers/util"; -import { SearchByFilter, SearchEntity, SearchFields } from "../../../../features/idir/search/types/types"; +import { + SearchByFilter, + SearchEntity, + SearchFields, +} from "../../../../features/idir/search/types/types"; import { SEARCH_RESULTS } from "../../../../routes/constants"; const SEARCH_BY_PERMIT_OPTIONS = [ - { label: "Permit Number", value: "permitNumber" }, + { label: "Permit Number", value: "permitNumber" }, { label: "Plate Number", value: "plate" }, ]; @@ -56,12 +65,17 @@ const getSearchByOptions = (searchEntity?: string | null) => { } }; -const getDefaultSearchBy = (searchEntity?: string | null, searchBy?: string | null) => { +const getDefaultSearchBy = ( + searchEntity?: string | null, + searchBy?: string | null, +) => { const defaultSearchEntity = getDefaultSearchEntity(searchEntity); - const searchByOptions = getSearchByOptions(defaultSearchEntity).map(option => option.value); + const searchByOptions = getSearchByOptions(defaultSearchEntity).map( + (option) => option.value, + ); return getDefaultRequiredVal( searchByOptions[0], - searchByOptions.find(option => option === searchBy) + searchByOptions.find((option) => option === searchBy), ); }; @@ -69,10 +83,18 @@ export const SearchFilter = () => { const [searchParams] = useSearchParams(); const navigate = useNavigate(); const searchEntity = getDefaultSearchEntity(searchParams.get("searchEntity")); - const [searchByOptions, setSearchByOptions] = useState(getSearchByOptions(searchEntity)); - const searchBy = getDefaultSearchBy(searchEntity, searchParams.get("searchByFilter")); - const searchValue = getDefaultRequiredVal("", searchParams.get("searchValue")); - const defaultSearchFilter = { + const [searchByOptions, setSearchByOptions] = useState( + getSearchByOptions(searchEntity), + ); + const searchBy = getDefaultSearchBy( + searchEntity, + searchParams.get("searchByFilter"), + ); + const searchValue = getDefaultRequiredVal( + "", + searchParams.get("searchValue"), + ); + const defaultSearchFilter = { searchEntity, searchByFilter: searchBy, searchValue, @@ -82,14 +104,17 @@ export const SearchFilter = () => { defaultValues: defaultSearchFilter, reValidateMode: "onBlur", }); - + const { handleSubmit, setValue, control } = formMethods; const handleSearchEntityChange = (searchEntity: string) => { setValue("searchEntity", searchEntity as SearchEntity); const updatedSearchByOptions = getSearchByOptions(searchEntity); setSearchByOptions(updatedSearchByOptions); - setValue("searchByFilter", updatedSearchByOptions[0].value as SearchByFilter); + setValue( + "searchByFilter", + updatedSearchByOptions[0].value as SearchByFilter, + ); }; const handleSearchByChange = (event: SelectChangeEvent) => { @@ -97,7 +122,9 @@ export const SearchFilter = () => { setValue("searchByFilter", searchBy as SearchByFilter); }; - const handleSearchValueChange = (event: React.ChangeEvent) => { + const handleSearchValueChange = ( + event: React.ChangeEvent, + ) => { const searchValue = event.target.value; setValue("searchValue", searchValue); }; @@ -106,7 +133,7 @@ export const SearchFilter = () => { const searchFields = Object.entries(data) .map(([key, value]) => `${key}=${value}`) .join("&"); - + navigate(`${SEARCH_RESULTS}?${searchFields}`); }; @@ -129,29 +156,17 @@ export const SearchFilter = () => { - } + control={} /> - } + control={} /> - } + control={} /> )} @@ -169,13 +184,15 @@ export const SearchFilter = () => { defaultValue={value} value={value} onChange={handleSearchByChange} - SelectDisplayProps={{ - "data-testid": `select-search-by` - } as CustomSelectDisplayProps} + SelectDisplayProps={ + { + "data-testid": `select-search-by`, + } as CustomSelectDisplayProps + } > {searchByOptions.map((option) => ( - @@ -195,10 +212,10 @@ export const SearchFilter = () => { value={value} onChange={handleSearchValueChange} /> - )} + )} /> - - - + return ( +
+ + + +
+ + +
- - ); -}); + ); + }, +); MyInfoForm.displayName = "MyInfoForm"; diff --git a/frontend/src/features/manageProfile/components/forms/userManagement/EditUser.tsx b/frontend/src/features/manageProfile/components/forms/userManagement/EditUser.tsx index db25d4727..9a2b0ca22 100644 --- a/frontend/src/features/manageProfile/components/forms/userManagement/EditUser.tsx +++ b/frontend/src/features/manageProfile/components/forms/userManagement/EditUser.tsx @@ -1,13 +1,6 @@ import { memo, useContext, useState } from "react"; -import { - Box, - Button, - Divider, - Link, - Stack, - Typography -} from "@mui/material"; +import { Box, Button, Divider, Link, Stack, Typography } from "@mui/material"; import { useMutation } from "@tanstack/react-query"; import { Controller, @@ -22,9 +15,7 @@ import { applyWhenNotNullable, getDefaultRequiredVal, } from "../../../../../common/helpers/util"; -import { - requiredMessage -} from "../../../../../common/helpers/validationMessages"; +import { requiredMessage } from "../../../../../common/helpers/validationMessages"; import { MANAGE_PROFILES } from "../../../../../routes/constants"; import { BC_COLOURS } from "../../../../../themes/bcGovStyles"; import { updateUserInfo } from "../../../apiManager/manageProfileAPI"; @@ -216,7 +207,7 @@ export const EditUserForm = memo( ); - } + }, ); EditUserForm.displayName = "EditUserForm"; diff --git a/frontend/src/features/manageProfile/components/user-management/UserManagementRowOptions.tsx b/frontend/src/features/manageProfile/components/user-management/UserManagementRowOptions.tsx index c5de84d23..29b2332bb 100644 --- a/frontend/src/features/manageProfile/components/user-management/UserManagementRowOptions.tsx +++ b/frontend/src/features/manageProfile/components/user-management/UserManagementRowOptions.tsx @@ -6,13 +6,14 @@ const USER_MANAGEMENT_OPTION_TYPES = { EDIT: "edit", } as const; -type UserManagementOptionType = typeof USER_MANAGEMENT_OPTION_TYPES[keyof typeof USER_MANAGEMENT_OPTION_TYPES]; +type UserManagementOptionType = + (typeof USER_MANAGEMENT_OPTION_TYPES)[keyof typeof USER_MANAGEMENT_OPTION_TYPES]; const USER_MANAGEMENT_OPTIONS: { label: string; value: UserManagementOptionType; }[] = [ - { + { label: "Edit", value: USER_MANAGEMENT_OPTION_TYPES.EDIT, }, diff --git a/frontend/src/features/manageProfile/pages/AddUserDashboard.tsx b/frontend/src/features/manageProfile/pages/AddUserDashboard.tsx index 0302b099f..7346d2729 100644 --- a/frontend/src/features/manageProfile/pages/AddUserDashboard.tsx +++ b/frontend/src/features/manageProfile/pages/AddUserDashboard.tsx @@ -4,14 +4,7 @@ import React, { useContext, useState } from "react"; import { faChevronRight } from "@fortawesome/free-solid-svg-icons"; import { FontAwesomeIcon } from "@fortawesome/react-fontawesome"; import { useNavigate } from "react-router-dom"; -import { - Box, - Button, - Divider, - Link, - Typography, - Stack, -} from "@mui/material"; +import { Box, Button, Divider, Link, Typography, Stack } from "@mui/material"; import { Controller, @@ -30,7 +23,10 @@ import { addUserToCompany } from "../apiManager/manageProfileAPI"; import { UserAuthRadioGroup } from "../components/forms/userManagement/UserAuthRadioGroup"; import UserGroupsAndPermissionsModal from "../components/user-management/UserGroupsAndPermissionsModal"; import { BCEID_PROFILE_TABS } from "../types/manageProfile.d"; -import { BCeIDAddUserRequest, BCEID_AUTH_GROUP } from "../types/userManagement.d"; +import { + BCeIDAddUserRequest, + BCEID_AUTH_GROUP, +} from "../types/userManagement.d"; /** * BCeID User - Add User Page. @@ -115,15 +111,11 @@ export const AddUserDashboard = React.memo(() => { return (
- + - + { Profile - + { User Management - + Add User - + - + User ID @@ -188,20 +169,12 @@ export const AddUserDashboard = React.memo(() => { - + - - Assign User Group - + Assign User Group - + { return ( - + Edit Company Information ); diff --git a/frontend/src/features/manageProfile/pages/DisplayCompanyInfo.tsx b/frontend/src/features/manageProfile/pages/DisplayCompanyInfo.tsx index 0d5f5c3fe..302a6f3f4 100644 --- a/frontend/src/features/manageProfile/pages/DisplayCompanyInfo.tsx +++ b/frontend/src/features/manageProfile/pages/DisplayCompanyInfo.tsx @@ -39,20 +39,14 @@ export const DisplayInfo = memo( {formatProvince( companyInfo?.mailingAddress.countryCode, - companyInfo?.mailingAddress.provinceCode + companyInfo?.mailingAddress.provinceCode, )} {`${companyInfo?.mailingAddress.city} ${companyInfo?.mailingAddress.postalCode}`} Company Contact Details - Email: { - getDefaultRequiredVal( - "", - companyEmail, - companyInfo?.email - ) - } + Email: {getDefaultRequiredVal("", companyEmail, companyInfo?.email)} {`Phone: ${formatPhoneNumber(companyInfo?.phone)} ${ companyInfo?.extension ? `Ext: ${companyInfo?.extension}` : "" @@ -66,15 +60,11 @@ export const DisplayInfo = memo( Company Primary Contact {`${companyInfo?.primaryContact.firstName} ${companyInfo?.primaryContact.lastName}`} - Email: { - getDefaultRequiredVal( - "", - companyInfo?.primaryContact?.email - ) - } + Email:{" "} + {getDefaultRequiredVal("", companyInfo?.primaryContact?.email)} {`Primary Phone: ${formatPhoneNumber( - companyInfo?.primaryContact.phone1 + companyInfo?.primaryContact.phone1, )} ${ companyInfo?.primaryContact.phone1Extension ? `Ext: ${companyInfo?.primaryContact.phone1Extension}` @@ -86,7 +76,7 @@ export const DisplayInfo = memo( {formatProvince( companyInfo?.primaryContact.countryCode, - companyInfo?.primaryContact.provinceCode + companyInfo?.primaryContact.provinceCode, )} {companyInfo?.primaryContact.city} @@ -106,7 +96,7 @@ export const DisplayInfo = memo( )}
); - } + }, ); DisplayInfo.displayName = "DisplayInfo"; diff --git a/frontend/src/features/manageProfile/pages/DisplayMyInfo.tsx b/frontend/src/features/manageProfile/pages/DisplayMyInfo.tsx index a5fedec68..a5510f595 100644 --- a/frontend/src/features/manageProfile/pages/DisplayMyInfo.tsx +++ b/frontend/src/features/manageProfile/pages/DisplayMyInfo.tsx @@ -6,60 +6,59 @@ import { faPencil } from "@fortawesome/free-solid-svg-icons"; import "./DisplayMyInfo.scss"; import { UserInformation } from "../types/manageProfile"; import { formatPhoneNumber } from "../../../common/components/form/subFormComponents/PhoneNumberInput"; -import { formatProvince, formatCountry } from "../../../common/helpers/formatCountryProvince"; +import { + formatProvince, + formatCountry, +} from "../../../common/helpers/formatCountryProvince"; -export const DisplayMyInfo = memo(({ - myInfo, - setIsEditing, -}: { - myInfo?: UserInformation; - setIsEditing: React.Dispatch>; -}) => { - if (!myInfo) return <>; - return ( -
- - - {`${myInfo.firstName} ${myInfo.lastName}`} - - - Email: {myInfo.email} - - - Primary Phone: {formatPhoneNumber(myInfo.phone1)} {myInfo.phone1Extension ? `Ext: ${myInfo.phone1Extension}` : ""} - - {myInfo.phone2 ? ( +export const DisplayMyInfo = memo( + ({ + myInfo, + setIsEditing, + }: { + myInfo?: UserInformation; + setIsEditing: React.Dispatch>; + }) => { + if (!myInfo) return <>; + return ( +
+ + + {`${myInfo.firstName} ${myInfo.lastName}`} + + Email: {myInfo.email} - Alternate Phone: {formatPhoneNumber(myInfo.phone2)} {myInfo.phone2Extension ? `Ext: ${myInfo.phone2Extension}` : ""} + Primary Phone: {formatPhoneNumber(myInfo.phone1)}{" "} + {myInfo.phone1Extension ? `Ext: ${myInfo.phone1Extension}` : ""} - ) : null} - {myInfo.fax ? ( + {myInfo.phone2 ? ( + + Alternate Phone: {formatPhoneNumber(myInfo.phone2)}{" "} + {myInfo.phone2Extension ? `Ext: ${myInfo.phone2Extension}` : ""} + + ) : null} + {myInfo.fax ? ( + Fax: {formatPhoneNumber(myInfo.fax)} + ) : null} + {formatCountry(myInfo.countryCode)} - Fax: {formatPhoneNumber(myInfo.fax)} + {formatProvince(myInfo.countryCode, myInfo.provinceCode)} - ) : null} - - {formatCountry(myInfo.countryCode)} - - - {formatProvince(myInfo.countryCode, myInfo.provinceCode)} - - - {myInfo.city} - - -
- + {myInfo.city} + +
+ +
-
- ); -}); + ); + }, +); DisplayMyInfo.displayName = "DisplayMyInfo"; diff --git a/frontend/src/features/manageProfile/pages/EditUserDashboard.tsx b/frontend/src/features/manageProfile/pages/EditUserDashboard.tsx index 8be45b196..50086bd79 100644 --- a/frontend/src/features/manageProfile/pages/EditUserDashboard.tsx +++ b/frontend/src/features/manageProfile/pages/EditUserDashboard.tsx @@ -1,9 +1,6 @@ import { faChevronRight } from "@fortawesome/free-solid-svg-icons"; import { FontAwesomeIcon } from "@fortawesome/react-fontawesome"; -import { - Box, - Typography -} from "@mui/material"; +import { Box, Typography } from "@mui/material"; import { useQuery } from "@tanstack/react-query"; import React from "react"; import { useNavigate, useParams } from "react-router-dom"; @@ -29,7 +26,7 @@ export const EditUserDashboard = React.memo(() => { const { data: userInfo, isLoading } = useQuery( ["userByuserGUID", userGUID], () => getCompanyUserByUserGUID(userGUID as string), - { retry: false, enabled: true, staleTime: Infinity } + { retry: false, enabled: true, staleTime: Infinity }, ); const onClickBreadcrumb = () => { @@ -42,13 +39,9 @@ export const EditUserDashboard = React.memo(() => { return (
- + Date Created: @@ -57,7 +50,7 @@ export const EditUserDashboard = React.memo(() => { (dateTimeStr: string) => toLocal(dateTimeStr, DATE_FORMATS.SHORT), userInfo?.createdDateTime, - "" + "", )}           Last Updated: {" "} @@ -66,14 +59,14 @@ export const EditUserDashboard = React.memo(() => { applyWhenNotNullable( (dateTimeStr: string) => toLocal(dateTimeStr, DATE_FORMATS.SHORT), - userInfo?.updatedDateTime + userInfo?.updatedDateTime, ), applyWhenNotNullable( (dateTimeStr: string) => toLocal(dateTimeStr, DATE_FORMATS.SHORT), userInfo?.createdDateTime, - "" - ) + "", + ), )}
} @@ -81,9 +74,7 @@ export const EditUserDashboard = React.memo(() => { />
- + { Profile - + { User Management - + Edit User diff --git a/frontend/src/features/manageProfile/pages/MyInfo.tsx b/frontend/src/features/manageProfile/pages/MyInfo.tsx index 1e5d1c380..5e4fa396d 100644 --- a/frontend/src/features/manageProfile/pages/MyInfo.tsx +++ b/frontend/src/features/manageProfile/pages/MyInfo.tsx @@ -13,10 +13,7 @@ import { ErrorFallback } from "../../../common/pages/ErrorFallback"; import { MyInfoForm } from "../components/forms/myInfo/MyInfoForm"; const Header = () => ( - + Edit My Information ); diff --git a/frontend/src/features/manageProfile/pages/UserManagement.tsx b/frontend/src/features/manageProfile/pages/UserManagement.tsx index fa774ca9b..20b9e13e3 100644 --- a/frontend/src/features/manageProfile/pages/UserManagement.tsx +++ b/frontend/src/features/manageProfile/pages/UserManagement.tsx @@ -89,7 +89,9 @@ export const UserManagement = () => { selectAllMode="page" // Enable checkboxes for row selection enableRowSelection={(row: MRT_Row): boolean => { - if (row?.original?.userGUID === userFromToken?.profile?.bceid_user_guid) { + if ( + row?.original?.userGUID === userFromToken?.profile?.bceid_user_guid + ) { return false; } return true; @@ -126,17 +128,18 @@ export const UserManagement = () => { return <>; } }, - [] + [], )} renderToolbarInternalActions={useCallback( () => ( - - + + ), - [hasNoRowsSelected] + [hasNoRowsSelected], )} /* * diff --git a/frontend/src/features/manageProfile/types/UserManagementColumns.tsx b/frontend/src/features/manageProfile/types/UserManagementColumns.tsx index c8b98f992..c0ecbe525 100644 --- a/frontend/src/features/manageProfile/types/UserManagementColumns.tsx +++ b/frontend/src/features/manageProfile/types/UserManagementColumns.tsx @@ -2,7 +2,11 @@ import { Stack } from "@mui/material"; import { MRT_ColumnDef } from "material-react-table"; import { DATE_FORMATS, toLocal } from "../../../common/helpers/formatDate"; import { UserManagementChip } from "../components/user-management/UserManagementChip"; -import { BCEID_AUTH_GROUP, BCeIDAuthGroup, ReadCompanyUser } from "./userManagement.d"; +import { + BCEID_AUTH_GROUP, + BCeIDAuthGroup, + ReadCompanyUser, +} from "./userManagement.d"; /** * Translates the userAuthGroup code into a more meaningful text for the user. @@ -68,7 +72,11 @@ export const UserManagementColumnsDefinition: MRT_ColumnDef[] = accessorKey: "createdDateTime", header: "Date Created", Cell: (props: { cell: any }) => { - return <>{toLocal(props.cell.getValue(), DATE_FORMATS.DATEONLY_SHORT_NAME)}; + return ( + <> + {toLocal(props.cell.getValue(), DATE_FORMATS.DATEONLY_SHORT_NAME)} + + ); }, }, ]; diff --git a/frontend/src/features/manageProfile/types/userManagement.d.ts b/frontend/src/features/manageProfile/types/userManagement.d.ts index d84b6f286..09b4192f0 100644 --- a/frontend/src/features/manageProfile/types/userManagement.d.ts +++ b/frontend/src/features/manageProfile/types/userManagement.d.ts @@ -14,7 +14,8 @@ export const USER_AUTH_GROUP = { EOFFICER: "EOFFICER", } as const; -export type UserAuthGroup = typeof USER_AUTH_GROUP[keyof typeof USER_AUTH_GROUP]; +export type UserAuthGroup = + (typeof USER_AUTH_GROUP)[keyof typeof USER_AUTH_GROUP]; /** * The types of user auth groups for BCeID users. @@ -25,7 +26,8 @@ export const BCEID_AUTH_GROUP = { ORGADMIN: USER_AUTH_GROUP.ORGADMIN, } as const; -export type BCeIDAuthGroup = typeof BCEID_AUTH_GROUP[keyof typeof BCEID_AUTH_GROUP]; +export type BCeIDAuthGroup = + (typeof BCEID_AUTH_GROUP)[keyof typeof BCEID_AUTH_GROUP]; /** * The types of user statuses for BCeID users. @@ -51,5 +53,4 @@ export interface ReadCompanyUser extends UserInformation { export type BCeIDAddUserRequest = { userName: string; userAuthGroup: BCeIDAuthGroup; -} - +}; diff --git a/frontend/src/features/manageVehicles/apiManager/hooks.ts b/frontend/src/features/manageVehicles/apiManager/hooks.ts index 5a7b0f9be..3900c65aa 100644 --- a/frontend/src/features/manageVehicles/apiManager/hooks.ts +++ b/frontend/src/features/manageVehicles/apiManager/hooks.ts @@ -28,7 +28,7 @@ export const useVehicleByIdQuery = (powerUnitId: string, companyId: string) => { return useQuery( ["powerUnitById", powerUnitId], () => getPowerUnit(powerUnitId, companyId), - { retry: false } + { retry: false }, ); }; diff --git a/frontend/src/features/manageVehicles/apiManager/vehiclesAPI.tsx b/frontend/src/features/manageVehicles/apiManager/vehiclesAPI.tsx index 0c2170489..baed0cbf2 100644 --- a/frontend/src/features/manageVehicles/apiManager/vehiclesAPI.tsx +++ b/frontend/src/features/manageVehicles/apiManager/vehiclesAPI.tsx @@ -22,7 +22,9 @@ import { * All Power Unit and Trailer Data * @return An array of combined PowerUnit and Trailers */ -export const getAllVehicles = async (companyId: string): Promise<(PowerUnit | Trailer)[]> => { +export const getAllVehicles = async ( + companyId: string, +): Promise<(PowerUnit | Trailer)[]> => { const powerUnits = await getAllPowerUnits(companyId); const trailers = await getAllTrailers(companyId); @@ -44,7 +46,9 @@ export const getAllVehicles = async (companyId: string): Promise<(PowerUnit | Tr * All Power Unit Data * @return {*} {Promise} */ -export const getAllPowerUnits = async (companyId: string): Promise => { +export const getAllPowerUnits = async ( + companyId: string, +): Promise => { const url = `${VEHICLES_URL}/companies/${companyId}/vehicles/powerUnits`; return httpGETRequest(url).then((response) => response.data); }; @@ -54,7 +58,10 @@ export const getAllPowerUnits = async (companyId: string): Promise * @param powerUnitId The powerUnitId * @returns A Promise containing the API response. */ -export const getPowerUnit = async (powerUnitId: string, companyId: string): Promise => { +export const getPowerUnit = async ( + powerUnitId: string, + companyId: string, +): Promise => { const url = `${VEHICLES_URL}/companies/${companyId}/vehicles/powerUnits/${powerUnitId}`; return httpGETRequest(url).then((response) => response.data); }; @@ -74,7 +81,7 @@ export const getPowerUnitTypes = async (): Promise> => { * @returns Promise containing the response from the create powerUnit API. */ export const addPowerUnit = async ({ - powerUnit, + powerUnit, companyId, }: { powerUnit: PowerUnit; @@ -116,7 +123,10 @@ export const getAllTrailers = async (companyId: string): Promise => { * @param trailerId The trailer to be retrieved. * @returns A Promise with data from the API. */ -export const getTrailer = async (trailerId: string, companyId: string): Promise => { +export const getTrailer = async ( + trailerId: string, + companyId: string, +): Promise => { const url = `${VEHICLES_URL}/companies/${companyId}/vehicles/trailers/${trailerId}`; return httpGETRequest(url).then((response) => response.data); }; @@ -158,7 +168,7 @@ export const addTrailer = async ({ trailer, companyId, }: { - trailer: Trailer; + trailer: Trailer; companyId: string; }) => { const url = `${VEHICLES_URL}/companies/${companyId}/vehicles/trailers`; diff --git a/frontend/src/features/manageVehicles/components/dashboard/AddVehicleButton.tsx b/frontend/src/features/manageVehicles/components/dashboard/AddVehicleButton.tsx index ef88029d0..ae9f9dd67 100644 --- a/frontend/src/features/manageVehicles/components/dashboard/AddVehicleButton.tsx +++ b/frontend/src/features/manageVehicles/components/dashboard/AddVehicleButton.tsx @@ -32,11 +32,11 @@ export const AddVehicleButton = () => { const options = [ { vehicleMode: VEHICLE_TYPES_ENUM.POWER_UNIT, - labelValue: "Power Unit" + labelValue: "Power Unit", }, { vehicleMode: VEHICLE_TYPES_ENUM.TRAILER, - labelValue: "Trailer" + labelValue: "Trailer", }, ]; @@ -59,7 +59,7 @@ export const AddVehicleButton = () => { const handleMenuItemClick = ( _event: React.MouseEvent, _index: number, - vehicleMode: VEHICLE_TYPES_ENUM + vehicleMode: VEHICLE_TYPES_ENUM, ) => { if (vehicleMode === VEHICLE_TYPES_ENUM.POWER_UNIT) { navigate(`/${MANAGE_VEHICLES}/${ADD_POWER_UNIT}`); @@ -102,7 +102,8 @@ export const AddVehicleButton = () => { aria-haspopup="true" onClick={handleToggle} > - Add Vehicle + Add Vehicle{" "} + - + {addVehicleMode === VEHICLE_TYPES_ENUM.POWER_UNIT && ( )} @@ -36,9 +34,7 @@ export const AddVehicleDashboard = React.memo( )} - + - + - + {addVehicleMode === VEHICLE_TYPES_ENUM.POWER_UNIT && @@ -71,21 +61,15 @@ export const AddVehicleDashboard = React.memo( - + - - + + {addVehicleMode === VEHICLE_TYPES_ENUM.POWER_UNIT && "Power Unit Details"} {addVehicleMode === VEHICLE_TYPES_ENUM.TRAILER && "Trailer Details"} @@ -99,7 +83,7 @@ export const AddVehicleDashboard = React.memo(
); - } + }, ); AddVehicleDashboard.displayName = "AddVehicleDashboard"; diff --git a/frontend/src/features/manageVehicles/components/dashboard/EditVehicleDashboard.tsx b/frontend/src/features/manageVehicles/components/dashboard/EditVehicleDashboard.tsx index b873e849a..d0a661feb 100644 --- a/frontend/src/features/manageVehicles/components/dashboard/EditVehicleDashboard.tsx +++ b/frontend/src/features/manageVehicles/components/dashboard/EditVehicleDashboard.tsx @@ -13,7 +13,10 @@ import { PowerUnitForm } from "../form/PowerUnitForm"; import { TrailerForm } from "../form/TrailerForm"; import { getVehicleById } from "../../apiManager/vehiclesAPI"; import { PowerUnit, Trailer } from "../../types/managevehicles"; -import { applyWhenNotNullable, getDefaultRequiredVal } from "../../../../common/helpers/util"; +import { + applyWhenNotNullable, + getDefaultRequiredVal, +} from "../../../../common/helpers/util"; import { DATE_FORMATS, toLocal } from "../../../../common/helpers/formatDate"; import { getCompanyIdFromSession } from "../../../../common/apiManager/httpRequestHandler"; @@ -23,22 +26,20 @@ export const EditVehicleDashboard = React.memo( const { vehicleId } = useParams(); const companyId = getDefaultRequiredVal("0", getCompanyIdFromSession()); - const isEditPowerUnit = (editVehicleMode: VEHICLE_TYPES_ENUM) => + const isEditPowerUnit = (editVehicleMode: VEHICLE_TYPES_ENUM) => editVehicleMode === VEHICLE_TYPES_ENUM.POWER_UNIT; - const isEditTrailer = (editVehicleMode: VEHICLE_TYPES_ENUM) => + const isEditTrailer = (editVehicleMode: VEHICLE_TYPES_ENUM) => editVehicleMode === VEHICLE_TYPES_ENUM.TRAILER; - + const { data: vehicleToEdit, isLoading } = useQuery( ["vehicleById", vehicleId], () => getVehicleById( vehicleId as string, - isEditPowerUnit(editVehicleMode) - ? "powerUnit" - : "trailer", - companyId + isEditPowerUnit(editVehicleMode) ? "powerUnit" : "trailer", + companyId, ), - { retry: false, enabled: true } + { retry: false, enabled: true }, ); const handleShowAddVehicle = () => { @@ -47,35 +48,39 @@ export const EditVehicleDashboard = React.memo( return (
- - {(isEditPowerUnit(editVehicleMode) || isEditTrailer(editVehicleMode)) && ( + + {(isEditPowerUnit(editVehicleMode) || + isEditTrailer(editVehicleMode)) && ( Date Created:   {applyWhenNotNullable( - (dateTimeStr: string) => toLocal(dateTimeStr, DATE_FORMATS.SHORT), + (dateTimeStr: string) => + toLocal(dateTimeStr, DATE_FORMATS.SHORT), vehicleToEdit?.createdDateTime, - "" + "", )}           Last Updated: {" "} {getDefaultRequiredVal( "", applyWhenNotNullable( - (dateTimeStr: string) => toLocal(dateTimeStr, DATE_FORMATS.SHORT), - vehicleToEdit?.updatedDateTime + (dateTimeStr: string) => + toLocal(dateTimeStr, DATE_FORMATS.SHORT), + vehicleToEdit?.updatedDateTime, ), applyWhenNotNullable( - (dateTimeStr: string) => toLocal(dateTimeStr, DATE_FORMATS.SHORT), + (dateTimeStr: string) => + toLocal(dateTimeStr, DATE_FORMATS.SHORT), vehicleToEdit?.createdDateTime, - "" - ) + "", + ), )}
} @@ -84,9 +89,7 @@ export const EditVehicleDashboard = React.memo( )} - + - + - + {editVehicleMode === VEHICLE_TYPES_ENUM.POWER_UNIT && @@ -119,36 +116,36 @@ export const EditVehicleDashboard = React.memo( - + - - + + {editVehicleMode === VEHICLE_TYPES_ENUM.POWER_UNIT && "Power Unit Details"} {editVehicleMode === VEHICLE_TYPES_ENUM.TRAILER && "Trailer Details"} {!isLoading && editVehicleMode === VEHICLE_TYPES_ENUM.POWER_UNIT && ( - + )} {!isLoading && editVehicleMode === VEHICLE_TYPES_ENUM.TRAILER && ( - + )} ); - } + }, ); EditVehicleDashboard.displayName = "EditVehicleDashboard"; diff --git a/frontend/src/features/manageVehicles/components/dashboard/ManageVehiclesDashboard.tsx b/frontend/src/features/manageVehicles/components/dashboard/ManageVehiclesDashboard.tsx index cdc030abc..c1e4dde01 100644 --- a/frontend/src/features/manageVehicles/components/dashboard/ManageVehiclesDashboard.tsx +++ b/frontend/src/features/manageVehicles/components/dashboard/ManageVehiclesDashboard.tsx @@ -55,11 +55,23 @@ export const ManageVehiclesDashboard = memo(() => { const tabs = [ { label: "Power Unit", - component: , + component: ( + + ), }, { label: "Trailer", - component: , + component: ( + + ), }, /** * TODO: Enable Vehicle Configuration page navigation when page is ready diff --git a/frontend/src/features/manageVehicles/components/form/PowerUnitForm.tsx b/frontend/src/features/manageVehicles/components/form/PowerUnitForm.tsx index 10b18b34d..c09ddced7 100644 --- a/frontend/src/features/manageVehicles/components/form/PowerUnitForm.tsx +++ b/frontend/src/features/manageVehicles/components/form/PowerUnitForm.tsx @@ -12,13 +12,16 @@ import { import { useNavigate } from "react-router-dom"; import { useContext } from "react"; import { SnackBarContext } from "../../../../App"; -import { getDefaultRequiredVal, getDefaultNullableVal } from "../../../../common/helpers/util"; -import { - invalidNumber, - invalidPlateLength, - invalidVINLength, - invalidYearMin, - requiredMessage +import { + getDefaultRequiredVal, + getDefaultNullableVal, +} from "../../../../common/helpers/util"; +import { + invalidNumber, + invalidPlateLength, + invalidVINLength, + invalidYearMin, + requiredMessage, } from "../../../../common/helpers/validationMessages"; /** @@ -81,8 +84,13 @@ export const PowerUnitForm = ({ powerUnit, companyId }: PowerUnitFormProps) => { */ const onAddOrUpdateVehicle = async (data: FieldValues) => { // return input as a number if it's a valid number value, or original value if invalid number - const convertToNumberIfValid = (str?: string | null, valueToReturnWhenInvalid?: 0 | string | null) => { - return str != null && str !== "" && !isNaN(Number(str)) ? Number(str) : valueToReturnWhenInvalid; + const convertToNumberIfValid = ( + str?: string | null, + valueToReturnWhenInvalid?: 0 | string | null, + ) => { + return str != null && str !== "" && !isNaN(Number(str)) + ? Number(str) + : valueToReturnWhenInvalid; }; if (powerUnit?.powerUnitId) { @@ -95,7 +103,10 @@ export const PowerUnitForm = ({ powerUnit, companyId }: PowerUnitFormProps) => { /* eslint-disable-next-line @typescript-eslint/no-explicit-any */ year: convertToNumberIfValid(data.year, data.year as string) as any, /* eslint-disable-next-line @typescript-eslint/no-explicit-any */ - licensedGvw: convertToNumberIfValid(data.licensedGvw, data.licensedGvw as string) as any, + licensedGvw: convertToNumberIfValid( + data.licensedGvw, + data.licensedGvw as string, + ) as any, }, companyId, }); @@ -115,8 +126,12 @@ export const PowerUnitForm = ({ powerUnit, companyId }: PowerUnitFormProps) => { ...powerUnitToBeAdded, // need to explicitly convert form values to number here (since we can't use valueAsNumber prop) year: !isNaN(Number(data.year)) ? Number(data.year) : data.year, - licensedGvw: data.licensedGvw != null && data.licensedGvw !== "" && !isNaN(Number(data.licensedGvw)) ? - Number(data.licensedGvw) : data.licensedGvw + licensedGvw: + data.licensedGvw != null && + data.licensedGvw !== "" && + !isNaN(Number(data.licensedGvw)) + ? Number(data.licensedGvw) + : data.licensedGvw, }, companyId, }); @@ -126,7 +141,7 @@ export const PowerUnitForm = ({ powerUnit, companyId }: PowerUnitFormProps) => { showSnackbar: true, setShowSnackbar: () => true, message: "Power unit has been added successfully", - alertType: "success" + alertType: "success", }); navigate("../"); } @@ -165,9 +180,9 @@ export const PowerUnitForm = ({ powerUnit, companyId }: PowerUnitFormProps) => { feature={FEATURE} options={{ name: "make", - rules: { - required: { value: true, message: requiredMessage() }, - maxLength: 20 + rules: { + required: { value: true, message: requiredMessage() }, + maxLength: 20, }, label: "Make", width: formFieldStyle.width, @@ -184,7 +199,8 @@ export const PowerUnitForm = ({ powerUnit, companyId }: PowerUnitFormProps) => { maxLength: 4, validate: { isNumber: (v) => !isNaN(v) || invalidNumber(), - lessThan1950: v => parseInt(v) > 1950 || invalidYearMin(1950), + lessThan1950: (v) => + parseInt(v) > 1950 || invalidYearMin(1950), }, }, inputType: "number", @@ -214,9 +230,9 @@ export const PowerUnitForm = ({ powerUnit, companyId }: PowerUnitFormProps) => { feature={FEATURE} options={{ name: "plate", - rules: { - required: { value: true, message: requiredMessage() }, - maxLength: { value: 10, message: invalidPlateLength(10) } + rules: { + required: { value: true, message: requiredMessage() }, + maxLength: { value: 10, message: invalidPlateLength(10) }, }, label: "Plate", width: formFieldStyle.width, diff --git a/frontend/src/features/manageVehicles/components/form/TrailerForm.tsx b/frontend/src/features/manageVehicles/components/form/TrailerForm.tsx index da074d81d..7a67ed4ed 100644 --- a/frontend/src/features/manageVehicles/components/form/TrailerForm.tsx +++ b/frontend/src/features/manageVehicles/components/form/TrailerForm.tsx @@ -37,7 +37,7 @@ interface TrailerFormProps { * If valid and available, the form will be in an editable state. */ trailerId?: string; - + companyId: string; } diff --git a/frontend/src/features/manageVehicles/components/form/tests/PowerUnitForm.test.tsx b/frontend/src/features/manageVehicles/components/form/tests/PowerUnitForm.test.tsx index 45fd645e7..653a847fe 100644 --- a/frontend/src/features/manageVehicles/components/form/tests/PowerUnitForm.test.tsx +++ b/frontend/src/features/manageVehicles/components/form/tests/PowerUnitForm.test.tsx @@ -1,31 +1,31 @@ import { vi } from "vitest"; import { chooseOption, - clickSubmit, - countrySelect, - licensedGvwInput, - makeInput, - numericInputs, - plateInput, - powerUnitTypeCodeSelect, - provinceSelect, - replaceValueForInput, - selectOptionsAndButtons, + clickSubmit, + countrySelect, + licensedGvwInput, + makeInput, + numericInputs, + plateInput, + powerUnitTypeCodeSelect, + provinceSelect, + replaceValueForInput, + selectOptionsAndButtons, steerAxleTireSizeInput, - submitVehicleForm, - textInputs, - unitNumberInput, - vinErrorDisplay, - vinInput, + submitVehicleForm, + textInputs, + unitNumberInput, + vinErrorDisplay, + vinInput, yearInput, } from "./helpers/access"; -import { - closeMockServer, - defaultPowerUnitSubtypes, - listenToMockServer, - powerUnitDetails, - renderTestPowerUnitForm, +import { + closeMockServer, + defaultPowerUnitSubtypes, + listenToMockServer, + powerUnitDetails, + renderTestPowerUnitForm, resetMockServer, } from "./helpers/prepare"; import { assertSuccessfulSubmit } from "./helpers/assert"; @@ -144,7 +144,7 @@ describe("Power Unit Form Submission", () => { it("should successfully submit form without errors shown on ui", async () => { // Arrange const { user } = renderTestPowerUnitForm(); - + // Act await submitVehicleForm(user, "powerUnit", powerUnitDetails); diff --git a/frontend/src/features/manageVehicles/components/form/tests/TrailerForm.test.tsx b/frontend/src/features/manageVehicles/components/form/tests/TrailerForm.test.tsx index d69648797..5090afa66 100644 --- a/frontend/src/features/manageVehicles/components/form/tests/TrailerForm.test.tsx +++ b/frontend/src/features/manageVehicles/components/form/tests/TrailerForm.test.tsx @@ -1,27 +1,27 @@ import { vi } from "vitest"; import { chooseOption, - clickSubmit, - countrySelect, - emptyTrailerWidthInput, - makeInput, - numericInputs, - plateInput, - provinceSelect, - selectOptionsAndButtons, - submitVehicleForm, - textInputs, - trailerTypeCodeSelect, - unitNumberInput, - vinInput, + clickSubmit, + countrySelect, + emptyTrailerWidthInput, + makeInput, + numericInputs, + plateInput, + provinceSelect, + selectOptionsAndButtons, + submitVehicleForm, + textInputs, + trailerTypeCodeSelect, + unitNumberInput, + vinInput, yearInput, } from "./helpers/access"; -import { - closeMockServer, - defaultTrailerSubtypes, - listenToMockServer, - renderTestTrailerForm, - resetMockServer, +import { + closeMockServer, + defaultTrailerSubtypes, + listenToMockServer, + renderTestTrailerForm, + resetMockServer, trailerDetails, } from "./helpers/prepare"; import { assertSuccessfulSubmit } from "./helpers/assert"; @@ -96,7 +96,7 @@ describe("Trailer Form Submission", () => { it("should successfully submit form without errors shown on ui", async () => { // Arrange const { user } = renderTestTrailerForm(); - + // Act await submitVehicleForm(user, "trailer", trailerDetails); diff --git a/frontend/src/features/manageVehicles/components/form/tests/helpers/access.ts b/frontend/src/features/manageVehicles/components/form/tests/helpers/access.ts index 4152af00d..50c8fa077 100644 --- a/frontend/src/features/manageVehicles/components/form/tests/helpers/access.ts +++ b/frontend/src/features/manageVehicles/components/form/tests/helpers/access.ts @@ -3,7 +3,9 @@ import { UserEvent } from "@testing-library/user-event/dist/types/setup/setup"; import { VehicleTypesAsString } from "../../../../types/managevehicles"; export const clickSubmit = async (user: UserEvent) => { - const submitButton = await screen.findByRole("button", { name: /Add To Inventory/i }); + const submitButton = await screen.findByRole("button", { + name: /Add To Inventory/i, + }); await user.click(submitButton); }; @@ -87,9 +89,17 @@ export const vinErrorDisplay = async () => { return await screen.findByTestId("alert-vin"); }; -export const replaceValueForInput = async (user: UserEvent, input: HTMLElement, offset: number, newVal: string) => { +export const replaceValueForInput = async ( + user: UserEvent, + input: HTMLElement, + offset: number, + newVal: string, +) => { await user.click(input); - await user.pointer([{target: input, offset: 0, keys: '[MouseLeft>]'}, { offset }]); + await user.pointer([ + { target: input, offset: 0, keys: "[MouseLeft>]" }, + { offset }, + ]); await user.paste(newVal); }; @@ -97,7 +107,11 @@ export const submitErrorsDisplay = async () => { return await screen.findByTestId("alert", { exact: false }); }; -export const chooseOption = async (user: UserEvent, select: HTMLElement, optionText: string) => { +export const chooseOption = async ( + user: UserEvent, + select: HTMLElement, + optionText: string, +) => { await user.click(select); const option = await screen.findByText(optionText); await user.click(option); @@ -119,7 +133,11 @@ export interface PowerUnitDetail extends VehicleFormDetail { newTireSize: string; } -export const submitVehicleForm = async (user: UserEvent, vehicleType: VehicleTypesAsString, details: VehicleFormDetail) => { +export const submitVehicleForm = async ( + user: UserEvent, + vehicleType: VehicleTypesAsString, + details: VehicleFormDetail, +) => { const unitNumber = await unitNumberInput(); const make = await makeInput(); const year = await yearInput(); @@ -138,8 +156,18 @@ export const submitVehicleForm = async (user: UserEvent, vehicleType: VehicleTyp const licensedGvw = await licensedGvwInput(); const steerAxleTireSize = await steerAxleTireSizeInput(); const subtype = await powerUnitTypeCodeSelect(); - await replaceValueForInput(user, licensedGvw, 1, `${powerUnitDetails.newGvw}`); - await replaceValueForInput(user, steerAxleTireSize, 0, powerUnitDetails.newTireSize); + await replaceValueForInput( + user, + licensedGvw, + 1, + `${powerUnitDetails.newGvw}`, + ); + await replaceValueForInput( + user, + steerAxleTireSize, + 0, + powerUnitDetails.newTireSize, + ); await chooseOption(user, subtype, details.newSubtype); } else { const subtype = await trailerTypeCodeSelect(); diff --git a/frontend/src/features/manageVehicles/components/form/tests/helpers/assert.ts b/frontend/src/features/manageVehicles/components/form/tests/helpers/assert.ts index dadfbca68..78ff45531 100644 --- a/frontend/src/features/manageVehicles/components/form/tests/helpers/assert.ts +++ b/frontend/src/features/manageVehicles/components/form/tests/helpers/assert.ts @@ -1,22 +1,25 @@ import { VehicleTypesAsString } from "../../../../types/managevehicles"; -import { +import { PowerUnitDetail, VehicleFormDetail, - countrySelect, - licensedGvwInput, - makeInput, - plateInput, - powerUnitTypeCodeSelect, - provinceSelect, - steerAxleTireSizeInput, - submitErrorsDisplay, - trailerTypeCodeSelect, - unitNumberInput, - vinInput, + countrySelect, + licensedGvwInput, + makeInput, + plateInput, + powerUnitTypeCodeSelect, + provinceSelect, + steerAxleTireSizeInput, + submitErrorsDisplay, + trailerTypeCodeSelect, + unitNumberInput, + vinInput, yearInput, } from "./access"; -export const assertSuccessfulSubmit = async (vehicleType: VehicleTypesAsString, vehicleDetails: VehicleFormDetail) => { +export const assertSuccessfulSubmit = async ( + vehicleType: VehicleTypesAsString, + vehicleDetails: VehicleFormDetail, +) => { const unitNumber = await unitNumberInput(); const make = await makeInput(); const year = await yearInput(); diff --git a/frontend/src/features/manageVehicles/components/form/tests/helpers/prepare.tsx b/frontend/src/features/manageVehicles/components/form/tests/helpers/prepare.tsx index 5dc090052..5181067a6 100644 --- a/frontend/src/features/manageVehicles/components/form/tests/helpers/prepare.tsx +++ b/frontend/src/features/manageVehicles/components/form/tests/helpers/prepare.tsx @@ -29,44 +29,62 @@ export const defaultTrailerSubtypes = [ const server = setupServer( // Mock getting power unit types rest.get(VEHICLES_API.POWER_UNIT_TYPES, async (_, res, ctx) => { - return res(ctx.json([ - ...defaultPowerUnitSubtypes, - ])); + return res(ctx.json([...defaultPowerUnitSubtypes])); }), // Mock getting trailer types rest.get(VEHICLES_API.TRAILER_TYPES, async (_, res, ctx) => { - return res(ctx.json([ - ...defaultTrailerSubtypes, - ])); + return res(ctx.json([...defaultTrailerSubtypes])); }), // Mock creating power unit vehicle - rest.post(`${VEHICLES_URL}/companies/:companyId/vehicles/powerUnits`, async (req, res, ctx) => { - const reqBody = await req.json(); - return res(ctx.status(201), ctx.json({ - ...reqBody, - })); - }), + rest.post( + `${VEHICLES_URL}/companies/:companyId/vehicles/powerUnits`, + async (req, res, ctx) => { + const reqBody = await req.json(); + return res( + ctx.status(201), + ctx.json({ + ...reqBody, + }), + ); + }, + ), // Mock updating power unit vehicle - rest.put(`${VEHICLES_URL}/companies/:companyId/vehicles/powerUnits/:powerUnitId`, async (req, res, ctx) => { - const reqBody = await req.json(); - return res(ctx.json({ - ...reqBody, - })); - }), + rest.put( + `${VEHICLES_URL}/companies/:companyId/vehicles/powerUnits/:powerUnitId`, + async (req, res, ctx) => { + const reqBody = await req.json(); + return res( + ctx.json({ + ...reqBody, + }), + ); + }, + ), // Mock creating trailer vehicle - rest.post(`${VEHICLES_URL}/companies/:companyId/vehicles/trailers`, async (req, res, ctx) => { - const reqBody = await req.json(); - return res(ctx.status(201), ctx.json({ - ...reqBody, - })); - }), + rest.post( + `${VEHICLES_URL}/companies/:companyId/vehicles/trailers`, + async (req, res, ctx) => { + const reqBody = await req.json(); + return res( + ctx.status(201), + ctx.json({ + ...reqBody, + }), + ); + }, + ), // Mock updating trailer vehicle - rest.put(`${VEHICLES_URL}/companies/:companyId/vehicles/trailers/:trailerId`, async (req, res, ctx) => { - const reqBody = await req.json(); - return res(ctx.json({ - ...reqBody, - })); - }), + rest.put( + `${VEHICLES_URL}/companies/:companyId/vehicles/trailers/:trailerId`, + async (req, res, ctx) => { + const reqBody = await req.json(); + return res( + ctx.json({ + ...reqBody, + }), + ); + }, + ), ); export const listenToMockServer = () => { @@ -84,7 +102,7 @@ export const closeMockServer = () => { export const renderTestPowerUnitForm = (powerUnit?: PowerUnit) => { const user = userEvent.setup(); const component = renderWithClient( - + , ); return { user, component }; @@ -93,7 +111,7 @@ export const renderTestPowerUnitForm = (powerUnit?: PowerUnit) => { export const renderTestTrailerForm = (trailer?: Trailer) => { const user = userEvent.setup(); const component = renderWithClient( - + , ); return { user, component }; diff --git a/frontend/src/features/manageVehicles/components/list/List.tsx b/frontend/src/features/manageVehicles/components/list/List.tsx index f9bd5a82e..525942ce5 100644 --- a/frontend/src/features/manageVehicles/components/list/List.tsx +++ b/frontend/src/features/manageVehicles/components/list/List.tsx @@ -43,7 +43,7 @@ import { NoRecordsFound } from "../../../../common/components/table/NoRecordsFou * @returns An array of column headers/accessor keys ofr Material React Table */ const getColumns = ( - vehicleType: VehicleTypesAsString + vehicleType: VehicleTypesAsString, ): MRT_ColumnDef[] => { if (vehicleType === "powerUnit") { return PowerUnitColumnDefinition; @@ -82,7 +82,7 @@ export const List = memo( // Column definitions for the table const columns = useMemo[]>( () => getColumns(vehicleType), - [] + [], ); const snackBar = useContext(SnackBarContext); @@ -213,14 +213,14 @@ export const List = memo( if (vehicleType === "powerUnit") { navigate( `/${MANAGE_VEHICLES}/power-units/${row.getValue( - "powerUnitId" - )}` + "powerUnitId", + )}`, ); } else if (vehicleType === "trailer") { navigate( `/${MANAGE_VEHICLES}/trailers/${row.getValue( - "trailerId" - )}` + "trailerId", + )}`, ); } }} @@ -254,7 +254,7 @@ export const List = memo( )} ), - [] + [], )} // Render a custom options Bar (inclues search and trash) renderTopToolbar={useCallback( @@ -262,11 +262,14 @@ export const List = memo( {DoesUserHaveRoleWithContext(ROLES.WRITE_VEHICLE) && ( - + )} ), - [hasNoRowsSelected] + [hasNoRowsSelected], )} /* * @@ -343,7 +346,7 @@ export const List = memo( /> ); - } + }, ); List.displayName = "List"; diff --git a/frontend/src/features/permits/apiManager/permitsAPI.ts b/frontend/src/features/permits/apiManager/permitsAPI.ts index ab561804c..7b361066a 100644 --- a/frontend/src/features/permits/apiManager/permitsAPI.ts +++ b/frontend/src/features/permits/apiManager/permitsAPI.ts @@ -6,11 +6,11 @@ import { PaginatedResponse } from "../../../common/types/common"; import { PERMIT_STATUSES } from "../types/PermitStatus"; import { PermitHistory } from "../types/PermitHistory"; import { getPermitTypeName } from "../types/PermitType"; -import { - CompleteTransactionRequestData, - CompleteTransactionResponseData, - StartTransactionRequestData, - StartTransactionResponseData, +import { + CompleteTransactionRequestData, + CompleteTransactionResponseData, + StartTransactionRequestData, + StartTransactionResponseData, } from "../types/payment"; import { @@ -39,7 +39,11 @@ import { PAYMENT_API, PERMITS_API, } from "./endpoints/endpoints"; -import { RevokePermitRequestData, VoidPermitRequestData, VoidPermitResponseData } from "../pages/Void/types/VoidPermit"; +import { + RevokePermitRequestData, + VoidPermitRequestData, + VoidPermitResponseData, +} from "../pages/Void/types/VoidPermit"; /** * Submits a new term oversize application. @@ -52,7 +56,7 @@ export const submitTermOversize = async (termOversizePermit: Application) => { replaceEmptyValuesWithNull({ // must convert application to ApplicationRequestData (dayjs fields to strings) ...mapApplicationToApplicationRequestData(termOversizePermit), - }) + }), ); }; @@ -64,14 +68,14 @@ export const submitTermOversize = async (termOversizePermit: Application) => { */ export const updateTermOversize = async ( termOversizePermit: Application, - applicationNumber: string + applicationNumber: string, ) => { return await httpPUTRequest( `${PERMITS_API.SUBMIT_TERM_OVERSIZE_PERMIT}/${applicationNumber}`, replaceEmptyValuesWithNull({ // must convert application to ApplicationRequestData (dayjs fields to strings) ...mapApplicationToApplicationRequestData(termOversizePermit), - }) + }), ); }; @@ -101,25 +105,25 @@ export const getApplicationsInProgress = async (): Promise< permitType: getPermitTypeName(application.permitType) as string, createdDateTime: toLocal( application.createdDateTime, - DATE_FORMATS.DATETIME_LONG_TZ + DATE_FORMATS.DATETIME_LONG_TZ, ), updatedDateTime: toLocal( application.updatedDateTime, - DATE_FORMATS.DATETIME_LONG_TZ + DATE_FORMATS.DATETIME_LONG_TZ, ), permitData: { ...application.permitData, startDate: toLocal( application.permitData.startDate, - DATE_FORMATS.DATEONLY_SHORT_NAME + DATE_FORMATS.DATEONLY_SHORT_NAME, ), expiryDate: toLocal( application.permitData.startDate, - DATE_FORMATS.DATEONLY_SHORT_NAME + DATE_FORMATS.DATEONLY_SHORT_NAME, ), }, } as PermitApplicationInProgress; - }) + }), ); return applications; }; @@ -130,7 +134,7 @@ export const getApplicationsInProgress = async (): Promise< * @returns ApplicationResponse data as response, or null if fetch failed */ export const getApplicationByPermitId = async ( - permitId?: string + permitId?: string, ): Promise => { try { const companyId = getCompanyIdFromSession(); @@ -152,10 +156,13 @@ export const getApplicationByPermitId = async ( * @returns A Promise with the API response. */ export const deleteApplications = async (applicationIds: Array) => { - const requestBody = { applicationIds, applicationStatus: PERMIT_STATUSES.CANCELLED }; + const requestBody = { + applicationIds, + applicationStatus: PERMIT_STATUSES.CANCELLED, + }; return await httpPOSTRequest( `${APPLICATION_UPDATE_STATUS_API}`, - replaceEmptyValuesWithNull(requestBody) + replaceEmptyValuesWithNull(requestBody), ); }; @@ -227,10 +234,13 @@ export const downloadReceiptPdf = async (permitId: string) => { * @returns {Promise} - A Promise that resolves to the submitted transaction with URL. */ export const startTransaction = async ( - requestData: StartTransactionRequestData + requestData: StartTransactionRequestData, ): Promise => { try { - const response = await httpPOSTRequest(PAYMENT_API, replaceEmptyValuesWithNull(requestData)); + const response = await httpPOSTRequest( + PAYMENT_API, + replaceEmptyValuesWithNull(requestData), + ); if (response.status !== 201) { return null; } @@ -249,20 +259,17 @@ export const startTransaction = async ( * @returns Promise that resolves to a successful transaction. */ export const completeTransaction = async (transactionData: { - transactionId: string, - transactionQueryString: string, - transactionDetails: CompleteTransactionRequestData + transactionId: string; + transactionQueryString: string; + transactionDetails: CompleteTransactionRequestData; }): Promise => { try { - const { - transactionId, - transactionDetails, - transactionQueryString, - } = transactionData; - + const { transactionId, transactionDetails, transactionQueryString } = + transactionData; + const response = await httpPUTRequest( `${PAYMENT_API}/${transactionId}/payment-gateway?queryString=${transactionQueryString}`, - transactionDetails + transactionDetails, ); if (response.status !== 200) { return null; @@ -285,13 +292,16 @@ export const issuePermits = async ( try { const companyId = getCompanyIdFromSession(); const response = await httpPOSTRequest( - PERMITS_API.ISSUE_PERMIT, - replaceEmptyValuesWithNull({ - applicationIds: [...ids], - companyId: applyWhenNotNullable((companyId) => Number(companyId), companyId), - }) + PERMITS_API.ISSUE_PERMIT, + replaceEmptyValuesWithNull({ + applicationIds: [...ids], + companyId: applyWhenNotNullable( + (companyId) => Number(companyId), + companyId, + ), + }), ); - + if (response.status !== 201) { return { success: [], @@ -336,7 +346,7 @@ export const getPermit = async (permitId?: string): Promise => { * @returns Permit application information, if any */ export const getCurrentAmendmentApplication = async ( - originalId?: string + originalId?: string, ): Promise => { if (!originalId) return null; const companyId = getDefaultRequiredVal("", getCompanyIdFromSession()); @@ -363,9 +373,9 @@ export const getCurrentAmendmentApplication = async ( * @param expired If set to true, expired permits will be retrieved. * @returns A list of permits. */ -export const getPermits = async ({ - expired = false, -} = {}): Promise => { +export const getPermits = async ({ expired = false } = {}): Promise< + Permit[] +> => { const companyId = getDefaultRequiredVal("", getCompanyIdFromSession()); let permitsURL = `${VEHICLES_URL}/permits/user`; const queryParams = []; @@ -382,7 +392,7 @@ export const getPermits = async ({ .then((response) => { const paginatedResponseObject = getDefaultRequiredVal( {}, - response.data + response.data, ) as PaginatedResponse; return paginatedResponseObject.items; }) @@ -392,25 +402,25 @@ export const getPermits = async ({ ...permit, createdDateTime: toLocal( permit.createdDateTime, - DATE_FORMATS.DATETIME_LONG_TZ + DATE_FORMATS.DATETIME_LONG_TZ, ), updatedDateTime: toLocal( permit.updatedDateTime, - DATE_FORMATS.DATETIME_LONG_TZ + DATE_FORMATS.DATETIME_LONG_TZ, ), permitData: { ...permit.permitData, startDate: toLocal( permit.permitData.startDate, - DATE_FORMATS.DATEONLY_SHORT_NAME + DATE_FORMATS.DATEONLY_SHORT_NAME, ), expiryDate: toLocal( permit.permitData.expiryDate, - DATE_FORMATS.DATEONLY_SHORT_NAME + DATE_FORMATS.DATEONLY_SHORT_NAME, ), }, } as Permit; - }) + }), ); return permits; }; @@ -418,9 +428,9 @@ export const getPermits = async ({ export const getPermitHistory = async (originalPermitId?: string) => { try { if (!originalPermitId) return []; - + const response = await httpGETRequest( - `${VEHICLES_URL}/permits/history?originalId=${originalPermitId}` + `${VEHICLES_URL}/permits/history?originalId=${originalPermitId}`, ); if (response.status === 200) { @@ -439,14 +449,14 @@ export const getPermitHistory = async (originalPermitId?: string) => { * @returns Response data containing successfully voided/revoked permit ids, as well as failed ones. */ export const voidPermit = async (voidPermitParams: { - permitId: string, - voidData: VoidPermitRequestData | RevokePermitRequestData + permitId: string; + voidData: VoidPermitRequestData | RevokePermitRequestData; }) => { const { permitId, voidData } = voidPermitParams; try { const response = await httpPOSTRequest( `${PERMITS_API.BASE}/${permitId}/void`, - replaceEmptyValuesWithNull(voidData) + replaceEmptyValuesWithNull(voidData), ); if (response.status === 201) { @@ -475,7 +485,7 @@ export const amendPermit = async (permit: Permit) => { PERMITS_API.SUBMIT_TERM_OVERSIZE_PERMIT, replaceEmptyValuesWithNull({ ...permit, - }) + }), ); }; diff --git a/frontend/src/features/permits/components/dashboard/ApplicationDashboard.tsx b/frontend/src/features/permits/components/dashboard/ApplicationDashboard.tsx index e8384559a..45dde0a2c 100644 --- a/frontend/src/features/permits/components/dashboard/ApplicationDashboard.tsx +++ b/frontend/src/features/permits/components/dashboard/ApplicationDashboard.tsx @@ -21,7 +21,8 @@ export const APPLICATION_STEPS = { Pay: "Pay", } as const; -export type ApplicationStep = typeof APPLICATION_STEPS[keyof typeof APPLICATION_STEPS]; +export type ApplicationStep = + (typeof APPLICATION_STEPS)[keyof typeof APPLICATION_STEPS]; const displayHeaderText = (stepKey: ApplicationStep) => { switch (stepKey) { @@ -39,19 +40,13 @@ export const ApplicationDashboard = () => { const { applicationNumber } = useParams(); // Get application number from route, if there is one (for edit applications) // Query for the application data whenever this page is rendered - const { - query: applicationDataQuery, - applicationData, - setApplicationData + const { + query: applicationDataQuery, + applicationData, + setApplicationData, } = useApplicationDetailsQuery(applicationNumber); - const { - currentStepIndex, - step, - back, - next, - goTo, - } = useMultiStepForm([ + const { currentStepIndex, step, back, next, goTo } = useMultiStepForm([ , , , diff --git a/frontend/src/features/permits/components/dashboard/tests/integration/ApplicationDashboard.test.tsx b/frontend/src/features/permits/components/dashboard/tests/integration/ApplicationDashboard.test.tsx index a0e9a9f42..dc7935579 100644 --- a/frontend/src/features/permits/components/dashboard/tests/integration/ApplicationDashboard.test.tsx +++ b/frontend/src/features/permits/components/dashboard/tests/integration/ApplicationDashboard.test.tsx @@ -1,28 +1,32 @@ import { waitFor } from "@testing-library/react"; import { formatPhoneNumber } from "../../../../../../common/components/form/subFormComponents/PhoneNumberInput"; -import { +import { findPowerUnit, - getAllPowerUnitTypes, - getAllPowerUnits, - getAllTrailers, + getAllPowerUnitTypes, + getAllPowerUnits, + getAllTrailers, resetVehicleSource, } from "./fixtures/getVehicleInfo"; import { getEmptyUserDetails } from "./fixtures/getUserDetails"; import { resetApplicationSource } from "./fixtures/getActiveApplication"; -import { DATE_FORMATS, dayjsToLocalStr, utcToLocalDayjs } from "../../../../../../common/helpers/formatDate"; -import { - closeMockServer, - companyInfo, - defaultUserDetails, - getVehicleDetails, - listenToMockServer, - newApplicationNumber, - renderTestComponent, +import { + DATE_FORMATS, + dayjsToLocalStr, + utcToLocalDayjs, +} from "../../../../../../common/helpers/formatDate"; +import { + closeMockServer, + companyInfo, + defaultUserDetails, + getVehicleDetails, + listenToMockServer, + newApplicationNumber, + renderTestComponent, resetMockServer, } from "./helpers/prepare"; import { getDefaultRequiredVal } from "../../../../../../common/helpers/util"; -import { +import { applicationCreatedDateDisplay, applicationNumberDisplay, applicationUpdatedDateDisplay, @@ -42,25 +46,28 @@ import { errMsgForVehicleYear, fillVehicleInfo, getSavedApplication, - inputWithValue, - makeInput, - openVehicleSelect, - openVehicleSubtypeSelect, - plateInput, - replaceValueForInput, - saveApplication, - sendPermitToEmailMsg, - unitNumberOrPlateSelect, + inputWithValue, + makeInput, + openVehicleSelect, + openVehicleSubtypeSelect, + plateInput, + replaceValueForInput, + saveApplication, + sendPermitToEmailMsg, + unitNumberOrPlateSelect, vehicleCountrySelect, - vehicleOptions, - vehicleProvinceSelect, - vehicleSelect, + vehicleOptions, + vehicleProvinceSelect, + vehicleSelect, vehicleSubtypeSelect, vehicleTypeSelect, vehicleYearInput, vinInput, } from "./helpers/access"; -import { formatCountry, formatProvince } from "../../../../../../common/helpers/formatCountryProvince"; +import { + formatCountry, + formatProvince, +} from "../../../../../../common/helpers/formatCountryProvince"; import { assertVehicleSubtypeOptions } from "./helpers/assert"; const { @@ -129,9 +136,19 @@ describe("Application Contact Details", () => { // Act - change various input field values and save application const newFirstName = "Myfirstname"; - await replaceValueForInput(user, firstNameInput, firstName.length, newFirstName); + await replaceValueForInput( + user, + firstNameInput, + firstName.length, + newFirstName, + ); const newLastName = "Mylastname"; - await replaceValueForInput(user, lastNameInput, lastName.length, newLastName); + await replaceValueForInput( + user, + lastNameInput, + lastName.length, + newLastName, + ); const newPhone1 = formatPhoneNumber("778-123-4567"); await replaceValueForInput(user, phone1Input, phone1.length, newPhone1); const newPhone2 = formatPhoneNumber("778-123-4568"); @@ -184,7 +201,9 @@ describe("Application Header", () => { newApplicationNumber, applicationData?.applicationNumber, ); - expect(await applicationNumberDisplay()).toHaveTextContent(expectedApplicationNumber); + expect(await applicationNumberDisplay()).toHaveTextContent( + expectedApplicationNumber, + ); }); it("should display proper created datetime after creating application", async () => { @@ -201,10 +220,12 @@ describe("Application Header", () => { applicationData?.createdDateTime, ); const formattedDt = dayjsToLocalStr( - utcToLocalDayjs(expectedCreatedDt), - DATE_FORMATS.LONG + utcToLocalDayjs(expectedCreatedDt), + DATE_FORMATS.LONG, + ); + expect(await applicationCreatedDateDisplay()).toHaveTextContent( + formattedDt, ); - expect(await applicationCreatedDateDisplay()).toHaveTextContent(formattedDt); }); it("should display proper updated datetime after updating application", async () => { @@ -221,10 +242,12 @@ describe("Application Header", () => { applicationData?.updatedDateTime, ); const formattedDt = dayjsToLocalStr( - utcToLocalDayjs(expectedUpdatedDt), - DATE_FORMATS.LONG + utcToLocalDayjs(expectedUpdatedDt), + DATE_FORMATS.LONG, + ); + expect(await applicationUpdatedDateDisplay()).toHaveTextContent( + formattedDt, ); - expect(await applicationUpdatedDateDisplay()).toHaveTextContent(formattedDt); }); it("should display company information", async () => { @@ -279,7 +302,9 @@ describe("Vehicle Details", () => { expect(await errMsgForPlate()).toHaveTextContent(requiredMsg); expect(await errMsgForMake()).toHaveTextContent(requiredMsg); const vehicleYearErrDisplay = await errMsgForVehicleYear(); - expect([requiredMsg, emptyYearMsg]).toContain(vehicleYearErrDisplay.textContent); + expect([requiredMsg, emptyYearMsg]).toContain( + vehicleYearErrDisplay.textContent, + ); expect(await errMsgForVehicleCountry()).toHaveTextContent(requiredMsg); expect(await errMsgForVehicleSubtype()).toHaveTextContent(requiredMsg); }); @@ -287,29 +312,39 @@ describe("Vehicle Details", () => { it("should add new vehicle to inventory if user chooses to", async () => { // Arrange const { user } = renderTestComponent(defaultUserDetails); - const { formDetails, additionalInfo: { originalVehicles } } = getVehicleDetails("create", true); - + const { + formDetails, + additionalInfo: { originalVehicles }, + } = getVehicleDetails("create", true); + // Act await fillVehicleInfo(user, formDetails); // Assert await waitFor(() => { - expect(getAllPowerUnits().length).toBeGreaterThan(originalVehicles.length); + expect(getAllPowerUnits().length).toBeGreaterThan( + originalVehicles.length, + ); }); }); it("should not add new vehicle to inventory if user chooses not to", async () => { // Arrange const { user } = renderTestComponent(defaultUserDetails); - const { formDetails, additionalInfo: { originalVehicles } } = getVehicleDetails("create", false); - + const { + formDetails, + additionalInfo: { originalVehicles }, + } = getVehicleDetails("create", false); + // Act await fillVehicleInfo(user, formDetails); // Assert await waitFor(() => { - expect(getAllPowerUnits().length).toBeGreaterThan(originalVehicles.length); - }).catch(err => { + expect(getAllPowerUnits().length).toBeGreaterThan( + originalVehicles.length, + ); + }).catch((err) => { expect(err).not.toBeUndefined(); }); }); @@ -317,14 +352,14 @@ describe("Vehicle Details", () => { it("should update vehicle in inventory if user chooses to", async () => { // Arrange const { user } = renderTestComponent(defaultUserDetails); - const { - formDetails, - additionalInfo: { + const { + formDetails, + additionalInfo: { updatedProvinceAbbr, - vehicleUsed: { vin } - } + vehicleUsed: { vin }, + }, } = getVehicleDetails("update", true); - + // Act await fillVehicleInfo(user, formDetails); @@ -338,14 +373,14 @@ describe("Vehicle Details", () => { it("should not update vehicle in inventory if user chooses not to", async () => { // Arrange const { user } = renderTestComponent(defaultUserDetails); - const { - formDetails, - additionalInfo: { + const { + formDetails, + additionalInfo: { updatedProvinceAbbr, - vehicleUsed: { vin } - } + vehicleUsed: { vin }, + }, } = getVehicleDetails("update", false); - + // Act await fillVehicleInfo(user, formDetails); @@ -353,7 +388,7 @@ describe("Vehicle Details", () => { await waitFor(() => { const updatedVehicle = findPowerUnit(vin); expect(updatedVehicle?.provinceCode).toBe(updatedProvinceAbbr); - }).catch(err => { + }).catch((err) => { expect(err).not.toBeUndefined(); }); }); @@ -408,7 +443,10 @@ describe("Vehicle Details", () => { it("should filter vehicle options by typing in unit number", async () => { // Arrange const { user } = renderTestComponent(defaultUserDetails); - const unitNumber = getDefaultRequiredVal("", getAllTrailers()[0].unitNumber); + const unitNumber = getDefaultRequiredVal( + "", + getAllTrailers()[0].unitNumber, + ); const unitNumberOrPlate = await unitNumberOrPlateSelect(); await chooseOption(user, unitNumberOrPlate, "Unit Number"); @@ -431,8 +469,9 @@ describe("Vehicle Details", () => { const unitNumber = getDefaultRequiredVal("", vehicle.unitNumber); const vehicleSubtype = getDefaultRequiredVal( "", - getAllPowerUnitTypes() - .find(subtype => subtype.typeCode === vehicle.powerUnitTypeCode)?.type + getAllPowerUnitTypes().find( + (subtype) => subtype.typeCode === vehicle.powerUnitTypeCode, + )?.type, ); // Act @@ -455,7 +494,9 @@ describe("Vehicle Details", () => { expect(make).toHaveValue(vehicle.make); expect(year).toHaveValue(vehicle.year); expect(country).toHaveTextContent(formatCountry(vehicle.countryCode)); - expect(province).toHaveTextContent(formatProvince(vehicle.countryCode, vehicle.provinceCode)); + expect(province).toHaveTextContent( + formatProvince(vehicle.countryCode, vehicle.provinceCode), + ); expect(type).toHaveTextContent("Power Unit"); expect(subtype).toHaveTextContent(vehicleSubtype); }); diff --git a/frontend/src/features/permits/components/dashboard/tests/integration/fixtures/getActiveApplication.ts b/frontend/src/features/permits/components/dashboard/tests/integration/fixtures/getActiveApplication.ts index 36cf2a254..bc9d0cc37 100644 --- a/frontend/src/features/permits/components/dashboard/tests/integration/fixtures/getActiveApplication.ts +++ b/frontend/src/features/permits/components/dashboard/tests/integration/fixtures/getActiveApplication.ts @@ -2,7 +2,11 @@ import { factory, nullable, primaryKey } from "@mswjs/data"; import dayjs from "dayjs"; import { ApplicationRequestData } from "../../../../../types/application"; -import { DATE_FORMATS, dayjsToLocalStr, now } from "../../../../../../../common/helpers/formatDate"; +import { + DATE_FORMATS, + dayjsToLocalStr, + now, +} from "../../../../../../../common/helpers/formatDate"; import { getDefaultUserDetails } from "./getUserDetails"; import { getDefaultPowerUnits } from "./getVehicleInfo"; import { getDefaultCompanyInfo } from "./getCompanyInfo"; @@ -62,22 +66,25 @@ const activeApplicationSource = factory({ }, feeSummary: nullable(String), }, - } + }, }); export const createApplication = (application: ApplicationRequestData) => { - return activeApplicationSource.application.create({...application}); + return activeApplicationSource.application.create({ ...application }); }; -export const updateApplication = (application: ApplicationRequestData, applicationNumber: string) => { +export const updateApplication = ( + application: ApplicationRequestData, + applicationNumber: string, +) => { return activeApplicationSource.application.update({ where: { applicationNumber: { - equals: applicationNumber - } + equals: applicationNumber, + }, }, data: { - ...application - } + ...application, + }, }); }; export const getApplication = () => { @@ -89,9 +96,9 @@ export const resetApplicationSource = () => { activeApplicationSource.application.deleteMany({ where: { applicationNumber: { - contains: "" - } - } + contains: "", + }, + }, }); }; @@ -124,7 +131,7 @@ export const getDefaultApplication = () => { unitNumber: vehicle.unitNumber, }; const commodities = [ - TROS_COMMODITIES[0], + TROS_COMMODITIES[0], TROS_COMMODITIES[1], { ...TROS_COMMODITIES[2], checked: true }, ]; diff --git a/frontend/src/features/permits/components/dashboard/tests/integration/fixtures/getVehicleInfo.ts b/frontend/src/features/permits/components/dashboard/tests/integration/fixtures/getVehicleInfo.ts index fd280a0fd..e12d60d9b 100644 --- a/frontend/src/features/permits/components/dashboard/tests/integration/fixtures/getVehicleInfo.ts +++ b/frontend/src/features/permits/components/dashboard/tests/integration/fixtures/getVehicleInfo.ts @@ -1,6 +1,12 @@ import { factory, nullable, primaryKey } from "@mswjs/data"; -import { PowerUnit, Trailer } from "../../../../../../manageVehicles/types/managevehicles"; -import { TROS_INELIGIBLE_POWERUNITS, TROS_INELIGIBLE_TRAILERS } from "../../../../../constants/termOversizeConstants"; +import { + PowerUnit, + Trailer, +} from "../../../../../../manageVehicles/types/managevehicles"; +import { + TROS_INELIGIBLE_POWERUNITS, + TROS_INELIGIBLE_TRAILERS, +} from "../../../../../constants/termOversizeConstants"; let powerUnitId = 1; let trailerId = 1; @@ -51,7 +57,7 @@ const vehicleSourceDef = factory({ }, }); -export const getDefaultPowerUnits = () => ([ +export const getDefaultPowerUnits = () => [ { companyId: 74, unitNumber: "61", @@ -67,9 +73,9 @@ export const getDefaultPowerUnits = () => ([ countryCode: "CA", powerUnitTypeCode: "PUTYPEB", }, -]); +]; -export const getDefaultTrailers = () => ([ +export const getDefaultTrailers = () => [ { companyId: 74, unitNumber: "3", @@ -84,49 +90,49 @@ export const getDefaultTrailers = () => ([ countryCode: "US", trailerTypeCode: "TRAILTC", }, -]); +]; -export const getDefaultPowerUnitTypes = () => ([ +export const getDefaultPowerUnitTypes = () => [ { typeCode: "PUTYPEA", type: "Power Unit Type A", - description: "Power Unit Type A." + description: "Power Unit Type A.", }, { typeCode: "PUTYPEB", type: "Power Unit Type B", - description: "Power Unit Type B." + description: "Power Unit Type B.", }, { typeCode: "PUTYPEC", type: "Power Unit Type C", - description: "Power Unit Type C." + description: "Power Unit Type C.", }, - {...TROS_INELIGIBLE_POWERUNITS[0]}, -]); + { ...TROS_INELIGIBLE_POWERUNITS[0] }, +]; -export const getDefaultTrailerTypes = () => ([ +export const getDefaultTrailerTypes = () => [ { typeCode: "TRAILTA", type: "Trailer Type A", - description: "Trailer Type A." + description: "Trailer Type A.", }, { typeCode: "TRAILTB", type: "Trailer Type B", - description: "Trailer Type B." + description: "Trailer Type B.", }, { typeCode: "TRAILTC", type: "Trailer Type C", - description: "Trailer Type C." + description: "Trailer Type C.", }, - {...TROS_INELIGIBLE_TRAILERS[0]}, -]); + { ...TROS_INELIGIBLE_TRAILERS[0] }, +]; export const createPowerUnit = (powerUnit: PowerUnit) => { try { - return vehicleSourceDef.powerUnit.create({...powerUnit}); + return vehicleSourceDef.powerUnit.create({ ...powerUnit }); } catch (e) { console.error(e); } @@ -136,12 +142,12 @@ export const updatePowerUnit = (powerUnitId: string, powerUnit: PowerUnit) => { return vehicleSourceDef.powerUnit.update({ where: { powerUnitId: { - equals: powerUnitId - } + equals: powerUnitId, + }, }, data: { ...powerUnit, - } + }, }); } catch (e) { console.error(e); @@ -152,13 +158,13 @@ export const findPowerUnit = (vin: string) => { where: { vin: { equals: vin, - } - } + }, + }, }); }; export const createTrailer = (trailer: Trailer) => { try { - return vehicleSourceDef.trailer.create({...trailer}); + return vehicleSourceDef.trailer.create({ ...trailer }); } catch (e) { console.error(e); } @@ -168,12 +174,12 @@ export const updateTrailer = (trailerId: string, trailer: Trailer) => { return vehicleSourceDef.trailer.update({ where: { trailerId: { - equals: trailerId - } + equals: trailerId, + }, }, data: { ...trailer, - } + }, }); } catch (e) { console.error(e); @@ -184,8 +190,8 @@ export const findTrailer = (vin: string) => { where: { vin: { equals: vin, - } - } + }, + }, }); }; @@ -206,7 +212,8 @@ const initVehicleSource = () => { export const getAllPowerUnits = () => vehicleSourceDef.powerUnit.getAll(); export const getAllTrailers = () => vehicleSourceDef.trailer.getAll(); -export const getAllPowerUnitTypes = () => vehicleSourceDef.powerUnitType.getAll(); +export const getAllPowerUnitTypes = () => + vehicleSourceDef.powerUnitType.getAll(); export const getAllTrailerTypes = () => vehicleSourceDef.trailerType.getAll(); export const resetVehicleSource = () => { @@ -215,30 +222,30 @@ export const resetVehicleSource = () => { vehicleSourceDef.powerUnit.deleteMany({ where: { powerUnitId: { - contains: "" - } - } + contains: "", + }, + }, }); vehicleSourceDef.trailer.deleteMany({ where: { trailerId: { - contains: "" - } - } + contains: "", + }, + }, }); vehicleSourceDef.powerUnitType.deleteMany({ where: { typeCode: { - contains: "" - } - } + contains: "", + }, + }, }); vehicleSourceDef.trailerType.deleteMany({ where: { typeCode: { - contains: "" - } - } + contains: "", + }, + }, }); initVehicleSource(); }; diff --git a/frontend/src/features/permits/components/dashboard/tests/integration/helpers/access.ts b/frontend/src/features/permits/components/dashboard/tests/integration/helpers/access.ts index f63de5bc6..613dcc70e 100644 --- a/frontend/src/features/permits/components/dashboard/tests/integration/helpers/access.ts +++ b/frontend/src/features/permits/components/dashboard/tests/integration/helpers/access.ts @@ -12,13 +12,25 @@ export const sendPermitToEmailMsg = async () => { return await screen.findByText(/The permit will be sent to the email/i); }; -export const replaceValueForInput = async (user: UserEvent, input: HTMLElement, offset: number, newVal: string) => { +export const replaceValueForInput = async ( + user: UserEvent, + input: HTMLElement, + offset: number, + newVal: string, +) => { await user.click(input); - await user.pointer([{target: input, offset: 0, keys: '[MouseLeft>]'}, { offset }]); + await user.pointer([ + { target: input, offset: 0, keys: "[MouseLeft>]" }, + { offset }, + ]); await user.paste(newVal); }; -export const chooseOption = async (user: UserEvent, select: HTMLElement, optionText: string) => { +export const chooseOption = async ( + user: UserEvent, + select: HTMLElement, + optionText: string, +) => { await user.click(select); const option = await screen.findByText(optionText, { selector: "li" }); await user.click(option); @@ -98,15 +110,21 @@ export const errMsgForVehicleYear = async () => { }; export const errMsgForVehicleCountry = async () => { - return await screen.findByTestId("alert-permitData.vehicleDetails.countryCode"); + return await screen.findByTestId( + "alert-permitData.vehicleDetails.countryCode", + ); }; export const errMsgForVehicleType = async () => { - return await screen.findByTestId("alert-permitData.vehicleDetails.vehicleType"); + return await screen.findByTestId( + "alert-permitData.vehicleDetails.vehicleType", + ); }; export const errMsgForVehicleSubtype = async () => { - return await screen.findByTestId("alert-permitData.vehicleDetails.vehicleSubType"); + return await screen.findByTestId( + "alert-permitData.vehicleDetails.vehicleSubType", + ); }; export const vinInput = async () => { @@ -126,19 +144,27 @@ export const vehicleYearInput = async () => { }; export const vehicleCountrySelect = async () => { - return await screen.findByTestId("select-permitData.vehicleDetails.countryCode"); + return await screen.findByTestId( + "select-permitData.vehicleDetails.countryCode", + ); }; export const vehicleProvinceSelect = async () => { - return await screen.findByTestId("select-permitData.vehicleDetails.provinceCode"); + return await screen.findByTestId( + "select-permitData.vehicleDetails.provinceCode", + ); }; export const vehicleTypeSelect = async () => { - return await screen.findByTestId("select-permitData.vehicleDetails.vehicleType"); + return await screen.findByTestId( + "select-permitData.vehicleDetails.vehicleType", + ); }; export const vehicleSubtypeSelect = async () => { - return await screen.findByTestId("select-permitData.vehicleDetails.vehicleSubType"); + return await screen.findByTestId( + "select-permitData.vehicleDetails.vehicleSubType", + ); }; export const openVehicleSubtypeSelect = async (user: UserEvent) => { @@ -146,7 +172,10 @@ export const openVehicleSubtypeSelect = async (user: UserEvent) => { await user.click(subtypeSelect); }; -export const chooseSaveVehicleToInventory = async (user: UserEvent, save: boolean) => { +export const chooseSaveVehicleToInventory = async ( + user: UserEvent, + save: boolean, +) => { if (save) { const saveOption = await screen.findByTestId("save-vehicle-yes"); await user.click(saveOption); @@ -173,9 +202,14 @@ export const vehicleOptions = async (vehicleType: VehicleTypesAsString) => { return await screen.findAllByTestId(`select-vehicle-option-${vehicleType}`); }; -export const subtypeOptions = async (shownSubtypes: string[], excludedSubtypes: string[]) => { +export const subtypeOptions = async ( + shownSubtypes: string[], + excludedSubtypes: string[], +) => { const subtypeOptions = await vehicleSubtypeOptions(); - const subtypeOptionsText = subtypeOptions.map(option => option.textContent ?? ""); + const subtypeOptionsText = subtypeOptions.map( + (option) => option.textContent ?? "", + ); const properOptions = subtypeOptionsText.filter((optionText) => { return shownSubtypes.includes(optionText); }); @@ -209,7 +243,10 @@ type VehicleDetail = { saveVehicle: boolean; }; -export const fillVehicleInfo = async (user: UserEvent, vehicle: VehicleDetail) => { +export const fillVehicleInfo = async ( + user: UserEvent, + vehicle: VehicleDetail, +) => { const vinTextField = await vinInput(); const plateTextField = await plateInput(); const makeTextField = await makeInput(); diff --git a/frontend/src/features/permits/components/dashboard/tests/integration/helpers/assert.ts b/frontend/src/features/permits/components/dashboard/tests/integration/helpers/assert.ts index 2fdd1038a..0497e5e14 100644 --- a/frontend/src/features/permits/components/dashboard/tests/integration/helpers/assert.ts +++ b/frontend/src/features/permits/components/dashboard/tests/integration/helpers/assert.ts @@ -1,15 +1,30 @@ import { VehicleTypesAsString } from "../../../../../../manageVehicles/types/managevehicles"; -import { getDefaultPowerUnitTypes, getDefaultTrailerTypes } from "../fixtures/getVehicleInfo"; +import { + getDefaultPowerUnitTypes, + getDefaultTrailerTypes, +} from "../fixtures/getVehicleInfo"; import { subtypeOptions } from "./access"; -export const assertVehicleSubtypeOptions = async (vehicleType: VehicleTypesAsString) => { - const shownSubtypes = vehicleType === "powerUnit" - ? getDefaultPowerUnitTypes().slice(0, -1).map(subtype => subtype.type) - : getDefaultTrailerTypes().slice(0, -1).map(subtype => subtype.type); - - const excludedSubtypes = vehicleType === "powerUnit" - ? getDefaultPowerUnitTypes().slice(-1).map(subtype => subtype.type) - : getDefaultTrailerTypes().slice(-1).map(subtype => subtype.type); +export const assertVehicleSubtypeOptions = async ( + vehicleType: VehicleTypesAsString, +) => { + const shownSubtypes = + vehicleType === "powerUnit" + ? getDefaultPowerUnitTypes() + .slice(0, -1) + .map((subtype) => subtype.type) + : getDefaultTrailerTypes() + .slice(0, -1) + .map((subtype) => subtype.type); + + const excludedSubtypes = + vehicleType === "powerUnit" + ? getDefaultPowerUnitTypes() + .slice(-1) + .map((subtype) => subtype.type) + : getDefaultTrailerTypes() + .slice(-1) + .map((subtype) => subtype.type); const options = await subtypeOptions(shownSubtypes, excludedSubtypes); expect(options.properOptions).toHaveLength(shownSubtypes.length); diff --git a/frontend/src/features/permits/components/dashboard/tests/integration/helpers/prepare.tsx b/frontend/src/features/permits/components/dashboard/tests/integration/helpers/prepare.tsx index e2b9996f8..a94269e16 100644 --- a/frontend/src/features/permits/components/dashboard/tests/integration/helpers/prepare.tsx +++ b/frontend/src/features/permits/components/dashboard/tests/integration/helpers/prepare.tsx @@ -4,28 +4,40 @@ import { setupServer } from "msw/node"; import { rest } from "msw"; import { renderWithClient } from "../../../../../../../common/helpers/testHelper"; -import OnRouteBCContext, { OnRouteBCContextType } from "../../../../../../../common/authentication/OnRouteBCContext"; +import OnRouteBCContext, { + OnRouteBCContextType, +} from "../../../../../../../common/authentication/OnRouteBCContext"; import { bcGovTheme } from "../../../../../../../themes/bcGovTheme"; import { ApplicationDashboard } from "../../../ApplicationDashboard"; import { PERMITS_API } from "../../../../../apiManager/endpoints/endpoints"; -import { dayjsToUtcStr, now } from "../../../../../../../common/helpers/formatDate"; -import { createApplication, getApplication, updateApplication } from "../fixtures/getActiveApplication"; +import { + dayjsToUtcStr, + now, +} from "../../../../../../../common/helpers/formatDate"; +import { + createApplication, + getApplication, + updateApplication, +} from "../fixtures/getActiveApplication"; import { VEHICLES_API } from "../../../../../../manageVehicles/apiManager/endpoints/endpoints"; import { VEHICLES_URL } from "../../../../../../../common/apiManager/endpoints/endpoints"; import { MANAGE_PROFILE_API } from "../../../../../../manageProfile/apiManager/endpoints/endpoints"; import { getDefaultCompanyInfo } from "../fixtures/getCompanyInfo"; import { getDefaultUserDetails } from "../fixtures/getUserDetails"; -import { - createPowerUnit, - createTrailer, - getAllPowerUnits, - getAllTrailers, - getDefaultPowerUnitTypes, - getDefaultTrailerTypes, +import { + createPowerUnit, + createTrailer, + getAllPowerUnits, + getAllTrailers, + getDefaultPowerUnitTypes, + getDefaultTrailerTypes, updatePowerUnit, } from "../fixtures/getVehicleInfo"; import { getDefaultRequiredVal } from "../../../../../../../common/helpers/util"; -import { formatCountry, formatProvince } from "../../../../../../../common/helpers/formatCountryProvince"; +import { + formatCountry, + formatProvince, +} from "../../../../../../../common/helpers/formatCountryProvince"; // Use some default user details values to give to the OnRouteBCContext context provider export const defaultUserDetails = getDefaultUserDetails(); @@ -37,107 +49,161 @@ const server = setupServer( // Mock creating/saving application rest.post(PERMITS_API.SUBMIT_TERM_OVERSIZE_PERMIT, async (req, res, ctx) => { const reqBody = await req.json(); - const applicationData = { + const applicationData = { ...reqBody, applicationNumber: newApplicationNumber, createdDateTime: dayjsToUtcStr(now()), updatedDateTime: dayjsToUtcStr(now()), }; const createdApplication = createApplication(applicationData); // add to mock application store - return res(ctx.status(201), ctx.json({ - ...createdApplication, - })); + return res( + ctx.status(201), + ctx.json({ + ...createdApplication, + }), + ); }), // Mock updating/saving application - rest.put(`${PERMITS_API.SUBMIT_TERM_OVERSIZE_PERMIT}/:id`, async (req, res, ctx) => { - const id = String(req.params.id); - const reqBody = await req.json(); - const applicationData = { - ...reqBody, - updatedDateTime: dayjsToUtcStr(now()), - } - const updatedApplication = updateApplication(applicationData, id); // update application in mock application store + rest.put( + `${PERMITS_API.SUBMIT_TERM_OVERSIZE_PERMIT}/:id`, + async (req, res, ctx) => { + const id = String(req.params.id); + const reqBody = await req.json(); + const applicationData = { + ...reqBody, + updatedDateTime: dayjsToUtcStr(now()), + }; + const updatedApplication = updateApplication(applicationData, id); // update application in mock application store - if (!updatedApplication) { - return res(ctx.status(404), ctx.json({ - message: "Application not found", - })); - } - return res(ctx.json({ - ...updatedApplication, - })); - }), + if (!updatedApplication) { + return res( + ctx.status(404), + ctx.json({ + message: "Application not found", + }), + ); + } + return res( + ctx.json({ + ...updatedApplication, + }), + ); + }, + ), // Mock getting application rest.get(`${VEHICLES_URL}/permits/applications/:permitId`, (_, res, ctx) => { - return res(ctx.json({ - // get application from mock application store (there's only 1 application or empty), since we're testing save/create/edit behaviour - data: getApplication(), - })); + return res( + ctx.json({ + // get application from mock application store (there's only 1 application or empty), since we're testing save/create/edit behaviour + data: getApplication(), + }), + ); }), // Mock getting power unit types rest.get(VEHICLES_API.POWER_UNIT_TYPES, async (_, res, ctx) => { - return res(ctx.json([ - ...getDefaultPowerUnitTypes() // get power unit types from mock vehicle store - ])); + return res( + ctx.json([ + ...getDefaultPowerUnitTypes(), // get power unit types from mock vehicle store + ]), + ); }), // Mock getting trailer types rest.get(VEHICLES_API.TRAILER_TYPES, async (_, res, ctx) => { - return res(ctx.json([ - ...getDefaultTrailerTypes() // get trailer types from mock vehicle store - ])); + return res( + ctx.json([ + ...getDefaultTrailerTypes(), // get trailer types from mock vehicle store + ]), + ); }), // Mock getting power unit vehicles - rest.get(`${VEHICLES_URL}/companies/:companyId/vehicles/powerUnits`, async (_, res, ctx) => { - return res(ctx.json([ - ...getAllPowerUnits(), // get power unit vehicles from mock vehicle store - ])); - }), + rest.get( + `${VEHICLES_URL}/companies/:companyId/vehicles/powerUnits`, + async (_, res, ctx) => { + return res( + ctx.json([ + ...getAllPowerUnits(), // get power unit vehicles from mock vehicle store + ]), + ); + }, + ), // Mock getting trailer vehicles - rest.get(`${VEHICLES_URL}/companies/:companyId/vehicles/trailers`, async (_, res, ctx) => { - return res(ctx.json([ - ...getAllTrailers(), // get trailer vehicles from mock vehicle store - ])); - }), + rest.get( + `${VEHICLES_URL}/companies/:companyId/vehicles/trailers`, + async (_, res, ctx) => { + return res( + ctx.json([ + ...getAllTrailers(), // get trailer vehicles from mock vehicle store + ]), + ); + }, + ), // Mock getting company details - rest.get(`${MANAGE_PROFILE_API.COMPANIES}/:companyId`, async (_, res, ctx) => { - return res(ctx.json({ - ...companyInfo, - })); - }), + rest.get( + `${MANAGE_PROFILE_API.COMPANIES}/:companyId`, + async (_, res, ctx) => { + return res( + ctx.json({ + ...companyInfo, + }), + ); + }, + ), // Mock creating power unit vehicle - rest.post(`${VEHICLES_URL}/companies/:companyId/vehicles/powerUnits`, async (req, res, ctx) => { - const reqBody = await req.json(); - const newPowerUnit = createPowerUnit(reqBody); // create power unit vehicle in mock vehicle store - return res(ctx.status(201), ctx.json({ - ...newPowerUnit - })); - }), + rest.post( + `${VEHICLES_URL}/companies/:companyId/vehicles/powerUnits`, + async (req, res, ctx) => { + const reqBody = await req.json(); + const newPowerUnit = createPowerUnit(reqBody); // create power unit vehicle in mock vehicle store + return res( + ctx.status(201), + ctx.json({ + ...newPowerUnit, + }), + ); + }, + ), // Mock updating power unit vehicle - rest.put(`${VEHICLES_URL}/companies/:companyId/vehicles/powerUnits/:powerUnitId`, async (req, res, ctx) => { - const id = String(req.params.powerUnitId); - const reqBody = await req.json(); - const updatedPowerUnit = updatePowerUnit(id, reqBody); // update power unit vehicle in mock vehicle store - return res(ctx.json({ - ...updatedPowerUnit, - })); - }), + rest.put( + `${VEHICLES_URL}/companies/:companyId/vehicles/powerUnits/:powerUnitId`, + async (req, res, ctx) => { + const id = String(req.params.powerUnitId); + const reqBody = await req.json(); + const updatedPowerUnit = updatePowerUnit(id, reqBody); // update power unit vehicle in mock vehicle store + return res( + ctx.json({ + ...updatedPowerUnit, + }), + ); + }, + ), // Mock creating trailer vehicle - rest.post(`${VEHICLES_URL}/companies/:companyId/vehicles/trailers`, async (req, res, ctx) => { - const reqBody = await req.json(); - const newTrailer = createTrailer(reqBody); // create trailer vehicle in mock vehicle store - return res(ctx.status(201), ctx.json({ - ...newTrailer - })); - }), + rest.post( + `${VEHICLES_URL}/companies/:companyId/vehicles/trailers`, + async (req, res, ctx) => { + const reqBody = await req.json(); + const newTrailer = createTrailer(reqBody); // create trailer vehicle in mock vehicle store + return res( + ctx.status(201), + ctx.json({ + ...newTrailer, + }), + ); + }, + ), // Mock updating trailer vehicle - rest.put(`${VEHICLES_URL}/companies/:companyId/vehicles/trailers/:trailerId`, async (req, res, ctx) => { - const id = String(req.params.trailerId); - const reqBody = await req.json(); - const updatedTrailer = updatePowerUnit(id, reqBody); // update trailer vehicle in mock vehicle store - return res(ctx.json({ - ...updatedTrailer, - })); - }), + rest.put( + `${VEHICLES_URL}/companies/:companyId/vehicles/trailers/:trailerId`, + async (req, res, ctx) => { + const id = String(req.params.trailerId); + const reqBody = await req.json(); + const updatedTrailer = updatePowerUnit(id, reqBody); // update trailer vehicle in mock vehicle store + return res( + ctx.json({ + ...updatedTrailer, + }), + ); + }, + ), ); export const listenToMockServer = () => { @@ -164,30 +230,34 @@ export const ComponentWithWrapper = (userDetails: OnRouteBCContextType) => { export const renderTestComponent = (userDetails: OnRouteBCContextType) => { const user = userEvent.setup(); - const component = renderWithClient( - ComponentWithWrapper(userDetails) - ); + const component = renderWithClient(ComponentWithWrapper(userDetails)); return { user, component }; }; -export const getVehicleDetails = (usage: "create" | "update", saveVehicle: boolean) => { +export const getVehicleDetails = ( + usage: "create" | "update", + saveVehicle: boolean, +) => { const powerUnits = getAllPowerUnits(); const existingVehicle = powerUnits[0]; const updatedProvinceAbbr = "AB"; const vehicle = { ...existingVehicle, - vin: usage === "create" ? - `${existingVehicle.vin.slice(1)}1` : existingVehicle.vin, - provinceCode: usage === "update" ? - updatedProvinceAbbr : existingVehicle.provinceCode, + vin: + usage === "create" + ? `${existingVehicle.vin.slice(1)}1` + : existingVehicle.vin, + provinceCode: + usage === "update" ? updatedProvinceAbbr : existingVehicle.provinceCode, }; const vehicleSubtype = getDefaultRequiredVal( "", - getDefaultPowerUnitTypes() - .find(subtype => subtype.typeCode === vehicle.powerUnitTypeCode)?.type + getDefaultPowerUnitTypes().find( + (subtype) => subtype.typeCode === vehicle.powerUnitTypeCode, + )?.type, ); - + return { formDetails: { vin: vehicle.vin, diff --git a/frontend/src/features/permits/components/dialog/LeaveApplicationDialog.tsx b/frontend/src/features/permits/components/dialog/LeaveApplicationDialog.tsx index 876da91ba..394a8f858 100644 --- a/frontend/src/features/permits/components/dialog/LeaveApplicationDialog.tsx +++ b/frontend/src/features/permits/components/dialog/LeaveApplicationDialog.tsx @@ -23,19 +23,18 @@ export const LeaveApplicationDialog = ({ >
- +
- - Are you sure you want to leave? - + Are you sure you want to leave?

You have unsaved changes. If you leave, all your changes will be lost.

-

- This action cannot be undone. -

+

This action cannot be undone.

) : ( <> diff --git a/frontend/src/features/permits/helpers/equality.ts b/frontend/src/features/permits/helpers/equality.ts index db5a0c84c..95d57b1e5 100644 --- a/frontend/src/features/permits/helpers/equality.ts +++ b/frontend/src/features/permits/helpers/equality.ts @@ -1,5 +1,8 @@ import { getDefaultRequiredVal } from "../../../common/helpers/util"; -import { DATE_FORMATS, dayjsToLocalStr } from "../../../common/helpers/formatDate"; +import { + DATE_FORMATS, + dayjsToLocalStr, +} from "../../../common/helpers/formatDate"; import { PermitData, Commodities, @@ -14,19 +17,22 @@ import { * @param mailingAddress2 second mailing address info * @returns true when mailing addresses are equivalent, false otherwise */ -const areMailingAddressesEqual = (mailingAddress1?: MailingAddress, mailingAddress2?: MailingAddress) => { +const areMailingAddressesEqual = ( + mailingAddress1?: MailingAddress, + mailingAddress2?: MailingAddress, +) => { if (!mailingAddress1 && !mailingAddress2) return true; // considered equal when both are undefined if (!mailingAddress1 || !mailingAddress2) return false; // considered not equal when only one is undefined - return mailingAddress1.addressLine1 === mailingAddress2.addressLine1 - && mailingAddress1.city === mailingAddress2.city - && mailingAddress1.provinceCode === mailingAddress2.provinceCode - && mailingAddress1.countryCode === mailingAddress2.countryCode - && mailingAddress1.postalCode === mailingAddress2.postalCode - && ( - (!mailingAddress1.addressLine2 && !mailingAddress2.addressLine2) - || (mailingAddress1.addressLine2 === mailingAddress2.addressLine2) - ); + return ( + mailingAddress1.addressLine1 === mailingAddress2.addressLine1 && + mailingAddress1.city === mailingAddress2.city && + mailingAddress1.provinceCode === mailingAddress2.provinceCode && + mailingAddress1.countryCode === mailingAddress2.countryCode && + mailingAddress1.postalCode === mailingAddress2.postalCode && + ((!mailingAddress1.addressLine2 && !mailingAddress2.addressLine2) || + mailingAddress1.addressLine2 === mailingAddress2.addressLine2) + ); }; /** @@ -35,7 +41,10 @@ const areMailingAddressesEqual = (mailingAddress1?: MailingAddress, mailingAddre * @param contactDetails2 second contact details info * @returns true when contact details are equivalent, false otherwise */ -const areContactDetailsEqual = (contactDetails1?: ContactDetailsType, contactDetails2?: ContactDetailsType) => { +const areContactDetailsEqual = ( + contactDetails1?: ContactDetailsType, + contactDetails2?: ContactDetailsType, +) => { if (!contactDetails1 && !contactDetails2) return true; // considered equal when both are undefined if (!contactDetails1 || !contactDetails2) return false; // considered not equal when only one is undefined @@ -54,10 +63,17 @@ const areContactDetailsEqual = (contactDetails1?: ContactDetailsType, contactDet * @param list2 second commodities list * @returns true when commodities lists are equivalent, false otherwise */ -export const areCommoditiesEqual = (list1: Commodities[], list2: Commodities[]) => { +export const areCommoditiesEqual = ( + list1: Commodities[], + list2: Commodities[], +) => { // Instead of comparing arrays directly (as items can be in different orders), transform them into maps and compare key-value pairs - const commodityMap1 = new Map(list1.map(commodity1 => [commodity1.condition, commodity1])); - const commodityMap2 = new Map(list2.map(commodity2 => [commodity2.condition, commodity2])); + const commodityMap1 = new Map( + list1.map((commodity1) => [commodity1.condition, commodity1]), + ); + const commodityMap2 = new Map( + list2.map((commodity2) => [commodity2.condition, commodity2]), + ); // Compare all key-value pairs of first commodities map with key-value pairs of second commodities map for (const [condition, commodity] of commodityMap1) { @@ -82,7 +98,10 @@ export const areCommoditiesEqual = (list1: Commodities[], list2: Commodities[]) * @param vehicleDetails2 second vehicle details info * @returns true when vehicle details are equivalent, false otherwise */ -const areVehicleDetailsEqual = (vehicleDetails1?: VehicleDetailsType, vehicleDetails2?: VehicleDetailsType) => { +const areVehicleDetailsEqual = ( + vehicleDetails1?: VehicleDetailsType, + vehicleDetails2?: VehicleDetailsType, +) => { if (!vehicleDetails1 && !vehicleDetails2) return true; // considered equal when both are undefined if (!vehicleDetails1 || !vehicleDetails2) return false; // considered not equal when only one is undefined @@ -101,14 +120,23 @@ const areVehicleDetailsEqual = (vehicleDetails1?: VehicleDetailsType, vehicleDet * @param data2 second application data info * @returns true when application data are equivalent, false otherwise */ -export const areApplicationDataEqual = (data1: PermitData, data2: PermitData) => { - return data1.permitDuration === data2.permitDuration - && dayjsToLocalStr(data1.startDate, DATE_FORMATS.DATEONLY) === dayjsToLocalStr(data2.startDate, DATE_FORMATS.DATEONLY) - && dayjsToLocalStr(data1.expiryDate, DATE_FORMATS.DATEONLY) === dayjsToLocalStr(data2.expiryDate, DATE_FORMATS.DATEONLY) - && areContactDetailsEqual(data1.contactDetails, data2.contactDetails) - && areVehicleDetailsEqual(data1.vehicleDetails, data2.vehicleDetails) - && areCommoditiesEqual(data1.commodities, data2.commodities) - && areMailingAddressesEqual(data1.mailingAddress, data2.mailingAddress) - && ((!data1.companyName && !data2.companyName) || (data1.companyName === data2.companyName)) - && ((!data1.clientNumber && !data2.clientNumber) || (data1.clientNumber === data2.clientNumber)); +export const areApplicationDataEqual = ( + data1: PermitData, + data2: PermitData, +) => { + return ( + data1.permitDuration === data2.permitDuration && + dayjsToLocalStr(data1.startDate, DATE_FORMATS.DATEONLY) === + dayjsToLocalStr(data2.startDate, DATE_FORMATS.DATEONLY) && + dayjsToLocalStr(data1.expiryDate, DATE_FORMATS.DATEONLY) === + dayjsToLocalStr(data2.expiryDate, DATE_FORMATS.DATEONLY) && + areContactDetailsEqual(data1.contactDetails, data2.contactDetails) && + areVehicleDetailsEqual(data1.vehicleDetails, data2.vehicleDetails) && + areCommoditiesEqual(data1.commodities, data2.commodities) && + areMailingAddressesEqual(data1.mailingAddress, data2.mailingAddress) && + ((!data1.companyName && !data2.companyName) || + data1.companyName === data2.companyName) && + ((!data1.clientNumber && !data2.clientNumber) || + data1.clientNumber === data2.clientNumber) + ); }; diff --git a/frontend/src/features/permits/helpers/feeSummary.ts b/frontend/src/features/permits/helpers/feeSummary.ts index bb685d4f7..012f91590 100644 --- a/frontend/src/features/permits/helpers/feeSummary.ts +++ b/frontend/src/features/permits/helpers/feeSummary.ts @@ -1,4 +1,7 @@ -import { applyWhenNotNullable, getDefaultRequiredVal } from "../../../common/helpers/util"; +import { + applyWhenNotNullable, + getDefaultRequiredVal, +} from "../../../common/helpers/util"; import { PermitHistory } from "../types/PermitHistory"; import { TRANSACTION_TYPES, TransactionType } from "../types/payment.d"; @@ -17,9 +20,18 @@ export const calculateFeeByDuration = (duration: number) => { * @param duration duration field for a permit (if exists) * @returns display text for the fee summary (currency amount to 2 decimal places) */ -export const feeSummaryDisplayText = (feeSummary?: string | null, duration?: number | null) => { - const feeFromSummary = applyWhenNotNullable((numericStr) => Number(numericStr).toFixed(2), feeSummary); - const feeFromDuration = applyWhenNotNullable((num) => calculateFeeByDuration(num).toFixed(2), duration); +export const feeSummaryDisplayText = ( + feeSummary?: string | null, + duration?: number | null, +) => { + const feeFromSummary = applyWhenNotNullable( + (numericStr) => Number(numericStr).toFixed(2), + feeSummary, + ); + const feeFromDuration = applyWhenNotNullable( + (num) => calculateFeeByDuration(num).toFixed(2), + duration, + ); const fee = getDefaultRequiredVal("0.00", feeFromSummary, feeFromDuration); const numericFee = Number(fee); return numericFee >= 0 ? `$${fee}` : `-$${(numericFee * -1).toFixed(2)}`; @@ -43,9 +55,13 @@ export const isTransactionTypeRefund = (transactionType: TransactionType) => { * @returns total net amount resulting from the history of transactions for the permit */ export const calculateNetAmount = (permitHistory: PermitHistory[]) => { - return permitHistory.map(permit => isTransactionTypeRefund(permit.transactionTypeId) - ? -1 * permit.transactionAmount - : permit.transactionAmount).reduce((prev, curr) => prev + curr, 0); + return permitHistory + .map((permit) => + isTransactionTypeRefund(permit.transactionTypeId) + ? -1 * permit.transactionAmount + : permit.transactionAmount, + ) + .reduce((prev, curr) => prev + curr, 0); }; /** @@ -54,7 +70,10 @@ export const calculateNetAmount = (permitHistory: PermitHistory[]) => { * @param currDuration Current (updated) duration of the permit * @returns Amount that needs to be refunded, or if negative then the amount that still needs to be paid */ -export const calculateAmountToRefund = (permitHistory: PermitHistory[], currDuration: number) => { +export const calculateAmountToRefund = ( + permitHistory: PermitHistory[], + currDuration: number, +) => { const netPaid = calculateNetAmount(permitHistory); const feeForCurrDuration = calculateFeeByDuration(currDuration); return netPaid - feeForCurrDuration; diff --git a/frontend/src/features/permits/helpers/getDefaultApplicationFormData.ts b/frontend/src/features/permits/helpers/getDefaultApplicationFormData.ts index 89e80ae44..5e8b9d514 100644 --- a/frontend/src/features/permits/helpers/getDefaultApplicationFormData.ts +++ b/frontend/src/features/permits/helpers/getDefaultApplicationFormData.ts @@ -4,7 +4,10 @@ import { getUserGuidFromSession } from "../../../common/apiManager/httpRequestHa import { BCeIDUserDetailContext } from "../../../common/authentication/OnRouteBCContext"; import { TROS_COMMODITIES } from "../constants/termOversizeConstants"; import { now } from "../../../common/helpers/formatDate"; -import { Address, CompanyProfile } from "../../manageProfile/types/manageProfile"; +import { + Address, + CompanyProfile, +} from "../../manageProfile/types/manageProfile"; import { PERMIT_STATUSES } from "../types/PermitStatus"; import { calculateFeeByDuration } from "./feeSummary"; import { PERMIT_TYPES } from "../types/PermitType"; @@ -31,7 +34,7 @@ import { export const getDefaultContactDetails = ( isNewApplication: boolean, contactDetails?: ContactDetails, - userDetails?: BCeIDUserDetailContext + userDetails?: BCeIDUserDetailContext, ) => { if (isNewApplication) { return { @@ -65,7 +68,7 @@ export const getDefaultContactDetails = ( */ export const getDefaultMailingAddress = ( mailingAddress?: MailingAddress, - alternateAddress?: Address + alternateAddress?: Address, ) => mailingAddress ? { @@ -103,11 +106,13 @@ export const getDefaultVehicleDetails = (vehicleDetails?: VehicleDetails) => ({ saveVehicle: getDefaultRequiredVal(false, vehicleDetails?.saveVehicle), }); -export const getDurationOrDefault = (applicationData?: Application | Permit): number => { +export const getDurationOrDefault = ( + applicationData?: Application | Permit, +): number => { return applyWhenNotNullable( (duration) => +duration, applicationData?.permitData?.permitDuration, - 30 + 30, ); }; @@ -122,71 +127,81 @@ export const getDefaultValues = ( applicationData?: Application, companyId?: number, userDetails?: BCeIDUserDetailContext, - companyInfo?: CompanyProfile + companyInfo?: CompanyProfile, ) => ({ companyId: +getDefaultRequiredVal(0, companyId), - originalPermitId: getDefaultRequiredVal("", applicationData?.originalPermitId), + originalPermitId: getDefaultRequiredVal( + "", + applicationData?.originalPermitId, + ), comment: getDefaultRequiredVal("", applicationData?.comment), applicationNumber: getDefaultRequiredVal( "", - applicationData?.applicationNumber + applicationData?.applicationNumber, + ), + userGuid: getDefaultRequiredVal( + "", + applicationData?.userGuid, + getUserGuidFromSession(), ), - userGuid: getDefaultRequiredVal("", applicationData?.userGuid, getUserGuidFromSession()), permitId: getDefaultRequiredVal("", applicationData?.permitId), permitNumber: getDefaultRequiredVal("", applicationData?.permitNumber), - permitType: getDefaultRequiredVal(PERMIT_TYPES.TROS, applicationData?.permitType), + permitType: getDefaultRequiredVal( + PERMIT_TYPES.TROS, + applicationData?.permitType, + ), permitStatus: getDefaultRequiredVal( PERMIT_STATUSES.IN_PROGRESS, - applicationData?.permitStatus + applicationData?.permitStatus, ), createdDateTime: applyWhenNotNullable( (date) => dayjs(date), applicationData?.createdDateTime, - now() + now(), ), updatedDateTime: applyWhenNotNullable( (date) => dayjs(date), applicationData?.updatedDateTime, - now() + now(), ), revision: getDefaultRequiredVal(0, applicationData?.revision), previousRevision: getDefaultRequiredVal( "", - applicationData?.previousRevision + applicationData?.previousRevision, ), documentId: getDefaultRequiredVal("", applicationData?.documentId), permitData: { companyName: getDefaultRequiredVal( "", - applicationData?.permitData?.companyName + applicationData?.permitData?.companyName, ), clientNumber: getDefaultRequiredVal( "", - applicationData?.permitData?.clientNumber + applicationData?.permitData?.clientNumber, ), startDate: applyWhenNotNullable( (date) => dayjs(date), applicationData?.permitData?.startDate, - now() + now(), ), permitDuration: getDurationOrDefault(applicationData), expiryDate: applyWhenNotNullable( (date) => dayjs(date), applicationData?.permitData?.expiryDate, - now() + now(), ), commodities: getDefaultRequiredVal( [TROS_COMMODITIES[0], TROS_COMMODITIES[1]], applyWhenNotNullable( (commodities) => commodities.map((commodity) => ({ ...commodity })), - applicationData?.permitData?.commodities - ) + applicationData?.permitData?.commodities, + ), ), contactDetails: getDefaultContactDetails( getDefaultRequiredVal("", applicationData?.applicationNumber).trim() === "", applicationData?.permitData?.contactDetails, - userDetails + userDetails, ), // Default values are updated from companyInfo query in the ContactDetails common component mailingAddress: getDefaultMailingAddress( @@ -194,11 +209,11 @@ export const getDefaultValues = ( companyInfo?.mailingAddress, ), vehicleDetails: getDefaultVehicleDetails( - applicationData?.permitData?.vehicleDetails + applicationData?.permitData?.vehicleDetails, ), feeSummary: getDefaultRequiredVal( `${calculateFeeByDuration(getDurationOrDefault(applicationData))}`, - applicationData?.permitData?.feeSummary + applicationData?.permitData?.feeSummary, ), }, }); diff --git a/frontend/src/features/permits/helpers/mappers.ts b/frontend/src/features/permits/helpers/mappers.ts index e49d0c582..71fdf3de7 100644 --- a/frontend/src/features/permits/helpers/mappers.ts +++ b/frontend/src/features/permits/helpers/mappers.ts @@ -10,18 +10,18 @@ import { VehicleTypesAsString, } from "../../manageVehicles/types/managevehicles"; -import { - Application, - ApplicationRequestData, +import { + Application, + ApplicationRequestData, ApplicationResponse, } from "../types/application"; -import { - DATE_FORMATS, - dayjsToLocalStr, - dayjsToUtcStr, - now, - toLocalDayjs, +import { + DATE_FORMATS, + dayjsToLocalStr, + dayjsToUtcStr, + now, + toLocalDayjs, utcToLocalDayjs, } from "../../../common/helpers/formatDate"; @@ -34,7 +34,7 @@ import { */ export const mapVinToVehicleObject = ( vehicles: VehicleTypes[] | undefined, - vin: string + vin: string, ): PowerUnit | Trailer | undefined => { if (!vehicles) return undefined; @@ -59,7 +59,7 @@ export const mapTypeCodeToObject = ( typeCode: string, vehicleType: string, powerUnitTypes: VehicleType[] | undefined, - trailerTypes: VehicleType[] | undefined + trailerTypes: VehicleType[] | undefined, ) => { let typeObject = undefined; @@ -81,7 +81,9 @@ export const mapTypeCodeToObject = ( * @param response ApplicationResponse object received as response data from backend * @returns converted Application object that can be used by form fields and the front-end app */ -export const mapApplicationResponseToApplication = (response: ApplicationResponse): Application => { +export const mapApplicationResponseToApplication = ( + response: ApplicationResponse, +): Application => { return { ...response, createdDateTime: applyWhenNotNullable( @@ -97,14 +99,14 @@ export const mapApplicationResponseToApplication = (response: ApplicationRespons startDate: applyWhenNotNullable( (datetimeStr: string): Dayjs => toLocalDayjs(datetimeStr), response.permitData.startDate, - now() + now(), ), expiryDate: applyWhenNotNullable( (datetimeStr: string): Dayjs => toLocalDayjs(datetimeStr), response.permitData.expiryDate, - now() + now(), ), - } + }, }; }; @@ -113,22 +115,24 @@ export const mapApplicationResponseToApplication = (response: ApplicationRespons * @param data Application form data * @returns ApplicationRequestData object that's used for payload to request to backend */ -export const mapApplicationToApplicationRequestData = (data: Application): ApplicationRequestData => { +export const mapApplicationToApplicationRequestData = ( + data: Application, +): ApplicationRequestData => { return { ...data, - createdDateTime: applyWhenNotNullable( - dayjsToUtcStr, - data.createdDateTime, - ), - updatedDateTime: applyWhenNotNullable( - dayjsToUtcStr, - data.updatedDateTime, - ), + createdDateTime: applyWhenNotNullable(dayjsToUtcStr, data.createdDateTime), + updatedDateTime: applyWhenNotNullable(dayjsToUtcStr, data.updatedDateTime), permitData: { ...data.permitData, - startDate: dayjsToLocalStr(data.permitData.startDate, DATE_FORMATS.DATEONLY), - expiryDate: dayjsToLocalStr(data.permitData.expiryDate, DATE_FORMATS.DATEONLY), - } + startDate: dayjsToLocalStr( + data.permitData.startDate, + DATE_FORMATS.DATEONLY, + ), + expiryDate: dayjsToLocalStr( + data.permitData.expiryDate, + DATE_FORMATS.DATEONLY, + ), + }, }; }; @@ -154,12 +158,16 @@ export const clonePermit = (permit: Permit): Permit => { ...permit, permitData: { ...permit.permitData, - contactDetails: permit.permitData.contactDetails ? { - ...permit.permitData.contactDetails, - } : undefined, - vehicleDetails: permit.permitData.vehicleDetails ? { - ...permit.permitData.vehicleDetails, - } : undefined, + contactDetails: permit.permitData.contactDetails + ? { + ...permit.permitData.contactDetails, + } + : undefined, + vehicleDetails: permit.permitData.vehicleDetails + ? { + ...permit.permitData.vehicleDetails, + } + : undefined, commodities: [...permit.permitData.commodities], mailingAddress: { ...permit.permitData.mailingAddress, @@ -179,7 +187,7 @@ export const transformPermitToApplication = (permit: Permit) => { permitId: `${permit.permitId}`, previousRevision: applyWhenNotNullable( (prevRev) => `${prevRev}`, - permit.previousRevision + permit.previousRevision, ), createdDateTime: applyWhenNotNullable( (datetimeStr: string): Dayjs => utcToLocalDayjs(datetimeStr), @@ -194,14 +202,14 @@ export const transformPermitToApplication = (permit: Permit) => { startDate: applyWhenNotNullable( (datetimeStr: string): Dayjs => toLocalDayjs(datetimeStr), permit.permitData.startDate, - now() + now(), ), expiryDate: applyWhenNotNullable( (datetimeStr: string): Dayjs => toLocalDayjs(datetimeStr), permit.permitData.expiryDate, - now() + now(), ), - } + }, }; }; @@ -211,32 +219,30 @@ export const transformPermitToApplication = (permit: Permit) => { * @returns Transformed Permit object */ export const transformApplicationToPermit = ( - application: Application + application: Application, ): Omit< - Permit, - "originalPermitId" | - "applicationNumber" | - "permitNumber" | - "permitApplicationOrigin" | - "permitApprovalSource" | - "revision" -> & Pick< - Application, - "originalPermitId" | - "applicationNumber" | - "permitNumber" | - "permitApplicationOrigin" | - "permitApprovalSource" | - "revision" -> => { + Permit, + | "originalPermitId" + | "applicationNumber" + | "permitNumber" + | "permitApplicationOrigin" + | "permitApprovalSource" + | "revision" +> & + Pick< + Application, + | "originalPermitId" + | "applicationNumber" + | "permitNumber" + | "permitApplicationOrigin" + | "permitApprovalSource" + | "revision" + > => { return { ...application, - permitId: applyWhenNotNullable( - id => +id, - application.permitId, - ), + permitId: applyWhenNotNullable((id) => +id, application.permitId), previousRevision: applyWhenNotNullable( - prevRev => +prevRev, + (prevRev) => +prevRev, application.previousRevision, ), createdDateTime: applyWhenNotNullable( @@ -249,8 +255,14 @@ export const transformApplicationToPermit = ( ), permitData: { ...application.permitData, - startDate: dayjsToLocalStr(application.permitData.startDate, DATE_FORMATS.DATEONLY), - expiryDate: dayjsToLocalStr(application.permitData.expiryDate, DATE_FORMATS.DATEONLY), - } + startDate: dayjsToLocalStr( + application.permitData.startDate, + DATE_FORMATS.DATEONLY, + ), + expiryDate: dayjsToLocalStr( + application.permitData.expiryDate, + DATE_FORMATS.DATEONLY, + ), + }, }; }; diff --git a/frontend/src/features/permits/helpers/payment.ts b/frontend/src/features/permits/helpers/payment.ts index 0843d9e43..68ddaf57c 100644 --- a/frontend/src/features/permits/helpers/payment.ts +++ b/frontend/src/features/permits/helpers/payment.ts @@ -1,10 +1,13 @@ import { PayBCPaymentDetails } from "../types/payment"; -import { applyWhenNotNullable, getDefaultRequiredVal } from "../../../common/helpers/util"; -import { - BAMBORA_PAYMENT_METHODS, - BamboraPaymentMethod, - CARD_TYPES, - CardType, +import { + applyWhenNotNullable, + getDefaultRequiredVal, +} from "../../../common/helpers/util"; +import { + BAMBORA_PAYMENT_METHODS, + BamboraPaymentMethod, + CARD_TYPES, + CardType, } from "../types/PaymentMethod"; import { parseRedirectUriPath } from "../pages/Payment/PaymentRedirect"; @@ -14,10 +17,12 @@ import { parseRedirectUriPath } from "../pages/Payment/PaymentRedirect"; * @param {URLSearchParams} params - The object containing URL query parameters. * @returns {PayBCPaymentDetails} The extracted PayBCPaymentDetails object. */ -export const getPayBCPaymentDetails = (params: URLSearchParams): PayBCPaymentDetails => { +export const getPayBCPaymentDetails = ( + params: URLSearchParams, +): PayBCPaymentDetails => { // Extract the query parameters and assign them to the corresponding properties of PayBCPaymentDetails - const path = getDefaultRequiredVal("", params.get("path")) - const {trnApproved} = parseRedirectUriPath(path) + const path = getDefaultRequiredVal("", params.get("path")); + const { trnApproved } = parseRedirectUriPath(path); const payBCPaymentDetails: PayBCPaymentDetails = { authCode: getDefaultRequiredVal("", params.get("authCode")), @@ -27,19 +32,29 @@ export const getPayBCPaymentDetails = (params: URLSearchParams): PayBCPaymentDet avsPostalMatch: getDefaultRequiredVal("", params.get("avsPostalMatch")), avsProcessed: getDefaultRequiredVal("", params.get("avsProcessed")), avsResult: getDefaultRequiredVal("", params.get("avsResult")), - cardType: getDefaultRequiredVal(CARD_TYPES.VI, params.get("cardType")) as CardType, + cardType: getDefaultRequiredVal( + CARD_TYPES.VI, + params.get("cardType"), + ) as CardType, cvdId: 1, // applyWhenNotNullable((cvdId) => Number(cvdId), params.get("cvdId"), 0), trnApproved: trnApproved, - messageId: '1', // getDefaultRequiredVal("", params.get("messageId")), + messageId: "1", // getDefaultRequiredVal("", params.get("messageId")), messageText: getDefaultRequiredVal("", params.get("messageText")), - paymentMethod: getDefaultRequiredVal(BAMBORA_PAYMENT_METHODS.CC, params.get("paymentMethod")) as BamboraPaymentMethod, + paymentMethod: getDefaultRequiredVal( + BAMBORA_PAYMENT_METHODS.CC, + params.get("paymentMethod"), + ) as BamboraPaymentMethod, ref1: getDefaultRequiredVal("", params.get("ref1")), ref2: getDefaultRequiredVal("", params.get("ref2")), ref3: getDefaultRequiredVal("", params.get("ref3")), ref4: getDefaultRequiredVal("", params.get("ref4")), ref5: getDefaultRequiredVal("", params.get("ref5")), responseType: getDefaultRequiredVal("", params.get("responseType")), - trnAmount: applyWhenNotNullable((trnAmount) => Number(trnAmount), params.get("trnAmount"), 0), + trnAmount: applyWhenNotNullable( + (trnAmount) => Number(trnAmount), + params.get("trnAmount"), + 0, + ), trnCustomerName: getDefaultRequiredVal("", params.get("trnCustomerName")), trnDate: getDefaultRequiredVal("", params.get("trnDate")), trnEmailAddress: getDefaultRequiredVal("", params.get("trnEmailAddress")), diff --git a/frontend/src/features/permits/helpers/permitPDFHelper.ts b/frontend/src/features/permits/helpers/permitPDFHelper.ts index d5f41d65c..ba2531204 100644 --- a/frontend/src/features/permits/helpers/permitPDFHelper.ts +++ b/frontend/src/features/permits/helpers/permitPDFHelper.ts @@ -1,5 +1,8 @@ import dayjs from "dayjs"; -import { downloadPermitApplicationPdf, downloadReceiptPdf } from "../apiManager/permitsAPI"; +import { + downloadPermitApplicationPdf, + downloadReceiptPdf, +} from "../apiManager/permitsAPI"; /** * Opens the PDF in a new browser tab. @@ -8,21 +11,20 @@ import { downloadPermitApplicationPdf, downloadReceiptPdf } from "../apiManager/ */ export const openBlobInNewTab = (blob: Blob) => { const objUrl = URL.createObjectURL( - new Blob([blob], { type: "application/pdf" }) + new Blob([blob], { type: "application/pdf" }), ); window.open(objUrl, "_blank"); }; /** - * Opens the receipt pdf in a new tab. - * @param permitId The permit id. - */ + * Opens the receipt pdf in a new tab. + * @param permitId The permit id. + */ export const viewReceiptPdf = async (permitId: string) => { if (permitId) { try { - const { blobObj: blobObjWithoutType } = await downloadReceiptPdf( - permitId - ); + const { blobObj: blobObjWithoutType } = + await downloadReceiptPdf(permitId); openBlobInNewTab(blobObjWithoutType); } catch (err) { console.error(err); @@ -36,9 +38,8 @@ export const viewReceiptPdf = async (permitId: string) => { */ export const viewPermitPdf = async (permitId: string) => { try { - const { blobObj: blobObjWithoutType } = await downloadPermitApplicationPdf( - permitId - ); + const { blobObj: blobObjWithoutType } = + await downloadPermitApplicationPdf(permitId); openBlobInNewTab(blobObjWithoutType); } catch (err) { console.error(err); diff --git a/frontend/src/features/permits/helpers/removeIneligibleVehicles.ts b/frontend/src/features/permits/helpers/removeIneligibleVehicles.ts index 35cd33bde..3e05b66f6 100644 --- a/frontend/src/features/permits/helpers/removeIneligibleVehicles.ts +++ b/frontend/src/features/permits/helpers/removeIneligibleVehicles.ts @@ -17,14 +17,16 @@ export const removeIneligibleVehicleSubTypes = ( vehicles: VehicleType[], vehicleType: "powerUnit" | "trailer", ineligiblePowerUnits: VehicleType[], - ineligibleTrailers: VehicleType[] + ineligibleTrailers: VehicleType[], ) => { let ineligibleList: VehicleType[] = []; if (vehicleType === "powerUnit") ineligibleList = ineligiblePowerUnits; if (vehicleType === "trailer") ineligibleList = ineligibleTrailers; - const filteredVehicles = vehicles.filter(vehicle => { - return !ineligibleList.some(ineligible => vehicle.typeCode === ineligible.typeCode); + const filteredVehicles = vehicles.filter((vehicle) => { + return !ineligibleList.some( + (ineligible) => vehicle.typeCode === ineligible.typeCode, + ); }); return filteredVehicles; @@ -40,17 +42,17 @@ export const removeIneligibleVehicleSubTypes = ( export const removeIneligibleVehicles = ( vehicles: Vehicle[], ineligiblePowerUnits: VehicleType[], - ineligibleTrailers: VehicleType[] + ineligibleTrailers: VehicleType[], ) => { - const filteredVehicles = vehicles.filter(vehicle => { + const filteredVehicles = vehicles.filter((vehicle) => { if (vehicle.vehicleType === "powerUnit") { const powerUnit = vehicle as PowerUnit; - return !ineligiblePowerUnits.some(ineligible => { + return !ineligiblePowerUnits.some((ineligible) => { return powerUnit.powerUnitTypeCode === ineligible.typeCode; }); } else if (vehicle.vehicleType === "trailer") { const trailer = vehicle as Trailer; - return !ineligibleTrailers.some(ineligible => { + return !ineligibleTrailers.some((ineligible) => { return trailer.trailerTypeCode === ineligible.typeCode; }); } else { diff --git a/frontend/src/features/permits/helpers/sorter.ts b/frontend/src/features/permits/helpers/sorter.ts index 1bc349744..57c363200 100644 --- a/frontend/src/features/permits/helpers/sorter.ts +++ b/frontend/src/features/permits/helpers/sorter.ts @@ -11,7 +11,7 @@ import { */ export const sortVehicleSubTypes = ( vehicleType: string, - options: VehicleType[] | undefined + options: VehicleType[] | undefined, ) => { if (!vehicleType || !options) return []; const sorted = [...options]; // make copy of original array (original shouldn't be changed) @@ -33,7 +33,7 @@ export const sortVehicleSubTypes = ( */ export const sortVehicles = ( chooseFrom: string, - options: Vehicle[] | undefined + options: Vehicle[] | undefined, ) => { if (!chooseFrom || !options) return []; diff --git a/frontend/src/features/permits/hooks/hooks.ts b/frontend/src/features/permits/hooks/hooks.ts index 53af68853..ffb3f9246 100644 --- a/frontend/src/features/permits/hooks/hooks.ts +++ b/frontend/src/features/permits/hooks/hooks.ts @@ -55,13 +55,15 @@ export const useSaveTermOversizeMutation = () => { * @returns appropriate Application data, or error if failed */ export const useApplicationDetailsQuery = (permitId?: string) => { - const [applicationData, setApplicationData] = useState(undefined); - + const [applicationData, setApplicationData] = useState< + Application | undefined + >(undefined); + // Currently, creating new application route doesn't contain permitId // ie. route === "/applications/permits" instead of "/applications/:permitId" // Thus we need to do a check const isPermitIdValid = permitId != null && !isNaN(Number(permitId)); - + const query = useQuery({ queryKey: ["termOversize"], queryFn: () => getApplicationByPermitId(permitId), @@ -75,9 +77,7 @@ export const useApplicationDetailsQuery = (permitId?: string) => { setApplicationData(undefined); } else { // if found, convert to ApplicationResponse object to Application (date string values to Dayjs objects to be used for date inputs) - setApplicationData( - mapApplicationResponseToApplication(application) - ); + setApplicationData(mapApplicationResponseToApplication(application)); } }, }); @@ -97,7 +97,7 @@ export const useApplicationDetailsQuery = (permitId?: string) => { */ export const usePermitDetailsQuery = (permitId?: string) => { const [permit, setPermit] = useState(undefined); - + const invalidPermitId = !permitId; const query = useQuery({ queryKey: ["permit"], @@ -123,7 +123,9 @@ export const usePermitDetailsQuery = (permitId?: string) => { * @returns The mutation object, as well as the transaction that was started (if there is one, or undefined if there's an error). */ export const useStartTransaction = () => { - const [transaction, setTransaction] = useState(undefined); + const [transaction, setTransaction] = useState< + StartTransactionResponseData | null | undefined + >(undefined); const queryClient = useQueryClient(); const mutation = useMutation({ @@ -154,12 +156,14 @@ export const useStartTransaction = () => { */ export const useCompleteTransaction = ( messageText: string, - paymentStatus: number + paymentStatus: number, ) => { const queryClient = useQueryClient(); - const [paymentApproved, setPaymentApproved] = useState(undefined); + const [paymentApproved, setPaymentApproved] = useState( + undefined, + ); const [message, setMessage] = useState(messageText); - + const onTransactionResult = (message: string, paymentApproved: boolean) => { setMessage(message); setPaymentApproved(paymentApproved); @@ -172,8 +176,8 @@ export const useCompleteTransaction = ( } if (err.response) { onTransactionResult( - `Payment approved but error in ORBC Backend: ${err.response.data.message}`, - false + `Payment approved but error in ORBC Backend: ${err.response.data.message}`, + false, ); } else { onTransactionResult("Request Error", false); @@ -213,7 +217,7 @@ export const useCompleteTransaction = ( */ export const usePermitHistoryQuery = (originalPermitId?: string) => { const [permitHistory, setPermitHistory] = useState([]); - + const query = useQuery({ queryKey: ["permitHistory"], queryFn: () => getPermitHistory(originalPermitId), @@ -238,7 +242,9 @@ export const usePermitHistoryQuery = (originalPermitId?: string) => { * @returns Mutation object, and the issued results response. */ export const useIssuePermits = () => { - const [issueResults, setIssueResults] = useState(undefined); + const [issueResults, setIssueResults] = useState< + IssuePermitsResponse | undefined + >(undefined); const queryClient = useQueryClient(); const mutation = useMutation({ @@ -316,8 +322,10 @@ export const useModifyAmendmentApplication = () => { * @returns Current application used for amendment, or null/undefined */ export const useAmendmentApplicationQuery = (originalPermitId?: string) => { - const [amendmentApplication, setAmendmentApplication] = useState(undefined); - + const [amendmentApplication, setAmendmentApplication] = useState< + Permit | null | undefined + >(undefined); + const isIdInvalid = !originalPermitId; const query = useQuery({ queryKey: ["amendmentApplication"], diff --git a/frontend/src/features/permits/hooks/useDefaultApplicationFormData.ts b/frontend/src/features/permits/hooks/useDefaultApplicationFormData.ts index 737036c8d..c605cd862 100644 --- a/frontend/src/features/permits/hooks/useDefaultApplicationFormData.ts +++ b/frontend/src/features/permits/hooks/useDefaultApplicationFormData.ts @@ -2,14 +2,14 @@ import { useState, useEffect, useRef } from "react"; import { useForm } from "react-hook-form"; import { Application, Commodities } from "../types/application"; -import { BCeIDUserDetailContext } from "../../../common/authentication/OnRouteBCContext"; +import { BCeIDUserDetailContext } from "../../../common/authentication/OnRouteBCContext"; import { areCommoditiesEqual } from "../helpers/equality"; import { getDefaultRequiredVal } from "../../../common/helpers/util"; import { CompanyProfile } from "../../manageProfile/types/manageProfile"; -import { - getDefaultContactDetails, - getDefaultMailingAddress, - getDefaultValues, +import { + getDefaultContactDetails, + getDefaultMailingAddress, + getDefaultValues, getDefaultVehicleDetails, } from "../helpers/getDefaultApplicationFormData"; @@ -27,9 +27,10 @@ export const useDefaultApplicationFormData = ( ) => { // initialize the entire form data with default values // Use default values (saved data from the TROS application context, or empty values) - const [defaultApplicationDataValues, setDefaultApplicationDataValues] = useState( - getDefaultValues(applicationData, companyId, userDetails, companyInfo) - ); + const [defaultApplicationDataValues, setDefaultApplicationDataValues] = + useState( + getDefaultValues(applicationData, companyId, userDetails, companyInfo), + ); // Update contact details form fields whenever these values are updated const contactDetailsDepArray = [ @@ -84,12 +85,20 @@ export const useDefaultApplicationFormData = ( // Recommended way of making deep comparisons (for arrays/objects) in dependency arrays // https://stackoverflow.com/questions/59467758/passing-array-to-useeffect-dependency-list - const commoditiesRef = useRef(applicationData?.permitData?.commodities); - const incomingCommodities = getDefaultRequiredVal([], applicationData?.permitData?.commodities); - if (!areCommoditiesEqual( // areCommoditiesEqual is a custom equality helper function to deep compare arrays of objects - incomingCommodities, - getDefaultRequiredVal([], commoditiesRef.current), - )) { + const commoditiesRef = useRef( + applicationData?.permitData?.commodities, + ); + const incomingCommodities = getDefaultRequiredVal( + [], + applicationData?.permitData?.commodities, + ); + if ( + !areCommoditiesEqual( + // areCommoditiesEqual is a custom equality helper function to deep compare arrays of objects + incomingCommodities, + getDefaultRequiredVal([], commoditiesRef.current), + ) + ) { commoditiesRef.current = incomingCommodities; } @@ -118,7 +127,7 @@ export const useDefaultApplicationFormData = ( useEffect(() => { setDefaultApplicationDataValues( - getDefaultValues(applicationData, companyId, userDetails, companyInfo) + getDefaultValues(applicationData, companyId, userDetails, companyInfo), ); }, applicationFormDataDepArray); @@ -134,24 +143,28 @@ export const useDefaultApplicationFormData = ( setValue( "permitData.contactDetails", getDefaultContactDetails( - getDefaultRequiredVal("", applicationData?.applicationNumber).trim() === "", - applicationData?.permitData?.contactDetails, - userDetails - ) + getDefaultRequiredVal("", applicationData?.applicationNumber).trim() === + "", + applicationData?.permitData?.contactDetails, + userDetails, + ), ); }, contactDetailsDepArray); useEffect(() => { setValue( "permitData.mailingAddress", - getDefaultMailingAddress(applicationData?.permitData?.mailingAddress, companyInfo?.mailingAddress) + getDefaultMailingAddress( + applicationData?.permitData?.mailingAddress, + companyInfo?.mailingAddress, + ), ); }, mailingAddressDepArray); useEffect(() => { setValue( - "permitData.vehicleDetails", - getDefaultVehicleDetails(applicationData?.permitData?.vehicleDetails) + "permitData.vehicleDetails", + getDefaultVehicleDetails(applicationData?.permitData?.vehicleDetails), ); }, vehicleDetailsDepArray); diff --git a/frontend/src/features/permits/hooks/usePermitVehicleManagement.ts b/frontend/src/features/permits/hooks/usePermitVehicleManagement.ts index 536c0d5b3..cd6970ee7 100644 --- a/frontend/src/features/permits/hooks/usePermitVehicleManagement.ts +++ b/frontend/src/features/permits/hooks/usePermitVehicleManagement.ts @@ -1,15 +1,18 @@ import { getDefaultRequiredVal } from "../../../common/helpers/util"; import { VehicleDetails } from "../types/application.d"; -import { PowerUnit, Trailer } from "../../manageVehicles/types/managevehicles.d"; +import { + PowerUnit, + Trailer, +} from "../../manageVehicles/types/managevehicles.d"; import { mapVinToVehicleObject } from "../helpers/mappers"; -import { - useAddPowerUnitMutation, - useAddTrailerMutation, - usePowerUnitTypesQuery, - useTrailerTypesQuery, - useUpdatePowerUnitMutation, +import { + useAddPowerUnitMutation, + useAddTrailerMutation, + usePowerUnitTypesQuery, + useTrailerTypesQuery, + useUpdatePowerUnitMutation, useUpdateTrailerMutation, - useVehiclesQuery, + useVehiclesQuery, } from "../../manageVehicles/apiManager/hooks"; export const usePermitVehicleManagement = (companyId: string) => { @@ -26,7 +29,10 @@ export const usePermitVehicleManagement = (companyId: string) => { // Vehicle details that have been fetched by vehicle details queries const fetchedVehicles = getDefaultRequiredVal([], allVehiclesQuery.data); - const fetchedPowerUnitTypes = getDefaultRequiredVal([], powerUnitTypesQuery.data); + const fetchedPowerUnitTypes = getDefaultRequiredVal( + [], + powerUnitTypesQuery.data, + ); const fetchedTrailerTypes = getDefaultRequiredVal([], trailerTypesQuery.data); const handleSaveVehicle = (vehicleData?: VehicleDetails) => { @@ -37,14 +43,11 @@ export const usePermitVehicleManagement = (companyId: string) => { const vehicle = vehicleData; // Check if the vehicle that is to be saved was created from an existing vehicle - const existingVehicle = mapVinToVehicleObject( - fetchedVehicles, - vehicle.vin - ); + const existingVehicle = mapVinToVehicleObject(fetchedVehicles, vehicle.vin); const transformByVehicleType = ( vehicleFormData: VehicleDetails, - existingVehicle?: PowerUnit | Trailer + existingVehicle?: PowerUnit | Trailer, ): PowerUnit | Trailer => { const defaultPowerUnit: PowerUnit = { powerUnitId: "", @@ -74,7 +77,10 @@ export const usePermitVehicleManagement = (companyId: string) => { case "trailer": return { ...defaultTrailer, - trailerId: getDefaultRequiredVal("", (existingVehicle as Trailer)?.trailerId), + trailerId: getDefaultRequiredVal( + "", + (existingVehicle as Trailer)?.trailerId, + ), unitNumber: getDefaultRequiredVal("", existingVehicle?.unitNumber), } as Trailer; case "powerUnit": @@ -82,14 +88,20 @@ export const usePermitVehicleManagement = (companyId: string) => { return { ...defaultPowerUnit, unitNumber: getDefaultRequiredVal("", existingVehicle?.unitNumber), - powerUnitId: getDefaultRequiredVal("", (existingVehicle as PowerUnit)?.powerUnitId), + powerUnitId: getDefaultRequiredVal( + "", + (existingVehicle as PowerUnit)?.powerUnitId, + ), } as PowerUnit; } }; // If the vehicle type is a power unit then create a power unit object if (vehicle.vehicleType === "powerUnit") { - const powerUnit = transformByVehicleType(vehicle, existingVehicle) as PowerUnit; + const powerUnit = transformByVehicleType( + vehicle, + existingVehicle, + ) as PowerUnit; // Either send a PUT or POST request based on powerUnitID if (powerUnit.powerUnitId) { @@ -105,11 +117,14 @@ export const usePermitVehicleManagement = (companyId: string) => { }); } } else if (vehicle.vehicleType === "trailer") { - const trailer = transformByVehicleType(vehicle, existingVehicle) as Trailer; - + const trailer = transformByVehicleType( + vehicle, + existingVehicle, + ) as Trailer; + if (trailer.trailerId) { - updateTrailerMutation.mutate({ - trailer, + updateTrailerMutation.mutate({ + trailer, trailerId: trailer.trailerId, companyId, }); diff --git a/frontend/src/features/permits/pages/Amend/AmendPermit.tsx b/frontend/src/features/permits/pages/Amend/AmendPermit.tsx index 678675907..5151c735b 100644 --- a/frontend/src/features/permits/pages/Amend/AmendPermit.tsx +++ b/frontend/src/features/permits/pages/Amend/AmendPermit.tsx @@ -8,7 +8,11 @@ import { hasPermitExpired } from "../../helpers/permitPDFHelper"; import { Banner } from "../../../../common/components/dashboard/Banner"; import { useMultiStepForm } from "../../hooks/useMultiStepForm"; import { AmendPermitContext } from "./context/AmendPermitContext"; -import { useAmendmentApplicationQuery, usePermitDetailsQuery, usePermitHistoryQuery } from "../../hooks/hooks"; +import { + useAmendmentApplicationQuery, + usePermitDetailsQuery, + usePermitHistoryQuery, +} from "../../hooks/hooks"; import { Loading } from "../../../../common/pages/Loading"; import OnRouteBCContext from "../../../../common/authentication/OnRouteBCContext"; import { USER_AUTH_GROUP } from "../../../manageProfile/types/userManagement.d"; @@ -18,9 +22,15 @@ import { Unexpected } from "../../../../common/pages/Unexpected"; import { AmendPermitReview } from "./components/AmendPermitReview"; import { AmendPermitFinish } from "./components/AmendPermitFinish"; import { AmendPermitForm } from "./components/AmendPermitForm"; -import { AmendPermitFormData, getDefaultFormDataFromPermit } from "./types/AmendPermitFormData"; +import { + AmendPermitFormData, + getDefaultFormDataFromPermit, +} from "./types/AmendPermitFormData"; import { SEARCH_RESULTS } from "../../../../routes/constants"; -import { SEARCH_BY_FILTERS, SEARCH_ENTITIES } from "../../../idir/search/types/types"; +import { + SEARCH_BY_FILTERS, + SEARCH_ENTITIES, +} from "../../../idir/search/types/types"; import { applyWhenNotNullable } from "../../../../common/helpers/util"; export const AMEND_PERMIT_STEPS = { @@ -29,7 +39,8 @@ export const AMEND_PERMIT_STEPS = { Finish: "Finish", } as const; -export type AmendPermitStep = typeof AMEND_PERMIT_STEPS[keyof typeof AMEND_PERMIT_STEPS]; +export type AmendPermitStep = + (typeof AMEND_PERMIT_STEPS)[keyof typeof AMEND_PERMIT_STEPS]; const displayHeaderText = (stepKey: AmendPermitStep) => { switch (stepKey) { @@ -48,16 +59,23 @@ const displayHeaderText = (stepKey: AmendPermitStep) => { * @returns whether or not the permit is amendable */ const isAmendable = (permit: Permit) => { - return permit.permitStatus === PERMIT_STATUSES.ISSUED - || (!isPermitInactive(permit.permitStatus) && !hasPermitExpired(permit.permitData.expiryDate)); + return ( + permit.permitStatus === PERMIT_STATUSES.ISSUED || + (!isPermitInactive(permit.permitStatus) && + !hasPermitExpired(permit.permitData.expiryDate)) + ); }; const isAmendableByUser = (authGroup?: string) => { - return authGroup === USER_AUTH_GROUP.PPCCLERK || authGroup === USER_AUTH_GROUP.SYSADMIN; + return ( + authGroup === USER_AUTH_GROUP.PPCCLERK || + authGroup === USER_AUTH_GROUP.SYSADMIN + ); }; -const searchRoute = `${SEARCH_RESULTS}?searchEntity=${SEARCH_ENTITIES.PERMIT}` - + `&searchByFilter=${SEARCH_BY_FILTERS.PERMIT_NUMBER}&searchValue=`; +const searchRoute = + `${SEARCH_RESULTS}?searchEntity=${SEARCH_ENTITIES.PERMIT}` + + `&searchByFilter=${SEARCH_BY_FILTERS.PERMIT_NUMBER}&searchValue=`; export const AmendPermit = () => { const { permitId } = useParams(); @@ -74,7 +92,8 @@ export const AmendPermit = () => { const { permitHistory } = usePermitHistoryQuery(originalPermitId); // Get latest amendment application, if any - const { amendmentApplication } = useAmendmentApplicationQuery(originalPermitId); + const { amendmentApplication } = + useAmendmentApplicationQuery(originalPermitId); const permitFormDefaultValues = () => { if (amendmentApplication) { @@ -83,33 +102,25 @@ export const AmendPermit = () => { return getDefaultFormDataFromPermit( applyWhenNotNullable( - p => ({ + (p) => ({ ...p, comment: "", - }), - permit - ) + }), + permit, + ), ); }; // Permit form data, populated whenever permit is fetched const [permitFormData, setPermitFormData] = useState( - permitFormDefaultValues() + permitFormDefaultValues(), ); useEffect(() => { - setPermitFormData( - permitFormDefaultValues() - ); + setPermitFormData(permitFormDefaultValues()); }, [amendmentApplication, permit]); - const { - currentStepIndex, - step, - back, - next, - goTo, - } = useMultiStepForm([ + const { currentStepIndex, step, back, next, goTo } = useMultiStepForm([ , , , @@ -143,7 +154,9 @@ export const AmendPermit = () => { ]; const getLinks = () => { - const filteredLinks = allLinks.filter((_, index) => index <= currentStepIndex + 1); + const filteredLinks = allLinks.filter( + (_, index) => index <= currentStepIndex + 1, + ); return filteredLinks.map((link, index) => { if (index === currentStepIndex + 1) { return { @@ -155,35 +168,40 @@ export const AmendPermit = () => { }; const isLoadingState = () => { - return typeof permit === "undefined" - || typeof amendmentApplication === "undefined"; + return ( + typeof permit === "undefined" || + typeof amendmentApplication === "undefined" + ); }; - const contextData = useMemo(() => ({ - permit, - permitFormData, - permitHistory, - setPermitFormData, - next, - back, - goTo, - currentStepIndex, - getLinks, - goHome, - afterFinishAmend: goHomeSuccess, - }), [ - permit, - permitFormData, - permitHistory, - setPermitFormData, - next, - back, - goTo, - currentStepIndex, - getLinks, - goHome, - goHomeSuccess, - ]); + const contextData = useMemo( + () => ({ + permit, + permitFormData, + permitHistory, + setPermitFormData, + next, + back, + goTo, + currentStepIndex, + getLinks, + goHome, + afterFinishAmend: goHomeSuccess, + }), + [ + permit, + permitFormData, + permitHistory, + setPermitFormData, + next, + back, + goTo, + currentStepIndex, + getLinks, + goHome, + goHomeSuccess, + ], + ); if (isLoadingState()) { return ; @@ -202,9 +220,7 @@ export const AmendPermit = () => { } return ( - + { - const { - permit, - permitFormData, - permitHistory, - getLinks, - afterFinishAmend, - } = useContext(AmendPermitContext); + const { permit, permitFormData, permitHistory, getLinks, afterFinishAmend } = + useContext(AmendPermitContext); - const permitId = applyWhenNotNullable(id => `${id}`, permitFormData?.permitId, ""); - - const amountToRefund = -1 * calculateAmountToRefund( - permitHistory, - getDefaultRequiredVal(0, permitFormData?.permitData?.permitDuration) + const permitId = applyWhenNotNullable( + (id) => `${id}`, + permitFormData?.permitId, + "", ); - const { - mutation: startTransactionMutation, - transaction, - } = useStartTransaction(); + const amountToRefund = + -1 * + calculateAmountToRefund( + permitHistory, + getDefaultRequiredVal(0, permitFormData?.permitData?.permitDuration), + ); + + const { mutation: startTransactionMutation, transaction } = + useStartTransaction(); - const { - mutation: issuePermitMutation, - issueResults, - } = useIssuePermits(); + const { mutation: issuePermitMutation, issueResults } = useIssuePermits(); const issueFailed = () => { if (!issueResults) return false; // since issue results might not be ready yet - return issueResults.success.length === 0 - || (issueResults.success.length === 1 && issueResults.success[0] === "") - || (issueResults.failure.length > 0 && issueResults.failure[0] !== ""); + return ( + issueResults.success.length === 0 || + (issueResults.success.length === 1 && issueResults.success[0] === "") || + (issueResults.failure.length > 0 && issueResults.failure[0] !== "") + ); }; useEffect(() => { @@ -71,11 +72,11 @@ export const AmendPermitFinish = () => { const handleFinish = (refundData: RefundFormData) => { const requestData = mapToAmendRequestData( - refundData, - -1 * amountToRefund, - permitId + refundData, + -1 * amountToRefund, + permitId, ); - + startTransactionMutation.mutate(requestData); }; @@ -83,7 +84,7 @@ export const AmendPermitFinish = () => {
- { - const { + const { permit, - permitFormData, + permitFormData, permitHistory, setPermitFormData, currentStepIndex, @@ -38,7 +44,10 @@ export const AmendPermitForm = () => { getLinks, } = useContext(AmendPermitContext); - const { formData, formMethods } = useAmendPermit(currentStepIndex === 0, permitFormData); + const { formData, formMethods } = useAmendPermit( + currentStepIndex === 0, + permitFormData, + ); //The name of this feature that is used for id's, keys, and associating form components const FEATURE = "amend-permit"; @@ -47,12 +56,8 @@ export const AmendPermitForm = () => { const modifyAmendmentMutation = useModifyAmendmentApplication(); const snackBar = useContext(SnackBarContext); - const { - handleSaveVehicle, - vehicleOptions, - powerUnitTypes, - trailerTypes, - } = usePermitVehicleManagement(`${formData.companyId}`); + const { handleSaveVehicle, vehicleOptions, powerUnitTypes, trailerTypes } = + usePermitVehicleManagement(`${formData.companyId}`); const { handleSubmit, getValues } = formMethods; @@ -68,10 +73,11 @@ export const AmendPermitForm = () => { vehicleDetails: { ...data.permitData.vehicleDetails, // Convert year to number here, as React doesn't accept valueAsNumber prop for input component - year: !isNaN(Number(data.permitData.vehicleDetails.year)) ? - Number(data.permitData.vehicleDetails.year) : data.permitData.vehicleDetails.year - } - } + year: !isNaN(Number(data.permitData.vehicleDetails.year)) + ? Number(data.permitData.vehicleDetails.year) + : data.permitData.vehicleDetails.year, + }, + }, } as AmendPermitFormData; }; @@ -85,7 +91,8 @@ export const AmendPermitForm = () => { await onSaveApplication(() => next()); }; - const isSavePermitSuccessful = (status: number) => status === 200 || status === 201; + const isSavePermitSuccessful = (status: number) => + status === 200 || status === 201; const onSaveSuccess = (responseData: Permit) => { snackBar.setSnackBar({ @@ -109,26 +116,38 @@ export const AmendPermitForm = () => { const onSaveApplication = async (additionalSuccessAction?: () => void) => { const permitToBeAmended = transformPermitFormData(getValues()); - const shouldUpdateApplication = permitToBeAmended.permitId !== permit?.permitId; - const response = shouldUpdateApplication ? await modifyAmendmentMutation.mutateAsync({ - applicationNumber: getDefaultRequiredVal("", permitToBeAmended.applicationNumber), - application: { - ...permitToBeAmended, - permitId: `${permitToBeAmended.permitId}`, - previousRevision: applyWhenNotNullable( - (prevRev) => `${prevRev}`, - permitToBeAmended.previousRevision - ), - permitData: { - ...permitToBeAmended.permitData, - companyName: getDefaultRequiredVal("", permitToBeAmended.permitData.companyName), - clientNumber: getDefaultRequiredVal("", permitToBeAmended.permitData.clientNumber), - } - }, - }) : await amendPermitMutation.mutateAsync( - mapFormDataToPermit(permitToBeAmended) as Permit - ); - + const shouldUpdateApplication = + permitToBeAmended.permitId !== permit?.permitId; + const response = shouldUpdateApplication + ? await modifyAmendmentMutation.mutateAsync({ + applicationNumber: getDefaultRequiredVal( + "", + permitToBeAmended.applicationNumber, + ), + application: { + ...permitToBeAmended, + permitId: `${permitToBeAmended.permitId}`, + previousRevision: applyWhenNotNullable( + (prevRev) => `${prevRev}`, + permitToBeAmended.previousRevision, + ), + permitData: { + ...permitToBeAmended.permitData, + companyName: getDefaultRequiredVal( + "", + permitToBeAmended.permitData.companyName, + ), + clientNumber: getDefaultRequiredVal( + "", + permitToBeAmended.permitData.clientNumber, + ), + }, + }, + }) + : await amendPermitMutation.mutateAsync( + mapFormDataToPermit(permitToBeAmended) as Permit, + ); + if (isSavePermitSuccessful(response.status)) { const responseData = response.data; onSaveSuccess(responseData as Permit); @@ -139,20 +158,23 @@ export const AmendPermitForm = () => { }; const revisionHistory = permitHistory - .filter(history => history.comment && history.transactionSubmitDate) - .map(history => ({ + .filter((history) => history.comment && history.transactionSubmitDate) + .map((history) => ({ permitId: history.permitId, comment: getDefaultRequiredVal("", history.comment), name: history.commentUsername, revisionDateTime: getDefaultRequiredVal( - dayjsToUtcStr(nowUtc()), - history.transactionSubmitDate + dayjsToUtcStr(nowUtc()), + history.transactionSubmitDate, ), })); - const permitOldDuration = getDefaultRequiredVal(30, permit?.permitData?.permitDuration); + const permitOldDuration = getDefaultRequiredVal( + 30, + permit?.permitData?.permitDuration, + ); const durationOptions = TROS_PERMIT_DURATIONS.filter( - duration => duration.value <= permitOldDuration + (duration) => duration.value <= permitOldDuration, ); return ( @@ -160,7 +182,7 @@ export const AmendPermitForm = () => { - { - const { - permit, - permitFormData, - permitHistory, - back, - next, - getLinks, - } = useContext(AmendPermitContext); + const { permit, permitFormData, permitHistory, back, next, getLinks } = + useContext(AmendPermitContext); const { data: companyInfo } = useCompanyInfoDetailsQuery( - getDefaultRequiredVal(0, permitFormData?.companyId) + getDefaultRequiredVal(0, permitFormData?.companyId), ); const powerUnitTypesQuery = usePowerUnitTypesQuery(); const trailerTypesQuery = useTrailerTypesQuery(); - + // For the confirmation checkboxes const [isChecked, setIsChecked] = useState(false); const [isSubmitted, setIsSubmitted] = useState(false); @@ -43,11 +43,13 @@ export const AmendPermitReview = () => { const oldFields = getDefaultFormDataFromPermit(permit); - const amountToRefund = -1 * calculateAmountToRefund( - permitHistory, - getDefaultRequiredVal(0, permitFormData?.permitData?.permitDuration) - ); - + const amountToRefund = + -1 * + calculateAmountToRefund( + permitHistory, + getDefaultRequiredVal(0, permitFormData?.permitData?.permitDuration), + ); + return (
@@ -74,16 +76,27 @@ export const AmendPermitReview = () => { powerUnitTypes={powerUnitTypesQuery.data} trailerTypes={trailerTypesQuery.data} vehicleDetails={permitFormData?.permitData?.vehicleDetails} - vehicleWasSaved={permitFormData?.permitData?.vehicleDetails?.saveVehicle} + vehicleWasSaved={ + permitFormData?.permitData?.vehicleDetails?.saveVehicle + } showChangedFields={true} oldFields={{ ...oldFields, - permitId: applyWhenNotNullable(id => `${id}`, oldFields.permitId), - previousRevision: applyWhenNotNullable(prevRev => `${prevRev}`, oldFields.previousRevision), + permitId: applyWhenNotNullable((id) => `${id}`, oldFields.permitId), + previousRevision: applyWhenNotNullable( + (prevRev) => `${prevRev}`, + oldFields.previousRevision, + ), permitData: { ...oldFields.permitData, - companyName: getDefaultRequiredVal("", oldFields.permitData.companyName), - clientNumber: getDefaultRequiredVal("", oldFields.permitData.clientNumber), + companyName: getDefaultRequiredVal( + "", + oldFields.permitData.companyName, + ), + clientNumber: getDefaultRequiredVal( + "", + oldFields.permitData.clientNumber, + ), }, }} calculatedFee={`${amountToRefund}`} diff --git a/frontend/src/features/permits/pages/Amend/components/form/AmendReason.tsx b/frontend/src/features/permits/pages/Amend/components/form/AmendReason.tsx index 19c1463e7..9777c0166 100644 --- a/frontend/src/features/permits/pages/Amend/components/form/AmendReason.tsx +++ b/frontend/src/features/permits/pages/Amend/components/form/AmendReason.tsx @@ -2,17 +2,11 @@ import "./AmendReason.scss"; import { CustomFormComponent } from "../../../../../../common/components/form/CustomFormComponents"; import { requiredMessage } from "../../../../../../common/helpers/validationMessages"; -export const AmendReason = ({ - feature, -}: { - feature: string; -}) => { +export const AmendReason = ({ feature }: { feature: string }) => { return (
-
- Reason for Amendment -
- Reason for Amendment
+
- {revision.name} - , + ,{" "} + {toLocal(revision.revisionDateTime, DATE_FORMATS.LONG)}
-
- {revision.comment} -
+
{revision.comment}
); }; diff --git a/frontend/src/features/permits/pages/Amend/components/form/AmendRevisionHistory.tsx b/frontend/src/features/permits/pages/Amend/components/form/AmendRevisionHistory.tsx index b776b9f86..099ac60ba 100644 --- a/frontend/src/features/permits/pages/Amend/components/form/AmendRevisionHistory.tsx +++ b/frontend/src/features/permits/pages/Amend/components/form/AmendRevisionHistory.tsx @@ -15,17 +15,14 @@ export const AmendRevisionHistory = ({ }) => { return revisionHistory.length > 0 ? (
- + Revision History
- {revisionHistory.map(revision => ( + {revisionHistory.map((revision) => ( ))}
- ): null; + ) : null; }; diff --git a/frontend/src/features/permits/pages/Amend/components/helpers/mapper.ts b/frontend/src/features/permits/pages/Amend/components/helpers/mapper.ts index a6f16588e..b93290f64 100644 --- a/frontend/src/features/permits/pages/Amend/components/helpers/mapper.ts +++ b/frontend/src/features/permits/pages/Amend/components/helpers/mapper.ts @@ -4,7 +4,7 @@ import { RefundFormData } from "../../../Refund/types/RefundFormData"; export const mapToAmendRequestData = ( refundData: RefundFormData, amountToRefund: number, - permitId: string + permitId: string, ) => { const isZeroAmount = Math.abs(amountToRefund) < 0.000001; const reqData = { @@ -24,8 +24,12 @@ export const mapToAmendRequestData = ( return { pgTransactionId: refundData.transactionId, - pgCardType: refundData.refundCardType ? refundData.refundCardType : undefined, - pgPaymentMethod: refundData.refundOnlineMethod ? refundData.refundOnlineMethod : undefined, + pgCardType: refundData.refundCardType + ? refundData.refundCardType + : undefined, + pgPaymentMethod: refundData.refundOnlineMethod + ? refundData.refundOnlineMethod + : undefined, ...reqData, }; }; diff --git a/frontend/src/features/permits/pages/Amend/components/review/ReviewReason.tsx b/frontend/src/features/permits/pages/Amend/components/review/ReviewReason.tsx index e75fbd6b4..896ac416f 100644 --- a/frontend/src/features/permits/pages/Amend/components/review/ReviewReason.tsx +++ b/frontend/src/features/permits/pages/Amend/components/review/ReviewReason.tsx @@ -2,21 +2,13 @@ import { Typography } from "@mui/material"; import "./ReviewReason.scss"; -export const ReviewReason = ({ - reason, -}: { - reason: string; -}) => { +export const ReviewReason = ({ reason }: { reason: string }) => { return (
- - Reason for Amendment - -
-
- {reason} + Reason for Amendment
+
{reason}
); }; diff --git a/frontend/src/features/permits/pages/Amend/context/AmendPermitContext.ts b/frontend/src/features/permits/pages/Amend/context/AmendPermitContext.ts index a9aa85ca8..575d26c31 100644 --- a/frontend/src/features/permits/pages/Amend/context/AmendPermitContext.ts +++ b/frontend/src/features/permits/pages/Amend/context/AmendPermitContext.ts @@ -14,7 +14,7 @@ interface AmendPermitContextType { goTo: (index: number) => void; goHome: () => void; afterFinishAmend: () => void; - getLinks: () => { text: string; onClick?: () => void; }[]; + getLinks: () => { text: string; onClick?: () => void }[]; currentStepIndex: number; } diff --git a/frontend/src/features/permits/pages/Amend/hooks/useAmendPermit.ts b/frontend/src/features/permits/pages/Amend/hooks/useAmendPermit.ts index 0a577e9d8..fe4247296 100644 --- a/frontend/src/features/permits/pages/Amend/hooks/useAmendPermit.ts +++ b/frontend/src/features/permits/pages/Amend/hooks/useAmendPermit.ts @@ -1,14 +1,14 @@ import { useEffect } from "react"; import { useForm } from "react-hook-form"; -import { - AmendPermitFormData, - getDefaultFromNullableFormData, +import { + AmendPermitFormData, + getDefaultFromNullableFormData, } from "../types/AmendPermitFormData"; export const useAmendPermit = ( repopulateFormData: boolean, - updatedPermitFormData?: AmendPermitFormData | null + updatedPermitFormData?: AmendPermitFormData | null, ) => { const formData = getDefaultFromNullableFormData(updatedPermitFormData); diff --git a/frontend/src/features/permits/pages/Amend/types/AmendPermitFormData.ts b/frontend/src/features/permits/pages/Amend/types/AmendPermitFormData.ts index 2f96e5d8a..a8f50701f 100644 --- a/frontend/src/features/permits/pages/Amend/types/AmendPermitFormData.ts +++ b/frontend/src/features/permits/pages/Amend/types/AmendPermitFormData.ts @@ -1,14 +1,25 @@ import { Permit } from "../../../types/permit"; import { getDefaultValues } from "../../../helpers/getDefaultApplicationFormData"; -import { applyWhenNotNullable, areValuesDifferent, getDefaultRequiredVal } from "../../../../../common/helpers/util"; -import { Application, PERMIT_APPLICATION_ORIGINS, PERMIT_APPROVAL_SOURCES } from "../../../types/application.d"; +import { + applyWhenNotNullable, + areValuesDifferent, + getDefaultRequiredVal, +} from "../../../../../common/helpers/util"; +import { + Application, + PERMIT_APPLICATION_ORIGINS, + PERMIT_APPROVAL_SOURCES, +} from "../../../types/application.d"; import { areApplicationDataEqual } from "../../../helpers/equality"; -import { transformApplicationToPermit, transformPermitToApplication } from "../../../helpers/mappers"; -import { - DATE_FORMATS, +import { + transformApplicationToPermit, + transformPermitToApplication, +} from "../../../helpers/mappers"; +import { + DATE_FORMATS, dayjsToLocalStr, - toLocalDayjs, - utcToLocalDayjs, + toLocalDayjs, + utcToLocalDayjs, } from "../../../../../common/helpers/formatDate"; export type AmendPermitFormData = Application; @@ -36,7 +47,9 @@ export const mapFormDataToPermit = (data: AmendPermitFormData) => { * @param permit Permit object received * @returns Default form data values */ -export const getDefaultFormDataFromPermit = (permit?: Permit | null): AmendPermitFormData => { +export const getDefaultFormDataFromPermit = ( + permit?: Permit | null, +): AmendPermitFormData => { // Default form values when permit is not available (or period of time when loading) if (!permit) { return { @@ -47,35 +60,44 @@ export const getDefaultFormDataFromPermit = (permit?: Permit | null): AmendPermi } return { - ...getDefaultValues({ - ...permit, - permitId: `${permit.permitId}`, - previousRevision: applyWhenNotNullable( - (prevRev) => `${prevRev}`, - permit.previousRevision - ), - createdDateTime: applyWhenNotNullable( - (createdAt) => utcToLocalDayjs(createdAt), - permit.createdDateTime - ), - updatedDateTime: applyWhenNotNullable( - (updatedAt) => utcToLocalDayjs(updatedAt), - permit.updatedDateTime - ), - permitData: { - ...permit.permitData, - startDate: applyWhenNotNullable( - (startAt) => toLocalDayjs(startAt), - permit.permitData?.startDate, + ...getDefaultValues( + { + ...permit, + permitId: `${permit.permitId}`, + previousRevision: applyWhenNotNullable( + (prevRev) => `${prevRev}`, + permit.previousRevision, ), - expiryDate: applyWhenNotNullable( - (endAt) => toLocalDayjs(endAt), - permit.permitData?.expiryDate + createdDateTime: applyWhenNotNullable( + (createdAt) => utcToLocalDayjs(createdAt), + permit.createdDateTime, ), - companyName: getDefaultRequiredVal("", permit.permitData?.companyName), - clientNumber: getDefaultRequiredVal("", permit.permitData?.clientNumber), + updatedDateTime: applyWhenNotNullable( + (updatedAt) => utcToLocalDayjs(updatedAt), + permit.updatedDateTime, + ), + permitData: { + ...permit.permitData, + startDate: applyWhenNotNullable( + (startAt) => toLocalDayjs(startAt), + permit.permitData?.startDate, + ), + expiryDate: applyWhenNotNullable( + (endAt) => toLocalDayjs(endAt), + permit.permitData?.expiryDate, + ), + companyName: getDefaultRequiredVal( + "", + permit.permitData?.companyName, + ), + clientNumber: getDefaultRequiredVal( + "", + permit.permitData?.clientNumber, + ), + }, }, - }, permit.companyId), + permit.companyId, + ), permitApplicationOrigin: permit.permitApplicationOrigin, permitApprovalSource: permit.permitApprovalSource, }; @@ -87,7 +109,7 @@ export const getDefaultFormDataFromPermit = (permit?: Permit | null): AmendPermi * @returns Default form data values */ export const getDefaultFromNullableFormData = ( - permitFormData?: AmendPermitFormData | null + permitFormData?: AmendPermitFormData | null, ): AmendPermitFormData => { // Default form values when permit is not available (or period of time when loading) if (!permitFormData) { @@ -100,66 +122,86 @@ export const getDefaultFromNullableFormData = ( return { ...permitFormData, - previousRevision: getDefaultRequiredVal("", permitFormData.previousRevision), + previousRevision: getDefaultRequiredVal( + "", + permitFormData.previousRevision, + ), comment: getDefaultRequiredVal("", permitFormData.comment), userGuid: getDefaultRequiredVal("", permitFormData.userGuid), documentId: getDefaultRequiredVal("", permitFormData.documentId), permitData: { ...permitFormData.permitData, - companyName: getDefaultRequiredVal("", permitFormData.permitData?.companyName), - clientNumber: getDefaultRequiredVal("", permitFormData.permitData?.clientNumber), + companyName: getDefaultRequiredVal( + "", + permitFormData.permitData?.companyName, + ), + clientNumber: getDefaultRequiredVal( + "", + permitFormData.permitData?.clientNumber, + ), }, }; }; export const arePermitsEqual = ( - permit1?: AmendPermitFormData | null, - permit2?: AmendPermitFormData | null + permit1?: AmendPermitFormData | null, + permit2?: AmendPermitFormData | null, ) => { if (!permit1 && !permit2) return true; // considered equal when both are undefined if (!permit1 || !permit2) return false; // considered not equal when only one is undefined - return permit1.permitId === permit2.permitId - && permit1.originalPermitId === permit2.originalPermitId - && permit1.revision === permit2.revision - && !areValuesDifferent(permit1.previousRevision, permit2.previousRevision) - && !areValuesDifferent(permit1.comment, permit2.comment) - && permit1.permitStatus === permit2.permitStatus - && permit1.companyId === permit2.companyId - && !areValuesDifferent(permit1.userGuid, permit2.userGuid) - && permit1.permitType === permit2.permitType - && permit1.applicationNumber === permit2.applicationNumber - && permit1.permitNumber === permit2.permitNumber - && permit1.permitApprovalSource === permit2.permitApprovalSource - && permit1.permitApplicationOrigin === permit2.permitApplicationOrigin - && !areValuesDifferent(permit1.documentId, permit2.documentId) - && !areValuesDifferent( + return ( + permit1.permitId === permit2.permitId && + permit1.originalPermitId === permit2.originalPermitId && + permit1.revision === permit2.revision && + !areValuesDifferent(permit1.previousRevision, permit2.previousRevision) && + !areValuesDifferent(permit1.comment, permit2.comment) && + permit1.permitStatus === permit2.permitStatus && + permit1.companyId === permit2.companyId && + !areValuesDifferent(permit1.userGuid, permit2.userGuid) && + permit1.permitType === permit2.permitType && + permit1.applicationNumber === permit2.applicationNumber && + permit1.permitNumber === permit2.permitNumber && + permit1.permitApprovalSource === permit2.permitApprovalSource && + permit1.permitApplicationOrigin === permit2.permitApplicationOrigin && + !areValuesDifferent(permit1.documentId, permit2.documentId) && + !areValuesDifferent( applyWhenNotNullable( - dt => dayjsToLocalStr(dt, DATE_FORMATS.DATETIME), - permit1.createdDateTime + (dt) => dayjsToLocalStr(dt, DATE_FORMATS.DATETIME), + permit1.createdDateTime, ), applyWhenNotNullable( - dt => dayjsToLocalStr(dt, DATE_FORMATS.DATETIME), - permit2.createdDateTime - ) - ) - && !areValuesDifferent( + (dt) => dayjsToLocalStr(dt, DATE_FORMATS.DATETIME), + permit2.createdDateTime, + ), + ) && + !areValuesDifferent( applyWhenNotNullable( - dt => dayjsToLocalStr(dt, DATE_FORMATS.DATETIME), - permit1.updatedDateTime - ), + (dt) => dayjsToLocalStr(dt, DATE_FORMATS.DATETIME), + permit1.updatedDateTime, + ), applyWhenNotNullable( - dt => dayjsToLocalStr(dt, DATE_FORMATS.DATETIME), - permit2.updatedDateTime - ) + (dt) => dayjsToLocalStr(dt, DATE_FORMATS.DATETIME), + permit2.updatedDateTime, + ), + ) && + areApplicationDataEqual( + { + ...permit1.permitData, + companyName: getDefaultRequiredVal("", permit1.permitData.companyName), + clientNumber: getDefaultRequiredVal( + "", + permit1.permitData.clientNumber, + ), + }, + { + ...permit2.permitData, + companyName: getDefaultRequiredVal("", permit2.permitData.companyName), + clientNumber: getDefaultRequiredVal( + "", + permit2.permitData.clientNumber, + ), + }, ) - && areApplicationDataEqual({ - ...permit1.permitData, - companyName: getDefaultRequiredVal("", permit1.permitData.companyName), - clientNumber: getDefaultRequiredVal("", permit1.permitData.clientNumber), - }, { - ...permit2.permitData, - companyName: getDefaultRequiredVal("", permit2.permitData.companyName), - clientNumber: getDefaultRequiredVal("", permit2.permitData.clientNumber), - }); + ); }; diff --git a/frontend/src/features/permits/pages/Payment/PaymentFailureRedirect.tsx b/frontend/src/features/permits/pages/Payment/PaymentFailureRedirect.tsx index 28bb97f67..93fadc73c 100644 --- a/frontend/src/features/permits/pages/Payment/PaymentFailureRedirect.tsx +++ b/frontend/src/features/permits/pages/Payment/PaymentFailureRedirect.tsx @@ -2,7 +2,5 @@ import { useParams } from "react-router"; export const PaymentFailureRedirect = () => { const { msg } = useParams(); - return ( -
{msg}
- ); + return
{msg}
; }; diff --git a/frontend/src/features/permits/pages/Payment/PaymentRedirect.tsx b/frontend/src/features/permits/pages/Payment/PaymentRedirect.tsx index 18162217f..15a0c5524 100644 --- a/frontend/src/features/permits/pages/Payment/PaymentRedirect.tsx +++ b/frontend/src/features/permits/pages/Payment/PaymentRedirect.tsx @@ -2,40 +2,48 @@ import { useEffect, useRef } from "react"; import { Navigate, useSearchParams } from "react-router-dom"; import { getPayBCPaymentDetails } from "../../helpers/payment"; -import { CompleteTransactionRequestData, PayBCPaymentDetails } from "../../types/payment"; +import { + CompleteTransactionRequestData, + PayBCPaymentDetails, +} from "../../types/payment"; import { Loading } from "../../../../common/pages/Loading"; import { useCompleteTransaction, useIssuePermits } from "../../hooks/hooks"; import { getDefaultRequiredVal } from "../../../../common/helpers/util"; import { DATE_FORMATS, toUtc } from "../../../../common/helpers/formatDate"; -const PERMIT_ID_DELIM = ',' -const PATH_DELIM = '?' +const PERMIT_ID_DELIM = ","; +const PATH_DELIM = "?"; const getPermitIdsArray = (permitIds?: string | null) => { - return getDefaultRequiredVal("", permitIds).split(PERMIT_ID_DELIM).filter(id => id !== "") -} + return getDefaultRequiredVal("", permitIds) + .split(PERMIT_ID_DELIM) + .filter((id) => id !== ""); +}; export const parseRedirectUriPath = (path?: string | null) => { - const splitPath = path?.split(PATH_DELIM) - let permitIds = '' - let trnApproved = 0 + const splitPath = path?.split(PATH_DELIM); + let permitIds = ""; + let trnApproved = 0; if (splitPath?.[0]) { - permitIds = splitPath[0] + permitIds = splitPath[0]; } if (splitPath?.[1]) { - trnApproved = parseInt(splitPath[1]?.split('=')?.[1]) + trnApproved = parseInt(splitPath[1]?.split("=")?.[1]); } - - return {permitIds, trnApproved} -} -const exportPathFromSearchParams = (params: URLSearchParams, trnApproved: number) => { - const localParams = new URLSearchParams(params) - localParams.delete('path') - const updatedPath = localParams.toString() - return encodeURIComponent(`trnApproved=${trnApproved}&` + updatedPath) -} + return { permitIds, trnApproved }; +}; + +const exportPathFromSearchParams = ( + params: URLSearchParams, + trnApproved: number, +) => { + const localParams = new URLSearchParams(params); + localParams.delete("path"); + const updatedPath = localParams.toString(); + return encodeURIComponent(`trnApproved=${trnApproved}&` + updatedPath); +}; /** * React component that handles the payment redirect and displays the payment status. @@ -43,38 +51,40 @@ const exportPathFromSearchParams = (params: URLSearchParams, trnApproved: number * Otherwise, it displays the payment status message. */ export const PaymentRedirect = () => { - const completedTransaction = useRef(false) - const issuedPermit = useRef(false) - const [searchParams] = useSearchParams() - const paymentDetails = getPayBCPaymentDetails(searchParams) - const transaction = mapTransactionDetails(paymentDetails) - - const path = getDefaultRequiredVal("", searchParams.get("path")) - const {permitIds, trnApproved} = parseRedirectUriPath(path) - const transactionQueryString = exportPathFromSearchParams(searchParams, trnApproved) - const transactionId = getDefaultRequiredVal("", searchParams.get("ref2")) - - const { + const completedTransaction = useRef(false); + const issuedPermit = useRef(false); + const [searchParams] = useSearchParams(); + const paymentDetails = getPayBCPaymentDetails(searchParams); + const transaction = mapTransactionDetails(paymentDetails); + + const path = getDefaultRequiredVal("", searchParams.get("path")); + const { permitIds, trnApproved } = parseRedirectUriPath(path); + const transactionQueryString = exportPathFromSearchParams( + searchParams, + trnApproved, + ); + const transactionId = getDefaultRequiredVal("", searchParams.get("ref2")); + + const { mutation: completeTransactionMutation, paymentApproved, message, setPaymentApproved, } = useCompleteTransaction( paymentDetails.messageText, - paymentDetails.trnApproved - ) + paymentDetails.trnApproved, + ); - const { - mutation: issuePermitsMutation, - issueResults, - } = useIssuePermits() + const { mutation: issuePermitsMutation, issueResults } = useIssuePermits(); const issueFailed = () => { if (!issueResults) return false; // since issue results might not be ready yet - return issueResults.success.length === 0 - || (issueResults.success.length === 1 && issueResults.success[0] === "") - || (issueResults.failure.length > 0 && issueResults.failure[0] !== ""); - } + return ( + issueResults.success.length === 0 || + (issueResults.success.length === 1 && issueResults.success[0] === "") || + (issueResults.failure.length > 0 && issueResults.failure[0] !== "") + ); + }; useEffect(() => { if (completedTransaction.current === false) { @@ -89,51 +99,48 @@ export const PaymentRedirect = () => { setPaymentApproved(false); } } - }, [paymentDetails.trnApproved]) + }, [paymentDetails.trnApproved]); useEffect(() => { if (issuedPermit.current === false) { - const permitIdsArray = getPermitIdsArray(permitIds) + const permitIdsArray = getPermitIdsArray(permitIds); if (paymentApproved === true && permitIdsArray.length > 0) { // Issue permit - issuePermitsMutation.mutate(permitIdsArray) - issuedPermit.current = true + issuePermitsMutation.mutate(permitIdsArray); + issuedPermit.current = true; } } - }, [paymentApproved, permitIds]) + }, [paymentApproved, permitIds]); if (paymentApproved === false) { - return ( - - ) + return ; } - + if (issueResults) { if (issueFailed()) { - const permitIssueFailedMsg = `Permit issue failed for ids ${issueResults.failure.join(",")}`; + const permitIssueFailedMsg = `Permit issue failed for ids ${issueResults.failure.join( + ",", + )}`; return ( - ); } return ( - ); - } + } - return + return ; }; const mapTransactionDetails = ( - paymentResponse: PayBCPaymentDetails + paymentResponse: PayBCPaymentDetails, ): CompleteTransactionRequestData => { return { pgTransactionId: paymentResponse.trnId, @@ -145,5 +152,5 @@ const mapTransactionDetails = ( pgPaymentMethod: paymentResponse.paymentMethod, pgMessageId: Number(paymentResponse.messageId), pgMessageText: paymentResponse.messageText, - } -} + }; +}; diff --git a/frontend/src/features/permits/pages/Refund/RefundPage.tsx b/frontend/src/features/permits/pages/Refund/RefundPage.tsx index d22114524..e90498a98 100644 --- a/frontend/src/features/permits/pages/Refund/RefundPage.tsx +++ b/frontend/src/features/permits/pages/Refund/RefundPage.tsx @@ -1,9 +1,9 @@ import { useState, useEffect } from "react"; import { Controller, FormProvider, useForm } from "react-hook-form"; -import { - Button, - FormControl, - FormControlLabel, +import { + Button, + FormControl, + FormControlLabel, RadioGroup, Radio, FormLabel, @@ -16,7 +16,11 @@ import { import "./RefundPage.scss"; import { permitTypeDisplayText } from "../../types/PermitType"; import { RefundFormData } from "./types/RefundFormData"; -import { REFUND_METHODS, getRefundMethodByCardType, refundMethodDisplayText } from "../../types/PaymentMethod"; +import { + REFUND_METHODS, + getRefundMethodByCardType, + refundMethodDisplayText, +} from "../../types/PaymentMethod"; import { requiredMessage } from "../../../../common/helpers/validationMessages"; import { getErrorMessage } from "../../../../common/components/form/CustomFormComponents"; import { PermitHistory } from "../../types/PermitHistory"; @@ -39,15 +43,20 @@ const permitActionText = (permitAction: PermitAction) => { const transactionIdRules = { validate: { - requiredWhenSelected: (value: string | undefined, formValues: RefundFormData) => { - return !formValues.shouldUsePrevPaymentMethod - || (value != null && value.trim() !== "") - || requiredMessage(); - } + requiredWhenSelected: ( + value: string | undefined, + formValues: RefundFormData, + ) => { + return ( + !formValues.shouldUsePrevPaymentMethod || + (value != null && value.trim() !== "") || + requiredMessage() + ); + }, }, }; -const refundOptions = Object.values(REFUND_METHODS).map(refundMethod => ({ +const refundOptions = Object.values(REFUND_METHODS).map((refundMethod) => ({ value: refundMethod, label: refundMethodDisplayText(refundMethod), })); @@ -75,10 +84,12 @@ export const RefundPage = ({ amountToRefund: number; onFinish: (refundData: RefundFormData) => void; }) => { - const [shouldUsePrevPaymentMethod, setShouldUsePrevPaymentMethod] = useState(true); + const [shouldUsePrevPaymentMethod, setShouldUsePrevPaymentMethod] = + useState(true); const getRefundMethodForPrevPayMethod = () => { - if (!permitHistory || permitHistory.length === 0) return DEFAULT_REFUND_METHOD; + if (!permitHistory || permitHistory.length === 0) + return DEFAULT_REFUND_METHOD; const cardType = permitHistory[0].pgCardType; return getRefundMethodByCardType(cardType); }; @@ -104,11 +115,11 @@ export const RefundPage = ({ reValidateMode: "onChange", }); - const { - control, - getValues, - handleSubmit, - setValue, + const { + control, + getValues, + handleSubmit, + setValue, formState: { errors }, register, clearErrors, @@ -125,7 +136,10 @@ export const RefundPage = ({ const usePrev = shouldUsePrev === "true"; setShouldUsePrevPaymentMethod(usePrev); setValue("shouldUsePrevPaymentMethod", usePrev); - setValue("refundMethod", usePrev ? getRefundMethodForPrevPayMethod() : REFUND_METHODS.Cheque); + setValue( + "refundMethod", + usePrev ? getRefundMethodForPrevPayMethod() : REFUND_METHODS.Cheque, + ); setValue("refundCardType", usePrev ? getRefundCardType() : ""); setValue("refundOnlineMethod", usePrev ? getRefundOnlineMethod() : ""); clearErrors("transactionId"); @@ -137,7 +151,8 @@ export const RefundPage = ({ }; const showSendSection = permitAction === "void" || permitAction === "revoke"; - const showReasonSection = (permitAction === "void" || permitAction === "revoke") && reason; + const showReasonSection = + (permitAction === "void" || permitAction === "revoke") && reason; // only show refund method selection when amount to refund is greater than 0 // we use a small epsilon since there may be decimal precision errors when doing decimal comparisons @@ -147,12 +162,8 @@ export const RefundPage = ({
-
- Transaction History -
- +
Transaction History
+
{showSendSection ? (
@@ -162,10 +173,7 @@ export const RefundPage = ({ {email ? (
Email: - + {email}
@@ -173,10 +181,7 @@ export const RefundPage = ({ {fax ? (
Fax: - + {fax}
@@ -185,19 +190,17 @@ export const RefundPage = ({ ) : null} {showReasonSection ? (
-
Reason for {permitActionText(permitAction)}
-
- {reason} +
+ Reason for {permitActionText(permitAction)}
+
{reason}
) : null}
{enableRefundSelection ? (
-
- Choose a Refund Method -
+
Choose a Refund Method
handleRefundMethodChange(e.target.value)} > -
- } + control={} />
( + render={({ field: { value } }) => ( Payment Method @@ -236,8 +239,8 @@ export const RefundPage = ({ disabled={true} value={value} > - {refundOptions.map(refundOption => ( - ( + @@ -253,8 +256,11 @@ export const RefundPage = ({ name="transactionId" control={control} rules={transactionIdRules} - render={({ field: { value }, fieldState: { invalid } }) => ( - ( + @@ -262,12 +268,17 @@ export const RefundPage = ({ Transaction ID {invalid ? ( - @@ -279,18 +290,18 @@ export const RefundPage = ({ />
-
- } + control={} />
@@ -307,11 +318,7 @@ export const RefundPage = ({
{permitActionText(permitAction)} Permit #: - - {permitNumber} - + {permitNumber}
-
- +
@@ -240,6 +242,6 @@ export const VoidPermitForm = ({ /> ) : null}
- + ); }; diff --git a/frontend/src/features/permits/pages/Void/components/VoidPermitHeader.tsx b/frontend/src/features/permits/pages/Void/components/VoidPermitHeader.tsx index 459ffbe78..90e1b0571 100644 --- a/frontend/src/features/permits/pages/Void/components/VoidPermitHeader.tsx +++ b/frontend/src/features/permits/pages/Void/components/VoidPermitHeader.tsx @@ -2,15 +2,14 @@ import { Box, Typography } from "@mui/material"; import "./VoidPermitHeader.scss"; import { Permit } from "../../../types/permit"; -import { DATE_FORMATS, toLocal } from "../../../../../common/helpers/formatDate"; +import { + DATE_FORMATS, + toLocal, +} from "../../../../../common/helpers/formatDate"; import { CompanyBanner } from "../../../../../common/components/banners/CompanyBanner"; import { permitTypeDisplayText } from "../../../types/PermitType"; -export const VoidPermitHeader = ({ - permit, -}: { - permit: Permit | null; -}) => { +export const VoidPermitHeader = ({ permit }: { permit: Permit | null }) => { return permit ? (
- + Voiding Permit #: - - + + - + Permit Start Date: - {toLocal(permit.permitData.startDate, DATE_FORMATS.DATEONLY_ABBR_MONTH)} + {toLocal( + permit.permitData.startDate, + DATE_FORMATS.DATEONLY_ABBR_MONTH, + )} - + Permit End Date: - {toLocal(permit.permitData.expiryDate, DATE_FORMATS.DATEONLY_ABBR_MONTH)} + {toLocal( + permit.permitData.expiryDate, + DATE_FORMATS.DATEONLY_ABBR_MONTH, + )} {permit.permitData.vehicleDetails?.plate ? ( - + Plate #: ) : null} - + {permit.permitData.clientNumber && permit.permitData.companyName ? ( { return { status: PERMIT_STATUSES.REVOKED, @@ -18,7 +18,7 @@ export const mapToRevokeRequestData = ( }; export const mapToVoidRequestData = ( - voidPermitFormData: VoidPermitFormData, + voidPermitFormData: VoidPermitFormData, refundData: RefundFormData, amountToRefund: number, ): VoidPermitRequestData => { @@ -27,8 +27,12 @@ export const mapToVoidRequestData = ( pgTransactionId: refundData.transactionId, paymentMethodId: "1", // hardcoded to "1" - Web transactionAmount: amountToRefund, - pgPaymentMethod: refundData.refundOnlineMethod ? refundData.refundOnlineMethod : undefined, - pgCardType: refundData.refundCardType ? refundData.refundCardType : undefined, + pgPaymentMethod: refundData.refundOnlineMethod + ? refundData.refundOnlineMethod + : undefined, + pgCardType: refundData.refundCardType + ? refundData.refundCardType + : undefined, comment: voidPermitFormData.reason, }; }; diff --git a/frontend/src/features/permits/pages/Void/hooks/useVoidPermit.ts b/frontend/src/features/permits/pages/Void/hooks/useVoidPermit.ts index 04af23140..6face18b5 100644 --- a/frontend/src/features/permits/pages/Void/hooks/useVoidPermit.ts +++ b/frontend/src/features/permits/pages/Void/hooks/useVoidPermit.ts @@ -5,7 +5,9 @@ import { VoidPermitResponseData } from "../types/VoidPermit"; import { voidPermit } from "../../../apiManager/permitsAPI"; export const useVoidPermit = () => { - const [voidResults, setVoidResults] = useState(undefined); + const [voidResults, setVoidResults] = useState< + VoidPermitResponseData | undefined + >(undefined); const queryClient = useQueryClient(); diff --git a/frontend/src/features/permits/pages/Void/hooks/useVoidPermitForm.ts b/frontend/src/features/permits/pages/Void/hooks/useVoidPermitForm.ts index 1c472b1d7..d269b1265 100644 --- a/frontend/src/features/permits/pages/Void/hooks/useVoidPermitForm.ts +++ b/frontend/src/features/permits/pages/Void/hooks/useVoidPermitForm.ts @@ -6,11 +6,8 @@ import { VoidPermitFormData } from "../types/VoidPermit"; import { VoidPermitContext } from "../context/VoidPermitContext"; export const useVoidPermitForm = () => { - const { - voidPermitData, - setVoidPermitData, - next, - } = useContext(VoidPermitContext); + const { voidPermitData, setVoidPermitData, next } = + useContext(VoidPermitContext); const defaultFormData = { permitId: voidPermitData.permitId, diff --git a/frontend/src/features/permits/types/PaymentMethod.ts b/frontend/src/features/permits/types/PaymentMethod.ts index 8f3a0e0c9..9408c2cd0 100644 --- a/frontend/src/features/permits/types/PaymentMethod.ts +++ b/frontend/src/features/permits/types/PaymentMethod.ts @@ -22,7 +22,8 @@ export const PAYMENT_METHODS = { WebVisaDebit: "WebVisaDebit", } as const; -export type PaymentMethod = typeof PAYMENT_METHODS[keyof typeof PAYMENT_METHODS]; +export type PaymentMethod = + (typeof PAYMENT_METHODS)[keyof typeof PAYMENT_METHODS]; export const REFUND_METHODS = { Cheque: "Cheque", @@ -35,7 +36,7 @@ export const REFUND_METHODS = { PPCVisaDebit: "PPCVisaDebit", } as const; -export type RefundMethod = typeof REFUND_METHODS[keyof typeof REFUND_METHODS]; +export type RefundMethod = (typeof REFUND_METHODS)[keyof typeof REFUND_METHODS]; export const paymentMethodDisplayText = (paymentMethod: PaymentMethod) => { switch (paymentMethod) { @@ -105,14 +106,19 @@ export const refundMethodDisplayText = (refundMethod: RefundMethod) => { } }; -export const mapPaymentMethodToRefundMethods = (paymentMethod: PaymentMethod, useCreditAccount?: boolean): RefundMethod => { +export const mapPaymentMethodToRefundMethods = ( + paymentMethod: PaymentMethod, + useCreditAccount?: boolean, +): RefundMethod => { switch (paymentMethod) { - case PAYMENT_METHODS.Cash: + case PAYMENT_METHODS.Cash: case PAYMENT_METHODS.Cheque: case PAYMENT_METHODS.GA: return REFUND_METHODS.Cheque; case PAYMENT_METHODS.CreditAccount: - return useCreditAccount ? REFUND_METHODS.CreditAccount : REFUND_METHODS.Cheque; + return useCreditAccount + ? REFUND_METHODS.CreditAccount + : REFUND_METHODS.Cheque; case PAYMENT_METHODS.IcepayAMEX: case PAYMENT_METHODS.PoSAMEX: case PAYMENT_METHODS.WebAMEX: @@ -144,7 +150,8 @@ export const BAMBORA_PAYMENT_METHODS = { IO: "IO", // Interac Online Transaction } as const; -export type BamboraPaymentMethod = typeof BAMBORA_PAYMENT_METHODS[keyof typeof BAMBORA_PAYMENT_METHODS]; +export type BamboraPaymentMethod = + (typeof BAMBORA_PAYMENT_METHODS)[keyof typeof BAMBORA_PAYMENT_METHODS]; export const CARD_TYPES = { VI: "VI", // Visa @@ -155,13 +162,13 @@ export const CARD_TYPES = { IO: "IO", // Interac Online } as const; -export type CardType = typeof CARD_TYPES[keyof typeof CARD_TYPES]; +export type CardType = (typeof CARD_TYPES)[keyof typeof CARD_TYPES]; // Incomplete, needs to confirm and change database schema for payment methods // since it's insufficient to determine payment method through Bambora payment method and card type alone export const getPaymentMethod = ( - payMethod?: BamboraPaymentMethod | null, - cardType?: CardType | null + payMethod?: BamboraPaymentMethod | null, + cardType?: CardType | null, ): PaymentMethod | undefined => { if (payMethod !== BAMBORA_PAYMENT_METHODS.CC) { return undefined; // Could be either cash, cheque, GA, Credit Account, or Interac/Debit @@ -180,11 +187,13 @@ export const getPaymentMethod = ( case CARD_TYPES.VI: return PAYMENT_METHODS.WebVisa; default: - return undefined; // unknown value for Interac payment + return undefined; // unknown value for Interac payment } }; -export const getRefundMethodByCardType = (cardType?: CardType | null): RefundMethod => { +export const getRefundMethodByCardType = ( + cardType?: CardType | null, +): RefundMethod => { switch (cardType) { case CARD_TYPES.AM: return REFUND_METHODS.PPCAMEX; diff --git a/frontend/src/features/permits/types/PermitStatus.ts b/frontend/src/features/permits/types/PermitStatus.ts index ef21ae0b2..b286e36e9 100644 --- a/frontend/src/features/permits/types/PermitStatus.ts +++ b/frontend/src/features/permits/types/PermitStatus.ts @@ -2,7 +2,7 @@ export const PERMIT_STATUSES = { APPROVED: "APPROVED", AUTO_APPROVED: "AUTO_APPROVED", CANCELLED: "CANCELLED", - IN_PROGRESS: "IN_PROGRESS", + IN_PROGRESS: "IN_PROGRESS", REJECTED: "REJECTED", UNDER_REVIEW: "UNDER_REVIEW", WAITING_APPROVAL: "WAITING_APPROVAL", @@ -15,10 +15,13 @@ export const PERMIT_STATUSES = { export const PERMIT_EXPIRED = "EXPIRED"; -export type PermitStatus = typeof PERMIT_STATUSES[keyof typeof PERMIT_STATUSES]; +export type PermitStatus = + (typeof PERMIT_STATUSES)[keyof typeof PERMIT_STATUSES]; export const isPermitInactive = (permitStatus?: string) => { - return permitStatus === PERMIT_STATUSES.VOIDED - || permitStatus === PERMIT_STATUSES.REVOKED - || permitStatus === PERMIT_STATUSES.SUPERSEDED; + return ( + permitStatus === PERMIT_STATUSES.VOIDED || + permitStatus === PERMIT_STATUSES.REVOKED || + permitStatus === PERMIT_STATUSES.SUPERSEDED + ); }; diff --git a/frontend/src/features/permits/types/PermitType.ts b/frontend/src/features/permits/types/PermitType.ts index 3c752ef0c..0204ffdec 100644 --- a/frontend/src/features/permits/types/PermitType.ts +++ b/frontend/src/features/permits/types/PermitType.ts @@ -24,7 +24,7 @@ export const PERMIT_TYPES = { TROW: "TROW", } as const; -export type PermitType = typeof PERMIT_TYPES[keyof typeof PERMIT_TYPES]; +export type PermitType = (typeof PERMIT_TYPES)[keyof typeof PERMIT_TYPES]; /** * Returns the name/description of the permit type. diff --git a/frontend/src/features/permits/types/application.d.ts b/frontend/src/features/permits/types/application.d.ts index cc729d766..9a806d758 100644 --- a/frontend/src/features/permits/types/application.d.ts +++ b/frontend/src/features/permits/types/application.d.ts @@ -9,7 +9,8 @@ export const PERMIT_APPLICATION_ORIGINS = { PPC: "PPC", } as const; -export type PermitApplicationOrigin = typeof PERMIT_APPLICATION_ORIGINS[keyof typeof PERMIT_APPLICATION_ORIGINS]; +export type PermitApplicationOrigin = + (typeof PERMIT_APPLICATION_ORIGINS)[keyof typeof PERMIT_APPLICATION_ORIGINS]; export const PERMIT_APPROVAL_SOURCES = { AUTO: "AUTO", @@ -17,10 +18,11 @@ export const PERMIT_APPROVAL_SOURCES = { TPS: "TPS", } as const; -export type PermitApprovalSource = typeof PERMIT_APPROVAL_SOURCES[keyof typeof PERMIT_APPROVAL_SOURCES]; +export type PermitApprovalSource = + (typeof PERMIT_APPROVAL_SOURCES)[keyof typeof PERMIT_APPROVAL_SOURCES]; /** - * A partial permit type that consists of all common fields used for a permit. + * A partial permit type that consists of all common fields used for a permit. * This is an incomplete type and meant to be extended for use. */ interface PartialApplication { @@ -55,21 +57,27 @@ export interface Application extends PartialApplication { /** * Type that replaces all Dayjs types inside direct PermitData entries to string types - * - * eg. PermitData = { c?: Dayjs }, - * + * + * eg. PermitData = { c?: Dayjs }, + * * and T = { a: number, b: PermitData }, - * + * * then TransformPermitData = { a: number, b: { c?: string } } */ type TransformPermitData = { - [K in keyof T]: T[K] extends PermitData ? ReplaceDayjsWithString : T[K]; + [K in keyof T]: T[K] extends PermitData + ? ReplaceDayjsWithString + : T[K]; }; // These two types are used to transform an application data response object (with strings as date fields) to Application type (with Dayjs as date fields) // and vice versa (Application type to application data request data object with strings as date fields) -export type ApplicationResponse = TransformPermitData>; -export type ApplicationRequestData = TransformPermitData>; +export type ApplicationResponse = TransformPermitData< + ReplaceDayjsWithString +>; +export type ApplicationRequestData = TransformPermitData< + ReplaceDayjsWithString +>; export interface MailingAddress { addressLine1: string; @@ -125,20 +133,19 @@ export interface PermitData { clientNumber?: string; } -export interface PermitApplicationInProgress extends Omit< - ReplaceDayjsWithString< - Required - >, - "originalPermitId" | - "comment" | - "permitApplicationOrigin" | - "permitApprovalSource" | - "permitNumber" | - "permitStatus" | - "documentId" | - "revision" | - "previousRevision" -> { +export interface PermitApplicationInProgress + extends Omit< + ReplaceDayjsWithString>, + | "originalPermitId" + | "comment" + | "permitApplicationOrigin" + | "permitApprovalSource" + | "permitNumber" + | "permitStatus" + | "documentId" + | "revision" + | "previousRevision" + > { permitApplicationOrigin?: PermitApplicationOrigin | null; permitApprovalSource?: PermitApprovalSource | null; permitData: ReplaceDayjsWithString; diff --git a/frontend/src/features/permits/types/payment.d.ts b/frontend/src/features/permits/types/payment.d.ts index 83988ef5d..f78e959f2 100644 --- a/frontend/src/features/permits/types/payment.d.ts +++ b/frontend/src/features/permits/types/payment.d.ts @@ -56,15 +56,16 @@ export interface PermitTransaction { export const TRANSACTION_TYPES = { P: "P", R: "R", - VP: "VP", - VR: "VR", - PA: "PA", - PAC: "PAC", + VP: "VP", + VR: "VR", + PA: "PA", + PAC: "PAC", Q: "Q", Z: "Z", } as const; -export type TransactionType = typeof TRANSACTION_TYPES[keyof typeof TRANSACTION_TYPES]; +export type TransactionType = + (typeof TRANSACTION_TYPES)[keyof typeof TRANSACTION_TYPES]; export interface PaymentGatewayData { pgTransactionId: string; @@ -78,7 +79,8 @@ export interface PaymentGatewayData { pgMessageText: string; } -export interface StartTransactionRequestData extends Partial { +export interface StartTransactionRequestData + extends Partial { transactionTypeId: TransactionType; paymentMethodId: string; applicationDetails: { @@ -87,7 +89,8 @@ export interface StartTransactionRequestData extends Partial }[]; } -export interface StartTransactionResponseData extends Partial { +export interface StartTransactionResponseData + extends Partial { transactionId: string; transactionTypeId: TransactionType; paymentMethodId: string; @@ -103,6 +106,7 @@ export interface StartTransactionResponseData extends Partial; -export interface CompleteTransactionResponseData extends Partial { +export interface CompleteTransactionResponseData + extends Partial { transactionid: string; } diff --git a/frontend/src/features/permits/types/permit.d.ts b/frontend/src/features/permits/types/permit.d.ts index aa57ae278..9dbb05a48 100644 --- a/frontend/src/features/permits/types/permit.d.ts +++ b/frontend/src/features/permits/types/permit.d.ts @@ -1,17 +1,15 @@ import { ReplaceDayjsWithString } from "./utility"; -import { - PartialApplication, - PermitData, -} from "./application"; +import { PartialApplication, PermitData } from "./application"; /** - * A partial permit type that consists of all common fields used for a permit. + * A partial permit type that consists of all common fields used for a permit. * This is an incomplete type and meant to be extended for use. */ -interface PartialPermit extends Omit< - Required, - "previousRevision" | "comment" | "userGuid" | "documentId" | "permitId" -> { +interface PartialPermit + extends Omit< + Required, + "previousRevision" | "comment" | "userGuid" | "documentId" | "permitId" + > { previousRevision?: number | null; comment?: string | null; userGuid?: string | null; @@ -22,7 +20,7 @@ interface PartialPermit extends Omit< /** * The request/response object structure to describe the permit object, * and used with the permit API. - * + * * This type is mostly used as a data transfer object (DTO) to pass permit objects * between frontend and backend, and also used on the frontend for permit-related logic. */ diff --git a/frontend/src/features/permits/types/utility.ts b/frontend/src/features/permits/types/utility.ts index 7bdda9f54..4effc95dd 100644 --- a/frontend/src/features/permits/types/utility.ts +++ b/frontend/src/features/permits/types/utility.ts @@ -15,8 +15,8 @@ export type ReplaceDayjsWithString = { [K in keyof T]: T[K] extends Dayjs ? string : T[K] extends Dayjs | undefined - ? string | undefined - : T[K]; + ? string | undefined + : T[K]; }; /** @@ -32,8 +32,11 @@ export type ReplaceDayjsWithString = { * then DateStringToDayjs = { a?: Dayjs, b: number } */ export type DateStringToDayjs = { - [K in keyof T]: K extends Fields - ? T[K] extends string ? Dayjs : T[K] extends string | undefined - ? Dayjs | undefined : T[K] + [K in keyof T]: K extends Fields + ? T[K] extends string + ? Dayjs + : T[K] extends string | undefined + ? Dayjs | undefined + : T[K] : T[K]; }; diff --git a/frontend/src/features/wizard/components/dashboard/CreateProfileSteps.tsx b/frontend/src/features/wizard/components/dashboard/CreateProfileSteps.tsx index f9dbc5e28..33b6e5244 100644 --- a/frontend/src/features/wizard/components/dashboard/CreateProfileSteps.tsx +++ b/frontend/src/features/wizard/components/dashboard/CreateProfileSteps.tsx @@ -91,7 +91,7 @@ const isSubmissionSuccessful = (status: number) => status === 201 || status === 200; const hasValidationErrors = (status: number) => status === 400; const getFirstValidationError = ( - errors: { field: string; message: string[] }[] + errors: { field: string; message: string[] }[], ) => { if (errors.length === 0 || errors[0].message.length === 0) return undefined; return `${getSectionNameByField(errors[0].field)} validation error: ${ @@ -124,7 +124,7 @@ export const CreateProfileSteps = React.memo(() => { defaultValues: { legalName: getDefaultRequiredVal( "", - user?.profile?.bceid_business_name as string + user?.profile?.bceid_business_name as string, ), mailingAddress: { addressLine1: "", @@ -202,7 +202,7 @@ export const CreateProfileSteps = React.memo(() => { } else if (hasValidationErrors(response.status)) { const { error } = response.data; const firstErrMsg = getFirstValidationError( - getDefaultRequiredVal([], error) + getDefaultRequiredVal([], error), ); if (firstErrMsg) { setSnackBar({ @@ -315,7 +315,7 @@ export const CreateProfileSteps = React.memo(() => { diff --git a/frontend/src/features/wizard/pages/OnRouteBCProfileCreated.tsx b/frontend/src/features/wizard/pages/OnRouteBCProfileCreated.tsx index 1da450432..5b124642a 100644 --- a/frontend/src/features/wizard/pages/OnRouteBCProfileCreated.tsx +++ b/frontend/src/features/wizard/pages/OnRouteBCProfileCreated.tsx @@ -56,7 +56,7 @@ export const OnRouteBCProfileCreated = memo(
); - } + }, ); OnRouteBCProfileCreated.displayName = "OnRouteBCProfileCreated"; diff --git a/frontend/src/features/wizard/pages/UserInformationWizardForm.tsx b/frontend/src/features/wizard/pages/UserInformationWizardForm.tsx index 12c51b390..df0171f79 100644 --- a/frontend/src/features/wizard/pages/UserInformationWizardForm.tsx +++ b/frontend/src/features/wizard/pages/UserInformationWizardForm.tsx @@ -4,14 +4,14 @@ import isEmail from "validator/lib/isEmail"; import "./UserInformationWizardForm.scss"; import { CustomFormComponent } from "../../../common/components/form/CustomFormComponents"; import { CountryAndProvince } from "../../../common/components/form/CountryAndProvince"; -import { - invalidCityLength, - invalidEmail, - invalidExtensionLength, - invalidFirstNameLength, - invalidLastNameLength, - invalidPhoneLength, - requiredMessage +import { + invalidCityLength, + invalidEmail, + invalidExtensionLength, + invalidFirstNameLength, + invalidLastNameLength, + invalidPhoneLength, + requiredMessage, } from "../../../common/helpers/validationMessages"; /** @@ -34,8 +34,8 @@ export const UserInformationWizardForm = memo(() => { required: { value: true, message: requiredMessage() }, validate: { validateFirstName: (firstName: string) => - (firstName.length >= 1 && firstName.length <= 100) - || invalidFirstNameLength(1, 100), + (firstName.length >= 1 && firstName.length <= 100) || + invalidFirstNameLength(1, 100), }, }, label: "First Name", @@ -51,8 +51,8 @@ export const UserInformationWizardForm = memo(() => { required: { value: true, message: requiredMessage() }, validate: { validateLastName: (lastName: string) => - (lastName.length >= 1 && lastName.length <= 100) - || invalidLastNameLength(1, 100), + (lastName.length >= 1 && lastName.length <= 100) || + invalidLastNameLength(1, 100), }, }, label: "Last Name", @@ -89,8 +89,8 @@ export const UserInformationWizardForm = memo(() => { }, validate: { validatePhone1: (phone: string) => - (phone.length >= 10 && phone.length <= 20) - || invalidPhoneLength(10, 20), + (phone.length >= 10 && phone.length <= 20) || + invalidPhoneLength(10, 20), }, }, label: "Primary Phone", @@ -102,13 +102,14 @@ export const UserInformationWizardForm = memo(() => { feature={FEATURE} options={{ name: "adminUser.phone1Extension", - rules: { + rules: { required: false, validate: { validateExt1: (ext?: string) => - (ext == null || ext === "") - || (ext != null && ext !== "" && ext.length <= 5) - || invalidExtensionLength(5), + ext == null || + ext === "" || + (ext != null && ext !== "" && ext.length <= 5) || + invalidExtensionLength(5), }, }, label: "Ext", @@ -122,13 +123,17 @@ export const UserInformationWizardForm = memo(() => { feature={FEATURE} options={{ name: "adminUser.phone2", - rules: { + rules: { required: false, validate: { validatePhone2: (phone2?: string) => - (phone2 == null || phone2 === "") - || (phone2 != null && phone2 !== "" && phone2.length >= 10 && phone2.length <= 20) - || invalidPhoneLength(10, 20), + phone2 == null || + phone2 === "" || + (phone2 != null && + phone2 !== "" && + phone2.length >= 10 && + phone2.length <= 20) || + invalidPhoneLength(10, 20), }, }, label: "Alternate Phone", @@ -140,13 +145,14 @@ export const UserInformationWizardForm = memo(() => { feature={FEATURE} options={{ name: "adminUser.phone2Extension", - rules: { + rules: { required: false, validate: { validateExt2: (ext?: string) => - (ext == null || ext === "") - || (ext != null && ext !== "" && ext.length <= 5) - || invalidExtensionLength(5), + ext == null || + ext === "" || + (ext != null && ext !== "" && ext.length <= 5) || + invalidExtensionLength(5), }, }, label: "Ext", @@ -159,13 +165,17 @@ export const UserInformationWizardForm = memo(() => { feature={FEATURE} options={{ name: "adminUser.fax", - rules: { + rules: { required: false, validate: { validateFax: (fax?: string) => - (fax == null || fax === "") - || (fax != null && fax !== "" && fax.length >= 10 && fax.length <= 20) - || invalidPhoneLength(10, 20), + fax == null || + fax === "" || + (fax != null && + fax !== "" && + fax.length >= 10 && + fax.length <= 20) || + invalidPhoneLength(10, 20), }, }, label: "Fax", @@ -190,8 +200,8 @@ export const UserInformationWizardForm = memo(() => { required: { value: true, message: requiredMessage() }, validate: { validateCity: (city: string) => - (city.length >= 1 && city.length <= 100) - || invalidCityLength(1, 100), + (city.length >= 1 && city.length <= 100) || + invalidCityLength(1, 100), }, }, label: "City", diff --git a/frontend/src/index.tsx b/frontend/src/index.tsx index 46f94a9f9..492e5da57 100644 --- a/frontend/src/index.tsx +++ b/frontend/src/index.tsx @@ -1,16 +1,16 @@ -import React from 'react'; -import ReactDOM from 'react-dom/client'; -import App from './App'; +import React from "react"; +import ReactDOM from "react-dom/client"; +import App from "./App"; // Import Styles -import './index.scss'; -import '@bcgov/bc-sans/css/BCSans.css'; +import "./index.scss"; +import "@bcgov/bc-sans/css/BCSans.css"; const root = ReactDOM.createRoot( - document.getElementById('root') as HTMLElement + document.getElementById("root") as HTMLElement, ); root.render( - + , ); diff --git a/frontend/src/routes/ProtectedRoutes.tsx b/frontend/src/routes/ProtectedRoutes.tsx index 39468bec7..cfcf731c1 100644 --- a/frontend/src/routes/ProtectedRoutes.tsx +++ b/frontend/src/routes/ProtectedRoutes.tsx @@ -47,9 +47,15 @@ export const ProtectedRoutes = ({ if (isIDIR(userIDP) && !idirUserDetails?.userAuthGroup) { if (typeof userRoles !== "undefined" && !userRoles) { // user roles is null, indicating an error occurred fetching roles (eg. user with no roles, 403) - return ; + return ( + + ); } - + return ( <> diff --git a/frontend/src/routes/Routes.tsx b/frontend/src/routes/Routes.tsx index e4a661eae..56ffff1d8 100644 --- a/frontend/src/routes/Routes.tsx +++ b/frontend/src/routes/Routes.tsx @@ -32,7 +32,10 @@ export const AppRoutes = () => { } /> } /> } /> - } /> + } + /> } /> {/* IDIR Routes */} @@ -88,7 +91,10 @@ export const AppRoutes = () => { }> } /> - } /> + } + /> }> { }> - } + element={} /> - } /> diff --git a/frontend/src/routes/constants.tsx b/frontend/src/routes/constants.tsx index c1173c8f8..c1863fce4 100644 --- a/frontend/src/routes/constants.tsx +++ b/frontend/src/routes/constants.tsx @@ -34,4 +34,4 @@ export const IDIR_WELCOME = `/${IDPS.IDIR}/welcome`; export const SEARCH_RESULTS = `/${IDPS.IDIR}/search-results`; // Payment -export const PAYMENT_REDIRECT = "payment" +export const PAYMENT_REDIRECT = "payment"; diff --git a/frontend/src/themes/bcGovTheme.ts b/frontend/src/themes/bcGovTheme.ts index 326ccba2c..7557173ee 100644 --- a/frontend/src/themes/bcGovTheme.ts +++ b/frontend/src/themes/bcGovTheme.ts @@ -21,7 +21,7 @@ export const bcGovTheme = createTheme({ textTransform: "none", }, fontFamily: ["BCSans", "Noto Sans", "Verdana", "Arial", "sans-serif"].join( - "," + ",", ), fontSize: 16, body1: { diff --git a/frontend/src/vite-env.d.ts b/frontend/src/vite-env.d.ts index 151aa6856..11f02fe2a 100644 --- a/frontend/src/vite-env.d.ts +++ b/frontend/src/vite-env.d.ts @@ -1 +1 @@ -/// \ No newline at end of file +///