Skip to content
This repository was archived by the owner on Apr 12, 2023. It is now read-only.

Commit 79d89fa

Browse files
committed
Lagrer data mellom stegene
1 parent ec37ee3 commit 79d89fa

File tree

9 files changed

+121
-55
lines changed

9 files changed

+121
-55
lines changed

components/ActivitySelector.tsx

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -9,7 +9,7 @@ export type ActivitySelectorProps = {
99
startDate: Date;
1010
endDate: Date;
1111
savedDates: SavedDates;
12-
setSavedDates: Dispatch<SetStateAction<{ [p: number]: { type: ActivityType | null, hours: number | null } }>>;
12+
setSavedDates: Dispatch<SetStateAction<SavedDates>>;
1313
}
1414

1515
export default function ActivitySelector(props: ActivitySelectorProps) {

components/Step1.tsx

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -15,7 +15,8 @@ export default function Step1(props: CommonFormProps) {
1515
setQuestionIllness,
1616
questionVacation,
1717
setQuestionVacation,
18-
nextStep
18+
nextStep,
19+
showLoader
1920
} = props;
2021

2122
const [isChecked, setIsChecked] = useState<boolean>(false);
@@ -105,7 +106,7 @@ export default function Step1(props: CommonFormProps) {
105106

106107
<Spacer />
107108

108-
<NavPanelWithButtons nextText="Neste steg" nextOnClick={checkForm} />
109+
<NavPanelWithButtons nextText="Neste steg" nextOnClick={checkForm} showLoader={showLoader} />
109110
</>
110111
);
111112
}

components/Step2.tsx

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -9,7 +9,7 @@ import { FormEvent, useState } from "react";
99

1010
export default function Step2(props: CommonFormProps) {
1111

12-
const { startDate, endDate, savedDates, setSavedDates, prevStep, nextStep } = props;
12+
const { startDate, endDate, savedDates, setSavedDates, prevStep, nextStep, showLoader } = props;
1313

1414
const [isChecked, setIsChecked] = useState<boolean>(false);
1515

@@ -45,7 +45,8 @@ export default function Step2(props: CommonFormProps) {
4545
<NavPanelWithButtons backText="Forrige steg"
4646
backOnClick={prevStep}
4747
nextText="Neste steg"
48-
nextOnClick={checkForm} />
48+
nextOnClick={checkForm}
49+
showLoader={showLoader} />
4950
</>
5051
);
5152
}

components/Step3.tsx

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -10,7 +10,8 @@ export default function Step3(props: CommonFormProps) {
1010
questionProceed,
1111
setQuestionProceed,
1212
prevStep,
13-
nextStep
13+
nextStep,
14+
showLoader
1415
} = props;
1516

1617
const [isChecked, setIsChecked] = useState<boolean>(false);
@@ -58,7 +59,8 @@ export default function Step3(props: CommonFormProps) {
5859
<NavPanelWithButtons backText="Forrige steg"
5960
backOnClick={prevStep}
6061
nextText="Neste steg"
61-
nextOnClick={checkForm} />
62+
nextOnClick={checkForm}
63+
showLoader={showLoader} />
6264
</>
6365
);
6466
}

components/Step4.tsx

Lines changed: 2 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,7 @@ import NavPanelWithButtons from "./NavPanelWithButtons";
55
import { CommonFormProps } from "../src/pages/form";
66
import { FormEvent, useState } from "react";
77
import { format } from "date-fns";
8+
import { ActivityType } from "../models/Data";
89

