From e34ec498731146c0f263e15ae2ee89a656a9d346 Mon Sep 17 00:00:00 2001
From: Andreas Ellewsen <ae@uio.no>
Date: Fri, 10 Dec 2021 13:23:54 +0100
Subject: [PATCH] Add validation to newGuestRole dates

---
 frontend/public/locales/en/common.json        |  1 -
 frontend/public/locales/nb/common.json        |  1 -
 frontend/public/locales/nn/common.json        |  1 -
 .../sponsor/guest/newGuestRole/index.tsx      | 52 +++++++++++++------
 4 files changed, 37 insertions(+), 18 deletions(-)

diff --git a/frontend/public/locales/en/common.json b/frontend/public/locales/en/common.json
index bf866efa..210cf747 100644
--- a/frontend/public/locales/en/common.json
+++ b/frontend/public/locales/en/common.json
@@ -16,7 +16,6 @@
     "roleStartDate": "From",
     "roleEndDate": "To",
     "comment": "Comment",
-    "contact": "Contact person",
     "searchable": "Available in search?",
     "email": "E-mail",
     "fullName": "Full name",
diff --git a/frontend/public/locales/nb/common.json b/frontend/public/locales/nb/common.json
index 290d8f21..f8fc3a00 100644
--- a/frontend/public/locales/nb/common.json
+++ b/frontend/public/locales/nb/common.json
@@ -16,7 +16,6 @@
     "roleStartDate": "Fra",
     "roleEndDate": "Til",
     "comment": "Kommentar",
-    "contact": "Kontaktperson",
     "searchable": "Synlig i søk?",
     "email": "E-post",
     "fullName": "Fullt navn",
diff --git a/frontend/public/locales/nn/common.json b/frontend/public/locales/nn/common.json
index b7beee8b..ca630977 100644
--- a/frontend/public/locales/nn/common.json
+++ b/frontend/public/locales/nn/common.json
@@ -17,7 +17,6 @@
     "roleStartDate": "Frå",
     "roleEndDate": "Til",
     "comment": "Kommentar",
-    "contact": "Kontaktperson",
     "searchable": "Synleg i søk?",
     "email": "E-post",
     "fullName": "Fullt namn",
diff --git a/frontend/src/routes/sponsor/guest/newGuestRole/index.tsx b/frontend/src/routes/sponsor/guest/newGuestRole/index.tsx
index bad293bd..3fc2155c 100644
--- a/frontend/src/routes/sponsor/guest/newGuestRole/index.tsx
+++ b/frontend/src/routes/sponsor/guest/newGuestRole/index.tsx
@@ -11,6 +11,7 @@ import {
   TextField,
   SelectChangeEvent,
   FormControlLabel,
+  Box,
 } from '@mui/material'
 import Page from 'components/page'
 import { format } from 'date-fns'
@@ -117,13 +118,14 @@ function NewGuestRole({ guest, reloadGuestInfo }: NewGuestRoleProps) {
   const [roleTypeChoice, setRoleTypeChoice] = useState<string>('')
   const [t, i18n] = useTranslation('common')
   const today = new Date()
+  const [maxDate, setMaxDate] = useState(today)
 
-  const todayPlusMaxDays = () => {
-    if (roleTypeChoice) {
-      const role = roleTypes.filter(
-        (rt) => rt.id.toString() === roleTypeChoice.toString()
-      )[0]
-      return addDays(role.max_days)(today)
+  const todayPlusMaxDays = (roleTypeId?: number) => {
+    if (roleTypeId) {
+      const role = roleTypes.find((rt) => rt.id === roleTypeId)
+      if (role !== undefined) {
+        return addDays(role.max_days)(today)
+      }
     }
     return addDays(0)(today)
   }
@@ -138,6 +140,7 @@ function NewGuestRole({ guest, reloadGuestInfo }: NewGuestRoleProps) {
   const handleRoleTypeChange = (event: SelectChangeEvent) => {
     setValue('type', event.target.value)
     setRoleTypeChoice(event.target.value)
+    setMaxDate(todayPlusMaxDays(Number(event.target.value)))
   }
   const handleOuChange = (event: SelectChangeEvent) => {
     if (event.target.value) {
@@ -193,18 +196,21 @@ function NewGuestRole({ guest, reloadGuestInfo }: NewGuestRoleProps) {
               label={t('common:ou')}
               onChange={handleOuChange}
             >
-              {ous.length > 0 ? (
+              {ous.length > 0 &&
                 ous
                   .sort(i18n.language === 'en' ? enSort : nbSort)
-                  .map((ou) => ouToItem(ou))
-              ) : (
-                <></>
-              )}
+                  .map((ou) => ouToItem(ou))}
             </Select>
           </FormControl>
           <Controller
             name="start_date"
             control={control}
+            rules={{
+              required: true,
+              validate: () =>
+                Number(getValues('start_date')) <=
+                Number(getValues('end_date')),
+            }}
             defaultValue={today}
             render={({ field }) => (
               <DatePicker
@@ -212,7 +218,7 @@ function NewGuestRole({ guest, reloadGuestInfo }: NewGuestRoleProps) {
                 label={t('input.roleStartDate')}
                 disabled={!roleTypeChoice}
                 value={field.value}
-                maxDate={todayPlusMaxDays()}
+                maxDate={maxDate}
                 inputFormat="yyyy-MM-dd"
                 onChange={(value) => {
                   field.onChange(value)
@@ -221,9 +227,26 @@ function NewGuestRole({ guest, reloadGuestInfo }: NewGuestRoleProps) {
               />
             )}
           />
+
+          {errors.start_date && errors.start_date.type === 'required' && (
+            <Box sx={{ typography: 'caption', color: 'error.main' }}>
+              {t('validation.startDateMustBeSet')}
+            </Box>
+          )}
+          {errors.start_date && errors.start_date.type === 'validate' && (
+            <Box sx={{ typography: 'caption', color: 'error.main' }}>
+              {t('validation.startDateMustBeBeforeEndDate')}
+            </Box>
+          )}
           <Controller
             name="end_date"
             control={control}
+            rules={{
+              required: true,
+              validate: () =>
+                Number(getValues('start_date')) <=
+                Number(getValues('end_date')),
+            }}
             defaultValue={today}
             render={({ field }) => (
               <DatePicker
@@ -231,7 +254,7 @@ function NewGuestRole({ guest, reloadGuestInfo }: NewGuestRoleProps) {
                 label={t('input.roleEndDate')}
                 disabled={!roleTypeChoice}
                 value={field.value}
-                maxDate={todayPlusMaxDays()}
+                maxDate={maxDate}
                 inputFormat="yyyy-MM-dd"
                 onChange={(value) => {
                   field.onChange(value)
@@ -240,10 +263,9 @@ function NewGuestRole({ guest, reloadGuestInfo }: NewGuestRoleProps) {
               />
             )}
           />
-
           <TextField
             id="contact"
-            label={t('input.contact')}
+            label={t('input.contactPersonUnit')}
             multiline
             rows={5}
             {...register('contact_person_unit')}
-- 
GitLab