From 68f4836935fafb4f13b347b9e28b044a6ed9bf51 Mon Sep 17 00:00:00 2001 From: andrei Date: Sat, 5 Oct 2024 14:11:29 +0500 Subject: [PATCH] ._. --- src/AppRouter.jsx | 4 +- src/api.jsx | 59 ++++++++ src/components/Header.jsx | 5 + src/pages/Users.jsx | 281 ++++++++++++++++++++++++++++++++++++++ 4 files changed, 348 insertions(+), 1 deletion(-) create mode 100644 src/pages/Users.jsx diff --git a/src/AppRouter.jsx b/src/AppRouter.jsx index 51ac508..3896a11 100755 --- a/src/AppRouter.jsx +++ b/src/AppRouter.jsx @@ -8,6 +8,7 @@ import FederalDistricts from "./pages/FederalDistricts.jsx"; import Roles from "./pages/Roles.jsx"; import Statuses from "./pages/Statuses.jsx"; import Trucks from "./pages/Trucks.jsx"; +import Users from "./pages/Users.jsx"; const RoutesComponent = () => ( @@ -19,7 +20,8 @@ const RoutesComponent = () => ( } /> } /> } />{" "} - } /> + } />{" "} + } /> ); diff --git a/src/api.jsx b/src/api.jsx index e289cab..6a8b7df 100755 --- a/src/api.jsx +++ b/src/api.jsx @@ -399,3 +399,62 @@ export const deleteTruck = async (id) => { throw error; } }; + +export const getUsers = async () => { + try { + const response = await axios.get(`${API_URL}/users`, { + headers: { + Authorization: `Bearer ${getAuthToken()}`, + Accept: "application/json", + }, + }); + return response.data; + } catch (error) { + console.log("Ошибка при загрузке пользователей:", error); + throw error; + } +}; + +export const createUser = async (userData) => { + try { + const response = await axios.post(`${API_URL}/users`, userData, { + headers: { + Authorization: `Bearer ${getAuthToken()}`, + "Content-Type": "application/json", + }, + }); + return response.data; + } catch (error) { + console.log("Ошибка при создании пользователя:", error); + throw error; + } +}; + +export const updateUser = async (id, userData) => { + try { + const response = await axios.put(`${API_URL}/users/${id}`, userData, { + headers: { + Authorization: `Bearer ${getAuthToken()}`, + "Content-Type": "application/json", + }, + }); + return response.data; + } catch (error) { + console.log("Ошибка при обновлении пользователя:", error); + throw error; + } +}; + +export const deleteUser = async (id) => { + try { + await axios.delete(`${API_URL}/users/${id}`, { + headers: { + Authorization: `Bearer ${getAuthToken()}`, + Accept: "application/json", + }, + }); + } catch (error) { + console.log("Ошибка при удалении пользователя:", error); + throw error; + } +}; diff --git a/src/components/Header.jsx b/src/components/Header.jsx index 810826e..cae6452 100644 --- a/src/components/Header.jsx +++ b/src/components/Header.jsx @@ -55,6 +55,11 @@ const Header = () => { Грузовики +
  • + + Пользователи + +
  • {isAuthenticated ? ( diff --git a/src/pages/Users.jsx b/src/pages/Users.jsx new file mode 100644 index 0000000..8df1425 --- /dev/null +++ b/src/pages/Users.jsx @@ -0,0 +1,281 @@ +import React, { useState, useEffect } from "react"; +import SelectionDialog from "../components/SelectionDialog.jsx"; +import { useNavigate } from "react-router-dom"; +import { getAuthToken } from "../api.jsx"; +import { + getUsers, + createUser, + updateUser, + deleteUser, + getRoles, +} from "../api.jsx"; + +const Users = () => { + const [users, setUsers] = useState([]); + const [roles, setRoles] = useState([]); + const [newUser, setNewUser] = useState({ + first_name: "", + last_name: "", + login: "", + password: "", + role_id: "", + }); + const [editingUserId, setEditingUserId] = useState(null); + const [error, setError] = useState(null); + const [showRoleDialog, setShowRoleDialog] = useState(false); + const navigate = useNavigate(); + + useEffect(() => { + fetchUsers(); + fetchRoles(); + }, []); + + const fetchUsers = async () => { + try { + const data = await getUsers(); + console.log(data); + setUsers(data); + } catch (error) { + console.error("Ошибка при загрузке пользователей:", error); + } + }; + + const fetchRoles = async () => { + try { + const data = await getRoles(); + setRoles(data); + } catch (error) { + console.error("Ошибка при загрузке ролей:", error); + } + }; + + const handleInputChange = (e) => { + const { name, value } = e.target; + setNewUser({ ...newUser, [name]: value }); + }; + + const handleSubmit = async (e) => { + e.preventDefault(); + + if ( + !newUser.first_name || + !newUser.last_name || + !newUser.login || + !newUser.password || + !newUser.role_id + ) { + setError("Пожалуйста, заполните все поля."); + return; + } + + try { + if (editingUserId) { + await updateUser(editingUserId, newUser); + } else { + await createUser(newUser); + } + fetchUsers(); + resetForm(); + } catch (error) { + console.error( + "Ошибка при добавлении или обновлении пользователя:", + error + ); + } + }; + + const handleEdit = (user) => { + setNewUser({ + first_name: user.first_name, + last_name: user.last_name, + login: user.login, + password: user.password, + role_id: user.role_id, + role_name: user.role_name, + }); + setEditingUserId(user.id); + }; + + const handleDelete = async (userId) => { + try { + await deleteUser(userId); + fetchUsers(); + } catch (error) { + console.error("Ошибка при удалении пользователя:", error); + } + }; + + const resetForm = () => { + setNewUser({ + first_name: "", + last_name: "", + login: "", + password: "", + role_id: "", + }); + setEditingUserId(null); + }; + + const handleDialogSelectRole = (selectedItem) => { + setNewUser({ + ...newUser, + role_id: selectedItem.id, + role_name: selectedItem.name, + }); + setShowRoleDialog(false); + }; + + if (getAuthToken() === null) { + navigate("/login"); + } + + return ( +
    +

    Пользователи

    +
    +
    + + +
    + +
    + + +
    + +
    + + +
    + +
    + + +
    + +
    + setShowRoleDialog(true)} + /> +
    + +
    +
    + +
    + + +
    + {error && ( +
    + {error} +
    + )} +
    +

    Список пользователей

    + + + + + + + + + + + + {users.map((user) => ( + + + + + + + + ))} + +
    ИмяФамилияЛогинРольДействия
    {user.first_name}{user.last_name}{user.login}{user.role_name} +
    + + +
    +
    + + setShowRoleDialog(false)} + items={roles} + columns={[ + { key: "id", label: "ID" }, + { key: "name", label: "Название" }, + ]} + onSelect={handleDialogSelectRole} + /> +
    + ); +}; + +export default Users;