From 45561d881dd8d7770501443f91a188fceda8d047 Mon Sep 17 00:00:00 2001 From: KilianBre <87305837+KilianBre@users.noreply.github.com> Date: Fri, 10 May 2024 00:22:09 +0200 Subject: [PATCH] =?UTF-8?q?Rajout=20des=20routes=20codepostal=20et=20city?= =?UTF-8?q?=20+=20am=C3=A9lioration=20du=20code=20existant?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../app/Http/Controllers/CityController.php | 20 ++ .../Http/Controllers/PostalCodeController.php | 20 ++ backend/routes/api.php | 7 + .../(front-office)/profil/page.tsx | 206 ++++++++++++------ frontend/src/types/city.ts | 4 + frontend/src/types/postalCode.ts | 4 + 6 files changed, 191 insertions(+), 70 deletions(-) create mode 100644 backend/app/Http/Controllers/CityController.php create mode 100644 backend/app/Http/Controllers/PostalCodeController.php create mode 100644 frontend/src/types/city.ts create mode 100644 frontend/src/types/postalCode.ts diff --git a/backend/app/Http/Controllers/CityController.php b/backend/app/Http/Controllers/CityController.php new file mode 100644 index 0000000..33bd7c0 --- /dev/null +++ b/backend/app/Http/Controllers/CityController.php @@ -0,0 +1,20 @@ +json($cities); + } +} diff --git a/backend/app/Http/Controllers/PostalCodeController.php b/backend/app/Http/Controllers/PostalCodeController.php new file mode 100644 index 0000000..faaf12f --- /dev/null +++ b/backend/app/Http/Controllers/PostalCodeController.php @@ -0,0 +1,20 @@ +json($postalCodes); + } +} diff --git a/backend/routes/api.php b/backend/routes/api.php index 1a7ff41..8bdb76b 100644 --- a/backend/routes/api.php +++ b/backend/routes/api.php @@ -7,6 +7,8 @@ use App\Http\Controllers\UserController; use App\Http\Controllers\Statistics\ConnectionController; use App\Http\Controllers\UserHistoryController; +use App\Http\Controllers\CityController; +use App\Http\Controllers\PostalCodeController; use App\Http\Controllers\RessourceController; use Illuminate\Support\Facades\Route; @@ -31,6 +33,11 @@ // Ressources Route::get('ressource/{id}', [RessourceController::class, 'getRessource']); +// Cities +Route::get('cities', [CityController::class, 'getAllCities']); + +// Postal Codes +Route::get('postalCodes', [PostalCodeController::class, 'getAllPostalCodes']); // Connected access Route::group(['middleware' => ['jwt.auth']], function () { diff --git a/frontend/src/app/(connected)/(front-office)/profil/page.tsx b/frontend/src/app/(connected)/(front-office)/profil/page.tsx index 6c5d4b2..ae07118 100644 --- a/frontend/src/app/(connected)/(front-office)/profil/page.tsx +++ b/frontend/src/app/(connected)/(front-office)/profil/page.tsx @@ -1,9 +1,11 @@ "use client" -import React, { useEffect, useState } from 'react'; -import { Card, Avatar, Typography, Spin, Button, message, Form, Space, Input } from 'antd'; +import React, { useEffect, useState, useCallback } from 'react'; +import { Card, Avatar, Typography, Spin, Button, message, Form, Space, Input, Select } from 'antd'; import { EditOutlined, SaveOutlined, LeftOutlined } from '@ant-design/icons'; import { UserOutlined } from '@ant-design/icons'; import type User from '@/types/user'; +import type City from '@/types/city'; +import type PostalCode from '@/types/postalCode'; import { useUser } from '@/providers/userProvider'; import { Row, Col } from 'antd'; import axios from 'axios'; @@ -15,6 +17,8 @@ import { Span } from 'next/dist/trace'; const { Meta } = Card; const { Title } = Typography; +const { Option } = Select; + const UserProfilePage = () => { const [userData, setUserData] = useState(null); @@ -23,73 +27,122 @@ const UserProfilePage = () => { const { user } = useUser(); const [form] = Form.useForm(); const [selectedCountry, setSelectedCountry] = useState(null); + const [cities, setCities] = useState([]); + const [postalCodes, setPostalCodes] = useState([]); - useEffect(() => { - const fetchUserData = async () => { - try { - setUserData(user); - form.setFieldsValue({ - id: user?.id, - lastName: user?.lastName, - firstName: user?.firstName, - email: user?.email, - city: user?.city, - postalCode: user?.postalCode, - country: user?.country, - role: user?.role, - }); - } catch (error) { - console.error('Error fetching user data:', error); - throw new Error('Utilisateur non connecté ou non trouvé'); - } finally { - setLoading(false); - } - }; - fetchUserData(); + // Déclarez fetchUserData en dehors de l'effet useEffect + const fetchUserData = useCallback(async () => { + try { + setUserData(user); + form.setFieldsValue({ + id: user?.id, + lastName: user?.lastName, + firstName: user?.firstName, + email: user?.email, + city: user?.city, + postalCode: user?.postalCode, + country: user?.country, + role: user?.role, + }); + } catch (error) { + console.error('Error fetching user data:', error); + throw new Error('Utilisateur non connecté ou non trouvé'); + } finally { + setLoading(false); + } }, [form, user]); - const handleEdit = () => { - // Activer le mode d'édition lors du clic sur le bouton "Modifier" - setEditing(true); + + const fetchCities = async () => { + try { + // Appel API pour récupérer la liste des villes depuis la base de données + const response = await axios({ + method: 'GET', + baseURL: process.env.NEXT_PUBLIC_BACKEND_API_URL, + url: '/cities', + responseType: 'json', + timeout: 10000, + withCredentials: true, + }); + setCities(response.data); // Stockez les villes dans l'état cities + } catch (error) { + console.error('Error fetching cities:', error); + message.error('Une erreur est survenue lors du chargement des villes.'); + } + }; + + const fetchPostalCode = async () => { + try { + // Appel API pour récupérer la liste des codes postaux depuis la base de données + const response = await axios({ + method: 'GET', + baseURL: process.env.NEXT_PUBLIC_BACKEND_API_URL, + url: '/postalCodes', + responseType: 'json', + timeout: 10000, + withCredentials: true, + }); + setPostalCodes(response.data); // Mettre à jour l'état des codes postaux avec la réponse de l'API + } catch (error) { + console.error('Error fetching postal code:', error); + message.error('Une erreur est survenue lors du chargement des codes postaux.'); + } }; + useEffect(() => { + fetchUserData(); + fetchCities(); + fetchPostalCode(); + }, [form, user, fetchUserData]); + + // Fonction pour gérer l'enregistrement des modifications de l'utilisateur const handleSave = async () => { let isFormValid = false; - + try { - await form.validateFields(); - - const values = form.getFieldsValue(); - - console.log('Données envoyées :', { - ...values, - }); - const response = await axios({ - method: 'post', - baseURL: process.env.NEXT_PUBLIC_BACKEND_API_URL, - url: "/profil/update", - data: { - ...values, - }, - withCredentials: true, - responseType: 'json', - timeout: 10000, - }); - - setUserData(response.data); - message.success('Data saved successfully!'); - - isFormValid = true; + await form.validateFields(); + + const values = form.getFieldsValue(); + + console.log('Données envoyées :', { + ...values, + }); + + // Appel à l'API pour enregistrer les modifications de l'utilisateur + const response = await axios({ + method: 'post', + baseURL: process.env.NEXT_PUBLIC_BACKEND_API_URL, + url: "/profil/update", + data: { + ...values, + }, + withCredentials: true, + responseType: 'json', + timeout: 10000, + }); + + // Si la mise à jour est réussie, actualisez les données de l'utilisateur + fetchUserData(); + + message.success('Data saved successfully!'); + + isFormValid = true; } catch (error) { - console.error('Error saving user data:', error); + console.error('Error saving user data:', error); } finally { - if (isFormValid) { - setEditing(false); - } + if (isFormValid) { + setEditing(false); + } } - }; - + }; + + + const handleEdit = () => { + // Activer le mode d'édition lors du clic sur le bouton "Modifier" + setEditing(true); + }; + const handleCancel = () => { // Désactiver le mode édition lors du clic sur le bouton "Retour" @@ -213,7 +266,16 @@ const UserProfilePage = () => { } ]} > - {editing ? : {userData?.city}} + {editing ? ( + + + ) : ( + {userData?.city} + )} { required: editing, message: 'Veuillez renseigner un code postal', }, - { - pattern: postalCodeRegex, - len: 5, - message: 'Le code postal doit contenir uniquement des chiffres et doit avoir une longueur de 5', - } ]} > - {editing ? : {userData?.postalCode}} + {editing ? ( + + + ) : ( + {userData?.postalCode} + )} { {userData?.role} - { userData?.isEmailVerified ? ( + {userData?.isEmailVerified ? ( {`Email vérifié, vous avez accès à toutes les fonctionnalités`} ) - : ( - - {`Email non vérifié, vous n'avez pas accès à toutes les fonctionnalités`} - - ) + : ( + + {`Email non vérifié, vous n'avez pas accès à toutes les fonctionnalités`} + + ) } diff --git a/frontend/src/types/city.ts b/frontend/src/types/city.ts new file mode 100644 index 0000000..100835c --- /dev/null +++ b/frontend/src/types/city.ts @@ -0,0 +1,4 @@ +export default interface City { + id: number; + name: string; +} diff --git a/frontend/src/types/postalCode.ts b/frontend/src/types/postalCode.ts new file mode 100644 index 0000000..cd88be6 --- /dev/null +++ b/frontend/src/types/postalCode.ts @@ -0,0 +1,4 @@ +export default interface PostalCode { + id: number; + postal_code: string; +}