frontend/src/pages/user/UserInfoPage.tsx   A
last analyzed

Complexity

Total Complexity 8
Complexity/F 0

Size

Lines of Code 122
Function Count 0

Duplication

Duplicated Lines 0
Ratio 0 %

Test Coverage

Coverage 51.35%

Importance

Changes 0
Metric Value
eloc 114
dl 0
loc 122
ccs 19
cts 37
cp 0.5135
rs 10
c 0
b 0
f 0
wmc 8
mnd 8
bc 8
fnc 0
bpm 0
cpm 0
noi 0
1
import { useState, useEffect } from 'react';
2
import {  useSelector } from 'react-redux';
3
import { RootState } from '../../redux/store/store';
4
import { Link } from 'react-router-dom';
5
import userImage from '../../assets/images/user.jpg';
6
import axios, {AxiosError, AxiosResponse} from 'axios';
7
import { API_URL, getHeader } from '../../helpers/config';
8
import { Button, ToggleSwitch, TextInput, Label } from "flowbite-react";
9
import { useNavigate } from 'react-router-dom';
10
import { toast } from 'react-toastify';
11
import UserGate from '../../components/UserGate';
12
13 2
const UserInfoPage: React.FC = () => {
14 2
    const navigate = useNavigate();
15
16 3
    const { isLoggedIn, token, role } = useSelector((state: RootState) => state.auth);
17 2
    const [userData, setUserData] = useState<AxiosResponse["data"]>(null);
18 2
    const [githubId, setGithubId] = useState("");
19 2
    const [isMonthlyPayment, setIsMonthlyPayment] = useState(false);
20 2
    const [accumulatedCost, setAccumulatedCost] = useState(0);
21 2
    const [balance, setBalance] = useState(0);
22
23 2
    const updateUserPay = async (e: React.FormEvent<HTMLFormElement>) => {
24
        e.preventDefault();
25
        const updatedData = {
26
          'isMonthlyPayment': isMonthlyPayment,
27
          'balance': balance,
28
          };
29
        try {
30
          const response = await axios.patch(`${API_URL}/users/${githubId}/adjust-funds`, updatedData, getHeader(token));
31
          console.log(response);
32
          toast.success("Payment was successful was updated");
33
          } catch(error)
34
          {
35
          const axiosError = error as AxiosError;
36
          toast.error(`Payment was not processed ${axiosError.message}`);
37 2
          console.error("Error:", axiosError.response || axiosError.toJSON());
38
        }
39
      }
40
  
41 2
    useEffect(() => {
42 2
        if (!isLoggedIn) 
43 1
            navigate("/")
44 1
        const getAuthMe = async () => {
45 1
            try {
46 1
                        const response = await axios.get(`${API_URL}/auth/me`, getHeader(token));
47
                        console.log(response.data);
48
                        const data = response.data;
49
                        setUserData(data);
50
                        setGithubId(data.githubId);
51
                        setIsMonthlyPayment(data.isMonthlyPayment);
52
                        setAccumulatedCost(data.accumulatedCost);
53
                        setBalance(data.balance);
54
                } catch (error) {
55
                    console.error('Error fetching user data', error);
56
                }
57
            };
58 1
        getAuthMe();
59
    },[token, isLoggedIn, navigate]);
60
61 2
return (
62
    <div className="flex justify-center min-h-screen" data-testid="user-info-page">
63
        <UserGate/>
64
        <div className="block h-fit w-max-2xl p-6 bg-white border border-gray-200 rounded-lg shadow hover:bg-gray-100 dark:bg-gray-800 dark:border-gray-700 dark:hover:bg-gray-700 flex flex-col">
65
            <img className="w-24 h-24 mb-3 rounded-full shadow-lg object-contain" src={userImage} alt="User image" />
66
            
67
            <p className="font-normal text-gray-700 dark:text-gray-400 p-2">
68
                Användare: <b>{userData?.username || "No User"}</b>
69
            </p>
70
71
            <p className="font-normal text-gray-700 dark:text-gray-400 p-2">
72
                Email: <b>{userData?.email|| "No Email"}</b>
73
            </p>
74
75
            <p className="font-normal text-gray-700 dark:text-gray-400 p-2">
76
                Skapat: <b>{userData?.createdAt || "No User"}</b>
77
            </p>
78
            
79
            <p className="font-normal text-gray-700 dark:text-gray-400 p-2">
80
                Roll: <b>{role}</b>
81
            </p>
82
            
83
            <p className="font-normal text-gray-700 dark:text-gray-400 p-2">
84
                Github Id: <b>{userData?.githubId || ":("}</b>
85
            </p>
86
            
87
              <section className="bg-white dark:bg-gray-900">
88
                      <div className="max-w-2xl px-4 py-8 mx-auto lg:py-16">
89
                          <h2 className="mb-4 text-xl font-bold text-gray-900 dark:text-white">Betalning för <b>{ userData?.username || "No User" }</b> </h2>
90
                          <form action="#" onSubmit={(e) => updateUserPay(e)}>
91
                              <div className="grid gap-4 mb-4">
92
                                  <div className="flex items-center gap-2"> 
93
                                  <ToggleSwitch color="blue" checked={isMonthlyPayment} label="Månatlig betalning" onChange={() => setIsMonthlyPayment(!isMonthlyPayment)} />
94
                                 </div>
95
                                  <div className="w-full">
96
                                      <Label htmlFor="ackkost" >Ackumulerad kostnad</Label>
97
                                      <TextInput color="blue" id="ackkost" type="text" value= {accumulatedCost} placeholder="" disabled/>
98
                                  </div>
99
            
100
                                  <div className="w-full">
101
                                    <Label htmlFor=" balans" >Hur mycket vill du fylla på med?</Label>
102 2
                                    <TextInput color="blue" id="balans" type="text" value={balance} onChange={(e)=> setBalance(parseFloat(e.target.value) || 0) } placeholder="" required/>
103
                                  </div>
104
                              </div>
105
                              <div className="flex items-center space-x-4">
106
                                  <Button type="submit" color="blue">
107
                                    Fyll på eller uppdatera!
108
                                  </Button>
109
                                  <Button color="light">
110
                                    <Link to="/customerstartpage">Gå tillbaka</Link>
111
                                  </Button>
112
                              </div>
113
                          </form>
114
                      </div>
115
                  </section>
116
        </div>
117
    </div>
118
);
119
};
120
121
export default UserInfoPage;
122