diff --git a/src/api/wallet.ts b/src/api/wallet.ts index 2b356a9..6e860e2 100644 --- a/src/api/wallet.ts +++ b/src/api/wallet.ts @@ -15,10 +15,12 @@ interface PaymentBody { } export async function sendPayment({ + userId, body, fromSquiz, paymentPurpose, }: { + userId: string; body: PaymentBody; fromSquiz: boolean; paymentPurpose: "paycart" | "replenishwallet"; @@ -44,9 +46,11 @@ export async function sendPayment({ }, phoneNumber: "79000000000", login: "login_test", - returnUrl: `https://${isStaging}hub.pena.digital/afterpay?from=${fromSquiz ? "quiz" : "hub"}&purpose=${paymentPurpose}`, - ...body - } + returnUrl: `https://${isStaging}hub.pena.digital/afterpay?from=${ + fromSquiz ? "quiz" : "hub" + }&purpose=${paymentPurpose}&userid=${userId}`, + ...body, + }, }); return [sendPaymentResponse]; diff --git a/src/pages/AfterPay/index.tsx b/src/pages/AfterPay/index.tsx index 0eb56c9..105df97 100644 --- a/src/pages/AfterPay/index.tsx +++ b/src/pages/AfterPay/index.tsx @@ -1,3 +1,4 @@ +import { useState, useEffect } from "react"; import { Box, Button, @@ -8,7 +9,7 @@ import { import { payCart } from "@root/api/cart"; import { useUserStore } from "@root/stores/user"; import wallet_icon from "@root/assets/Icons/ColorWallet.svg"; -import { Link } from "react-router-dom"; +import { Link, useSearchParams } from "react-router-dom"; const MINUTE = 1000 * 60; @@ -54,12 +55,60 @@ const { domain, pathname } = (() => { })(); export default () => { + const [redirectUrl, setRedirectUrl] = useState("/"); const theme = useTheme(); const phone = useMediaQuery(theme.breakpoints.down(375)); const userId = useUserStore((state) => state.user?._id); - const redirectUrl = new URL(`https://${domain}.pena.digital${pathname}`); - redirectUrl.searchParams.append("afterpay", "true"); - redirectUrl.searchParams.append("userid", userId ?? ""); + const [searchParams] = useSearchParams(); + const paymentUserId = searchParams.get("userid"); + + useEffect(() => { + const from = searchParams.get("from") || "hub"; + const purpose = searchParams.get("purpose"); + + if (purpose === "paycart" || from === "quiz") { + let tryCount = 0; + + if (userId !== paymentUserId) { + return; + } + + const payCartPendingRequestDeadline = localStorage.getItem( + "payCartPendingRequestDeadline" + ); + const deadline = payCartPendingRequestDeadline + ? Number(payCartPendingRequestDeadline) + : Date.now() + 20 * MINUTE; + + localStorage.setItem( + "payCartPendingRequestDeadline", + deadline.toString() + ); + + tryPayCart(); + + async function tryPayCart() { + tryCount += 1; + + const [, payCartError] = await payCart(); + + if (!payCartError || Date.now() > deadline) { + localStorage.removeItem("payCartPendingRequestDeadline"); + return; + } + + setTimeout(tryPayCart, tryCount > 10 ? MINUTE / 60 : MINUTE / 6); + } + } + + const host = window.location.hostname; + const domain = (host.includes("s") ? "s" : "") + from; + const pathname = from === "hub" ? "/tariffs" : "/list"; + + setRedirectUrl( + `https://${domain}.pena.digital${pathname}?afterpay=${true}&userid=${userId}` + ); + }, []); return ( (""); - const [selectedPaymentMethod, setSelectedPaymentMethod] = - useState(""); - const [warnModalOpen, setWarnModalOpen] = useState(false); - const [sorryModalOpen, setSorryModalOpen] = useState(false); - const [paymentValueField, setPaymentValueField] = useState("0"); - const [paymentLink, setPaymentLink] = useState(""); - const [fromSquiz, setIsFromSquiz] = useState(false); - const location = useLocation(); - const verificationStatus = useUserStore((state) => state.verificationStatus); - const navigate = useNavigate(); - const handleCustomBackNavigation = useHistoryTracker(); + const theme = useTheme(); + const upMd = useMediaQuery(theme.breakpoints.up("md")); + const upSm = useMediaQuery(theme.breakpoints.up("sm")); + const isTablet = useMediaQuery(theme.breakpoints.down(1000)); + const [promocodeField, setPromocodeField] = useState(""); + const [selectedPaymentMethod, setSelectedPaymentMethod] = + useState(""); + const [warnModalOpen, setWarnModalOpen] = useState(false); + const [sorryModalOpen, setSorryModalOpen] = useState(false); + const [paymentValueField, setPaymentValueField] = useState("0"); + const [paymentLink, setPaymentLink] = useState(""); + const [fromSquiz, setIsFromSquiz] = useState(false); + const location = useLocation(); + const verificationStatus = useUserStore((state) => state.verificationStatus); + const userId = useUserStore((state) => state.userId); + const navigate = useNavigate(); + const handleCustomBackNavigation = useHistoryTracker(); - const notEnoughMoneyAmount = (location.state?.notEnoughMoneyAmount as number) ?? 0; + const notEnoughMoneyAmount = + (location.state?.notEnoughMoneyAmount as number) ?? 0; - console.log("notEnoughMoneyAmount ", paymentValueField) - const paymentValue = parseFloat(paymentValueField) * 100; + console.log("notEnoughMoneyAmount ", paymentValueField); + const paymentValue = parseFloat(paymentValueField) * 100; - useLayoutEffect(() => { - console.log("notEnoughMoneyAmount ", notEnoughMoneyAmount) - setPaymentValueField((notEnoughMoneyAmount / 100).toString()); - const params = new URLSearchParams(window.location.search); - const fromSquiz = params.get("action"); - if (fromSquiz === "squizpay") { - setIsFromSquiz(true); - setPaymentValueField((Number(params.get("dif") || "0") / 100).toString()); - } - history.pushState(null, document.title, "/payment"); - console.log(fromSquiz); - }, []); - - async function handleChoosePaymentClick() { - if (!selectedPaymentMethod) { - enqueueSnackbar("Введите метод оплаты"); - return; - } - - if (Number(paymentValueField) === 0) { - enqueueSnackbar("Введите сумму"); - return; - } - - if (selectedPaymentMethod !== "rspay") { - const [sendPaymentResponse, sendPaymentError] = await sendPayment({ - fromSquiz, - body: { - type: selectedPaymentMethod, - amount: Math.trunc(Number(paymentValueField) * 100), - }, - paymentPurpose: notEnoughMoneyAmount ? "paycart" : "replenishwallet", - }); - - if (sendPaymentError) { - return enqueueSnackbar(sendPaymentError); - } - - if (sendPaymentResponse) { - setPaymentLink(sendPaymentResponse.link); - } - - return; - } else { - if (verificationStatus !== VerificationStatus.VERIFICATED) { - setWarnModalOpen(true); - - return; - } - - if (Number(paymentValueField) < 900) { - enqueueSnackbar("Минимальная сумма 900р"); - - return; - } - - const sendRSPaymentError = await sendRSPayment(Number(paymentValueField)); - - if (sendRSPaymentError) { - return enqueueSnackbar(sendRSPaymentError); - } - - enqueueSnackbar( - "Cпасибо за заявку, в течении 24 часов вам будет выставлен счёт для оплаты услуг." - ); - - navigate("/settings"); - - } + useLayoutEffect(() => { + console.log("notEnoughMoneyAmount ", notEnoughMoneyAmount); + setPaymentValueField((notEnoughMoneyAmount / 100).toString()); + const params = new URLSearchParams(window.location.search); + const fromSquiz = params.get("action"); + if (fromSquiz === "squizpay") { + setIsFromSquiz(true); + setPaymentValueField((Number(params.get("dif") || "0") / 100).toString()); + } + history.pushState(null, document.title, "/payment"); + console.log(fromSquiz); + }, []); + async function handleChoosePaymentClick() { + if (!selectedPaymentMethod) { + enqueueSnackbar("Введите метод оплаты"); + return; } - function handleApplyPromocode() { - if (!promocodeField) return; - - activatePromocode(promocodeField).then(response => { - enqueueSnackbar(response); - mutate("discounts"); - }).catch(error => { - enqueueSnackbar(error.message); - }); + if (Number(paymentValueField) === 0) { + enqueueSnackbar("Введите сумму"); + return; } - return ( - { + enqueueSnackbar(response); + mutate("discounts"); + }) + .catch((error) => { + enqueueSnackbar(error.message); + }); + } + + return ( + + + {!upMd && ( + + + + )} + Способ оплаты + + {!upMd && ( + + Выберите способ оплаты + + )} + + - + {paymentMethods.map(({ name, label, image, unpopular = false }) => ( + { + setSelectedPaymentMethod(name); + setPaymentLink(""); }} - > - {!upMd && ( - - - - )} - Способ оплаты - - {!upMd && ( - - Выберите способ оплаты - + unpopular={false} + /> + ))} + { + setSelectedPaymentMethod("rspay"); + setPaymentLink(""); + }} + unpopular={false} + /> + + + + + + {upMd && Выберите способ оплаты} + К оплате + {paymentLink ? ( + + {currencyFormatter.format(paymentValue / 100)} + + ) : ( + { + const value = parseFloat( + e.target.value.replace(/^0+(?=\d\.)/, "") + ); + setPaymentValueField(isNaN(value) ? "" : value.toString()); + }} + id="payment-amount" + gap={upMd ? "16px" : "10px"} + color={"#F2F3F7"} + FormInputSx={{ mb: "28px" }} + /> )} - + {paymentLink ? ( + - ) : ( - - )} - - - - - - ); + Оплатить + + ) : ( + + )} + + + + + + ); }