Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat(driving-license): start on advanced driving-license #16647

Open
wants to merge 4 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from 3 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,7 @@ export const Alert: FC<React.PropsWithChildren<Props>> = ({
}) => {
const { formatMessage } = useLocale()
const { title, type, message, heading } = field.props as Field
console.log('message', formatText(message, application, formatMessage))

return (
<Box justifyContent={'spaceBetween'}>
{heading && (
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,157 @@
import React, { FC, useEffect, useState } from 'react'

import { Box, Checkbox, ErrorMessage, Text } from '@island.is/island-ui/core'
import { FieldBaseProps } from '@island.is/application/types'
import { useFormContext } from 'react-hook-form'
import {
organizedAdvancedLicenseMap,
AdvancedLicense as AdvancedLicenseEnum,
} from '../../lib/constants'
import { useLocale } from '@island.is/localization'
import { m } from '../../lib/messages'
import { joinWithAnd } from '../../lib/utils'

const AdvancedLicense: FC<React.PropsWithChildren<FieldBaseProps>> = ({
errors,
}) => {
const { formatMessage } = useLocale()
const { setValue, watch } = useFormContext()

const requiredMessage = (errors as { advancedLicense?: string })
?.advancedLicense
? formatMessage(m.applicationForAdvancedRequiredError)
: ''

const advancedLicenseValue = watch('advancedLicense') ?? []

const [selectedLicenses, setSelectedLicenses] =
useState<Array<keyof typeof AdvancedLicenseEnum>>(advancedLicenseValue)

useEffect(() => {
setValue('advancedLicense', selectedLicenses)
}, [selectedLicenses, setValue])
Comment on lines +25 to +32
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🛠️ Refactor suggestion

Optimize hook usage to prevent unnecessary rerenders.

The current implementation could cause unnecessary rerenders due to the watch hook and effect combination.

-const advancedLicenseValue = watch('advancedLicense') ?? []
+const advancedLicenseValue = watch('advancedLicense', [])

-useEffect(() => {
-  setValue('advancedLicense', selectedLicenses)
-}, [selectedLicenses, setValue])
+useEffect(() => {
+  if (JSON.stringify(advancedLicenseValue) !== JSON.stringify(selectedLicenses)) {
+    setValue('advancedLicense', selectedLicenses, { shouldDirty: true })
+  }
+}, [selectedLicenses, setValue, advancedLicenseValue])
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
const advancedLicenseValue = watch('advancedLicense') ?? []
const [selectedLicenses, setSelectedLicenses] =
useState<Array<keyof typeof AdvancedLicenseEnum>>(advancedLicenseValue)
useEffect(() => {
setValue('advancedLicense', selectedLicenses)
}, [selectedLicenses, setValue])
const advancedLicenseValue = watch('advancedLicense', [])
const [selectedLicenses, setSelectedLicenses] =
useState<Array<keyof typeof AdvancedLicenseEnum>>(advancedLicenseValue)
useEffect(() => {
if (JSON.stringify(advancedLicenseValue) !== JSON.stringify(selectedLicenses)) {
setValue('advancedLicense', selectedLicenses, { shouldDirty: true })
}
}, [selectedLicenses, setValue, advancedLicenseValue])


return (
<Box>
{Object.entries(organizedAdvancedLicenseMap).map(([, options], index) => {
const s1arr = options.map((option) => {
return option.code
})

const s1 = joinWithAnd(s1arr)

const s2 = options.find((x) => x.minAge)?.minAge

const requiredAgeText =
s1 &&
s2 &&
formatMessage(m[`applicationForAdvancedAgeRequired`], {
licenses: s1,
age: String(s2),
})

return (
<Box
key={`license-group-${index}`}
marginTop={index === 0 ? 2 : 5}
marginBottom={5}
>
{requiredAgeText && (
<Box marginBottom={2}>
<Text variant="medium" as="div">
{requiredAgeText}
</Text>
</Box>
)}
{options.map((option, index) => {
const name = `field-${option.code}`

return (
<Box
key={index}
marginBottom={2}
stjanilofts marked this conversation as resolved.
Show resolved Hide resolved
paddingX={3}
paddingTop={2}
paddingBottom={3}
background="blue100"
borderRadius="large"
border="standard"
>
<Text as="div" marginBottom={2}>
{formatMessage(
m[`applicationForAdvancedLicenseTitle${option.code}`],
)}
</Text>
<Checkbox
label={formatMessage(
m[`applicationForAdvancedLicenseLabel${option.code}`],
)}
id={name}
name={name}
backgroundColor="blue"
labelVariant="medium"
checked={advancedLicenseValue.includes(option.code)}
onChange={() => {
setSelectedLicenses((prev) => {
return prev.includes(option.code)
? prev
.filter((item) => item !== option.code)
.filter(
(item) => item !== option.professional?.code,
)
: [...prev, option.code]
})
}}
Comment on lines +94 to +104
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🛠️ Refactor suggestion

Simplify checkbox handlers using callback utilities.

The onChange handlers contain complex logic that could be simplified for better maintainability.

const handleLicenseToggle = useCallback((code: string, professional?: string) => (checked: boolean) => {
  setSelectedLicenses(prev => {
    if (!checked) {
      return prev.filter(item => item !== code && item !== professional);
    }
    return professional ? [...prev, professional] : [...prev, code];
  });
}, []);

Then use it in the JSX:

-onChange={() => {
-  setSelectedLicenses((prev) => {
-    return prev.includes(option.code)
-      ? prev
-          .filter((item) => item !== option.code)
-          .filter(
-            (item) => item !== option.professional?.code,
-          )
-      : [...prev, option.code]
-  })
-}}
+onChange={(e) => handleLicenseToggle(option.code, option.professional?.code)(e.target.checked)}

Also applies to: 128-138

/>
{option?.professional?.code && (
<Box
key={`professional-${option.professional.code}`}
marginTop={2}
paddingX={3}
paddingY={2}
background="blue100"
borderRadius="large"
border="standard"
>
<Checkbox
disabled={!selectedLicenses.includes(option?.code)}
label={formatMessage(
m[
`applicationForAdvancedLicenseLabel${option.professional.code}`
],
)}
backgroundColor="blue"
labelVariant="small"
checked={advancedLicenseValue.includes(
option?.professional?.code,
)}
onChange={(e) => {
setSelectedLicenses((prev) => {
if (e.target.checked && option.professional?.code) {
return [...prev, option.professional.code]
}

return prev.filter(
(item) => item !== option.professional?.code,
)
})
}}
/>
</Box>
)}
</Box>
)
})}
</Box>
)
})}
{!selectedLicenses?.length && requiredMessage && (
<ErrorMessage>
<div>{requiredMessage}</div>
</ErrorMessage>
)}
</Box>
)
}

export { AdvancedLicense }
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
export { AdvancedLicense } from './AdvancedLicense'
Original file line number Diff line number Diff line change
Expand Up @@ -4,5 +4,6 @@ export { EligibilitySummary } from './EligibilitySummary'
export { SubmitAndDecline } from './SubmitAndDecline'
export { LinkExistingApplication } from './LinkExistingApplication'
export { PaymentPending } from './PaymentPending'
export { AdvancedLicense } from './AdvancedLicense'
export { QualityPhoto } from './QualityPhoto'
export { default as HealthRemarks } from './HealthRemarks'
Original file line number Diff line number Diff line change
Expand Up @@ -8,13 +8,23 @@ import { sectionApplicationFor } from './sectionApplicationFor'
import { sectionRequirements } from './sectionRequirements'
import { sectionExistingApplication } from './sectionExistingApplication'
import { sectionDigitalLicenseInfo } from './sectionDigitalLicenseInfo'
import { sectionAdvancedLicenseSelection } from './sectionAdvancedLicenseSelection'

interface DrivingLicenseFormConfig {
allowFakeData?: boolean
allowPickLicense?: boolean
allowBELicense?: boolean
allow65Renewal?: boolean
allowAdvanced?: boolean
}

export const getForm = ({
allowFakeData = false,
allowPickLicense = false,
allowBELicense = false,
allow65Renewal = false,
}): Form =>
allowAdvanced = false,
}: DrivingLicenseFormConfig): Form =>
buildForm({
id: 'DrivingLicenseApplicationPrerequisitesForm',
title: '',
Expand All @@ -31,8 +41,15 @@ export const getForm = ({
sectionExternalData,
sectionExistingApplication,
...(allowPickLicense
? [sectionApplicationFor(allowBELicense, allow65Renewal)]
? [
sectionApplicationFor(
allowBELicense,
allow65Renewal,
allowAdvanced,
),
]
: []),
...(allowAdvanced ? [sectionAdvancedLicenseSelection] : []),
sectionDigitalLicenseInfo,
sectionRequirements,
],
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
import {
buildCustomField,
buildMultiField,
buildSubSection,
getValueViaPath,
} from '@island.is/application/core'
import { m } from '../../lib/messages'
import { LicenseTypes } from '../../lib/constants'

export const sectionAdvancedLicenseSelection = buildSubSection({
id: 'sectionAdvancedLicenseSelection',
title: m.applicationForAdvancedLicenseTitle,
condition: (answers) => {
const applicationFor = getValueViaPath<LicenseTypes>(
answers,
'applicationFor',
)

return applicationFor != null && applicationFor === LicenseTypes.B_ADVANCED
},
children: [
buildMultiField({
id: 'advancedLicenseSelectionFields',
title: m.applicationForAdvancedLicenseTitle,
description: m.applicationForAdvancedLicenseDescription,
children: [
buildCustomField({
id: 'advancedLicense',
title: 'Advanced License',
component: 'AdvancedLicense',
}),
stjanilofts marked this conversation as resolved.
Show resolved Hide resolved
],
}),
],
})
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ import {
import { m } from '../../lib/messages'
import { DrivingLicense } from '../../lib/types'
import {
B_ADVANCED,
B_FULL,
B_FULL_RENEWAL_65,
B_TEMP,
Expand All @@ -17,6 +18,7 @@ import {
export const sectionApplicationFor = (
allowBELicense = false,
allow65Renewal = false,
allowAdvanced = false,
) =>
buildSubSection({
id: 'applicationFor',
Expand Down Expand Up @@ -112,6 +114,17 @@ export const sectionApplicationFor = (
})
}

if (allowAdvanced) {
options = options.concat({
label: m.applicationForAdvancedLicenseTitle,
subLabel: m.applicationForAdvancedLicenseDescription,
value: B_ADVANCED,
disabled: !categories?.some(
(c) => c.nr.toUpperCase() === 'B' && c.validToCode !== 8,
),
stjanilofts marked this conversation as resolved.
Show resolved Hide resolved
})
}

return options
},
}),
Expand Down
Loading