gestion accueil MAJ

This commit is contained in:
sebvtl728
2025-02-02 20:34:44 +01:00
parent f70d21ae71
commit 6eaa0fcf64
3 changed files with 188 additions and 160 deletions
+37 -35
View File
@@ -13,6 +13,7 @@ import {
import LogoutIcon from "@mui/icons-material/Logout"; // Icône de déconnexion import LogoutIcon from "@mui/icons-material/Logout"; // Icône de déconnexion
import ArticleIcon from "@mui/icons-material/Article"; import ArticleIcon from "@mui/icons-material/Article";
import DashboardIcon from "@mui/icons-material/Dashboard"; import DashboardIcon from "@mui/icons-material/Dashboard";
import HomeIcon from "@mui/icons-material/Home"; // Icône pour la gestion page d'accueil
function Dashboard() { function Dashboard() {
const navigate = useNavigate(); const navigate = useNavigate();
@@ -51,10 +52,10 @@ function Dashboard() {
borderRadius: 3, borderRadius: 3,
boxShadow: 6, boxShadow: 6,
textAlign: "center", textAlign: "center",
position: "relative", // Permet de positionner des éléments enfants position: "relative",
}} }}
> >
{/* Bouton de déconnexion placé en haut à gauche de la boîte blanche */} {/* Bouton de déconnexion placé en haut à gauche */}
<Button <Button
variant="contained" variant="contained"
color="error" color="error"
@@ -69,9 +70,7 @@ function Dashboard() {
fontSize: "0.875rem", fontSize: "0.875rem",
padding: "6px 12px", padding: "6px 12px",
}} }}
> />
</Button>
{/* En-tête */} {/* En-tête */}
<Typography variant="h4" sx={{ fontWeight: "bold", mb: 4, mt: 4 }}> <Typography variant="h4" sx={{ fontWeight: "bold", mb: 4, mt: 4 }}>
@@ -81,7 +80,39 @@ function Dashboard() {
{/* Cartes du Dashboard */} {/* Cartes du Dashboard */}
<Grid container spacing={3} justifyContent="center"> <Grid container spacing={3} justifyContent="center">
<Grid item xs={12} sm={6} md={4}> {/* ✅ Gestion Page d'Accueil - Première carte */}
<Grid item xs={12} sm={6}>
<Card
onClick={() => navigate("/admin/Gestion-Page-Accueil")}
sx={{
cursor: "pointer",
textAlign: "center",
padding: 2,
transition: "0.3s",
"&:hover": {
backgroundColor: "#0e467f",
color: "#ffffff",
transform: "scale(1.05)",
boxShadow: 8,
},
"&:hover svg": {
fill: "#ffffff",
},
}}
>
<CardContent>
<IconButton sx={{ fontSize: 40, color: "#0e467f" }}>
<HomeIcon fontSize="inherit" />
</IconButton>
<Typography variant="h6" sx={{ fontWeight: "bold" }}>
Gestion Page d'Accueil
</Typography>
</CardContent>
</Card>
</Grid>
{/* ✅ Gérer les Articles - Deuxième carte */}
<Grid item xs={12} sm={6}>
<Card <Card
onClick={() => navigate("/admin/gestion-articles")} onClick={() => navigate("/admin/gestion-articles")}
sx={{ sx={{
@@ -109,35 +140,6 @@ function Dashboard() {
</Typography> </Typography>
</CardContent> </CardContent>
</Card> </Card>
<Card
onClick={() => navigate("/admin/Gestion-Page-Accueil")}
sx={{
cursor: "pointer",
textAlign: "center",
padding: 2,
transition: "0.3s",
"&:hover": {
backgroundColor: "#0e467f",
color: "#ffffff",
transform: "scale(1.05)",
boxShadow: 8,
},
"&:hover svg": {
fill: "#ffffff",
},
}}
>
<CardContent>
<IconButton sx={{ fontSize: 40, color: "#0e467f" }}>
<ArticleIcon fontSize="inherit" />
</IconButton>
<Typography variant="h6" sx={{ fontWeight: "bold" }}>
Gestion Page d'Accueil
</Typography>
</CardContent>
</Card>
</Grid> </Grid>
</Grid> </Grid>
</Box> </Box>
@@ -1,144 +1,167 @@
import React, { useState, useEffect } from "react"; import React, { useState, useEffect } from "react";
import { updateHomePageACF, uploadImage } from "../../wordpress";
import { useNavigate } from "react-router-dom"; import { useNavigate } from "react-router-dom";
import { updateHomePageACF } from "../../wordpress"; import { Box, Button, TextField, Typography, Snackbar, Alert, Paper, Card, CardMedia } from "@mui/material";
import { getToken } from "../../auth"; import api from "../../api";
import {
Box, const PAGE_ID = 13; // ID de la page d'accueil
Typography,
TextField,
Button,
Container,
Paper,
} from "@mui/material";
const GestionPageAccueil = () => { const GestionPageAccueil = () => {
const navigate = useNavigate();
const [heroTitle, setHeroTitle] = useState(""); const [heroTitle, setHeroTitle] = useState("");
const [heroText, setHeroText] = useState(""); const [heroText, setHeroText] = useState("");
const [loading, setLoading] = useState(true); const [heroImage, setHeroImage] = useState(null);
const [error, setError] = useState(null); const [heroImageId, setHeroImageId] = useState(null);
const [message, setMessage] = useState({ type: "", text: "" });
const navigate = useNavigate(); // 🔥 Gestion de la navigation
// ✅ Vérification de l'authentification (Redirection si non connecté) // ✅ Charger les données ACF existantes
useEffect(() => {
if (!getToken()) {
navigate("/admin/login");
}
}, [navigate]);
// ✅ Chargement des données ACF depuis WordPress
useEffect(() => { useEffect(() => {
const fetchPageData = async () => { const fetchPageData = async () => {
try { try {
const response = await fetch( const response = await api.get(`wp/v2/pages/${PAGE_ID}?_fields=acf`);
"https://preprod.octopusdesign.fr/api-octopus/server/wp-json/wp/v2/pages/13?_fields=acf", const acfData = response.data.acf;
{
method: "GET",
headers: {
"Content-Type": "application/json",
},
}
);
if (!response.ok) { if (acfData) {
throw new Error("Erreur de chargement des données"); setHeroTitle(acfData.hero_title || "");
} setHeroText(acfData.hero_text || "");
const data = await response.json(); if (acfData.img_hero) {
setHeroTitle(data.acf?.hero_title || ""); setHeroImageId(acfData.img_hero);
setHeroText(data.acf?.hero_text || ""); const imageResponse = await api.get(`wp/v2/media/${acfData.img_hero}`);
setLoading(false); setHeroImage(imageResponse.data.source_url);
}
}
} catch (error) { } catch (error) {
console.error("❌ Erreur chargement ACF :", error); console.error("❌ Erreur chargement ACF :", error);
setError("Impossible de charger les données."); setMessage({ type: "error", text: "Erreur lors du chargement des données." });
setLoading(false);
} }
}; };
fetchPageData(); fetchPageData();
}, []); }, []);
// ✅ Mise à jour des champs ACF // ✅ Sauvegarde des données ACF
const handleSave = async () => { const handleSave = async () => {
try { try {
const newData = { const formData = {
acf: {
hero_title: heroTitle, hero_title: heroTitle,
hero_text: heroText, hero_text: heroText,
img_hero: heroImageId || null, // ✅ Mise à jour avec l'ID de l'image
}
}; };
console.log("📢 Données envoyées pour mise à jour ACF :", newData); console.log("📢 Envoi des nouvelles données ACF :", formData);
const updatedData = await updateHomePageACF(13, newData); await updateHomePageACF(PAGE_ID, formData);
alert("✅ Mise à jour réussie !"); setMessage({ type: "success", text: "✅ Mise à jour réussie !" });
console.log("🔍 Données mises à jour reçues :", updatedData);
window.location.reload(); // 🔄 Rafraîchissement pour voir les changements // ✅ 🔥 Redirection vers le Dashboard après 1.5 sec
setTimeout(() => {
navigate("/admin/dashboard");
}, 1500);
} catch (error) { } catch (error) {
console.error("❌ Erreur mise à jour :", error); console.error("❌ Erreur mise à jour ACF :", error);
alert("⚠ Impossible de mettre à jour les champs ACF."); setMessage({ type: "error", text: "❌ Échec de la mise à jour. Vérifie les permissions WordPress." });
}
};
// ✅ Gestion de l'upload d'image
const handleImageUpload = async (event) => {
const file = event.target.files[0];
if (!file) return;
try {
const imageId = await uploadImage(file);
setHeroImageId(imageId);
const imageResponse = await api.get(`wp/v2/media/${imageId}`);
setHeroImage(imageResponse.data.source_url);
setMessage({ type: "success", text: "✅ Image uploadée avec succès !" });
} catch (error) {
console.error("❌ Erreur lors de l'upload de l'image :", error);
setMessage({ type: "error", text: "❌ Échec de l'upload de l'image." });
} }
}; };
return ( return (
<Container maxWidth="md" sx={{ mt: 5 }}> <Box sx={{ padding: "40px", maxWidth: "700px", margin: "auto", mt: 5 }}>
<Paper elevation={3} sx={{ padding: 4, borderRadius: 3 }}> <Paper sx={{ padding: "30px", borderRadius: "10px", boxShadow: 3 }}>
{/* ✅ En-tête */}
<Typography variant="h4" sx={{ fontWeight: "bold", textAlign: "center", mb: 3 }}> <Typography variant="h4" sx={{ fontWeight: "bold", textAlign: "center", mb: 3 }}>
Gestion de la Page d'Accueil 🏠 Gestion de la Page d'Accueil
</Typography> </Typography>
{/* ✅ Affichage du statut de chargement */} {message.text && (
{loading ? ( <Snackbar open autoHideDuration={3000} onClose={() => setMessage({ type: "", text: "" })}>
<Typography textAlign="center">Chargement des données...</Typography> <Alert severity={message.type} sx={{ width: '100%' }}>
) : error ? ( {message.text}
<Typography textAlign="center" color="error"> </Alert>
{error} </Snackbar>
</Typography> )}
) : (
<> {/* ✅ Aperçu de l'image actuelle */}
{/* ✅ Formulaire de modification */} {heroImage && (
<Card sx={{ mb: 3, boxShadow: 3 }}>
<CardMedia
component="img"
height="200"
image={heroImage}
alt="Image actuelle du héros"
sx={{ objectFit: "cover" }}
/>
</Card>
)}
{/* ✅ Bouton pour modifier l'image */}
<Button variant="outlined" component="label" fullWidth sx={{ mb: 3 }}>
Modifier l'image
<input type="file" hidden onChange={handleImageUpload} />
</Button>
<TextField <TextField
label="Titre Héros" label="Titre Héros"
fullWidth fullWidth
margin="normal"
variant="outlined" variant="outlined"
value={heroTitle} value={heroTitle}
onChange={(e) => setHeroTitle(e.target.value)} onChange={(e) => setHeroTitle(e.target.value)}
sx={{ mb: 2 }} sx={{ "& .MuiInputBase-input": { fontSize: "1.2rem" } }}
/> />
<TextField <TextField
label="Texte Héros" label="Texte Héros"
fullWidth fullWidth
margin="normal"
variant="outlined" variant="outlined"
value={heroText} value={heroText}
onChange={(e) => setHeroText(e.target.value)} onChange={(e) => setHeroText(e.target.value)}
sx={{ mb: 2 }} multiline
rows={3}
sx={{ "& .MuiInputBase-input": { fontSize: "1rem" } }}
/> />
{/* ✅ Bouton d'enregistrement */}
<Button <Button
variant="contained" variant="contained"
color="primary" color="primary"
fullWidth fullWidth
sx={{ mt: 3 }} sx={{ mt: 3, fontSize: "1.1rem", fontWeight: "bold" }}
onClick={handleSave} onClick={handleSave}
> >
Enregistrer les modifications 💾 Enregistrer les modifications
</Button> </Button>
{/* ✅ Bouton retour au Dashboard */} {/* ✅ Bouton retour Dashboard */}
<Button <Button
variant="outlined" variant="outlined"
color="secondary" color="secondary"
fullWidth fullWidth
sx={{ mt: 2 }} sx={{ mt: 2, fontSize: "1rem", fontWeight: "bold" }}
onClick={() => navigate("/admin/dashboard")} onClick={() => navigate("/admin/dashboard")}
> >
Retour au Dashboard Retour au Dashboard
</Button> </Button>
</>
)}
</Paper> </Paper>
</Container> </Box>
); );
}; };
@@ -278,10 +278,13 @@ add_action('rest_api_init', function () {
'acf', // Champ ACF 'acf', // Champ ACF
[ [
'get_callback' => function ($object) { 'get_callback' => function ($object) {
return get_fields($object['id']); return get_fields($object['id']); // ✅ Vérifie que l'ID est correct
}, },
'update_callback' => function ($value, $object) { 'update_callback' => function ($value, $object) {
return update_fields($object->ID, $value); foreach ($value as $field_key => $field_value) {
update_field($field_key, $field_value, $object->ID); // ✅ Correction ici
}
return true;
}, },
'schema' => null, 'schema' => null,
] ]