Skip to content

Commit

Permalink
- En del oppsett for sykemelding validering i frontend
Browse files Browse the repository at this point in the history
- Lagt til en SwrMutateContext for behandling av mutate for trigger endepunkt i validering
- Endringer på DollyErrorMessage for at meldinger kun skal vises dersom showErrorContext er true
- Mindre oppdatering av rammeverk
#deploy-test-frontend
  • Loading branch information
stigus committed Dec 10, 2024
1 parent 90351f2 commit 41494ca
Show file tree
Hide file tree
Showing 13 changed files with 272 additions and 184 deletions.
210 changes: 96 additions & 114 deletions apps/dolly-frontend/src/main/js/package-lock.json

Large diffs are not rendered by default.

2 changes: 1 addition & 1 deletion apps/dolly-frontend/src/main/js/src/api/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -113,7 +113,7 @@ export const cvFetcher = (url, headers) =>
})

export const sykemeldingFetcher = (url, body) =>
axios.post(url, { body: body }).then((res) => {
axios.post(url, body).then((res) => {
return res.data
})

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -1535,6 +1535,17 @@ const mapSykemelding = (bestillingData, data) => {
'Hensyn på arbeidsplass',
_.get(sykemeldingKriterier.detaljertSykemelding, 'detaljer.beskrivHensynArbeidsplassen'),
),
obj(
'Begrunnelse ikke kontakt',
_.get(
sykemeldingKriterier.detaljertSykemelding,
'kontaktMedPasient.begrunnelseIkkeKontakt',
),
),
obj(
'Kontaktdato',
formatDate(sykemeldingKriterier.detaljertSykemelding?.kontaktMedPasient?.kontaktDato),
),
obj(
'Arbeidsfør etter endt periode',
sykemeldingKriterier.detaljertSykemelding.detaljer &&
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
import React from 'react'

export const SwrMutateContext: any = React.createContext(undefined)
Original file line number Diff line number Diff line change
Expand Up @@ -3,8 +3,9 @@ import { UseFormReturn } from 'react-hook-form/dist/types'
import { useContext } from 'react'
import { BestillingsveilederContext } from './BestillingsveilederContext'

export const useStateModifierFns = (formMethods: UseFormReturn) => {
export const useStateModifierFns = (formMethods: UseFormReturn, setFormMutate: any) => {
const opts = useContext(BestillingsveilederContext)

const set = (path, value) => {
formMethods.setValue(path, value)
}
Expand All @@ -14,6 +15,9 @@ export const useStateModifierFns = (formMethods: UseFormReturn) => {
const values = (path) => {
return formMethods.watch(path)
}
const delMutate = () => {
return setFormMutate?.(() => undefined)
}
const del = (path) => {
if (isArray(path)) {
path.forEach((p) => {
Expand Down Expand Up @@ -45,6 +49,7 @@ export const useStateModifierFns = (formMethods: UseFormReturn) => {
.map((b) => b.label)

const batchUpdate = (attrs, ignoreKeys = [], key = 'add') => {
delMutate()
Object.entries(attrs)
.filter(([name, value]) => {
return !ignoreKeys?.includes(name)
Expand All @@ -60,12 +65,14 @@ export const useStateModifierFns = (formMethods: UseFormReturn) => {
setMulti: (...arrays: any[]) => void
opts: any
del: (path: any) => void
delMutate: () => void
has: (path: any) => boolean
values: (path: any) => any
methods: any
}) => {},
) => {
const attrs = fn({ set, setMulti, opts, del, has, values, methods: formMethods }) || {}
const attrs =
fn({ set, setMulti, opts, del, delMutate, has, values, methods: formMethods }) || {}
const checked = allCheckedLabels(attrs)
return {
attrs,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -23,18 +23,23 @@ import {
ShowErrorContextType,
} from '@/components/bestillingsveileder/ShowErrorContext'
import { DollyValidation } from './steg/steg2/DollyValidation'
import { SwrMutateContext } from '@/components/bestillingsveileder/SwrMutateContext'

const STEPS = [Steg1, Steg2, Steg3]
const manualMutateFields = ['manual.sykemelding.detaljertSykemelding']

export const devEnabled =
window.location.hostname.includes('localhost') ||
window.location.hostname.includes('dolly-frontend-dev')

export const StegVelger = ({ initialValues, onSubmit }) => {
const context: any = useContext(BestillingsveilederContext)
const [loading, setLoading] = useState(false)
const errorContext: ShowErrorContextType = useContext(ShowErrorContext)

const [formMutate, setFormMutate] = useState(() => null)
const [loading, setLoading] = useState(false)
const [step, setStep] = useState(0)

const CurrentStepComponent: any = STEPS[step]
const stepMaxIndex = STEPS.length - 1
const formMethods = useForm({
Expand All @@ -43,14 +48,15 @@ export const StegVelger = ({ initialValues, onSubmit }) => {
resolver: yupResolver(DollyValidation),
context: context,
})
const stateModifier = useStateModifierFns(formMethods)
const stateModifier = useStateModifierFns(formMethods, setFormMutate)

const mutate = useMatchMutate()
const matchMutate = useMatchMutate()

const validationPaths = Object.keys(DollyValidation?.fields)

const isLastStep = () => step === STEPS.length - 1
const handleNext = () => {

const validateForm = () => {
formMethods.trigger(validationPaths).then(() => {
const errorFelter = Object.keys(formMethods.formState.errors)
const kunEnvironmentError = errorFelter.length === 1 && errorFelter[0] === 'environments'
Expand All @@ -65,6 +71,21 @@ export const StegVelger = ({ initialValues, onSubmit }) => {
})
}

const handleNext = () => {
if (step === 1 && formMutate) {
formMethods.clearErrors(manualMutateFields)
errorContext?.setShowError(true)
formMutate().then((response) => {
if (response.status === 'INVALID') {
return
}
validateForm()
})
} else {
validateForm()
}
}

const handleBack = () => {
errorContext?.setShowError(false)
if (step !== 0) setStep(step - 1)
Expand All @@ -82,44 +103,46 @@ export const StegVelger = ({ initialValues, onSubmit }) => {
formMethods.handleSubmit(onSubmit(values))

formMethods.reset()
mutate(REGEX_BACKEND_GRUPPER)
mutate(REGEX_BACKEND_ORGANISASJONER)
mutate(REGEX_BACKEND_BESTILLINGER)
matchMutate(REGEX_BACKEND_GRUPPER)
matchMutate(REGEX_BACKEND_ORGANISASJONER)
matchMutate(REGEX_BACKEND_BESTILLINGER)
}

const labels = STEPS.map((v) => ({ label: v.label }))

return (
<FormProvider {...formMethods}>
<Stepper orientation="horizontal" activeStep={step + 1}>
{labels.map((label, index) => (
<Stepper.Step
key={index}
completed={index < step}
onClick={() => index < stepMaxIndex && setStep(index)}
>
{label.label}
</Stepper.Step>
))}
</Stepper>
<BestillingsveilederHeader />
<CurrentStepComponent stateModifier={stateModifier} loadingBestilling={loading} />
{devEnabled && (
<>
<DisplayFormState />
<DisplayFormErrors errors={formMethods.formState.errors} label={'Vis errors'} />
</>
)}
{!loading && (
<Navigation
step={step}
onPrevious={handleBack}
isLastStep={isLastStep()}
handleSubmit={() => {
return _handleSubmit(formMethods.getValues())
}}
/>
)}
</FormProvider>
<SwrMutateContext.Provider value={setFormMutate}>
<FormProvider {...formMethods}>
<Stepper orientation="horizontal" activeStep={step + 1}>
{labels.map((label, index) => (
<Stepper.Step
key={index}
completed={index < step}
onClick={() => index < stepMaxIndex && setStep(index)}
>
{label.label}
</Stepper.Step>
))}
</Stepper>
<BestillingsveilederHeader />
<CurrentStepComponent stateModifier={stateModifier} loadingBestilling={loading} />
{devEnabled && (
<>
<DisplayFormState />
<DisplayFormErrors errors={formMethods.formState.errors} label={'Vis errors'} />
</>
)}
{!loading && (
<Navigation
step={step}
onPrevious={handleBack}
isLastStep={isLastStep()}
handleSubmit={() => {
return _handleSubmit(formMethods.getValues())
}}
/>
)}
</FormProvider>
</SwrMutateContext.Provider>
)
}
Original file line number Diff line number Diff line change
Expand Up @@ -41,7 +41,7 @@ export const SykdomPanel = ({ stateModifier, formValues }: any) => {

SykdomPanel.heading = 'Sykdom og skade'

SykdomPanel.initialValues = ({ set, del, has }: any) => ({
SykdomPanel.initialValues = ({ set, del, delMutate, has }: any) => ({
sykemelding: {
label: 'Har sykemelding',
checked: has('sykemelding'),
Expand All @@ -56,6 +56,7 @@ SykdomPanel.initialValues = ({ set, del, has }: any) => ({
},
remove() {
del('sykemelding')
delMutate?.()
},
},
yrkesskader: {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,7 @@ export type SykemeldingDetaljert = {
helsepersonell: Helsepersonell
arbeidsgiver: Arbeidsgiver
detaljer: Detaljer
kontaktMedPasient?: KontaktMedPasient
perioder: Array<Periode>
}
idx: number
Expand All @@ -44,6 +45,11 @@ export type Diagnose = {
system?: string
}

export type KontaktMedPasient = {
begrunnelseIkkeKontakt: string
kontaktDato?: string
}

export type Helsepersonell = {
fornavn: string
mellomnavn?: string
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -15,9 +15,12 @@ import {
} from '@/components/fagsystem/sykdom/SykemeldingTypes'
import { useKodeverk } from '@/utils/hooks/useKodeverk'
import { getRandomValue } from '@/components/fagsystem/utils'
import { useEffect } from 'react'
import { useContext, useEffect } from 'react'
import { useHelsepersonellOptions } from '@/utils/hooks/useSelectOptions'
import { useSykemeldingValidering } from '@/utils/hooks/useSykemelding'
import { DollyErrorMessage } from '@/utils/DollyErrorMessage'
import { useWatch } from 'react-hook-form'
import { SwrMutateContext } from '@/components/bestillingsveileder/SwrMutateContext'

type DiagnoseSelect = {
diagnoseNavn: string
Expand All @@ -43,23 +46,35 @@ const initialValuesPeriode = {
const KODESYSTEM = '2.16.578.1.12.4.1.1.7170'

export const DetaljertSykemelding = ({ formMethods }: SykemeldingForm) => {
const setContextMutate: any = useContext(SwrMutateContext)

const handleDiagnoseChange = (v: DiagnoseSelect, path: string) => {
formMethods.setValue(`${path}.diagnose`, v.diagnoseNavn)
formMethods.setValue(`${path}.system`, KODESYSTEM)
}
const detaljertSykemelding = formMethods.watch('sykemelding.detaljertSykemelding')
const detaljertSykemelding = useWatch({
name: 'sykemelding.detaljertSykemelding',
control: formMethods.control,
})

const { data, mutate, errorMessage } = useSykemeldingValidering(detaljertSykemelding)

const { validation, missingFields, mutate, error } =
useSykemeldingValidering(detaljertSykemelding)
console.log('error: ', error) //TODO - SLETT MEG
console.log('validation: ', validation) //TODO - SLETT MEG
console.log('missingFields: ', missingFields) //TODO - SLETT MEG
console.log('detaljertSykemelding: ', detaljertSykemelding) //TODO - SLETT MEG
useEffect(() => {
if (errorMessage && errorMessage.length > 0) {
formMethods.setError('manual.sykemelding.detaljertSykemelding', {
type: 'manual',
message: errorMessage,
})
} else formMethods.clearErrors('manual.sykemelding.detaljertSykemelding')
}, [errorMessage, data])

useEffect(() => {
console.log('Mutating!') //TODO - SLETT MEG
mutate()
}, [detaljertSykemelding])
setContextMutate(() => mutate)
formMethods.setError('manual.sykemelding.detaljertSykemelding', {
type: 'manual',
message: 'Trykk "Videre" for å validere sykemeldingen',
})
}, [mutate])

const handleLegeChange = (v: Helsepersonell) => {
formMethods.setValue('sykemelding.detaljertSykemelding.helsepersonell', {
Expand Down Expand Up @@ -109,6 +124,7 @@ export const DetaljertSykemelding = ({ formMethods }: SykemeldingForm) => {

return (
<div className="flexbox--wrap">
<DollyErrorMessage name={'manual.sykemelding.detaljertSykemelding'} />
<div className="flexbox--flex-wrap">
<FormDatepicker name="sykemelding.detaljertSykemelding.startDato" label="Startdato" />
<FormCheckbox
Expand Down Expand Up @@ -136,6 +152,19 @@ export const DetaljertSykemelding = ({ formMethods }: SykemeldingForm) => {
/>
</div>
</Kategori>
<Kategori title="Tilbakedatering" vis="sykemelding">
<div className="flexbox--flex-wrap">
<FormTextInput
name="sykemelding.detaljertSykemelding.kontaktMedPasient.begrunnelseIkkeKontakt"
label="Begrunnelse"
size="xlarge"
/>
<FormDatepicker
name={'sykemelding.detaljertSykemelding.kontaktMedPasient.kontaktDato'}
label="Kontaktdato"
/>
</div>
</Kategori>
<FormDollyFieldArray
name="sykemelding.detaljertSykemelding.biDiagnoser"
header="Bidiagnose"
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -67,6 +67,10 @@ const initialValuesDetaljertSykemelding = {
tom: addDays(new Date(), -1),
},
],
kontaktMedPasient: {
kontaktDato: null,
begrunnelseIkkeKontakt: '',
},
startDato: new Date(),
umiddelbarBistand: false,
},
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@ export const panelError = (attributtPath) => {
// Strings er akseptert, men konverter til Array
if (!Array.isArray(attributtPath)) attributtPath = [attributtPath]

return attributtPath.some((attr) => _.has(errors, attr))
return attributtPath.some((attr) => _.has(errors, attr) || _.has(errors, `manual.${attr}`))
}

export const SyntEvent = (name, value) => ({ target: { name, value } })
Expand Down
18 changes: 13 additions & 5 deletions apps/dolly-frontend/src/main/js/src/utils/DollyErrorMessage.tsx
Original file line number Diff line number Diff line change
@@ -1,16 +1,24 @@
import * as React from 'react'
import { useContext } from 'react'
import { useFormContext } from 'react-hook-form'
import { ErrorMessage } from '@hookform/error-message'
import {
ShowErrorContext,
ShowErrorContextType,
} from '@/components/bestillingsveileder/ShowErrorContext'

export const DollyErrorMessage = ({ name }: { name: string }) => {
const {
formState: { errors },
} = useFormContext()
const errorContext: ShowErrorContextType = useContext(ShowErrorContext)
return (
<ErrorMessage
name={name}
errors={errors}
render={({ message }) => <p style={{ color: '#ba3a26', fontStyle: 'italic' }}>{message}</p>}
/>
errorContext.showError && (
<ErrorMessage
name={name}
errors={errors}
render={({ message }) => <p style={{ color: '#ba3a26', fontStyle: 'italic' }}>{message}</p>}
/>
)
)
}
Loading

0 comments on commit 41494ca

Please sign in to comment.