import React, { useState, useContext, useEffect } from "react" import { CardElement, useElements, useStripe } from "@stripe/react-stripe-js" import { Row, Col, Button, Form } from "react-bootstrap" import Swal from "sweetalert2"; import withReactContent from "sweetalert2-react-content"; import { CartContext } from "../components/Cart"; import { useNavigate } from "react-router-dom"; import { useForm } from "react-hook-form"; import Cookies from "universal-cookie"; const CARD_OPTIONS = { iconStyle: "solid", style: { base: { iconColor: "black", color: "white", fontWeight: 500, fontFamily: "Roboto, Open Sans, Segoe UI, sans-serif", fontSize: "16px", fontSmoothing: "antialiased", ":-webkit-autofill": { color: "beige" }, "::placeholder": { color: "lightgray" } }, invalid: { iconColor: "red", color: "red" } } } const PaymentForm = ({ cost, invoice }) => { const navigate = useNavigate(); const { register, handleSubmit, setValue, formState: { errors } } = useForm(); const cookies = new Cookies(); const mySwal = withReactContent(Swal); const [cardName, setCardName] = useState(""); const [cardPhone, setCardPhone] = useState(""); const [cardEmail, setCardEmail] = useState(""); const [isLoading, setIsLoading] = useState(false); const [userAddresses, setUserAddresses] = useState([]); const [currentAdress, setCurrentAdress] = useState({ civicNumber: "", appartment: "", street: "", city: "", province: "", country: "", postalCode: "" }) const stripe = useStripe(); const elements = useElements(); const cart = useContext(CartContext); useEffect(() => { const userInfo = cookies.get("GMGM"); if (userInfo != null && userInfo.LoggedIn == true) { fetch("https://localhost:7292/api/Address", { method: 'GET', credentials: 'include', mode: 'cors' },).then(async (response) => { if (response.ok) { const json = await response.json(); setUserAddresses(json); if (json.length >= 1) { setFormAddress(json[0]); } } }); } }, []); const setFormAddress = (address) => { setCurrentAdress((e) => { return { ...e, civicNumber: address.civicNumber, appartment: address.appartment, street: address.street, city: address.city, province: address.province, country: address.country, postalCode: address.postalCode } }); setValue("civicNumber", address.civicNumber); setValue("appartment", address.appartment); setValue("street", address.street); setValue("city", address.city); setValue("province", address.province); setValue("country", address.country); setValue("postalCode", address.postalCode); } const onSubmit = async (e) => { //e.preventDefault(); setIsLoading(true); const { error } = await stripe.createPaymentMethod({ type: "card", card: elements.getElement(CardElement) }) if (cost <= 0) { console.log("Coût invalide: ", cost); return; } if (!error) { stripe.createToken(elements.getElement(CardElement), { name: cardName }) .then((result) => { if (!result.error) { invoice.token = result.token.id; invoice.description = `Payement de ${cost} à GM`; invoice.amountInCents = cost; invoice.currencyCode = "CAD"; invoice.name = cardName; invoice.email = cardEmail; invoice.phone = cardPhone; invoice.lastFourDigits = result.token.card.last4; invoice.billCivicNumber = currentAdress.civicNumber; invoice.billAppartment = currentAdress.appartment; invoice.billStreet = currentAdress.street; invoice.billCity = currentAdress.city; invoice.billProvince = currentAdress.province; invoice.billCountry = currentAdress.country; invoice.billPostalCode = currentAdress.postalCode; const json = JSON.stringify(invoice); console.log(invoice); fetch(`https://localhost:7292/api/Invoice`, { method: 'POST', credentials: 'include', mode: 'cors', headers: { 'Accept': 'application/json', 'Content-Type': 'application/json' }, body: json }).then((response) => { if (response.ok) { mySwal.fire({ title: 'Commande envoyée avec succès!', timer: 2000, icon: "success" }).then( () => { cart.emptyCart(); navigate('/myInvoices'); } ); } else { mySwal.fire({ title: 'Erreur!', timer: 2000, icon: "error" }).then(() => { setIsLoading(false); }); } }); } }); } else { console.log(error.message); } } return ( <> {

Adresse de Facturation

Adresse setFormAddress(userAddresses[e.target.value])}> {userAddresses.map((a, i) => ( ))}
setCurrentAdress((prev) => { return { ...prev, civicNumber: e.target.value } })} />
{errors.civicNumber && errors.civicNumber.type === 'required' && Vous devez entrer une numéro civique!}
setCurrentAdress((prev) => { return { ...prev, street: e.target.value } })} />
{errors.street && errors.street.type === 'required' && Vous devez entrer votre rue!} {errors.street && errors.street.type === 'minLength' && Votre rue doit avoir au moins 3 lettres!} {errors.street && errors.street.type === 'maxLength' && Votre rue doit avoir moins de 51 lettres!}
setCurrentAdress((prev) => { return { ...prev, appartment: e.target.value } })} />
setCurrentAdress((prev) => { return { ...prev, city: e.target.value } })} />
{errors.city && errors.city.type === 'required' && Vous devez entrer votre ville!} {errors.city && errors.city.type === 'minLength' && Votre ville doit avoir au moins 4 lettres!} {errors.city && errors.city.type === 'maxLength' && Votre ville doit avoir moins de 51 lettres!}
setCurrentAdress((prev) => { return { ...prev, province: e.target.value } })} />
{errors.province && errors.province.type === 'required' && Vous devez entrer votre province!} {errors.province && errors.province.type === 'maxLength' && Votre province doit avoir moins de 4 lettres!}
setCurrentAdress((prev) => { return { ...prev, country: e.target.value } })} />
{errors.country && errors.country.type === 'required' && Vous devez entrer votre pays!} {errors.country && errors.country.type === 'minLength' && Votre pays doit avoir au moins 4 lettres!} {errors.cicountryty && errors.country.type === 'maxLength' && Votre pays doit avoir moins de 31 lettres!}
setCurrentAdress((prev) => { return { ...prev, postalCode: e.target.value } })} />
{errors.postalCode && errors.postalCode.type === 'required' && Vous devez entrer votre code postal!} {errors.postalCode && errors.postalCode.type === 'pattern' && Veuillez entrer un code postal valide!}
setCardName(e.target.value)} /> setCardPhone(e.target.value)} /> setCardEmail(e.target.value)} />
{ isLoading &&
Paiement en cours...
}
} ) } export default PaymentForm;