910
export default function Step4(props: CommonFormProps) {
1011

@@ -43,7 +44,7 @@ export default function Step4(props: CommonFormProps) {
4344
for (const key in savedDates) {
4445
const date = format(new Date(+key), "dd.MM.yy");
4546
const type = savedDates[key].type;
46-
const hours = type == 'work' ? '(' + savedDates[key].hours + ' t)' : '';
47+
const hours = type == ActivityType.WORK ? '(' + savedDates[key].hours + ' t)' : '';
4748
const str = date + ' ' + type + ' ' + hours;
4849

4950
days.push(
@@ -96,9 +97,7 @@ export default function Step4(props: CommonFormProps) {
9697
<Heading spacing level="4" size="small">
9798
Registrerte dager
9899
</Heading>
99-
<BodyShort>
100100
{days}
101-
</BodyShort>
102101
</Panel>
103102
<Panel>
104103
<Heading spacing level="4" size="small">

models/Data.ts

Lines changed: 4 additions & 20 deletions
Original file line numberDiff line numberDiff line change
@@ -14,27 +14,11 @@ export type Day = {
1414
hours: number | null;
1515
}
1616

17-
export type LoadedData = {
18-
id: string;
19-
questionWork: boolean | null;
20-
questionMeasures: boolean | null;
21-
questionIllness: boolean | null;
22-
questionVacation: boolean | null;
23-
days: LoadedDay[];
24-
questionProceed: boolean | null;
25-
}
26-
27-
export type LoadedDay = {
28-
date: string;
29-
type: string;
30-
hours: number | null;
31-
}
32-
3317
export enum ActivityType {
34-
WORK,
35-
ILLNESS,
36-
MEASURES,
37-
VACATION
18+
WORK = "WORK",
19+
ILLNESS = "ILLNESS",
20+
MEASURES = "MEASURES",
21+
VACATION = "VACATION"
3822
}
3923

4024
export type SavedDates = {

models/LoadedData.ts

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,15 @@
1+
export type LoadedData = {
2+
id: string;
3+
questionWork: boolean | null;
4+
questionMeasures: boolean | null;
5+
questionIllness: boolean | null;
6+
questionVacation: boolean | null;
7+
days: LoadedDay[];
8+
questionProceed: boolean | null;
9+
}
10+
11+
export type LoadedDay = {
12+
date: string;
13+
type: string;
14+
hours: number | null;
15+
}

src/pages/api/send.ts

Lines changed: 42 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,42 @@
1+
import type { NextApiRequest, NextApiResponse } from "next";
2+
import { getSession } from "../../auth.utils";
3+
import { v4 as uuid } from 'uuid';
4+
5+
export default async function handler(
6+
req: NextApiRequest,
7+
res: NextApiResponse
8+
) {
9+
try {
10+
const session = await getSession(req);
11+
12+
if (!session) {
13+
return res.status(401).end(); //skal aldri skje siden vi har wonderwall med enforcedlogin
14+
}
15+
16+
const audienceRappApi = `${process.env.NAIS_CLUSTER_NAME}:raptus:dp-rapp-api`;
17+
18+
const onBehalfOfToken = await session.apiToken(audienceRappApi);
19+
20+
const callId = uuid();
21+
const dpRappApiUrl = process.env.DP_RAPP_API_URL;
22+
const url = `${dpRappApiUrl}/api/v1/send`;
23+
const response = await fetch(url, {
24+
method: "POST",
25+
headers: {
26+
"Content-Type": "application/json",
27+
Accept: "application/json",
28+
Authorization: `Bearer ${onBehalfOfToken}`,
29+
"X-Request-ID": callId
30+
},
31+
body: JSON.stringify(req.body),
32+
})
33+
34+
if (!response.ok) {
35+
return res.status(500).send(`Unexpected response status: ${response.statusText}`)
36+
}
37+
38+
return res.json(response);
39+
} catch (error) {
40+
return res.status(500).send(error);
41+
}
42+
}

src/pages/form.tsx

Lines changed: 47 additions & 25 deletions
Original file line numberDiff line numberDiff line change
@@ -7,9 +7,10 @@ import Step3 from "../../components/Step3";
77
import Step4 from "../../components/Step4";
88
import Receipt from "../../components/Receipt";
99
import CancelButton from "../../components/CancelButton";
10-
import { format, getISOWeek } from "date-fns";
10+
import { format, getISOWeek, parseISO } from "date-fns";
1111
import { Dispatch, FormEventHandler, SetStateAction, useState } from "react";
12-
import { ActivityType, Data, Day, LoadedData, SavedDates } from "../../models/Data";
12+
import { ActivityType, Data, Day, SavedDates } from "../../models/Data";
13+
import { LoadedData } from "../../models/LoadedData";
1314

1415
type InitialState = {
1516
currentId: string;
@@ -55,11 +56,18 @@ export async function getServerSideProps() {
5556
questionProceed: null
5657
}
5758

58-
const response = await fetch(process.env.DP_RAPP_API_URL + '/api/v1/get/' + currentId);
59-
if (response.ok) {
60-
loadedData = await response.json();
59+
// Get saved values
60+
try {
61+
const response = await fetch(process.env.DP_RAPP_API_URL + '/api/v1/get/' + currentId);
62+
if (response.ok) {
63+
loadedData = await response.json();
64+
}
65+
} catch (e) {
66+
console.warn("Kunne ikke hente lagrede verdier", e);
6167
}
6268

69+
70+
// Data comes to page as props
6371
return {
6472
props: {
6573
currentId,
@@ -77,15 +85,17 @@ export default function Page(props: InitialState) {
7785
const [showReceipt, setShowReceipt] = useState<boolean>(false);
7886
const [error, setError] = useState<string>('');
7987

88+
// Pre-fetched data (initial state) comes to the page as props
8089
const { currentId, loadedData } = props;
8190

82-
// Use loaded data as initial state
91+
// Convert loaded days to SavedDates
8392
const loadedSavedDates: SavedDates = {}
8493
loadedData?.days.forEach((day) => {
8594
// @ts-ignore
86-
loadedSavedDates[Date.parse(day.date + " 12:00:00")] = { type: ActivityType[day.type], hours: day.hours }
95+
loadedSavedDates[parseISO(day.date + "T12:00:00").getTime()] = { type: ActivityType[day.type], hours: day.hours }
8796
});
8897

98+
// Use loaded data as initial state for variables
8999
const [questionWork, setQuestionWork] = useState<boolean | null>(loadedData.questionWork);
90100
const [questionMeasures, setQuestionMeasures] = useState<boolean | null>(loadedData.questionMeasures);
91101
const [questionIllness, setQuestionIllness] = useState<boolean | null>(loadedData.questionIllness);
@@ -109,13 +119,39 @@ export default function Page(props: InitialState) {
109119
}
110120
};
111121

112-
const nextStep = () => {
122+
const nextStep = async () => {
113123
if (currentStep < maxStep) {
124+
await save();
114125
setCurrentStep(currentStep + 1);
115126
}
116127
};
117128

129+
const save = async () => {
130+
const response = await postData('/api/save');
131+
132+
if (!response.ok) {
133+
setError('Feil i vårt baksystem. Kunne ikke lagre data');
134+
}
135+
136+
// Hide loader
137+
setShowLoader(false);
138+
}
139+
118140
const send = async () => {
141+
const response = await postData('/api/send');
142+
143+
if (response.ok) {
144+
setCurrentStep(currentStep + 1);
145+
setShowReceipt(true);
146+
} else {
147+
setError('Feil i vårt baksystem. Prøv senere');
148+
}
149+
150+
// Hide loader
151+
setShowLoader(false);
152+
}
153+
154+
const postData = async (endpoint: string) => {
119155
// Reset error
120156
setError('');
121157

@@ -146,9 +182,6 @@ export default function Page(props: InitialState) {
146182
// Send the data to the server in JSON format.
147183
const JSONdata = JSON.stringify(data);
148184

149-
// API endpoint where we send form data.
150-
const endpoint = '/api/save';
151-
152185
// Form the request for sending data to the server.
153186
const options = {
154187
// The method is POST because we are sending data.
@@ -162,19 +195,7 @@ export default function Page(props: InitialState) {
162195
};
163196

164197
// Send the form data to our forms API on Vercel and get a response.
165-
const response = await fetch(endpoint, options);
166-
167-
if (response.ok) {
168-
// Get the response data from server as JSON.
169-
// const result = await response.json();
170-
setCurrentStep(currentStep + 1);
171-
setShowReceipt(true);
172-
} else {
173-
setError('Feil i vårt baksystem. Prøv senere');
174-
}
175-
176-
// Hide loader
177-
setShowLoader(false);
198+
return await fetch(endpoint, options);
178199
}
179200

180201
const commonFormProps: CommonFormProps = {
@@ -204,7 +225,8 @@ export default function Page(props: InitialState) {
204225
return (
205226
<main>
206227
<Heading level="1" size="xlarge">Dagpenger rapportering</Heading>
207-
<Heading level="2" size="medium">Uke {getISOWeek(startDate)} - {getISOWeek(endDate)} ({startDateStr} - {endDateStr})</Heading>
228+
<Heading level="2"
229+
size="medium">Uke {getISOWeek(startDate)} - {getISOWeek(endDate)} ({startDateStr} - {endDateStr})</Heading>
208230

209231
<Divider />
210232

0 commit comments

Comments
 (0)