All files / src/components CheckoutButton.jsx

92% Statements 23/25
85.71% Branches 24/28
100% Functions 4/4
92% Lines 23/25

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                    1x 11x 11x 11x 11x 11x 11x   11x 5x         5x 2x   2x 2x     3x   3x       5x 3x       3x   5x 2x 2x             1x       11x                                  
import React from "react";
import { useNavigate, useLocation } from "react-router-dom";
import { toast } from "react-toastify";
import { Button } from "@mui/material";
import ShoppingCartCheckoutIcon from "@mui/icons-material/ShoppingCartCheckout";
import LockIcon from "@mui/icons-material/Lock";
import { useLanguage } from "../contexts/LanguageContext";
import { useAuth } from "../contexts/AuthContext";
import { createOrder } from "../db/api";
 
const CheckoutButton = ({ cartItems = [] }) => {
  const navigate = useNavigate();
  const location = useLocation();
  const { t } = useLanguage();
  const auth = useAuth();
  const isLoggedIn = auth?.isLoggedIn ?? auth?.isAuthenticated ?? false;
  const safeCartItems = Array.isArray(cartItems) ? cartItems : [];
 
  const handleCheckout = async () => {
    Iif (safeCartItems.length === 0) {
      toast.error(t("checkout.toast.empty"));
      return;
    }
 
    if (!isLoggedIn) {
      toast.info("Faça login para finalizar seu pedido.");
      // Preserve current path so we can come back after login
      navigate(`/login?next=${encodeURIComponent(location.pathname)}`);
      return;
    }
 
    try {
      const idempotencyKey =
        typeof crypto !== "undefined" && crypto.randomUUID
          ? crypto.randomUUID()
          : `idemp-${Date.now()}`;
 
      const orderItems = safeCartItems
        .map((item) => ({
          productId: Number(item?.product_id ?? item?.id),
          quantity: Number(item?.quantity ?? 1),
        }))
        .filter((item) => Number.isInteger(item.productId) && item.productId > 0 && Number.isInteger(item.quantity) && item.quantity > 0);
 
      const order = await createOrder({ idempotencyKey, items: orderItems });
      toast.success(t("checkout.processing"));
      navigate("/payments", {
        state: {
          cartItems: safeCartItems,
          order,
        },
      });
    } catch (err) {
      toast.error(err?.message || "Erro ao processar checkout.");
    }
  };
 
  return (
    <Button
      variant="contained"
      color="primary"
      size="large"
      fullWidth
      startIcon={isLoggedIn ? <ShoppingCartCheckoutIcon /> : <LockIcon />}
      onClick={handleCheckout}
      sx={{ py: 1.5, fontSize: "1.1rem" }}
      disabled={safeCartItems.length === 0}
    >
      {isLoggedIn ? t("checkout.button") : "Entrar para Finalizar"}
    </Button>
  );
};
 
export default CheckoutButton;