All files / src/pages ConfirmationPage.tsx

100% Statements 50/50
100% Branches 18/18
100% Functions 9/9
100% Lines 47/47

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153                                                    20x 20x 20x 20x 20x   20x   20x 20x 20x   20x   16x   16x 16x   16x 16x 2x     16x 4x 4x 4x   12x   2x 2x 2x 2x     10x 10x 10x 10x   10x 8x     6x     2x 2x     2x 2x   10x     10x     20x                   20x 8x                 12x 9x                         3x                             1x     1x     1x                  
import { useEffect, useState } from 'react';
import Box from '@mui/material/Box';
import Typography from '@mui/material/Typography';
import Button from '@mui/material/Button';
import { useLocation, useNavigate } from 'react-router-dom';
import { useTranslation } from 'react-i18next';
import { useAuthStore } from '../stores/useAuthStore';
import { useLanguageStore } from '../stores/useLanguageStore';
import { getPaymentStatus } from '../services/paymentService';
import OlympicLoader from '../components/OlympicLoader';
import { ErrorDisplay } from '../components/ErrorDisplay';
import { PageWrapper } from '../components/PageWrapper';
import Seo from '../components/Seo';
import { logError, logWarn } from '../utils/logger';
import { useCartStore } from '../stores/useCartStore';
 
interface LocationState {
  paymentUuid?: string;
}
 
interface PaymentDetails {
  status: string;
  paid_at: string;
}
 
export default function ConfirmationPage() {
  const { t } = useTranslation('checkout');
  const location = useLocation();
  const navigate = useNavigate();
  const token = useAuthStore((s) => s.authToken);
  const lang = useLanguageStore((s) => s.lang);
 
  const unlockCart = useCartStore((s) => s.unlockCart);
 
  const [loading, setLoading] = useState<boolean>(true);
  const [error, setError] = useState<string | null>(null);
  const [paymentInfo, setPaymentInfo] = useState<PaymentDetails | null>(null);
 
  useEffect(() => {
    // Dès l'arrivée sur cette page, on s'assure que le panier est déverrouillé
    unlockCart();
 
    const state = location.state as LocationState;
    let paymentUuid = state?.paymentUuid;
    // Optionnel: lire depuis query param si besoin
    const params = new URLSearchParams(location.search);
    if (!paymentUuid && params.get('paymentUuid')) {
      paymentUuid = params.get('paymentUuid')!;
    }
 
    if (!paymentUuid) {
      setError(t('errors.no_uuid'));
      setLoading(false);
      return;
    }
    if (!token) {
      // Si pas de token, rediriger vers login ou afficher message
      setError(t('errors.not_authenticated'));
      setLoading(false);
      navigate(`/login?next=${encodeURIComponent(location.pathname + location.search)}`);
      return;
    }
 
    const fetchInfo = async () => {
      setLoading(true);
      setError(null);
      try {
        // Ici on utilise getPaymentStatus pour récupérer le statut / détails
        const { status, data } = await getPaymentStatus(paymentUuid, token);
        if (status === 200 && data) {
          // data correspond à PaymentStatusResponse, éventuellement wrapper selon votre service
          // Si getPaymentStatus renvoie { data: PaymentStatusResponse }, c’est correct.
          setPaymentInfo(data as PaymentDetails);
        } else {
          // statut inattendu
          logWarn('Unexpected status getPaymentStatus:', data);
          setError(t('errors.fetch_error'));
        }
      } catch (err: any) {
        logError('Error fetching payment status:', err);
        setError(t('errors.fetch_error'));
      } finally {
        setLoading(false);
      }
    };
    fetchInfo();
  }, [location, token, lang, navigate, t, unlockCart]);
 
  const formattedDate = paymentInfo?.paid_at
    ? new Date(paymentInfo.paid_at).toLocaleString(lang, {
        year: 'numeric',
        month: 'long',
        day: '2-digit',
        hour: '2-digit',
        minute: '2-digit',
      })
    : '-';
 
  if (loading) {
    return (
      <>
        <Seo title={t('seo.confirmation_title')} description={t('seo.confirmation_description')} />
        <Box sx={{ textAlign: 'center', py: 4 }}>
          <OlympicLoader />
        </Box>
      </>
    );
  }
  if (error) {
    return (
      <PageWrapper>
        <ErrorDisplay
          title={t('errors.error_confirmation')}
          message={error}
          showRetry={false}
          showHome={true}
          homeButtonText={t('confirmation.go_home')}
        />
      </PageWrapper>
    );
  }
 
  return (
    <>
      <Seo title={t('seo.confirmation_title')} description={t('seo.confirmation_description')} />
      <PageWrapper>
        <Box sx={{ maxWidth: 600, mx: 'auto', mt: 4, p: 2 }}>
          <Typography variant="h4" gutterBottom>
            {t('confirmation.thank_you')}
          </Typography>
          <Typography variant="body1" sx={{ mb: 2 }}>
            {t('confirmation.see_mail')}
          </Typography>
          <Typography variant="body2" sx={{ mb: 2 }}>
            {t('confirmation.paid_at', { date: formattedDate })}
          </Typography>
          <Box sx={{ mt: 3 }}>
            <Button variant="outlined" onClick={() => navigate('/')}>
              {t('confirmation.continue_shopping')}
            </Button>
            <Button variant="text" sx={{ ml: 2 }} onClick={() => navigate('/user/orders')}>
              {t('confirmation.view_orders')}
            </Button>
            <Button variant="text" sx={{ ml: 2 }} onClick={() => navigate('/user/tickets')}>
              {t('confirmation.view_tickets')}
            </Button>
          </Box>
        </Box>
      </PageWrapper>
    </>
  );
}