Newer
Older
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
<script lang="ts" setup>
import { useRouter } from 'vue-router'
import { computed, onMounted, type Ref, ref, watch } from 'vue'
import type { Goal } from '@/types/goal'
import ProgressBar from '@/components/ProgressBar.vue'
import authInterceptor from '@/services/authInterceptor'
import ModalComponent from '@/components/ModalComponent.vue'
import InteractiveSpare from '@/components/InteractiveSpare.vue'
const router = useRouter()
const uploadedFile: Ref<File | null> = ref(null)
const minDate = new Date(new Date().setDate(new Date().getDate() + 1)).toISOString().slice(0, 10)
const selectedDate = ref<string>(minDate)
const modalMessage = ref<string>('')
const modalTitle = ref<string>('')
const errorModalOpen = ref<boolean>(false)
const confirmModalOpen = ref<boolean>(false)
const goalInstance = ref<Goal>({
title: '',
saved: 0,
target: 0,
description: '',
due: ''
})
watch(selectedDate, (newDate) => {
goalInstance.value.due = newDate
})
const isEdit = computed(() => router.currentRoute.value.name === 'edit-goal')
const pageTitle = computed(() => (isEdit.value ? 'Rediger sparemål🎨' : 'Nytt sparemål🎨'))
const submitButton = computed(() => (isEdit.value ? 'Oppdater' : 'Opprett'))
const completion = computed(() => (goalInstance.value.saved / goalInstance.value.target) * 100)
function validateInputs() {
const errors = []
goalInstance.value.due = selectedDate.value + 'T23:59:59.999Z'
if (!goalInstance.value.title) {
errors.push('Tittel må fylles ut')
}
if (!goalInstance.value.target) {
errors.push('Målbeløp må fylles ut')
}
if (!goalInstance.value.due) {
errors.push('Forfallsdato må fylles ut')
}
if (goalInstance.value.target < 1) {
errors.push('Målbeløp må være større enn 0')
}
if (goalInstance.value.saved < 0) {
errors.push('Sparebeløp kan ikke være negativt')
}
if (goalInstance.value.saved > goalInstance.value.target) {
errors.push('Sparebeløp kan ikke være større enn målbeløp')
}
return errors
}
const submitAction = async () => {
const errors = validateInputs()
if (errors.length > 0) {
const formatErrors = errors.join('<br>')
modalTitle.value = 'Oops! Noe er feil med det du har fylt ut🚨'
modalMessage.value = formatErrors
errorModalOpen.value = true
return
}
try {
let response
if (isEdit.value) {
response = await updateGoal()
} else {
response = await createGoal()
}
const goalId = isEdit.value ? goalInstance.value.id : response.id // Adjusted to handle the returned data
if (uploadedFile.value && goalId) {
const formData = new FormData()
formData.append('file', uploadedFile.value)
formData.append('id', goalId.toString())
await authInterceptor.post('/goals/picture', formData, {
headers: { 'Content-Type': 'multipart/form-data' }
})
}
await router.push({ name: 'goals' })
} catch (error) {
console.error('Error during goal submission:', error)
modalTitle.value = 'Systemfeil'
modalMessage.value = 'En feil oppstod under lagring av utfordringen.'
errorModalOpen.value = true
}
}
watch(selectedDate, (newDate) => {
console.log(newDate)
})
onMounted(async () => {
if (isEdit.value) {
const goalId = router.currentRoute.value.params.id
if (!goalId) return router.push({ name: 'goals' })
await authInterceptor(`/goals/${goalId}`)
.then((response) => {
goalInstance.value = response.data
selectedDate.value = response.data.due.slice(0, 10)
})
.catch((error) => {
console.error(error)
router.push({ name: 'goals' })
})
} else {
goalInstance.value.due = selectedDate.value
}
})
const createGoal = async (): Promise<any> => {
try {
const response = await authInterceptor.post('/goals', goalInstance.value)
return response.data // Ensure the response data is returned
} catch (error) {
console.error('Failed to create goal:', error)
throw error // Rethrow the error to handle it in the submitAction method
}
}
const updateGoal = async (): Promise<any> => {
try {
const response = await authInterceptor.put(
`/goals/${goalInstance.value.id}`,
goalInstance.value
)
return response.data // Ensure the response data is returned
} catch (error) {
console.error('Failed to update goal:', error)
throw error // Rethrow the error to handle it in the submitAction method
}
}
const deleteGoal = () => {
authInterceptor
.delete(`/goals/${goalInstance.value.id}`)
.then(() => {
router.push({ name: 'goals' })
})
.catch((error) => {
console.error(error)
})
}
function cancelCreation() {
if (
goalInstance.value.title !== '' ||
goalInstance.value.description !== '' ||
goalInstance.value.target !== 0 ||
selectedDate.value !== ''
) {
modalTitle.value = 'Du er i ferd med å avbryte redigeringen🚨'
modalMessage.value = 'Er du sikker på at du vil avbryte?'
confirmModalOpen.value = true
} else {
router.push({ name: 'goals' })
}
}
const confirmCancel = () => {
router.push({ name: 'goals' })
confirmModalOpen.value = false
}
const handleFileChange = (event: Event) => {
const target = event.target as HTMLInputElement
if (target.files && target.files.length > 0) {
uploadedFile.value = target.files[0] // Save the first selected file
} else {
uploadedFile.value = null
}
}
const removeUploadedFile = () => {
uploadedFile.value = null
}
onMounted(async () => {
if (isEdit.value) {
const goalId = router.currentRoute.value.params.id
if (!goalId) return router.push({ name: 'goals' })
await authInterceptor(`/goals/${goalId}`)
.then((response) => {
goalInstance.value = response.data
selectedDate.value = response.data.due.slice(0, 16)
})
.catch((error) => {
console.error(error)
router.push({ name: 'goals' })
})
}
})
</script>
<template>
<div class="relative flex-1 min-h-screen">
<h1 class="font-bold flex justify-center items-center" v-text="pageTitle" />
<div class="flex md:flex-row flex-col justify-center md:items-start items-center">
<div class="flex flex-col gap-5 items-center justify-center">
<div class="flex flex-col">
<p class="mx-4">Tittel*</p>
<input v-model="goalInstance.title" placeholder="Skriv en tittel" type="text" />
</div>
<div class="flex flex-col">
<p class="mx-4">Beskrivelse (valgfri)</p>
<textarea
v-model="goalInstance.description"
class="w-80 h-20 no-rezise"
placeholder="Beskriv sparemålet"
/>
</div>
<div class="flex flex-col sm:flex-row gap-3">
<div class="flex flex-col">
<p class="mx-4">Kroner spart💸</p>
<input
v-model="goalInstance.saved"
class="w-40 text-right"
placeholder="Sparebeløp"
type="number"
/>
</div>
<div class="flex flex-col">
<p class="mx-4">Av målbeløp💯*</p>
<input
v-model="goalInstance.target"
class="w-40 text-right"
placeholder="Målbeløp"
type="number"
/>
</div>
</div>
<ProgressBar :completion="completion" />
<div class="flex flex-row gap-4">
<div class="flex flex-col">
<p class="mx-4">Forfallsdato*</p>
<input
:min="minDate"
v-model="selectedDate"
placeholder="Forfallsdato"
type="date"
/>
</div>
<div class="flex flex-col items-center">
<p>Last opp ikon for utfordringen📸</p>
<label
for="fileUpload"
class="bg-white text-black text-lg cursor-pointer leading-none rounded-full border p-3 border-black"
>
Legg til 💾
</label>
<input
id="fileUpload"
type="file"
accept=".jpg, .png"
hidden
@change="handleFileChange"
/>
<div v-if="uploadedFile" class="flex justify-center items-center mt-2">
<p class="text-sm">{{ uploadedFile.name }}</p>
<button
@click="removeUploadedFile"
class="ml-2 text-xs font-bold border-2 p-1 rounded text-red-500"
>
Fjern fil
</button>
</div>
</div>
</div>
<div class="flex flex-row justify-between w-full">
<button
v-if="isEdit"
class="ml-2 primary danger"
@click="deleteGoal"
v-text="'Slett'"
/>
<button
v-else
class="ml-2 primary danger"
@click="cancelCreation"
v-text="'Avbryt'"
/>
<button class="primary" @click="submitAction" v-text="submitButton" />
</div>
<ModalComponent
:title="modalTitle"
:message="modalMessage"
:isModalOpen="errorModalOpen"
@close="errorModalOpen = false"
>
<template v-slot:buttons>
<button class="primary" @click="errorModalOpen = false">Lukk</button>
</template>
</ModalComponent>
<ModalComponent
:title="modalTitle"
:message="modalMessage"
:isModalOpen="confirmModalOpen"
@close="confirmModalOpen = false"
>
<template v-slot:buttons>
<button class="primary" @click="confirmCancel">Bekreft</button>
<button class="primary danger" @click="confirmModalOpen = false">
Avbryt
</button>
</template>
</ModalComponent>
</div>
<div
class="lg:absolute right-5 lg:top-1/4 max-lg:bottom-0 max-lg:mt-44 transform -translate-y-1/2 lg:w-1/4 lg:max-w-xs"
>
<InteractiveSpare
:png-size="10"
:speech="[`Trenger du hjelp? Trykk på ❓ nede i høyre hjørne!`]"