gestion accueil MAJ avec gestion photo hero

This commit is contained in:
sebvtl728
2025-02-02 22:20:15 +01:00
parent 6eaa0fcf64
commit f25b0fa6e4
@@ -1,167 +1,223 @@
import React, { useState, useEffect } from "react"; import { useState, useEffect } from "react";
import { updateHomePageACF, uploadImage } from "../../wordpress";
import { useNavigate } from "react-router-dom"; import { useNavigate } from "react-router-dom";
import { Box, Button, TextField, Typography, Snackbar, Alert, Paper, Card, CardMedia } from "@mui/material"; import { updateHomePageACF, uploadImage } from "../../wordpress";
import api from "../../api"; import { getToken } from "../../auth";
import {
const PAGE_ID = 13; // ID de la page d'accueil Typography,
TextField,
Button,
Container,
Paper,
Box,
CircularProgress,
} 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 [heroImage, setHeroImage] = useState(null); const [heroImage, setHeroImage] = useState(null);
const [heroImageId, setHeroImageId] = useState(null); const [loading, setLoading] = useState(true);
const [message, setMessage] = useState({ type: "", text: "" }); const [error, setError] = useState(null);
const navigate = useNavigate(); // 🔥 Gestion de la navigation const [successMessage, setSuccessMessage] = useState("");
// ✅ Charger les données ACF existantes // ✅ Vérification de l'authentification (Redirection si non connecté)
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 api.get(`wp/v2/pages/${PAGE_ID}?_fields=acf`); const response = await fetch(
const acfData = response.data.acf; "https://preprod.octopusdesign.fr/api-octopus/server/wp-json/wp/v2/pages/13?_fields=acf",
{
if (acfData) { method: "GET",
setHeroTitle(acfData.hero_title || ""); headers: {
setHeroText(acfData.hero_text || ""); "Content-Type": "application/json",
},
if (acfData.img_hero) {
setHeroImageId(acfData.img_hero);
const imageResponse = await api.get(`wp/v2/media/${acfData.img_hero}`);
setHeroImage(imageResponse.data.source_url);
} }
);
if (!response.ok) {
throw new Error("Erreur de chargement des données");
} }
const data = await response.json();
setHeroTitle(data.acf?.hero_title || "");
setHeroText(data.acf?.hero_text || "");
// ✅ Récupération de l'image Hero
if (data.acf?.img_hero) {
const mediaResponse = await fetch(
`https://preprod.octopusdesign.fr/api-octopus/server/wp-json/wp/v2/media/${data.acf.img_hero}`
);
const mediaData = await mediaResponse.json();
setHeroImage(mediaData.source_url);
}
setLoading(false);
} catch (error) { } catch (error) {
console.error("❌ Erreur chargement ACF :", error); console.error("❌ Erreur chargement ACF :", error);
setMessage({ type: "error", text: "Erreur lors du chargement des données." }); setError("Impossible de charger les données.");
setLoading(false);
} }
}; };
fetchPageData(); fetchPageData();
}, []); }, []);
// ✅ Sauvegarde des données ACF // ✅ Mise à jour des champs ACF
const handleSave = async () => { const handleSave = async () => {
try { try {
const formData = { const newData = {
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("📢 Envoi des nouvelles données ACF :", formData); console.log("📢 Données envoyées pour mise à jour ACF :", newData);
await updateHomePageACF(PAGE_ID, formData); await updateHomePageACF(13, newData);
setMessage({ type: "success", text: "✅ Mise à jour réussie !" }); setSuccessMessage("✅ Modifications enregistrées avec succès !");
setTimeout(() => setSuccessMessage(""), 3000);
// ✅ 🔥 Redirection vers le Dashboard après 1.5 sec
setTimeout(() => {
navigate("/admin/dashboard");
}, 1500);
} catch (error) { } catch (error) {
console.error("❌ Erreur mise à jour ACF :", error); console.error("❌ Erreur mise à jour :", error);
setMessage({ type: "error", text: "❌ Échec de la mise à jour. Vérifie les permissions WordPress." }); setError("⚠ Impossible de mettre à jour les champs ACF.");
} }
}; };
// ✅ Gestion de l'upload d'image // ✅ Gérer le téléversement dune nouvelle image Hero
const handleImageUpload = async (event) => { const handleImageUpload = async (event) => {
const file = event.target.files[0]; const file = event.target.files[0];
if (!file) return; if (file) {
try { try {
const imageId = await uploadImage(file); const imageId = await uploadImage(file);
setHeroImageId(imageId); setHeroImage(URL.createObjectURL(file)); // Affichage immédiat
await updateHomePageACF(13, { img_hero: imageId });
const imageResponse = await api.get(`wp/v2/media/${imageId}`); setSuccessMessage("✅ Image mise à jour !");
setHeroImage(imageResponse.data.source_url);
setMessage({ type: "success", text: "✅ Image uploadée avec succès !" });
} catch (error) { } catch (error) {
console.error("❌ Erreur lors de l'upload de l'image :", error); console.error("❌ Erreur lors de l'upload :", error);
setMessage({ type: "error", text: "❌ Échec de l'upload de l'image." }); setError("❌ Échec de l'upload de l'image.");
}
} }
}; };
return ( return (
<Box sx={{ padding: "40px", maxWidth: "700px", margin: "auto", mt: 5 }}> <Container maxWidth="md" sx={{ mt: 16, mb:5 }}>
<Paper sx={{ padding: "30px", borderRadius: "10px", boxShadow: 3 }}> <Paper elevation={6} sx={{ padding: 4, borderRadius: 3, backgroundColor: "#f8f9fa" }}>
<Typography variant="h4" sx={{ fontWeight: "bold", textAlign: "center", mb: 3 }}> {/* ✅ En-tête */}
<Typography variant="h4" sx={{ fontWeight: "bold", textAlign: "center", mb: 3, color: "#0e467f" }}>
🏠 Gestion de la Page d'Accueil 🏠 Gestion de la Page d'Accueil
</Typography> </Typography>
{message.text && ( {/* ✅ Affichage du statut de chargement */}
<Snackbar open autoHideDuration={3000} onClose={() => setMessage({ type: "", text: "" })}> {loading ? (
<Alert severity={message.type} sx={{ width: '100%' }}> <Box display="flex" justifyContent="center" alignItems="center">
{message.text} <CircularProgress />
</Alert> </Box>
</Snackbar> ) : error ? (
<Typography textAlign="center" color="error">
{error}
</Typography>
) : (
<>
{/* ✅ Message de succès */}
{successMessage && (
<Box
sx={{
backgroundColor: "#d4edda",
color: "#155724",
padding: "12px",
borderRadius: "8px",
marginBottom: "16px",
textAlign: "center",
boxShadow: "0px 2px 10px rgba(0,0,0,0.1)",
}}
>
<Typography variant="body1" fontWeight="bold">
{successMessage}
</Typography>
</Box>
)} )}
{/* ✅ Aperçu de l'image actuelle */} {/* ✅ Affichage de l'image actuelle */}
{heroImage && ( {heroImage && (
<Card sx={{ mb: 3, boxShadow: 3 }}> <Box sx={{ textAlign: "center", mb: 2 }}>
<CardMedia <img
component="img" src={heroImage}
height="200" alt="Hero"
image={heroImage} style={{
alt="Image actuelle du héros" width: "100%",
sx={{ objectFit: "cover" }} maxHeight: "250px",
objectFit: "cover",
borderRadius: "8px",
}}
/> />
</Card> </Box>
)} )}
{/* ✅ Bouton pour modifier l'image */} {/* ✅ Bouton pour changer l'image */}
<Button variant="outlined" component="label" fullWidth sx={{ mb: 3 }}> <Button variant="contained" component="label" fullWidth sx={{ mb: 2 }}>
Modifier l'image 📸 Modifier l'Image Hero
<input type="file" hidden onChange={handleImageUpload} /> <input type="file" hidden onChange={handleImageUpload} />
</Button> </Button>
{/* ✅ Formulaire de modification */}
<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={{ "& .MuiInputBase-input": { fontSize: "1.2rem" } }} sx={{ mb: 2, backgroundColor: "#fff", borderRadius: "5px" }}
/> />
<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, backgroundColor: "#fff", borderRadius: "5px" }}
multiline multiline
rows={3} 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, fontSize: "1.1rem", fontWeight: "bold" }} sx={{
mt: 3,
fontSize: "1.1rem",
fontWeight: "bold",
color:"#ffffff",
backgroundColor: "#0e467f",
"&:hover": { backgroundColor: "#093a6b" },
}}
onClick={handleSave} onClick={handleSave}
> >
💾 Enregistrer les modifications 💾 Enregistrer les modifications
</Button> </Button>
{/* ✅ Bouton retour Dashboard */} {/* ✅ Bouton retour au Dashboard */}
<Button <Button
variant="outlined" variant="outlined"
color="secondary" color="secondary"
fullWidth fullWidth
sx={{ mt: 2, fontSize: "1rem", fontWeight: "bold" }} sx={{ mt: 2, fontSize: "1rem", fontWeight: "bold", borderColor: "#0e467f", color: "#0e467f" }}
onClick={() => navigate("/admin/dashboard")} onClick={() => navigate("/admin/dashboard")}
> >
Retour au Dashboard Retour au Dashboard
</Button> </Button>
</>
)}
</Paper> </Paper>
</Box> </Container>
); );
}; };