From 1877e538ed4f5d7b0b3f54341a6c3faca6e9b71e Mon Sep 17 00:00:00 2001
From: Tore Brede <Tore.Brede@uib.no>
Date: Mon, 20 Dec 2021 13:36:57 +0100
Subject: [PATCH] GREG-156: Updating max date for role when user presses back
 button

---
 frontend/src/hooks/useRoleTypes/index.tsx     | 21 ++++----
 .../src/routes/sponsor/register/formData.ts   |  2 +-
 .../sponsor/register/stepPersonForm.tsx       | 49 +++++++++++++------
 .../routes/sponsor/register/stepSummary.tsx   |  3 +-
 4 files changed, 48 insertions(+), 27 deletions(-)

diff --git a/frontend/src/hooks/useRoleTypes/index.tsx b/frontend/src/hooks/useRoleTypes/index.tsx
index a1867130..85d63070 100644
--- a/frontend/src/hooks/useRoleTypes/index.tsx
+++ b/frontend/src/hooks/useRoleTypes/index.tsx
@@ -1,4 +1,5 @@
 import { useState, useEffect } from 'react'
+import { fetchJsonOpts } from '../../utils'
 
 type RoleTypeData = {
   id: number
@@ -11,16 +12,16 @@ type RoleTypeData = {
 function useRoleTypes(): RoleTypeData[] {
   const [roleTypes, setRoleTypes] = useState<RoleTypeData[]>([])
 
-  async function fetchRoleTypes() {
-    fetch(`/api/ui/v1/roletypes/`)
-      .then((data) => data.text())
-      .then((result) => {
-        // The response is a JSON-array
-        setRoleTypes(JSON.parse(result))
-      })
-      .catch((error) => {
-        console.debug(error)
-      })
+  const fetchRoleTypes = async () => {
+    const response = await fetch(`/api/ui/v1/roletypes/`, fetchJsonOpts())
+
+    if (response.ok) {
+      // The response is a JSON-array
+      const roleTypesJson = await response.json()
+      setRoleTypes(roleTypesJson)
+    } else {
+      console.error(response)
+    }
   }
 
   useEffect(() => {
diff --git a/frontend/src/routes/sponsor/register/formData.ts b/frontend/src/routes/sponsor/register/formData.ts
index 6700f957..b0ccade7 100644
--- a/frontend/src/routes/sponsor/register/formData.ts
+++ b/frontend/src/routes/sponsor/register/formData.ts
@@ -1,7 +1,7 @@
 export type RegisterFormData = {
   first_name?: string
   last_name?: string
-  role_type?: string
+  role_type?: number
   role_start: Date
   role_end: Date
   contact_person_unit?: string
diff --git a/frontend/src/routes/sponsor/register/stepPersonForm.tsx b/frontend/src/routes/sponsor/register/stepPersonForm.tsx
index e28bc3c4..40a68404 100644
--- a/frontend/src/routes/sponsor/register/stepPersonForm.tsx
+++ b/frontend/src/routes/sponsor/register/stepPersonForm.tsx
@@ -58,21 +58,18 @@ const StepPersonForm = forwardRef(
       nextHandler(data)
     }
 
+    // Set up the form with the data given as input to the component
     const {
       register,
       control,
       handleSubmit,
       formState: { errors },
-      reset,
       setValue,
       getValues,
-    } = useForm<RegisterFormData>()
+      trigger,
+    } = useForm<RegisterFormData>({ defaultValues: formData })
     const onSubmit = handleSubmit(submit)
 
-    useEffect(() => {
-      reset(formData)
-    }, [])
-
     const handleOuChange = (event: any) => {
       if (event.target.value) {
         setOuChoice(event.target.value)
@@ -86,16 +83,40 @@ const StepPersonForm = forwardRef(
       required: t<string>('validation.roleTypeRequired'),
     })
 
+    const getMaxDateForRoleType = (roleType: RoleTypeData | undefined) => {
+      if (roleType === undefined) {
+        return today
+      }
+      return addDays(roleType.max_days)(today)
+    }
+
+    function updateMaxDaysForRoleType(roleTypeId: any) {
+      const selectedRoleTypeInfo = roleTypes.find((rt) => rt.id === roleTypeId)
+      const maxDate = getMaxDateForRoleType(selectedRoleTypeInfo)
+      setTodayPlusMaxDays(maxDate)
+      // Trigger revalidation of role end since the max end date is
+      // different for different role types
+      trigger('role_end')
+    }
+
+    // When the component is first rendered and there is some role_type set in
+    // the input formData, the roleTypes-array is most
+    // probably empty since the data has not come back from the server yet.
+    // Need to have this effect here to make sure the max end date gets
+    // updated when the role types are available
+    useEffect(() => {
+      if (formData.role_type) {
+        updateMaxDaysForRoleType(formData.role_type)
+      }
+    }, [roleTypes])
+
     const handleRoleTypeChange = (event: any) => {
-      setValue('role_type', event.target.value)
-      setSelectedRoleType(event.target.value)
-      const selectedRoleTypeInfo = roleTypes.find(
-        (rt) => rt.id === event.target.value
-      )
-      if (selectedRoleTypeInfo === undefined) {
-        setTodayPlusMaxDays(today)
+      if (event.target.value) {
+        setValue('role_type', event.target.value)
+        setSelectedRoleType(event.target.value)
+        updateMaxDaysForRoleType(event.target.value)
       } else {
-        setTodayPlusMaxDays(addDays(selectedRoleTypeInfo.max_days)(today))
+        setValue('role_type', undefined)
       }
     }
 
diff --git a/frontend/src/routes/sponsor/register/stepSummary.tsx b/frontend/src/routes/sponsor/register/stepSummary.tsx
index 9824fc99..c079ad39 100644
--- a/frontend/src/routes/sponsor/register/stepSummary.tsx
+++ b/frontend/src/routes/sponsor/register/stepSummary.tsx
@@ -37,8 +37,7 @@ function StepSummary(props: StepSummaryProperties) {
   // TODO Fix this confusing mix between use of id and identifier
   const selectedRoleType = roleTypes.find(
     (value) =>
-      value.id ===
-      (formData.role_type === undefined ? -1 : parseInt(formData.role_type, 10))
+      value.id === (formData.role_type === undefined ? -1 : formData.role_type)
   )
   const roleTypeName =
     selectedRoleType === undefined
-- 
GitLab