From 730af84710ce759a7a8569ffb6b552d14d8ebc6d Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?Trygve=20J=C3=B8rgensen?= <trygjor@stud.ntnu.no>
Date: Thu, 2 May 2024 17:30:31 +0200
Subject: [PATCH] fix(config): config post refactor for better reliability

---
 src/router/index.ts                           |   1 -
 src/stores/userConfigStore.ts                 | 117 ++++++++++--------
 src/stores/userStore.ts                       |   1 -
 src/views/ConfigAccountNumberView.vue         |  12 +-
 src/views/ConfigBiometricView.vue             |   7 +-
 src/views/ConfigSpendingItemsAmountView.vue   |   4 +-
 .../ConfigSpendingItemsTotalAmountView.vue    |   4 +-
 src/views/ConfigSpendingItemsView.vue         |   9 +-
 8 files changed, 90 insertions(+), 65 deletions(-)

diff --git a/src/router/index.ts b/src/router/index.ts
index e440a31..b50a37b 100644
--- a/src/router/index.ts
+++ b/src/router/index.ts
@@ -177,7 +177,6 @@ router.beforeEach(async (to, from, next) => {
         }
 
         const isConfigured = userStore.user.isConfigured
-
         if (configRequired && !isConfigured) {
             await router.replace({ name: 'configure-biometric' })
             return next({ name: 'configure-biometric' })
diff --git a/src/stores/userConfigStore.ts b/src/stores/userConfigStore.ts
index 2e562ca..a7a372f 100644
--- a/src/stores/userConfigStore.ts
+++ b/src/stores/userConfigStore.ts
@@ -2,30 +2,36 @@ import { ref } from 'vue'
 import { defineStore } from 'pinia'
 import authInterceptor from '@/services/authInterceptor'
 import { AxiosError } from 'axios'
+import type { ChallengeConfig } from '@/types/challengeConfig'
+import router from '@/router'
 
 export const useUserConfigStore = defineStore('userConfig', () => {
-    const role = ref('USER')
-    const experience = ref('')
-    const motivation = ref('')
-    const challengeTypeConfigs = ref(
-        [] as {
-            type: string
-            specificAmount: number
-            generalAmount: number
-        }[]
-    )
-    const accounts = ref({
-        savings: '',
-        spending: ''
+    const challengeConfig = ref<ChallengeConfig>({
+        experience: '',
+        motivation: '',
+        challengeTypeConfigs: []
     })
+
+    const savingAccount = ref({
+        accountType: 'SAVING',
+        accNumber: 0,
+        balance: 0
+    })
+
+    const spendingAccount = ref({
+        accountType: 'SPENDING',
+        accNumber: 0,
+        balance: 0
+    })
+
     const errorMessage = ref<string>('')
 
     const setExperience = (value: string) => {
-        experience.value = value
+        challengeConfig.value.experience = value
     }
 
     const setMotivation = (value: string) => {
-        motivation.value = value
+        challengeConfig.value.motivation = value
     }
 
     const addChallengeTypeConfig = (
@@ -33,53 +39,64 @@ export const useUserConfigStore = defineStore('userConfig', () => {
         specificAmount: number,
         generalAmount: number
     ) => {
-        challengeTypeConfigs.value.push({ type, specificAmount, generalAmount })
+        challengeConfig.value.challengeTypeConfigs.push({
+            type: type,
+            specificAmount: specificAmount,
+            generalAmount: generalAmount
+        })
     }
 
-    const postAccount = async (
-        accountType: 'SAVING' | 'SPENDING',
-        accNumber: string,
-        balance: number
-    ) => {
-        const payload = {
-            accountType,
-            accNumber,
-            balance
+    const setAccount = (type: 'SAVING' | 'SPENDING', accNumber: number) => {
+        if (type === 'SAVING') {
+            savingAccount.value.accNumber = accNumber
+        } else {
+            spendingAccount.value.accNumber = accNumber
         }
-        await authInterceptor.post('/accounts', payload).catch((error) => {
-            const axiosError = error as AxiosError
-            errorMessage.value =
-                (axiosError.response?.data as string) || 'An error occurred while posting account'
-            console.error('Error posting account:', errorMessage.value)
-        })
     }
 
-    const postUserConfig = async () => {
-        const payload = {
-            experience: experience.value,
-            motivation: motivation.value,
-            challengeTypeConfigs: Array.from(challengeTypeConfigs.value)
+    const createConfig = () => {
+        authInterceptor
+            .post('/accounts', savingAccount.value)
+            .then(() => authInterceptor.post('/accounts', spendingAccount.value))
+            .then(() => authInterceptor.post('/config/challenge', challengeConfig.value))
+            .then(() => {
+                resetConfig()
+                return router.push({ name: 'home', query: { firstLogin: 'true' } })
+            })
+            .catch((error: AxiosError) => {
+                console.error(error)
+                resetConfig()
+                return router.push({ name: 'configurations1' })
+            })
+    }
+
+    const resetConfig = () => {
+        challengeConfig.value = {
+            experience: '',
+            motivation: '',
+            challengeTypeConfigs: []
+        }
+        savingAccount.value = {
+            accountType: 'SAVING',
+            accNumber: 0,
+            balance: 0
+        }
+        spendingAccount.value = {
+            accountType: 'SPENDING',
+            accNumber: 0,
+            balance: 0
         }
-        await authInterceptor.post('/config/challenge', payload).catch((error) => {
-            const axiosError = error as AxiosError
-            errorMessage.value =
-                (axiosError.response?.data as string) ||
-                'An error occurred while updating configuration'
-            console.error('Error updating configuration:', errorMessage.value)
-        })
     }
 
     return {
-        role,
-        experience,
-        motivation,
-        challengeTypeConfigs,
-        accounts,
+        challengeConfig,
         errorMessage,
         setExperience,
         setMotivation,
+        setAccount,
         addChallengeTypeConfig,
-        postAccount,
-        postUserConfig
+        createConfig
     }
 })
+
+
diff --git a/src/stores/userStore.ts b/src/stores/userStore.ts
index e94e851..3bdb2eb 100644
--- a/src/stores/userStore.ts
+++ b/src/stores/userStore.ts
@@ -238,7 +238,6 @@ export const useUserStore = defineStore('user', () => {
     const checkIfUserConfigured = async () => {
         await authInterceptor('/config')
             .then((response) => {
-                console.log('User configured: ' + user.value.isConfigured)
                 user.value.isConfigured = response.data.challengeConfig != null
             })
             .catch(() => {
diff --git a/src/views/ConfigAccountNumberView.vue b/src/views/ConfigAccountNumberView.vue
index 6b827b1..f49e366 100644
--- a/src/views/ConfigAccountNumberView.vue
+++ b/src/views/ConfigAccountNumberView.vue
@@ -63,7 +63,6 @@
 import { computed, ref } from 'vue'
 import { useUserConfigStore } from '@/stores/userConfigStore'
 import ContinueButtonComponent from '@/components/ContinueButtonComponent.vue'
-import router from '@/router'
 import SpareComponent from '@/components/SpareComponent.vue'
 
 const MAX_DIGITS = 11
@@ -80,14 +79,13 @@ const isFormValid = computed(() => {
 })
 
 async function onButtonClick() {
-    const savingAccountNumber = savingsAccount.value.replace(/\./g, '')
-    const spendingAccountNumber = spendingAccount.value.replace(/\./g, '')
+    const savingAccountNumber = parseInt(savingsAccount.value.replace(/\./g, ''))
+    const spendingAccountNumber = parseInt(spendingAccount.value.replace(/\./g, ''))
 
-    await userConfigStore.postAccount('SAVING', savingAccountNumber, 0)
-    await userConfigStore.postAccount('SPENDING', spendingAccountNumber, 0)
-    await userConfigStore.postUserConfig()
+    userConfigStore.setAccount('SAVING', savingAccountNumber)
+    userConfigStore.setAccount('SPENDING', spendingAccountNumber)
 
-    await router.push({ name: 'home', query: { firstLogin: 'true' } })
+    await userConfigStore.createConfig()
 }
 
 function restrictToNumbers(event: InputEvent, type: string) {
diff --git a/src/views/ConfigBiometricView.vue b/src/views/ConfigBiometricView.vue
index a1421d8..0a6647a 100644
--- a/src/views/ConfigBiometricView.vue
+++ b/src/views/ConfigBiometricView.vue
@@ -7,7 +7,7 @@
             <img alt="bioAuthFace" class="w-40 h-40" src="@/assets/bioAuthFace.png" />
         </div>
         <div class="flex flex-col gap-5">
-            <button @click="userStore.bioRegister()">Legg til nå!</button>
+            <button @click="bioRegister">Legg til nå!</button>
             <button @click="router.push({ name: 'configurations1' })">Jeg gjør det senere</button>
         </div>
     </div>
@@ -17,6 +17,11 @@ import { useUserStore } from '@/stores/userStore'
 import router from '@/router'
 
 const userStore = useUserStore()
+
+const bioRegister = async () => {
+    await userStore.bioRegister()
+    await router.push({ name: 'configurations1' })
+}
 </script>
 
 <style scoped></style>
diff --git a/src/views/ConfigSpendingItemsAmountView.vue b/src/views/ConfigSpendingItemsAmountView.vue
index b1f28b2..ef2ac42 100644
--- a/src/views/ConfigSpendingItemsAmountView.vue
+++ b/src/views/ConfigSpendingItemsAmountView.vue
@@ -95,14 +95,14 @@ import SpareComponent from '@/components/SpareComponent.vue'
 
 const userConfigStore = useUserConfigStore()
 
-const options = ref(userConfigStore.challengeTypeConfigs)
+const options = ref(userConfigStore.challengeConfig.challengeTypeConfigs)
 const amounts = ref(options.value.map(() => ''))
 
 const isAllAmountsFilled = computed(() => amounts.value.every((amount) => amount.trim() !== ''))
 
 const onButtonClick = () => {
     options.value.forEach((option, index) => {
-        userConfigStore.challengeTypeConfigs[index].specificAmount =
+        userConfigStore.challengeConfig.challengeTypeConfigs[index].specificAmount =
             parseFloat(amounts.value[index]) || 0
     })
     router.push({ name: 'configurations5' })
diff --git a/src/views/ConfigSpendingItemsTotalAmountView.vue b/src/views/ConfigSpendingItemsTotalAmountView.vue
index e416dc5..0291e9e 100644
--- a/src/views/ConfigSpendingItemsTotalAmountView.vue
+++ b/src/views/ConfigSpendingItemsTotalAmountView.vue
@@ -95,14 +95,14 @@ import SpareComponent from '@/components/SpareComponent.vue'
 
 const userConfigStore = useUserConfigStore()
 
-const options = ref(userConfigStore.challengeTypeConfigs)
+const options = ref(userConfigStore.challengeConfig.challengeTypeConfigs)
 const amounts = ref(options.value.map(() => ''))
 
 const isAllAmountsFilled = computed(() => amounts.value.every((amount) => amount.trim() !== ''))
 
 const onButtonClick = async () => {
     options.value.forEach((option, index) => {
-        userConfigStore.challengeTypeConfigs[index].generalAmount =
+        userConfigStore.challengeConfig.challengeTypeConfigs[index].generalAmount =
             parseFloat(amounts.value[index]) || 0
     })
 
diff --git a/src/views/ConfigSpendingItemsView.vue b/src/views/ConfigSpendingItemsView.vue
index 7313cc1..d3e032d 100644
--- a/src/views/ConfigSpendingItemsView.vue
+++ b/src/views/ConfigSpendingItemsView.vue
@@ -122,7 +122,14 @@ const onButtonClick = () => {
             generalAmount: 0
         }))
 
-    userConfigStore.challengeTypeConfigs = [...predefinedChallengeTypes, ...customChallengeTypes]
+    for (const challengeType of predefinedChallengeTypes.concat(customChallengeTypes)) {
+        userConfigStore.addChallengeTypeConfig(
+            challengeType.type,
+            challengeType.specificAmount,
+            challengeType.generalAmount
+        )
+    }
+
     router.push({ name: 'configurations4' })
 }
 </script>
-- 
GitLab