Merge branch 'develop' into 'main'

Develop

See merge request witapp/aura-webapp!154
This commit is contained in:
Daniil Chemerkin 2024-06-02 00:51:18 +00:00
commit 0b042eb02d
117 changed files with 1996 additions and 1676 deletions

View File

@ -1,5 +1,6 @@
AURA_API_HOST=https://api-web.aura.wit.life
AURA_DAPI_HOST=https://dev.api.aura.witapps.us
AURA_DAPI_PREFIX=v2
AURA_SITE_HOST=https://aura.wit.life
AURA_PREFIX=api/v1
AURA_OPEN_AI_HOST=https://api.openai.com

View File

@ -1,5 +1,6 @@
AURA_API_HOST=https://api-web.aura.wit.life
AURA_DAPI_HOST=https://api.aura.witapps.us
AURA_DAPI_PREFIX=v2
AURA_SITE_HOST=https://aura.wit.life
AURA_PREFIX=api/v1
AURA_OPEN_AI_HOST=https://api.openai.com

View File

@ -6,7 +6,7 @@
name="viewport"
content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no"
/>
<link rel="preload" as="image" href="/leo.png" fetchpriority="high" />
<link rel="preload" as="image" href="/leo.webp" fetchpriority="high" />
<link rel="apple-touch-icon" sizes="180x180" href="/apple-touch-icon.png" />
<link rel="icon" type="image/png" sizes="32x32" href="/favicon-32x32.png" />
<link rel="icon" type="image/png" sizes="16x16" href="/favicon-16x16.png" />
@ -69,7 +69,7 @@
</head>
<body>
<!-- Yandex.Metrika counter -->
<script type="text/javascript" async="async">
<script type="text/javascript">
(function (m, e, t, r, i, k, a) {
m[i] =
m[i] ||
@ -133,7 +133,7 @@
<!-- End Google Tag Manager (noscript) -->
<div id="root">
<div class="splash-screen">
<img src="/leo.png" alt="Aura - Energy of your Horoscope" />
<img src="/leo.webp" alt="Aura - Energy of your Horoscope" />
</div>
</div>
<script type="module" src="/src/main.ts"></script>

BIN
public/leo.webp Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 118 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 41 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 34 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 42 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 44 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 42 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 52 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 48 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 38 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 34 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 21 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 38 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 35 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 31 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 33 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 32 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 26 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 44 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 51 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 33 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 39 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 36 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 39 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 27 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 22 KiB

View File

@ -11,7 +11,6 @@ import {
DailyForecasts,
SubscriptionItems,
SubscriptionCheckout,
SubscriptionReceipts,
SubscriptionStatus,
AICompatCategories,
AICompats,
@ -28,6 +27,8 @@ import {
SinglePayment,
Products,
Palmistry,
Paywall,
Payment,
} from './resources'
const api = {
@ -48,8 +49,8 @@ const api = {
getSubscriptionPlans: createMethod<SubscriptionPlans.Payload, SubscriptionPlans.Response>(SubscriptionPlans.createRequest),
getSubscriptionCheckout: createMethod<SubscriptionCheckout.Payload, SubscriptionCheckout.Response>(SubscriptionCheckout.createRequest),
getSubscriptionStatus: createMethod<SubscriptionStatus.Payload, SubscriptionStatus.Response>(SubscriptionStatus.createRequest),
getSubscriptionReceipt: createMethod<SubscriptionReceipts.GetPayload, SubscriptionReceipts.Response>(SubscriptionReceipts.createGetRequest),
createSubscriptionReceipt: createMethod<SubscriptionReceipts.Payload, SubscriptionReceipts.Response>(SubscriptionReceipts.createRequest),
// new get subscription status
getSubscriptionStatusNew: createMethod<SubscriptionStatus.Payload, SubscriptionStatus.ResponseNew>(SubscriptionStatus.createRequestNew),
getAiCompatCategories: createMethod<AICompatCategories.Payload, AICompatCategories.Response>(AICompatCategories.createRequest),
getAiCompat: createMethod<AICompats.Payload, AICompats.Response>(AICompats.createRequest),
getAiRequest: createMethod<AIRequests.Payload, AIRequests.Response>(AIRequests.createRequest),
@ -75,6 +76,10 @@ const api = {
getPalmistryLines: createMethod<Palmistry.Payload, Palmistry.Response>(Palmistry.createRequest),
// New Authorization
authorization: createMethod<User.ICreateAuthorizePayload, User.ICreateAuthorizeResponse>(User.createAuthorizeRequest),
// Paywall
getPaywallByPlacementKey: createMethod<Paywall.PayloadGet, Paywall.ResponseGet>(Paywall.createRequestGet),
// Payment
makePayment: createMethod<Payment.PayloadPost, Payment.ResponsePost>(Payment.createRequestPost),
}
export type ApiContextValue = typeof api

View File

@ -0,0 +1,46 @@
import routes from "@/routes";
import { getAuthHeaders } from "../utils";
interface Payload {
token: string;
}
export interface PayloadPost extends Payload {
productId: string;
}
interface ResponsePostSuccess {
status: "payment_intent_created" | "paid" | unknown,
type: "setup" | "payment",
data: {
client_secret: string,
paymentIntentId: string,
return_url?: string,
public_key: string,
product: {
id: string,
name: string,
description?: string,
price: {
id: string,
unit_amount: number,
currency: "USD" | string
}
}
}
}
interface ResponsePostError {
status: string;
message: string;
}
export type ResponsePost = ResponsePostSuccess | ResponsePostError;
export const createRequestPost = ({ token, productId }: PayloadPost): Request => {
const url = new URL(routes.server.makePayment());
const body = JSON.stringify({
productId
});
return new Request(url, { method: "POST", headers: getAuthHeaders(token), body });
};

View File

@ -0,0 +1,67 @@
import routes from "@/routes";
import { getAuthHeaders } from "../utils";
interface Payload {
token: string;
}
export interface PayloadGet extends Payload {
placementKey: EPlacementKeys;
}
export enum EPlacementKeys {
"aura.placement.main" = "aura.placement.main",
"aura.placement.redesign.main" = "aura.placement.redesign.main",
"aura.placement.email.marketing" = "aura.placement.email.marketing",
"aura.placement.secret.discount" = "aura.placement.secret.discount",
"aura.placement.palmistry.main" = "aura.placement.palmistry.main"
}
interface ResponseGetSuccess {
paywall: IPaywall;
}
interface ResponseGetError {
status: string;
message: string;
}
export interface IPaywall {
_id: string;
key: string;
name: string;
products: IPaywallProduct[];
properties: IPaywallProperties[];
}
export interface IPaywallProduct {
_id: string;
key: string;
productId: string;
name: string;
priceId: string;
type: string;
description: string;
discountPrice: null;
discountPriceId: null;
isDiscount: boolean;
isFreeTrial: boolean;
isTrial: boolean;
price: number;
trialDuration: number;
trialPrice: number;
trialPriceId: string;
}
interface IPaywallProperties {
_id: string;
key: string;
value: string;
}
export type ResponseGet = ResponseGetSuccess | ResponseGetError;
export const createRequestGet = ({ token, placementKey }: PayloadGet): Request => {
const url = new URL(routes.server.getPaywallByPlacementKey(placementKey));
return new Request(url, { method: "GET", headers: getAuthHeaders(token) });
};

View File

@ -32,10 +32,18 @@ export interface PayloadPost extends Payload {
}
export interface ResponseGet {
key: string;
productId: string;
amount: number;
currency: string;
_id: string,
key: string,
name: string,
type: string,
description: string,
discountPrice: null | unknown,
isDiscount: boolean,
isFreeTrial: boolean,
isTrial: boolean,
price: number,
trialDuration: number,
trialPrice: number
}
interface ResponsePostNewPaymentData {

View File

@ -14,3 +14,12 @@ export const createRequest = ({ token }: Payload): Request => {
const url = new URL(routes.server.subscriptionStatus())
return new Request(url, { method: 'GET', headers: getAuthHeaders(token) })
}
export interface ResponseNew {
subscription: boolean;
}
export const createRequestNew = ({ token }: Payload): Request => {
const url = new URL(routes.server.subscriptionStatusNew())
return new Request(url, { method: 'GET', headers: getAuthHeaders(token) })
}

View File

@ -10,7 +10,6 @@ export * as AuthTokens from "./AuthTokens";
export * as SubscriptionItems from "./UserSubscriptionItemPrices";
export * as SubscriptionCheckout from "./UserSubscriptionCheckout";
export * as SubscriptionStatus from "./UserSubscriptionStatus";
export * as SubscriptionReceipts from "./UserSubscriptionReceipts";
export * as AICompatCategories from "./AICompatCategories";
export * as AICompats from "./AICompats";
export * as AIRequests from "./AIRequests";
@ -26,3 +25,5 @@ export * as OpenAI from "./OpenAI";
export * as SinglePayment from "./SinglePayment";
export * as Products from "./Products";
export * as Palmistry from "./Palmistry";
export * as Paywall from "./Paywall";
export * as Payment from "./Payment";

View File

@ -57,7 +57,6 @@ import { Asset } from "@/api/resources/Assets";
import PaymentResultPage from "../PaymentPage/results";
import PaymentSuccessPage from "../PaymentPage/results/SuccessPage";
import PaymentFailPage from "../PaymentPage/results/ErrorPage";
import { StripePage } from "../StripePage";
import AuthPage from "../AuthPage";
import AuthResultPage from "../AuthResultPage";
import MagicBallPage from "../pages/MagicBall";
@ -113,8 +112,8 @@ import AddConsultationPage from "../pages/AdditionalPurchases/pages/AddConsultat
import StepsManager from "@/components/palmistry/steps-manager/steps-manager";
import Advisors from "../pages/Advisors";
import AdvisorChatPage from "../pages/AdvisorChat";
import SuccessPaymentPage from "../pages/PaymentWithEmailPage/ResultPayment/SuccessPaymentPage";
import FailPaymentPage from "../pages/PaymentWithEmailPage/ResultPayment/FailPaymentPage";
import SuccessPaymentPage from "../pages/SinglePaymentPage/ResultPayment/SuccessPaymentPage";
import FailPaymentPage from "../pages/SinglePaymentPage/ResultPayment/FailPaymentPage";
import { useSchemeColorByElement } from "@/hooks/useSchemeColorByElement";
import GetInformationPartnerPage from "../pages/GetInformationPartner";
import BirthPlacePage from "../pages/BirthPlacePage";
@ -162,6 +161,10 @@ function App(): JSX.Element {
const birthdate = user?.profile?.birthday || birthdateFromStore;
const birthPlace = user?.profile?.birthplace || birthPlaceFromStore;
useLayoutEffect(() => {
dispatch(actions.paywalls.resetIsMustUpdate());
}, [dispatch]);
useEffect(() => {
// api.getAppConfig({ bundleId: "auraweb" }),
dispatch(
@ -219,10 +222,13 @@ function App(): JSX.Element {
token,
});
if (has_subscription && user) {
const { subscription: subscriptionStatusNew } =
await api.getSubscriptionStatusNew({ token });
if ((has_subscription || subscriptionStatusNew) && user) {
return dispatch(actions.status.update("subscribed"));
}
if (!has_subscription && user) {
if (!has_subscription && !subscriptionStatusNew && user) {
return dispatch(actions.status.update("unsubscribed"));
}
if (!user) {
@ -292,7 +298,9 @@ function App(): JSX.Element {
<Route
path={routes.client.epeGender()}
element={<GenderPage productKey={EProductKeys["moons.pdf.aura"]} />}
/>
>
<Route path=":targetId" element={<GenderPage />} />
</Route>
</Route>
<Route
element={
@ -419,7 +427,9 @@ function App(): JSX.Element {
<Route
path={routes.client.advisorChatGender()}
element={<GenderPage productKey={EProductKeys["chat.aura"]} />}
/>
>
<Route path=":targetId" element={<GenderPage />} />
</Route>
</Route>
<Route
element={
@ -590,34 +600,6 @@ function App(): JSX.Element {
</Route>
{/* Advisor short path */}
{/* Single Payment Page Short Path */}
{/* <Route
element={
<ShortPathOutlet
productKey={EProductKeys["chat.aura"]}
redirectUrls={{
data: {
no: routes.client.advisorChatGender(),
force: routes.client.advisorChatBirthdate(),
},
}}
requiredParameters={[
birthdate,
birthPlace,
isForceShortPath || gender,
]}
/>
}
>
<Route
path={routes.client.advisorChatPayment()}
element={<PaymentWithEmailPage />}
>
<Route path=":productId" element={<PaymentWithEmailPage />} />
</Route>
</Route> */}
{/* Single Payment Page Short Path */}
{/* Test Routes Start */}
<Route path={routes.client.notFound()} element={<NotFoundPage />} />
<Route path={routes.client.gender()} element={<GenderPage />}>
@ -805,10 +787,6 @@ function App(): JSX.Element {
/>
<Route path={routes.client.static()} element={<StaticPage />} />
<Route path={routes.client.priceList()} element={<PriceListPage />} />
{/* <Route
path={routes.client.wallpaper()}
element={<ProtectWallpaperPage />}
/> */}
</Route>
<Route element={<AuthorizedUserOutlet />}>
<Route
@ -820,18 +798,10 @@ function App(): JSX.Element {
</Route>
<Route element={<PrivateOutlet />}>
<Route element={<AuthorizedUserOutlet />}>
{/* <Route
path={routes.client.subscription()}
element={<SubscriptionPage />}
/> */}
<Route
path={routes.client.paymentMethod()}
element={<PaymentPage />}
/>
<Route
path={routes.client.paymentStripe()}
element={<StripePage />}
/>
</Route>
<Route element={<PrivateSubscriptionOutlet />}>
<Route path={routes.client.home()} element={<HomePage />} />

View File

@ -4,7 +4,6 @@ import { useNavigate, useParams } from "react-router-dom";
import { useTranslation } from "react-i18next";
import { useDispatch, useSelector } from "react-redux";
import { actions, selectors } from "@/store";
import { useApi } from "@/api";
import Title from "../Title";
import Policy from "../Policy";
import EmailInput from "./EmailInput";
@ -12,9 +11,10 @@ import MainButton from "../MainButton";
import Loader, { LoaderColor } from "../Loader";
import routes from "@/routes";
import NameInput from "./NameInput";
import { ISubscriptionPlan } from "@/api/resources/SubscriptionPlans";
import { useAuthentication } from "@/hooks/authentication/use-authentication";
import { ESourceAuthorization } from "@/api/resources/User";
import { EPlacementKeys, IPaywallProduct } from "@/api/resources/Paywall";
import { usePaywall } from "@/hooks/paywall/usePaywall";
interface IEmailEnterPage {
redirectUrl?: string;
@ -25,8 +25,7 @@ function EmailEnterPage({
redirectUrl = routes.client.emailConfirm(),
isRequiredName = false,
}: IEmailEnterPage): JSX.Element {
const api = useApi();
const { t, i18n } = useTranslation();
const { t } = useTranslation();
const dispatch = useDispatch();
const navigate = useNavigate();
const [email, setEmail] = useState("");
@ -35,51 +34,31 @@ function EmailEnterPage({
const [isValidEmail, setIsValidEmail] = useState(false);
const [isValidName, setIsValidName] = useState(!isRequiredName);
const [isAuth, setIsAuth] = useState(false);
const [subPlans, setSubPlans] = useState<ISubscriptionPlan[]>([]);
const activeSubPlanFromStore = useSelector(selectors.selectActiveSubPlan);
const [activeSubPlan, setActiveSubPlan] = useState<ISubscriptionPlan | null>(
activeSubPlanFromStore
);
const locale = i18n.language;
const activeProductFromStore = useSelector(selectors.selectActiveProduct);
const { subPlan } = useParams();
const { error, isLoading, authorization } = useAuthentication();
const { products } = usePaywall({
placementKey: EPlacementKeys["aura.placement.main"],
});
const [activeProduct, setActiveProduct] = useState<IPaywallProduct | null>(
activeProductFromStore
);
useEffect(() => {
if (subPlan) {
const targetSubPlan = subPlans.find(
(sub_plan) =>
const targetProduct = products.find(
(product) =>
String(
sub_plan?.trial?.price_cents
? Math.floor((sub_plan?.trial?.price_cents + 1) / 100)
: sub_plan.id.replace(".", "")
product?.trialPrice
? Math.floor((product?.trialPrice + 1) / 100)
: product.key.replace(".", "")
) === subPlan
);
if (targetSubPlan) {
setActiveSubPlan(targetSubPlan);
if (targetProduct) {
setActiveProduct(targetProduct);
}
}
}, [subPlan, subPlans]);
useEffect(() => {
(async () => {
const { sub_plans } = await api.getSubscriptionPlans({ locale });
const plans = sub_plans
.filter((plan: ISubscriptionPlan) => plan.provider === "stripe")
.sort((a, b) => {
if (!a.trial || !b.trial) {
return 0;
}
if (a?.trial?.price_cents < b?.trial?.price_cents) {
return -1;
}
if (a?.trial?.price_cents > b?.trial?.price_cents) {
return 1;
}
return 0;
});
setSubPlans(plans);
})();
}, [api, locale]);
}, [subPlan, products]);
const handleValidEmail = (email: string) => {
dispatch(actions.form.addEmail(email));
@ -124,7 +103,7 @@ function EmailEnterPage({
await authorization(email, source);
dispatch(
actions.payment.update({
activeSubPlan,
activeProduct,
})
);
setIsAuth(true);

View File

@ -1,7 +1,6 @@
import { getRandomArbitrary, getRandomName } from "@/services/random-value";
import EmailItem, { IEmailItemProps } from "../EmailItem";
import styles from "./styles.module.css";
import { useTranslation } from "react-i18next";
import { useEffect, useRef, useState } from "react";
const getEmails = (): IEmailItemProps[] => {
@ -18,6 +17,7 @@ const getEmails = (): IEmailItemProps[] => {
};
interface IEmailsListProps {
title: string | JSX.Element | JSX.Element[];
classNameContainer?: string;
classNameTitle?: string;
classNameEmailItem?: string;
@ -25,25 +25,16 @@ interface IEmailsListProps {
}
function EmailsList({
title,
classNameContainer = "",
classNameTitle = "",
classNameEmailItem = "",
direction = "up-down",
}: IEmailsListProps): JSX.Element {
const { t } = useTranslation();
const [countUsers, setCountUsers] = useState(752);
const [emails, setEmails] = useState(getEmails());
const [elementIdx, setElementIdx] = useState(0);
const itemsRef = useRef<HTMLDivElement[]>([]);
useEffect(() => {
const randomDelay = getRandomArbitrary(3000, 5000);
const countUsersTimeOut = setTimeout(() => {
setCountUsers((prevState) => prevState + 1);
}, randomDelay);
return () => clearTimeout(countUsersTimeOut);
}, [countUsers]);
useEffect(() => {
let randomDelay = getRandomArbitrary(500, 5000);
if (!elementIdx) {
@ -69,11 +60,7 @@ function EmailsList({
return (
<div className={`${styles.container} ${classNameContainer}`}>
<span className={`${styles["title"]} ${classNameTitle}`}>
{t("people_joined_today", {
countPeoples: <strong>{countUsers}</strong>,
})}
</span>
<span className={`${styles["title"]} ${classNameTitle}`}>{title}</span>
<div className={`${styles["emails-container"]} ${styles[direction]}`}>
{emails.map(({ email, price }, idx) => (
<div

View File

@ -5,14 +5,14 @@ import {
useElements,
} from "@stripe/react-stripe-js";
import { PaymentRequest } from "@stripe/stripe-js";
import { ISubscriptionPlan } from "@/api/resources/SubscriptionPlans";
import styles from "./styles.module.css";
import { useDispatch } from "react-redux";
import { useNavigate } from "react-router-dom";
import routes from "@/routes";
import { IPaywallProduct } from "@/api/resources/Paywall";
interface ApplePayButtonProps {
activeSubPlan: ISubscriptionPlan | null;
activeProduct: IPaywallProduct | null;
client_secret: string;
subscriptionReceiptId?: string;
returnUrl?: string;
@ -20,7 +20,7 @@ interface ApplePayButtonProps {
}
function ApplePayButton({
activeSubPlan,
activeProduct,
client_secret,
subscriptionReceiptId,
returnUrl,
@ -34,15 +34,15 @@ function ApplePayButton({
null
);
const getAmountFromSubPlan = (subPlan: ISubscriptionPlan) => {
if (subPlan.trial) {
return subPlan.trial.price_cents;
const getAmountFromProduct = (subPlan: IPaywallProduct) => {
if (subPlan.isTrial) {
return subPlan.trialPrice;
}
return subPlan.price_cents;
return subPlan.price;
};
useEffect(() => {
if (!stripe || !elements || !activeSubPlan) {
if (!stripe || !elements || !activeProduct) {
return;
}
@ -50,8 +50,8 @@ function ApplePayButton({
country: "US",
currency: "usd",
total: {
label: activeSubPlan.name || "Subscription",
amount: getAmountFromSubPlan(activeSubPlan),
label: activeProduct.name || "Subscription",
amount: getAmountFromProduct(activeProduct),
},
requestPayerName: true,
requestPayerEmail: true,
@ -95,7 +95,6 @@ function ApplePayButton({
});
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [
activeSubPlan,
client_secret,
dispatch,
elements,

View File

@ -16,12 +16,14 @@ interface ICheckoutFormProps {
children?: JSX.Element | null;
subscriptionReceiptId?: string;
returnUrl?: string;
confirmType?: "payment" | "setup";
}
export default function CheckoutForm({
children,
subscriptionReceiptId,
returnUrl,
confirmType = "payment",
}: ICheckoutFormProps) {
const stripe = useStripe();
const elements = useElements();
@ -42,7 +44,9 @@ export default function CheckoutForm({
setIsProcessing(true);
try {
const { error } = await stripe.confirmPayment({
const { error } = await stripe[
confirmType === "payment" ? "confirmPayment" : "confirmSetup"
]({
elements,
confirmParams: {
return_url: returnUrl

View File

@ -1,16 +0,0 @@
import { useTranslation } from 'react-i18next'
import MainButton from '@/components/MainButton'
interface IStripeButtonProps {
onClick: () => void
}
export function StripeButton({ onClick }: IStripeButtonProps): JSX.Element {
const { t } = useTranslation()
return (
<MainButton color='blue' onClick={onClick}>
{t('stripe')}
</MainButton>
)
}

View File

@ -1,115 +0,0 @@
import styles from "./styles.module.css";
import { useApi } from "@/api";
import Modal from "@/components/Modal";
import Loader from "@/components/Loader";
import { useEffect, useState } from "react";
import { Stripe, loadStripe } from "@stripe/stripe-js";
import { Elements } from "@stripe/react-stripe-js";
import CheckoutForm from "./CheckoutForm";
import { useAuth } from "@/auth";
import { useSelector } from "react-redux";
import { selectors } from "@/store";
import Title from "@/components/Title";
import ApplePayButton from "@/components/StripePage/ApplePayButton";
import SubPlanInformation from "@/components/SubPlanInformation";
import { useTranslation } from "react-i18next";
import { useNavigate } from "react-router-dom";
import routes from "@/routes";
interface StripeModalProps {
open: boolean;
onClose: () => void;
// onSuccess: (receipt: SubscriptionReceipts.SubscriptionReceipt) => void;
// onError: (error: Error) => void;
}
export function StripeModal({
open,
onClose,
}: // onSuccess,
// onError,
StripeModalProps): JSX.Element {
const { i18n } = useTranslation();
const api = useApi();
const { token } = useAuth();
const locale = i18n.language;
const navigate = useNavigate();
const activeSubPlan = useSelector(selectors.selectActiveSubPlan);
const email = useSelector(selectors.selectUser).email;
const [stripePromise, setStripePromise] =
useState<Promise<Stripe | null> | null>(null);
const [clientSecret, setClientSecret] = useState<string>("");
const [subscriptionReceiptId, setSubscriptionReceiptId] =
useState<string>("");
const [isLoading, setIsLoading] = useState(true);
if (!activeSubPlan) {
navigate(routes.client.trialChoice());
}
useEffect(() => {
(async () => {
const siteConfig = await api.getAppConfig({ bundleId: "auraweb" });
setStripePromise(loadStripe(siteConfig.data.stripe_public_key));
const { sub_plans } = await api.getSubscriptionPlans({ locale });
const isActiveSubPlan = sub_plans.find(
(subPlan) => subPlan.id === activeSubPlan?.id
);
if (!activeSubPlan || !isActiveSubPlan) {
navigate(routes.client.priceList());
}
})();
}, [activeSubPlan, api, locale, navigate]);
useEffect(() => {
(async () => {
const { subscription_receipt } = await api.createSubscriptionReceipt({
token,
way: "stripe",
subscription_receipt: {
sub_plan_id: activeSubPlan?.id || "stripe.7",
},
});
const { id } = subscription_receipt;
const { client_secret } = subscription_receipt.data;
setSubscriptionReceiptId(id);
setClientSecret(client_secret);
setIsLoading(false);
})();
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [api, token]);
const handleClose = () => {
onClose();
};
return (
<Modal open={open} onClose={handleClose}>
{isLoading ? (
<div className={styles["payment-loader"]}>
<Loader />
</div>
) : null}
{!isLoading && (
<>
<Title variant="h2" className={styles.title}>
Choose payment method
</Title>
<p className={styles.email}>{email}</p>
</>
)}
{stripePromise && clientSecret && subscriptionReceiptId && (
<Elements stripe={stripePromise} options={{ clientSecret }}>
<ApplePayButton
activeSubPlan={activeSubPlan}
client_secret={clientSecret}
subscriptionReceiptId={subscriptionReceiptId}
/>
{activeSubPlan && (
<SubPlanInformation subPlan={activeSubPlan} />
)}
<CheckoutForm subscriptionReceiptId={subscriptionReceiptId} />
</Elements>
)}
</Modal>
);
}

View File

@ -1,2 +0,0 @@
export * from './Button'
export * from './Modal'

View File

@ -3,89 +3,17 @@ import { useEffect, useState } from "react";
import { useSearchParams } from "react-router-dom";
import { useDispatch } from "react-redux";
import { actions } from "@/store";
// import { SubscriptionReceipts, useApi, useApiCall } from "@/api";
// import { useAuth } from "@/auth";
import styles from "./styles.module.css";
import Loader from "@/components/Loader";
import { paymentResultPathsOfProducts } from "@/data/products";
function PaymentResultPage(): JSX.Element {
// const api = useApi();
// const { token } = useAuth();
const navigate = useNavigate();
const dispatch = useDispatch();
const [searchParams] = useSearchParams();
const status = searchParams.get("redirect_status");
const redirect_type = searchParams.get("redirect_type");
// const { id } = useParams();
// const requestTimeOutRef = useRef<NodeJS.Timeout>();
const [isLoading] = useState(true);
// const [subscriptionReceipt, setSubscriptionReceipt] =
// useState<SubscriptionReceipts.SubscriptionReceipt>();
// const loadData = useCallback(async () => {
// if (!id) {
// return null;
// }
// const getSubscriptionReceiptStatus = async () => {
// const { subscription_receipt } = await api.getSubscriptionReceipt({
// token,
// id,
// });
// const { stripe_status } = subscription_receipt.data;
// if (stripe_status === "incomplete") {
// requestTimeOutRef.current = setTimeout(
// getSubscriptionReceiptStatus,
// 3000
// );
// }
// setSubscriptionReceipt(subscription_receipt);
// return { subscription_receipt };
// };
// return getSubscriptionReceiptStatus();
// }, [api, id, token]);
// useApiCall<SubscriptionReceipts.Response | null>(loadData);
// useEffect(() => {
// if (!subscriptionReceipt) {
// if (id?.length) return;
// return () => {
// if (requestTimeOutRef.current) {
// clearTimeout(requestTimeOutRef.current);
// }
// navigate(routes.client.paymentFail());
// };
// }
// const { stripe_status } = subscriptionReceipt.data;
// if (stripe_status === "succeeded") {
// dispatch(actions.status.update("subscribed"));
// setIsLoading(false);
// return () => {
// if (requestTimeOutRef.current) {
// clearTimeout(requestTimeOutRef.current);
// }
// navigate(routes.client.paymentSuccess());
// };
// } else if (stripe_status === "payment_failed") {
// setIsLoading(false);
// return () => {
// if (requestTimeOutRef.current) {
// clearTimeout(requestTimeOutRef.current);
// }
// navigate(routes.client.paymentFail());
// };
// }
// }, [dispatch, id, navigate, subscriptionReceipt]);
// useEffect(() => {
// return () => {
// if (requestTimeOutRef.current) {
// clearTimeout(requestTimeOutRef.current);
// }
// };
// }, []);
useEffect(() => {
if (status === "succeeded") {

View File

@ -3,37 +3,39 @@ import PriceItem from "../PriceItem";
import styles from "./styles.module.css";
import { useDispatch } from "react-redux";
import { actions } from "@/store";
import { ISubscriptionPlan } from "@/api/resources/SubscriptionPlans";
import { IPaywallProduct } from "@/api/resources/Paywall";
interface PriceListProps {
subPlans: ISubscriptionPlan[];
products: IPaywallProduct[];
activeItem: number | null;
classNameItem?: string;
classNameItemActive?: string;
click: () => void;
}
const getPrice = (plan: ISubscriptionPlan) => {
return (plan.trial?.price_cents || 0) / 100;
const getPrice = (product: IPaywallProduct) => {
return (product.trialPrice || 0) / 100;
};
function PriceList({
click,
subPlans,
products,
classNameItem = "",
classNameItemActive = "",
}: PriceListProps): JSX.Element {
const dispatch = useDispatch();
const [activePlanItem, setActivePlanItem] =
useState<ISubscriptionPlan | null>(null);
const [activeProduct, setActiveProduct] = useState<IPaywallProduct | null>(
null
);
const priceItemClick = (id: string) => {
const activePlan = subPlans.find((item) => item.id === String(id)) || null;
setActivePlanItem(activePlan);
if (activePlan) {
const activeProduct =
products.find((item) => item._id === String(id)) || null;
setActiveProduct(activeProduct);
if (activeProduct) {
dispatch(
actions.payment.update({
activeSubPlan: activePlan,
activeProduct,
})
);
}
@ -42,12 +44,12 @@ function PriceList({
return (
<div className={`${styles.container}`}>
{subPlans.map((plan, idx) => (
{products.map((product, idx) => (
<PriceItem
active={plan.id === activePlanItem?.id}
active={product._id === activeProduct?._id}
key={idx}
value={getPrice(plan)}
id={plan.id}
value={getPrice(product)}
id={product._id}
className={classNameItem}
classNameActive={classNameItemActive}
click={priceItemClick}

View File

@ -8,42 +8,31 @@ import Title from "../Title";
import { useTranslation } from "react-i18next";
import EmailsList from "../EmailsList";
import PriceList from "../PriceList";
import { useApi } from "@/api";
import { useEffect, useState } from "react";
import { ISubscriptionPlan } from "@/api/resources/SubscriptionPlans";
import Loader from "../Loader";
import { usePaywall } from "@/hooks/paywall/usePaywall";
import { EPlacementKeys } from "@/api/resources/Paywall";
import { getRandomArbitrary } from "@/services/random-value";
function PriceListPage(): JSX.Element {
const { t, i18n } = useTranslation();
const locale = i18n.language;
const api = useApi();
const { t } = useTranslation();
const navigate = useNavigate();
const dispatch = useDispatch();
const homeConfig = useSelector(selectors.selectHome);
const selectedPrice = useSelector(selectors.selectSelectedPrice);
const [subPlans, setSubPlans] = useState<ISubscriptionPlan[]>([]);
const email = useSelector(selectors.selectEmail);
const { products, getText } = usePaywall({
placementKey: EPlacementKeys["aura.placement.main"],
});
const [countUsers, setCountUsers] = useState(752);
useEffect(() => {
(async () => {
const { sub_plans } = await api.getSubscriptionPlans({ locale });
const plans = sub_plans
.filter((plan: ISubscriptionPlan) => plan.provider === "stripe")
.sort((a, b) => {
if (!a.trial || !b.trial) {
return 0;
}
if (a.trial?.price_cents < b.trial?.price_cents) {
return -1;
}
if (a.trial?.price_cents > b.trial?.price_cents) {
return 1;
}
return 0;
});
setSubPlans(plans);
})();
}, [api, locale]);
const randomDelay = getRandomArbitrary(3000, 5000);
const countUsersTimeOut = setTimeout(() => {
setCountUsers((prevState) => prevState + 1);
}, randomDelay);
return () => clearTimeout(countUsersTimeOut);
}, [countUsers]);
const handleNext = () => {
dispatch(
@ -60,25 +49,33 @@ function PriceListPage(): JSX.Element {
<>
<UserHeader email={email} />
<section className={`${styles.page} page`}>
{!!subPlans.length && (
{!!products.length && (
<>
<Title className={styles.title} variant="h2">
{t("choose_your_own_fee")}
</Title>
<p className={styles.slogan}>{t("aura.web.price_selection")}</p>
<div className={styles["emails-list-container"]}>
<EmailsList />
<EmailsList
title={getText("text.5", {
replacementSelector: "strong",
replacement: {
target: "${quantity}",
replacement: countUsers.toString(),
},
})}
/>
</div>
<div className={styles["price-list-container"]}>
<PriceList
activeItem={selectedPrice}
subPlans={subPlans}
products={products}
click={handleNext}
/>
</div>
</>
)}
{!subPlans.length && <Loader />}
{!products.length && <Loader />}
</section>
</>
);

View File

@ -1,98 +0,0 @@
import { useApi } from "@/api";
import Loader from "@/components/Loader";
import { useEffect, useState } from "react";
import { Stripe, loadStripe } from "@stripe/stripe-js";
import { Elements } from "@stripe/react-stripe-js";
import CheckoutForm from "../PaymentPage/methods/Stripe/CheckoutForm";
import { useAuth } from "@/auth";
import styles from "./styles.module.css";
import { useSelector } from "react-redux";
import { selectors } from "@/store";
import { useNavigate } from "react-router-dom";
import routes from "@/routes";
import SubPlanInformation from "../SubPlanInformation";
import Title from "../Title";
import { useTranslation } from "react-i18next";
import ApplePayButton from "./ApplePayButton";
export function StripePage(): JSX.Element {
const { i18n } = useTranslation();
const api = useApi();
const { token } = useAuth();
const locale = i18n.language;
const navigate = useNavigate();
const activeSubPlan = useSelector(selectors.selectActiveSubPlan);
const email = useSelector(selectors.selectUser).email;
const [stripePromise, setStripePromise] =
useState<Promise<Stripe | null> | null>(null);
const [clientSecret, setClientSecret] = useState<string>("");
const [subscriptionReceiptId, setSubscriptionReceiptId] =
useState<string>("");
const [isLoading, setIsLoading] = useState(true);
if (!activeSubPlan) {
navigate(routes.client.priceList());
}
useEffect(() => {
(async () => {
const siteConfig = await api.getAppConfig({ bundleId: "auraweb" });
setStripePromise(loadStripe(siteConfig.data.stripe_public_key));
const { sub_plans } = await api.getSubscriptionPlans({ locale });
const isActiveSubPlan = sub_plans.find(
(subPlan) => subPlan.id === activeSubPlan?.id
);
if (!activeSubPlan || !isActiveSubPlan) {
navigate(routes.client.priceList());
}
})();
}, [activeSubPlan, api, locale, navigate]);
useEffect(() => {
(async () => {
const { subscription_receipt } = await api.createSubscriptionReceipt({
token,
way: "stripe",
subscription_receipt: {
sub_plan_id: activeSubPlan?.id || "stripe.7",
},
});
const { id } = subscription_receipt;
const { client_secret } = subscription_receipt.data;
setSubscriptionReceiptId(id);
setClientSecret(client_secret);
setIsLoading(false);
})();
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [api, token]);
return (
<div className={`${styles.page} page`}>
{isLoading ? (
<div className={styles["payment-loader"]}>
<Loader />
</div>
) : null}
{!isLoading && (
<>
<Title variant="h2" className={styles.title}>
Pay
</Title>
<p className={styles.email}>{email}</p>
</>
)}
{stripePromise && clientSecret && subscriptionReceiptId && (
<Elements stripe={stripePromise} options={{ clientSecret }}>
<ApplePayButton
activeSubPlan={activeSubPlan}
client_secret={clientSecret}
subscriptionReceiptId={subscriptionReceiptId}
/>
{activeSubPlan && (
<SubPlanInformation subPlan={activeSubPlan} />
)}
<CheckoutForm subscriptionReceiptId={subscriptionReceiptId} />
</Elements>
)}
</div>
);
}

View File

@ -1,38 +0,0 @@
.page {
/* position: relative; */
position: static;
/* height: calc(100vh - 50px);
max-height: -webkit-fill-available; */
display: flex;
justify-items: center;
justify-content: center;
gap: 16px;
}
.payment-loader {
display: flex;
justify-content: center;
align-items: center;
}
.cross {
position: absolute;
top: -36px;
right: 28px;
width: 22px;
height: 22px;
cursor: pointer;
z-index: 9;
}
.title {
font-size: 27px;
font-weight: 700;
margin: 0;
}
.email {
font-size: 17px;
font-weight: 500;
margin: 0;
}

View File

@ -1,34 +1,34 @@
import { useTranslation } from "react-i18next";
import styles from "./styles.module.css";
import { ISubscriptionPlan } from "@/api/resources/SubscriptionPlans";
import TotalToday from "./TotalToday";
import ApplePayButton from "../StripePage/ApplePayButton";
import ApplePayButton from "../PaymentPage/methods/ApplePayButton";
import { IPaywallProduct } from "@/api/resources/Paywall";
interface ISubPlanInformationProps {
subPlan: ISubscriptionPlan;
product: IPaywallProduct;
client_secret?: string;
}
const getPrice = (plan: ISubscriptionPlan): string => {
const getPrice = (product: IPaywallProduct): string => {
return `$${
(plan.trial?.price_cents === 100 ? 99 : plan.trial?.price_cents || 0) / 100
(product.trialPrice === 100 ? 99 : product.trialPrice || 0) / 100
}`;
};
function SubPlanInformation({
subPlan,
product,
client_secret,
}: ISubPlanInformationProps): JSX.Element {
const { t } = useTranslation();
return (
<div className={styles.container}>
<TotalToday total={getPrice(subPlan)} />
<TotalToday total={getPrice(product)} />
{client_secret && (
<ApplePayButton activeSubPlan={subPlan} client_secret={client_secret} />
<ApplePayButton activeProduct={product} client_secret={client_secret} />
)}
<p className={styles.description}>
{t("auweb.pay.information").replaceAll("%@", getPrice(subPlan))}.
{t("auweb.pay.information").replaceAll("%@", getPrice(product))}.
</p>
</div>
);

View File

@ -11,22 +11,23 @@ import styles from "./styles.module.css";
// import Header from "../Header";
// import SpecialWelcomeOffer from "../SpecialWelcomeOffer";
import { useEffect, useState } from "react";
import { ISubscriptionPlan, ITrial } from "@/api/resources/SubscriptionPlans";
import { ApiError, extractErrorMessage, useApi } from "@/api";
import { useAuth } from "@/auth";
import { getClientLocale, getClientTimezone } from "@/locales";
import Loader from "../Loader";
import Title from "../Title";
import ErrorText from "../ErrorText";
import { EPlacementKeys, IPaywallProduct } from "@/api/resources/Paywall";
import { usePaywall } from "@/hooks/paywall/usePaywall";
const currency = Currency.USD;
const locale = getClientLocale() as Locale;
const getPriceFromTrial = (trial: ITrial | null) => {
if (!trial) {
const getPrice = (product: IPaywallProduct | null) => {
if (!product?.trialPrice) {
return 0;
}
return (trial.price_cents === 100 ? 99 : trial.price_cents || 0) / 100;
return (product.trialPrice === 100 ? 99 : product.trialPrice || 0) / 100;
};
function SubscriptionPage(): JSX.Element {
@ -48,37 +49,40 @@ function SubscriptionPage(): JSX.Element {
const [isLoading, setIsLoading] = useState<boolean>(false);
const [apiError, setApiError] = useState<ApiError | null>(null);
const [error, setError] = useState<boolean>(false);
const [subPlans, setSubPlans] = useState<ISubscriptionPlan[]>([]);
const activeSubPlanFromStore = useSelector(selectors.selectActiveSubPlan);
const [activeSubPlan, setActiveSubPlan] = useState<ISubscriptionPlan | null>(
activeSubPlanFromStore
);
const { subPlan } = useParams();
const birthday = useSelector(selectors.selectBirthday);
console.log(nameError)
console.log(nameError);
const { products } = usePaywall({
placementKey: EPlacementKeys["aura.placement.main"],
});
const activeProductFromStore = useSelector(selectors.selectActiveProduct);
const [activeProduct, setActiveProduct] = useState<IPaywallProduct | null>(
activeProductFromStore
);
useEffect(() => {
if (subPlan) {
const targetSubPlan = subPlans.find(
(sub_plan) =>
const targetProduct = products.find(
(product) =>
String(
sub_plan?.trial?.price_cents
? Math.floor((sub_plan?.trial?.price_cents + 1) / 100)
: sub_plan.id.replace(".", "")
product?.trialPrice
? Math.floor((product?.trialPrice + 1) / 100)
: product.key.replace(".", "")
) === subPlan
);
if (targetSubPlan) {
setActiveSubPlan(targetSubPlan);
if (targetProduct) {
setActiveProduct(targetProduct);
}
}
}, [subPlan, subPlans]);
}, [products, subPlan]);
const paymentItems = [
{
title: activeSubPlan?.name || "Per 7-Day Trial For",
price: getPriceFromTrial(activeSubPlan?.trial || null),
description: activeSubPlan?.desc.length
? activeSubPlan?.desc
title: activeProduct?.name || "Per 7-Day Trial For",
price: getPrice(activeProduct),
description: activeProduct?.description?.length
? activeProduct.description
: t("au.2week_plan.web"),
},
];
@ -111,7 +115,7 @@ function SubscriptionPage(): JSX.Element {
dispatch(actions.status.update("registred"));
dispatch(
actions.payment.update({
activeSubPlan,
activeProduct,
})
);
setIsLoading(false);
@ -176,29 +180,6 @@ function SubscriptionPage(): JSX.Element {
setName(name);
};
useEffect(() => {
(async () => {
const { sub_plans } = await api.getSubscriptionPlans({ locale });
const plans = sub_plans
.filter(
(plan: ISubscriptionPlan) => plan.provider === "stripe"
)
.sort((a, b) => {
if (!a.trial || !b.trial) {
return 0;
}
if (a?.trial?.price_cents < b?.trial?.price_cents) {
return -1;
}
if (a?.trial?.price_cents > b?.trial?.price_cents) {
return 1;
}
return 0;
});
setSubPlans(plans);
})();
}, [api]);
return (
<>
{/* <SpecialWelcomeOffer open={isOpenModal} onClose={handleClick} /> */}
@ -274,7 +255,7 @@ function SubscriptionPage(): JSX.Element {
</div>
<div className={styles["subscription-action"]}>
<MainButton onClick={handleClick}>
Start ${getPriceFromTrial(activeSubPlan?.trial || null)}
Start ${getPrice(activeProduct || null)}
</MainButton>
</div>
<Policy>

View File

@ -2,38 +2,37 @@ import { useState } from "react";
import styles from "./styles.module.css";
import { useDispatch } from "react-redux";
import { actions } from "@/store";
import { ISubscriptionPlan } from "@/api/resources/SubscriptionPlans";
import PriceItem from "../PriceItem";
import { IPaywallProduct } from "@/api/resources/Paywall";
interface PriceListProps {
subPlans: ISubscriptionPlan[];
products: IPaywallProduct[];
activeItem: number | null;
classNameItem?: string;
classNameItemActive?: string;
click: () => void;
}
const getPrice = (plan: ISubscriptionPlan) => {
return (plan.trial?.price_cents || 0) / 100;
const getPrice = (product: IPaywallProduct) => {
return (product.trialPrice || 0) / 100;
};
function PriceList({
click,
subPlans,
products,
classNameItem = "",
classNameItemActive = "",
}: PriceListProps): JSX.Element {
const dispatch = useDispatch();
const [activePlanItem, setActivePlanItem] =
useState<ISubscriptionPlan | null>(null);
const [activeProductItem, setActiveProductItem] = useState<IPaywallProduct>();
const priceItemClick = (id: string) => {
const activePlan = subPlans.find((item) => item.id === String(id)) || null;
setActivePlanItem(activePlan);
if (activePlan) {
const activeProduct = products.find((item) => item._id === String(id));
setActiveProductItem(activeProduct);
if (activeProduct) {
dispatch(
actions.payment.update({
activeSubPlan: activePlan,
activeProduct,
})
);
}
@ -42,12 +41,12 @@ function PriceList({
return (
<div className={`${styles.container}`}>
{subPlans.map((plan, idx) => (
{products.map((product, idx) => (
<PriceItem
active={plan.id === activePlanItem?.id}
active={product._id === activeProductItem?._id}
key={idx}
value={getPrice(plan)}
id={plan.id}
value={getPrice(product)}
id={product._id}
className={classNameItem}
classNameActive={classNameItemActive}
click={priceItemClick}

View File

@ -15,4 +15,5 @@
.image {
position: absolute;
bottom: 8px;
z-index: -1;
}

View File

@ -1,6 +1,5 @@
import { IAnswer } from "@/data";
import styles from "./styles.module.css";
import { useState } from "react";
import { useTranslation } from "react-i18next";
import { useDispatch, useSelector } from "react-redux";
import { actions, selectors } from "@/store";
@ -20,34 +19,36 @@ function MultiplyAnswers({ answers }: IMultiplyAnswersProps) {
const { currentlyAffecting, gender } = useSelector(
selectors.selectQuestionnaire
);
const [selectedAnswers, setSelectedAnswers] = useState<string[]>(
currentlyAffecting?.split("$") || []
);
const handleClick = (answer: IAnswer) => {
if (selectedAnswers.includes(answer.id)) {
return setSelectedAnswers((prevState) =>
prevState.filter((item) => item !== answer.id)
if (currentlyAffecting.includes(`$${answer.id}`)) {
return dispatch(
actions.questionnaire.update({
currentlyAffecting: currentlyAffecting.replace(`$${answer.id}`, ""),
})
);
}
if (answer.id === "none_of_these") {
return setSelectedAnswers([answer.id]);
return dispatch(
actions.questionnaire.update({
currentlyAffecting: `$${answer.id}`,
})
);
}
if (
selectedAnswers.includes("none_of_these") &&
currentlyAffecting.includes("$none_of_these") &&
answer.id !== "none_of_these"
) {
return;
}
return setSelectedAnswers((prevState) => [...prevState, answer.id]);
return dispatch(
actions.questionnaire.update({
currentlyAffecting: `${currentlyAffecting}$${answer.id}`,
})
);
};
const handleNext = () => {
dispatch(
actions.questionnaire.update({
currentlyAffecting: selectedAnswers.join("$"),
})
);
navigate(
`${routes.client.questionnaireV1()}/relationships/partnerPriority`
);
@ -55,30 +56,35 @@ function MultiplyAnswers({ answers }: IMultiplyAnswersProps) {
return (
<>
{answers.map((answer, index) => (
<Answer
key={index}
answer={answer}
disabled={
selectedAnswers.includes("none_of_these") &&
answer.id !== "none_of_these"
}
classNameContainer={
selectedAnswers.includes(answer.id) ? styles["answer-active"] : ""
}
type="multiply"
active={selectedAnswers.includes(answer.id)}
gender={gender}
onClick={() => handleClick(answer)}
/>
))}
<QuestionnaireGreenButton
className={styles.button}
onClick={handleNext}
disabled={!selectedAnswers.length}
>
{t("next")}
</QuestionnaireGreenButton>
<div className={styles["multiply-answers"]}>
{answers.map((answer, index) => (
<Answer
key={index}
answer={answer}
disabled={
currentlyAffecting.includes("$none_of_these") &&
answer.id !== "none_of_these"
}
classNameContainer={
currentlyAffecting.includes(`${answer.id}`)
? styles["answer-active"]
: ""
}
type="multiply"
active={currentlyAffecting.includes(`${answer.id}`)}
gender={gender}
onClick={() => handleClick(answer)}
/>
))}
</div>
{!!currentlyAffecting.length && (
<QuestionnaireGreenButton
className={styles.button}
onClick={handleNext}
>
{t("next")}
</QuestionnaireGreenButton>
)}
</>
);
}

View File

@ -1,4 +1,19 @@
.multiply-answers {
display: flex;
flex-direction: column;
align-items: center;
gap: 11px;
z-index: 0;
padding-bottom: 116px;
width: 100%;
}
.button {
position: fixed;
bottom: calc(0dvh + 16px);
width: calc(100% - 64px);
max-width: 396px;
margin-top: 8px;
}

View File

@ -49,6 +49,7 @@
align-items: center;
gap: 11px;
margin-top: 28px;
z-index: 0;
}
.description {

View File

@ -0,0 +1,152 @@
import { IZodicSignsInfo } from "@/data";
export const zodiacSignsInfo: IZodicSignsInfo = {
male: [
{
name: "Capricorn",
img: "/questionnaire-redesign/zodiacs/male/pdf.sex.CAPRICORN.MALE.webp",
description:
"The Capricorn male, with mountain goat tenacity, climbs life's peaks with disciplined dedication.",
},
{
name: "Aquarius",
img: "/questionnaire-redesign/zodiacs/male/pdf.sex.AQUARIUS.MALE.webp",
description:
"Revolutionary in thought, the Aquarius male breaks boundaries, envisioning a brighter, unconventional tomorrow.",
},
{
name: "Pisces",
img: "/questionnaire-redesign/zodiacs/male/pdf.sex.PISCES.MALE.webp",
description:
"Dreamy and empathetic, the Pisces male navigates realms of emotion, often expressing his soul through artistry.",
},
{
name: "Aries",
img: "/questionnaire-redesign/zodiacs/male/pdf.sex.ARIES.MALE.webp",
description:
"The Aries male charges forward with unparalleled energy, always ready to conquer new frontiers.",
},
{
name: "Taurus",
img: "/questionnaire-redesign/zodiacs/male/pdf.sex.TAURUS.MALE.webp",
description:
"The Taurus male values stability, often displaying a potent mix of resilience and sensuality.",
},
{
name: "Gemini",
img: "/questionnaire-redesign/zodiacs/male/pdf.sex.GEMINI.MALE.webp",
description:
"Ever-curious, the Gemini male is a whirlwind of ideas, often switching between topics with excitement.",
},
{
name: "Cancer",
img: "/questionnaire-redesign/zodiacs/male/pdf.sex.CANCER.MALE.webp",
description:
"Deeply intuitive, the Cancer male guards his emotional realm, drawing strength from familial bonds.",
},
{
name: "Leo",
img: "/questionnaire-redesign/zodiacs/male/pdf.sex.LEO.MALE.webp",
description:
"With his regal demeanor, the Leo male has a magnetic charisma that demands the spotlight.",
},
{
name: "Virgo",
img: "/questionnaire-redesign/zodiacs/male/pdf.sex.VIRGO.MALE.webp",
description:
"With an eye for detail, the Virgo male seeks perfection, often being the methodical problem solver in the room.",
},
{
name: "Libra",
img: "/questionnaire-redesign/zodiacs/male/pdf.sex.LIBRA.MALE.webp",
description:
"Driven by harmony, the Libra male gracefully balances life's challenges, always seeking the middle ground.",
},
{
name: "Scorpio",
img: "/questionnaire-redesign/zodiacs/male/pdf.sex.SCORPIO.MALE.webp",
description:
"The Scorpio male delves deep, with an intensity that can unravel life's mysteries, driven by passion and determination.",
},
{
name: "Sagittarius",
img: "/questionnaire-redesign/zodiacs/male/pdf.sex.SAGITTARIUS.MALE.webp",
description:
"With wanderlust in his heart, the Sagittarius male chases knowledge and adventure, ever the eternal optimist.",
},
],
female: [
{
name: "Capricorn",
img: "/questionnaire-redesign/zodiacs/female/pdf.sex.CAPRICORN.FEMALE.webp",
description:
"Grounded and wise, the Capricorn female stands as a pillar of resilience, merging ambition with purpose.",
},
{
name: "Aquarius",
img: "/questionnaire-redesign/zodiacs/female/pdf.sex.AQUARIUS.FEMALE.webp",
description:
"The Aquarius female, with her avant-garde spirit, dances to her own rhythm, forever championing innovation.",
},
{
name: "Pisces",
img: "/questionnaire-redesign/zodiacs/female/pdf.sex.PISCES.FEMALE.webp",
description:
"Ethereal and compassionate, the Pisces female feels deeply, weaving tales of romance and magic in her wake.",
},
{
name: "Aries",
img: "/questionnaire-redesign/zodiacs/female/pdf.sex.ARIES.FEMALE.webp",
description:
"Radiating confidence, the Aries female often leads the pack, fueled by ambition and determination.",
},
{
name: "Taurus",
img: "/questionnaire-redesign/zodiacs/female/pdf.sex.TAURUS.FEMALE.webp",
description:
"Grounded and graceful, the Taurus female appreciates the beauty and luxury in life, always seeking comfort.",
},
{
name: "Gemini",
img: "/questionnaire-redesign/zodiacs/female/pdf.sex.GEMINI.FEMALE.webp",
description:
"Sparkling with wit, the Gemini female charms with her versatility, constantly adapting to change.",
},
{
name: "Cancer",
img: "/questionnaire-redesign/zodiacs/female/pdf.sex.CANCER.FEMALE.webp",
description:
"The nurturing spirit of a Cancer female creates an embracing cocoon of comfort for loved ones.",
},
{
name: "Leo",
img: "/questionnaire-redesign/zodiacs/female/pdf.sex.LEO.FEMALE.webp",
description:
"Vibrant and confident, the Leo female radiates warmth, ruling her domain with generosity and grace.",
},
{
name: "Virgo",
img: "/questionnaire-redesign/zodiacs/female/pdf.sex.VIRGO.FEMALE.webp",
description:
"Discerning and diligent, the Virgo female navigates life with analytical prowess and a pure heart.",
},
{
name: "Libra",
img: "/questionnaire-redesign/zodiacs/female/pdf.sex.LIBRA.FEMALE.webp",
description:
"Charm personified, the Libra female is the embodiment of elegance, wielding diplomacy with an artful touch.",
},
{
name: "Scorpio",
img: "/questionnaire-redesign/zodiacs/female/pdf.sex.SCORPIO.FEMALE.webp",
description:
"The enigmatic Scorpio female possesses a magnetic allure, her depths veiling strength and vulnerability.",
},
{
name: "Sagittarius",
img: "/questionnaire-redesign/zodiacs/female/pdf.sex.SAGITTARIUS.FEMALE.webp",
description:
"Vivacious and free-spirited, the Sagittarius female journeys through life, spreading joy and infectious enthusiasm.",
},
],
};

View File

@ -4,10 +4,8 @@ import { useNavigate, useParams } from "react-router-dom";
import { useTranslation } from "react-i18next";
import { useDispatch, useSelector } from "react-redux";
import { actions, selectors } from "@/store";
import { useApi } from "@/api";
import routes from "@/routes";
import NameInput from "./NameInput";
import { ISubscriptionPlan } from "@/api/resources/SubscriptionPlans";
import Title from "@/components/Title";
import EmailInput from "./EmailInput";
import Policy from "@/components/Policy";
@ -18,6 +16,8 @@ import { useDynamicSize } from "@/hooks/useDynamicSize";
import QuestionnaireGreenButton from "../../ui/GreenButton";
import { ESourceAuthorization } from "@/api/resources/User";
import { useAuthentication } from "@/hooks/authentication/use-authentication";
import { usePaywall } from "@/hooks/paywall/usePaywall";
import { EPlacementKeys, IPaywallProduct } from "@/api/resources/Paywall";
interface IEmailEnterPage {
redirectUrl?: string;
@ -28,8 +28,7 @@ function EmailEnterPage({
redirectUrl = routes.client.emailConfirmV1(),
isRequiredName = false,
}: IEmailEnterPage): JSX.Element {
const api = useApi();
const { t, i18n } = useTranslation();
const { t } = useTranslation();
const dispatch = useDispatch();
const navigate = useNavigate();
const [email, setEmail] = useState("");
@ -38,53 +37,33 @@ function EmailEnterPage({
const [isValidEmail, setIsValidEmail] = useState(false);
const [isValidName, setIsValidName] = useState(!isRequiredName);
const [isAuth, setIsAuth] = useState(false);
const [subPlans, setSubPlans] = useState<ISubscriptionPlan[]>([]);
const activeSubPlanFromStore = useSelector(selectors.selectActiveSubPlan);
const [activeSubPlan, setActiveSubPlan] = useState<ISubscriptionPlan | null>(
activeSubPlanFromStore
);
const locale = i18n.language;
const { subPlan } = useParams();
const { width: pageWidth, elementRef: pageRef } = useDynamicSize({});
const { error, isLoading, authorization } = useAuthentication();
const { gender } = useSelector(selectors.selectQuestionnaire);
const activeProductFromStore = useSelector(selectors.selectActiveProduct);
const { products } = usePaywall({
placementKey: EPlacementKeys["aura.placement.redesign.main"],
});
const [activeProduct, setActiveProduct] = useState<IPaywallProduct | null>(
activeProductFromStore
);
useEffect(() => {
if (subPlan) {
const targetSubPlan = subPlans.find(
(sub_plan) =>
const targetProduct = products.find(
(product) =>
String(
sub_plan?.trial?.price_cents
? Math.floor((sub_plan?.trial?.price_cents + 1) / 100)
: sub_plan.id.replace(".", "")
product?.trialPrice
? Math.floor((product?.trialPrice + 1) / 100)
: product.key.replace(".", "")
) === subPlan
);
if (targetSubPlan) {
setActiveSubPlan(targetSubPlan);
if (targetProduct) {
setActiveProduct(targetProduct);
}
}
}, [subPlan, subPlans]);
useEffect(() => {
(async () => {
const { sub_plans } = await api.getSubscriptionPlans({ locale });
const plans = sub_plans
.filter((plan: ISubscriptionPlan) => plan.provider === "stripe")
.sort((a, b) => {
if (!a.trial || !b.trial) {
return 0;
}
if (a?.trial?.price_cents < b?.trial?.price_cents) {
return -1;
}
if (a?.trial?.price_cents > b?.trial?.price_cents) {
return 1;
}
return 0;
});
setSubPlans(plans);
})();
}, [api, locale]);
}, [subPlan, products]);
const handleValidEmail = (email: string) => {
dispatch(actions.form.addEmail(email));
@ -129,7 +108,7 @@ function EmailEnterPage({
await authorization(email, source);
dispatch(
actions.payment.update({
activeSubPlan,
activeProduct,
})
);
setIsAuth(true);

View File

@ -5,6 +5,8 @@ import routes from "@/routes";
import { useNavigate } from "react-router-dom";
import { onboardingTitles } from "../../data/onboarding";
import ProgressBarLine from "@/components/ui/ProgressBarLine";
import { usePaywall } from "@/hooks/paywall/usePaywall";
import { EPlacementKeys } from "@/api/resources/Paywall";
function OnboardingPage() {
const navigate = useNavigate();
@ -14,6 +16,7 @@ function OnboardingPage() {
const classNameTimeOut = useRef<NodeJS.Timeout>();
const [progress, setProgress] = useState(0);
const progressInterval = useRef<NodeJS.Timeout>();
usePaywall({ placementKey: EPlacementKeys["aura.placement.redesign.main"] });
const handleNext = useCallback(() => {
navigate(routes.client.trialChoiceV1());
@ -51,7 +54,11 @@ function OnboardingPage() {
return (
<section className={`${styles.page} page`}>
<img className={styles.image} src="/leo.png" alt="Leo" />
<img
className={`${styles.image} ${styles[periodClassName]}`}
src="/leo.png"
alt="Leo"
/>
{onboardingTitles[activeIndexTitle] && (
<Title className={`${styles.title} ${styles[periodClassName]}`}>
{onboardingTitles[activeIndexTitle]}

View File

@ -16,6 +16,7 @@
margin-top: 100px;
width: 100%;
max-width: 273px;
transition: opacity 1s;
}
.title {

View File

@ -61,12 +61,12 @@ function RelationshipZodiacInfoPage() {
/>
<div className={styles["image-container"]}>
<img
src={`/questionnaire/zodiacs/${gender}/${zodiacSign?.toLowerCase()}.webp`}
src={`/questionnaire-redesign/zodiacs/${gender}/pdf.sex.${zodiacSign?.toUpperCase()}.${gender.toUpperCase()}.webp`}
alt="The zodiac signs"
/>
<img src="/plus.svg" alt="Plus" />
<img
src={`/questionnaire/zodiacs/${partnerGender}/${partnerZodiacSign?.toLowerCase()}.webp`}
src={`/questionnaire-redesign/zodiacs/${partnerGender}/pdf.sex.${partnerZodiacSign?.toUpperCase()}.${partnerGender.toUpperCase()}.webp`}
alt="The zodiac signs"
/>
</div>

View File

@ -20,15 +20,17 @@
}
.image-container {
display: flex;
justify-content: center;
display: grid;
align-items: center;
justify-items: center;
grid-template-columns: calc(50% - 30px) min-content calc(50% - 30px);
width: 100%;
gap: 32px;
gap: 6px;
}
.image-container > img {
max-width: 118px;
/* max-width: 118px; */
max-height: 196px;
}
.compatibility-description-container {

View File

@ -4,17 +4,18 @@ import { selectors } from "@/store";
import { getZodiacSignByDate } from "@/services/zodiac-sign";
import { useNavigate } from "react-router-dom";
import routes from "@/routes";
import { IZodicSignsInfo, zodicSignsInfo } from "@/data";
import { IZodicSignsInfo } from "@/data";
import Title from "@/components/Title";
import Header from "../../components/Header";
import QuestionnaireGreenButton from "../../ui/GreenButton";
import { zodiacSignsInfo } from "../../data/zodiacSignsInfo";
function SingleZodiacInfoPage() {
const navigate = useNavigate();
const birthdate = useSelector(selectors.selectQuestionnaire).birthdate;
const gender = useSelector(selectors.selectQuestionnaire).gender;
const zodiac = getZodiacSignByDate(birthdate);
const zodiacInfo = zodicSignsInfo[gender as keyof IZodicSignsInfo].find(
const zodiacInfo = zodiacSignsInfo[gender as keyof IZodicSignsInfo].find(
(sign) => sign.name === zodiac
);

View File

@ -1,8 +1,5 @@
import styles from "./styles.module.css";
import { useEffect, useMemo, useState } from "react";
import { ISubscriptionPlan } from "@/api/resources/SubscriptionPlans";
import { useTranslation } from "react-i18next";
import { useApi } from "@/api";
import { useEffect, useState } from "react";
import { useDispatch, useSelector } from "react-redux";
import { actions, selectors } from "@/store";
import { useNavigate } from "react-router-dom";
@ -13,66 +10,32 @@ import BackgroundTopBlob from "../../ui/BackgroundTopBlob";
import { useDynamicSize } from "@/hooks/useDynamicSize";
import PriceList from "../../components/PriceList";
import QuestionnaireGreenButton from "../../ui/GreenButton";
interface IPlanKey {
[key: string]: number;
}
import { usePaywall } from "@/hooks/paywall/usePaywall";
import { EPlacementKeys } from "@/api/resources/Paywall";
import { getRandomArbitrary } from "@/services/random-value";
import Loader from "@/components/Loader";
function TrialChoicePage() {
const { i18n } = useTranslation();
const locale = i18n.language;
const api = useApi();
const dispatch = useDispatch();
const navigate = useNavigate();
const selectedPrice = useSelector(selectors.selectSelectedPrice);
const homeConfig = useSelector(selectors.selectHome);
const email = useSelector(selectors.selectEmail);
const [subPlans, setSubPlans] = useState<ISubscriptionPlan[]>([]);
const [isDisabled, setIsDisabled] = useState(true);
const allowedPlans = useMemo(() => [""], []);
const [countUsers, setCountUsers] = useState(752);
const { width: pageWidth, elementRef: pageRef } = useDynamicSize({});
const { gender } = useSelector(selectors.selectQuestionnaire);
const { products, isLoading, getText } = usePaywall({
placementKey: EPlacementKeys["aura.placement.redesign.main"],
});
useEffect(() => {
(async () => {
const { sub_plans } = await api.getSubscriptionPlans({ locale });
const plansWithoutTest = sub_plans.filter(
(plan: ISubscriptionPlan) => !plan.name.includes("(test)")
);
const plansKeys: IPlanKey = {};
const plans: ISubscriptionPlan[] = [];
for (const plan of plansWithoutTest) {
plansKeys[plan.name] = plansKeys[plan.name]
? plansKeys[plan.name] + 1
: 1;
if (
(plansKeys[plan.name] > 1 && !plan.trial?.is_free && !!plan.trial) ||
allowedPlans.includes(plan.id)
) {
const targetPlan = plansWithoutTest.find(
(item) => item.name === plan.name && item.id.includes("stripe")
);
plans.push(targetPlan as ISubscriptionPlan);
}
}
plans.sort((a, b) => {
if (!a.trial || !b.trial) {
return 0;
}
if (a.trial?.price_cents < b.trial?.price_cents) {
return -1;
}
if (a.trial?.price_cents > b.trial?.price_cents) {
return 1;
}
return 0;
});
setSubPlans(plans);
})();
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [api, locale]);
const randomDelay = getRandomArbitrary(3000, 5000);
const countUsersTimeOut = setTimeout(() => {
setCountUsers((prevState) => prevState + 1);
}, randomDelay);
return () => clearTimeout(countUsersTimeOut);
}, [countUsers]);
const handlePriceItem = () => {
setIsDisabled(false);
@ -101,60 +64,76 @@ function TrialChoicePage() {
height={180}
/>
<Header className={styles.header} />
<p className={styles.text} style={{ marginTop: "60px" }}>
We've helped{" "}
<span className={styles.blue}>
<b>millions</b>
</span>{" "}
of people to have happier lives and better relationships, and we want to
help you too.
</p>
<p className={`${styles.text} ${styles.bold}`}>
Money shouldnt stand in the way of finding astrology guidance that
finally works. So, choose an amount that you think is reasonable to try
us out for one week.
</p>
<p className={`${styles.text} ${styles.bold} ${styles.blue}`}>
It costs us $13.67 to offer a 3-day trial, but please choose the amount
you are comfortable with.
</p>
<div className={styles["price-container"]}>
<PriceList
subPlans={subPlans}
activeItem={selectedPrice}
classNameItem={styles["price-item"]}
classNameItemActive={`${styles["price-item-active"]} ${styles[gender]}`}
click={handlePriceItem}
/>
<p className={styles["auxiliary-text"]} style={{ maxWidth: "75%" }}>
This option will help us support those who need to select the lowest
trial prices!
</p>
<img
className={styles["arrow-image"]}
src="/arrow.svg"
alt={`Arrow to $${subPlans.at(-1)}`}
/>
</div>
<div className={styles["emails-list-container"]}>
<EmailsList
classNameContainer={`${styles["emails-container"]} ${styles[gender]}`}
classNameTitle={styles["emails-title"]}
classNameEmailItem={styles["email-item"]}
direction="right-left"
/>
</div>
<p className={styles.email}>{email}</p>
<QuestionnaireGreenButton
className={styles.button}
disabled={isDisabled}
onClick={handleNext}
>
See my plan
</QuestionnaireGreenButton>
<p className={styles["auxiliary-text"]}>
*Cost of trial as of February 2024
</p>
{!isLoading && (
<>
<p className={styles.text} style={{ marginTop: "60px" }}>
{getText("text.0", {
replacementSelector: "b",
color: "#1C38EA",
})}
</p>
<p className={`${styles.text} ${styles.bold}`}>
{getText("text.1", {
color: "#1C38EA",
})}
</p>
<p className={`${styles.text} ${styles.bold} ${styles.blue}`}>
{getText("text.2", {
color: "#1C38EA",
})}
</p>
<div className={styles["price-container"]}>
<PriceList
products={products}
activeItem={selectedPrice}
classNameItem={styles["price-item"]}
classNameItemActive={`${styles["price-item-active"]} ${styles[gender]}`}
click={handlePriceItem}
/>
<p className={styles["auxiliary-text"]} style={{ maxWidth: "75%" }}>
{getText("text.3", {
color: "#1C38EA",
})}
</p>
<img
className={styles["arrow-image"]}
src="/arrow.svg"
alt={`Arrow to $${products.at(-1)?.trialPrice}`}
/>
</div>
<div className={styles["emails-list-container"]}>
<EmailsList
title={getText("text.5", {
replacementSelector: "strong",
replacement: {
target: "${quantity}",
replacement: countUsers.toString(),
},
})}
classNameContainer={`${styles["emails-container"]} ${styles[gender]}`}
classNameTitle={styles["emails-title"]}
classNameEmailItem={styles["email-item"]}
direction="right-left"
/>
</div>
<p className={styles.email}>{email}</p>
<QuestionnaireGreenButton
className={styles.button}
disabled={isDisabled}
onClick={handleNext}
>
{getText("text.button.1", {
color: "#1C38EA",
})}
</QuestionnaireGreenButton>
<p className={styles["auxiliary-text"]}>
{getText("text.4", {
color: "#1C38EA",
})}
</p>
</>
)}
{isLoading && <Loader className={styles.loader} />}
</section>
);
}

View File

@ -137,4 +137,11 @@
.email {
font-weight: 500;
}
.loader {
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
}

View File

@ -1,6 +1,8 @@
import { useSelector } from "react-redux";
import CustomButton from "../CustomButton";
import DiscountExpires from "../DiscountExpires";
import styles from "./styles.module.css";
import { selectors } from "@/store";
interface IHeaderProps {
buttonText?: string;
@ -13,8 +15,14 @@ function Header({
buttonText = "get my reading",
buttonClassName = "",
}: IHeaderProps) {
const { gender } = useSelector(selectors.selectQuestionnaire);
return (
<header className={styles.header}>
<header
className={styles.header}
style={{
backgroundColor: gender === "male" ? "#C1E5FF" : "#F7EBFF",
}}
>
<DiscountExpires />
<CustomButton
className={`${styles.button} ${buttonClassName}`}

View File

@ -1,5 +1,7 @@
.header {
position: relative;
position: sticky;
top: 0;
z-index: 30;
height: 62px;
width: 100%;
max-width: 560px;

View File

@ -4,53 +4,61 @@ import PaymentMethodsChoice from "../PaymentMethodsChoice";
import { useEffect, useMemo, useState } from "react";
import { EPaymentMethod, paymentMethods } from "@/data/paymentMethods";
import { Elements } from "@stripe/react-stripe-js";
import ApplePayButton from "@/components/StripePage/ApplePayButton";
import CheckoutForm from "@/components/PaymentPage/methods/Stripe/CheckoutForm";
import ApplePayButton from "@/components/PaymentPage/methods/ApplePayButton";
import CheckoutForm from "@/components/PaymentPage/methods/CheckoutForm";
import { Stripe, loadStripe } from "@stripe/stripe-js";
import { useSelector } from "react-redux";
import { selectors } from "@/store";
import { ISubscriptionPlan } from "@/api/resources/SubscriptionPlans";
import { useApi } from "@/api";
import { useNavigate } from "react-router-dom";
import routes from "@/routes";
import { useTranslation } from "react-i18next";
import { useAuth } from "@/auth";
import Loader from "@/components/Loader";
import { getPriceFromTrial } from "@/services/price";
import SecurityPayments from "../SecurityPayments";
import { EPlacementKeys, IPaywallProduct } from "@/api/resources/Paywall";
import { usePaywall } from "@/hooks/paywall/usePaywall";
import { useMakePayment } from "@/hooks/payment/useMakePayment";
interface IPaymentModalProps {
activeSubscriptionPlan?: ISubscriptionPlan;
activeProduct?: IPaywallProduct;
noTrial?: boolean;
returnUrl?: string;
placementKey?: EPlacementKeys;
}
const getPrice = (product: IPaywallProduct) => {
return (product.trialPrice || 0) / 100;
};
function PaymentModal({
activeSubscriptionPlan,
activeProduct,
noTrial,
returnUrl,
placementKey = EPlacementKeys["aura.placement.redesign.main"],
}: IPaymentModalProps) {
const { i18n } = useTranslation();
const locale = i18n.language;
const api = useApi();
const { token } = useAuth();
const navigate = useNavigate();
const activeSubPlanFromStore = useSelector(selectors.selectActiveSubPlan);
const activeSubPlan = activeSubscriptionPlan
? activeSubscriptionPlan
: activeSubPlanFromStore;
const [stripePromise, setStripePromise] =
useState<Promise<Stripe | null> | null>(null);
const [clientSecret, setClientSecret] = useState<string>("");
const [subscriptionReceiptId, setSubscriptionReceiptId] =
useState<string>("");
const [isLoading, setIsLoading] = useState(true);
const [isError, setIsError] = useState<boolean>(false);
const activeProductFromStore = useSelector(selectors.selectActiveProduct);
const _activeProduct = activeProduct ? activeProduct : activeProductFromStore;
const {
paymentIntentId,
clientSecret,
returnUrl: checkoutUrl,
paymentType,
publicKey,
isLoading,
error,
} = useMakePayment({
productId: _activeProduct?._id || "",
returnPaidUrl:
returnUrl
});
if (checkoutUrl?.length) {
window.location.href = checkoutUrl;
}
const paymentMethodsButtons = useMemo(() => {
// return paymentMethods.filter(
// (method) => method.id !== EPaymentMethod.PAYMENT_BUTTONS
// );
return paymentMethods;
}, []);
@ -58,49 +66,24 @@ function PaymentModal({
EPaymentMethod.PAYMENT_BUTTONS
);
const { products } = usePaywall({ placementKey });
const onSelectPaymentMethod = (method: EPaymentMethod) => {
setSelectedPaymentMethod(method);
};
useEffect(() => {
(async () => {
const siteConfig = await api.getAppConfig({ bundleId: "auraweb" });
setStripePromise(loadStripe(siteConfig.data.stripe_public_key));
const { sub_plans } = await api.getSubscriptionPlans({ locale });
const isActiveSubPlan = sub_plans.find(
(subPlan) => subPlan.id === activeSubPlan?.id
if (!products?.length || !publicKey) return;
setStripePromise(loadStripe(publicKey));
const isActiveProduct = products.find(
(product) => product._id === _activeProduct?._id
);
if (!activeSubPlan || !isActiveSubPlan) {
navigate(routes.client.priceList());
if (!_activeProduct || !isActiveProduct) {
navigate(routes.client.trialChoiceV1());
}
})();
}, [activeSubPlan, api, locale, navigate]);
useEffect(() => {
(async () => {
try {
const { subscription_receipt } = await api.createSubscriptionReceipt({
token,
way: "stripe",
subscription_receipt: {
sub_plan_id: activeSubPlan?.id || "stripe.7",
},
});
const { id } = subscription_receipt;
const { client_secret } = subscription_receipt.data;
const { checkout_url } = subscription_receipt.data;
if (checkout_url?.length) {
window.location.href = checkout_url;
}
setSubscriptionReceiptId(id);
setClientSecret(client_secret);
setIsLoading(false);
} catch (error) {
console.error(error);
setIsError(true);
}
})();
}, [activeSubPlan?.id, api, token]);
}, [_activeProduct, navigate, products, publicKey]);
if (isLoading) {
return (
@ -112,7 +95,7 @@ function PaymentModal({
);
}
if (isError) {
if (error?.length) {
return (
<div className={styles["payment-modal"]}>
<Title variant="h3" className={styles.title}>
@ -132,16 +115,13 @@ function PaymentModal({
selectedPaymentMethod={selectedPaymentMethod}
onSelectPaymentMethod={onSelectPaymentMethod}
/>
{activeSubPlan && (
{_activeProduct && (
<div>
{!noTrial && (
<>
<p className={styles["sub-plan-description"]}>
You will be charged only{" "}
<b>
${getPriceFromTrial(activeSubPlan?.trial)} for your 3-day
trial.
</b>
<b>${getPrice(_activeProduct)} for your 3-day trial.</b>
</p>
<p className={styles["sub-plan-description"]}>
We`ll <b>email you a reminder</b> before your trial period ends.
@ -160,16 +140,17 @@ function PaymentModal({
{selectedPaymentMethod === EPaymentMethod.PAYMENT_BUTTONS && (
<div className={styles["payment-method"]}>
<ApplePayButton
activeSubPlan={activeSubPlan}
activeProduct={_activeProduct}
client_secret={clientSecret}
subscriptionReceiptId={subscriptionReceiptId}
subscriptionReceiptId={paymentIntentId}
/>
</div>
)}
{selectedPaymentMethod === EPaymentMethod.CREDIT_CARD && (
<CheckoutForm
subscriptionReceiptId={subscriptionReceiptId}
confirmType={paymentType}
subscriptionReceiptId={paymentIntentId}
returnUrl={returnUrl}
/>
)}

View File

@ -1,19 +1,22 @@
import Title from "@/components/Title";
import styles from "./styles.module.css";
import { getPriceFromTrial } from "@/services/price";
import { ISubscriptionPlan } from "@/api/resources/SubscriptionPlans";
import CustomButton from "../CustomButton";
import GuardPayments from "../GuardPayments";
import { useState } from "react";
import FullScreenModal from "@/components/FullScreenModal";
import { IPaywallProduct } from "@/api/resources/Paywall";
interface IPaymentTableProps {
subPlan: ISubscriptionPlan;
product: IPaywallProduct;
gender: string;
buttonClick: () => void;
}
function PaymentTable({ gender, subPlan, buttonClick }: IPaymentTableProps) {
const getPrice = (product: IPaywallProduct) => {
return (product.trialPrice || 0) / 100;
};
function PaymentTable({ gender, product, buttonClick }: IPaymentTableProps) {
const [isOpenPrivacyModal, setIsOpenPrivacyModal] = useState<boolean>(false);
const handleSubscriptionPolicyClick = (event: React.MouseEvent) => {
event.preventDefault();
@ -50,20 +53,18 @@ function PaymentTable({ gender, subPlan, buttonClick }: IPaymentTableProps) {
<div className={styles["table-container"]}>
<Title variant="h3" className={styles.title}>
Personalized reading for{" "}
<span className={styles.purple}>
${getPriceFromTrial(subPlan?.trial)}
</span>
<span className={styles.purple}>${getPrice(product)}</span>
</Title>
<div className={styles["table-element"]}>
<p className={styles["total-today"]}>Total today:</p>
<span>${getPriceFromTrial(subPlan?.trial)}</span>
<span>${getPrice(product)}</span>
</div>
<hr />
<div className={styles["table-element"]}>
<p>Your cost per 2 weeks after trial</p>
<div>
<span className={styles.discount}>$65</span>
<span>${subPlan.price_cents / 100}</span>
<span>${product.trialPrice / 100}</span>
</div>
</div>
</div>
@ -75,9 +76,9 @@ function PaymentTable({ gender, subPlan, buttonClick }: IPaymentTableProps) {
<p className={styles.policy}>
You are enrolling in 2 weeks subscription. By continuing you agree that
if you don't cancel prior to the end of the 3-day trial for the $
{getPriceFromTrial(subPlan?.trial)} you will automatically be charged
$19 every 2 weeks until you cancel in settings. Learn more about
cancellation and refund policy in{" "}
{getPrice(product)} you will automatically be charged $19 every 2 weeks
until you cancel in settings. Learn more about cancellation and refund
policy in{" "}
<a onClick={handleSubscriptionPolicyClick}>Subscription policy</a>
</p>
</>

View File

@ -22,7 +22,7 @@ function PersonalInformation({
>
<div className={styles["image-container"]}>
<img
src={`/questionnaire/zodiacs/${gender}/${zodiacSign?.toLowerCase()}.webp`}
src={`/questionnaire-redesign/zodiacs/${gender}/pdf.sex.${zodiacSign?.toUpperCase()}.${gender.toUpperCase()}.webp`}
alt={`${gender} ${zodiacSign}`}
/>
</div>

View File

@ -33,14 +33,15 @@ function WithPartnerInformation(props: IWithPartnerInformationProps) {
<div className={styles["images-container"]}>
<div className={styles["image-container"]}>
<img
src={`/questionnaire/zodiacs/${gender}/${zodiacSign?.toLowerCase()}.webp`}
src={`/questionnaire-redesign/zodiacs/${gender}/pdf.sex.${zodiacSign?.toUpperCase()}.${gender.toUpperCase()}.webp`}
alt={`${gender} ${zodiacSign}`}
/>
<p>You</p>
</div>
<img src="/plus.svg" alt="Plus" />
<div className={styles["image-container"]}>
<img
src={`/questionnaire/zodiacs/${partnerGender}/${partnerZodiacSign?.toLowerCase()}.webp`}
src={`/questionnaire-redesign/zodiacs/${partnerGender}/pdf.sex.${partnerZodiacSign?.toUpperCase()}.${partnerGender.toUpperCase()}.webp`}
alt={`${partnerGender} ${partnerZodiacSign}`}
/>
<p>Partner</p>

View File

@ -17,8 +17,10 @@
min-height: 100px;
border-top-left-radius: 15px;
border-top-right-radius: 15px;
display: flex;
justify-content: space-around;
display: grid;
grid-template-columns: calc(50% - 28px) min-content calc(50% - 28px);
align-items: center;
gap: 4px;
padding-top: 10px;
padding-bottom: 6px;
}
@ -33,6 +35,8 @@
.image-container > img {
height: 196px;
width: 100%;
object-fit: contain;
}
.image-container > p {

View File

@ -40,7 +40,7 @@ function YourReading({
</Title>
<div className={styles["image-container"]}>
<img
src={`/questionnaire/zodiacs/${gender}/${zodiacSign?.toLowerCase()}.webp`}
src={`/questionnaire-redesign/zodiacs/${gender}/pdf.sex.${zodiacSign?.toUpperCase()}.${gender.toUpperCase()}.webp`}
alt={`${gender} ${zodiacSign}`}
/>
</div>

View File

@ -12,11 +12,7 @@ import YourReading from "./components/YourReading";
import Reviews from "./components/Reviews";
import PointsList from "./components/PointsList";
import OftenAsk from "./components/OftenAsk";
import { ISubscriptionPlan } from "@/api/resources/SubscriptionPlans";
import { useEffect, useState } from "react";
import { useApi } from "@/api";
import { getClientLocale } from "@/locales";
import { Locale } from "@/components/PaymentTable";
import WithPartnerInformation from "./components/WithPartnerInformation";
import Modal from "@/components/Modal";
import PaymentModal from "./components/PaymentModal";
@ -26,12 +22,11 @@ import TrialPaymentHeader from "./components/Header";
import Header from "../../components/Header";
import BackgroundTopBlob from "../../ui/BackgroundTopBlob";
import { useDynamicSize } from "@/hooks/useDynamicSize";
const locale = getClientLocale() as Locale;
import { EPlacementKeys, IPaywallProduct } from "@/api/resources/Paywall";
import { usePaywall } from "@/hooks/paywall/usePaywall";
function TrialPaymentPage() {
const dispatch = useDispatch();
const api = useApi();
const navigate = useNavigate();
const birthdate = useSelector(selectors.selectBirthdate);
const zodiacSign = getZodiacSignByDate(birthdate);
@ -46,10 +41,12 @@ function TrialPaymentPage() {
flowChoice,
} = useSelector(selectors.selectQuestionnaire);
const partnerZodiacSign = getZodiacSignByDate(partnerBirthdate);
const [subPlans, setSubPlans] = useState<ISubscriptionPlan[]>([]);
const activeSubPlanFromStore = useSelector(selectors.selectActiveSubPlan);
const [activeSubPlan, setActiveSubPlan] = useState<ISubscriptionPlan | null>(
activeSubPlanFromStore
const { products } = usePaywall({
placementKey: EPlacementKeys["aura.placement.redesign.main"],
});
const activeProductFromStore = useSelector(selectors.selectActiveProduct);
const [activeProduct, setActiveProduct] = useState<IPaywallProduct | null>(
activeProductFromStore
);
const [isOpenPaymentModal, setIsOpenPaymentModal] = useState<boolean>(false);
const [singleOrWithPartner, setSingleOrWithPartner] = useState<
@ -57,43 +54,32 @@ function TrialPaymentPage() {
>("single");
const { subPlan } = useParams();
useEffect(() => {
(async () => {
const { sub_plans } = await api.getSubscriptionPlans({ locale });
const plans = sub_plans
.filter((plan: ISubscriptionPlan) => plan.provider === "stripe")
.sort((a, b) => {
if (!a.trial || !b.trial) {
return 0;
}
if (a?.trial?.price_cents < b?.trial?.price_cents) {
return -1;
}
if (a?.trial?.price_cents > b?.trial?.price_cents) {
return 1;
}
return 0;
});
setSubPlans(plans);
})();
}, [api]);
useEffect(() => {
if (subPlan) {
const targetSubPlan = subPlans.find(
(sub_plan) =>
const targetProduct = products.find(
(product) =>
String(
sub_plan?.trial?.price_cents
? Math.floor((sub_plan?.trial?.price_cents + 1) / 100)
: sub_plan.id.replace(".", "")
product?.trialPrice
? Math.floor((product?.trialPrice + 1) / 100)
: product.key.replace(".", "")
) === subPlan
);
if (targetSubPlan) {
setActiveSubPlan(targetSubPlan);
dispatch(actions.payment.update({ activeSubPlan: targetSubPlan }));
if (targetProduct) {
setActiveProduct(targetProduct);
dispatch(actions.payment.update({ activeProduct }));
}
}
}, [dispatch, subPlan, subPlans]);
}, [dispatch, subPlan, products, activeProduct]);
useEffect(() => {
if (!products.length) return;
const isActiveProduct = products.find(
(product) => product._id === activeProduct?._id
);
if (!activeProduct || !isActiveProduct) {
navigate(routes.client.trialChoiceV1());
}
}, [activeProduct, navigate, products]);
useEffect(() => {
if (["relationship", "married"].includes(flowChoice)) {
@ -103,12 +89,12 @@ function TrialPaymentPage() {
setSingleOrWithPartner("single");
}, [flowChoice]);
if (!activeSubPlan) {
return <Navigate to={routes.client.trialChoice()} />;
if (!activeProduct) {
return <Navigate to={routes.client.trialChoiceV1()} />;
}
if (!birthdate || !gender || !birthPlace) {
return <Navigate to={routes.client.gender()} />;
return <Navigate to={routes.client.genderV1()} />;
}
const handleDiscount = () => {
@ -168,7 +154,7 @@ function TrialPaymentPage() {
<Goal goal={goal} />
<PaymentTable
gender={gender}
subPlan={activeSubPlan}
product={activeProduct}
buttonClick={openStripeModal}
/>
<YourReading
@ -185,7 +171,7 @@ function TrialPaymentPage() {
<OftenAsk />
<PaymentTable
gender={gender}
subPlan={activeSubPlan}
product={activeProduct}
buttonClick={openStripeModal}
/>
</section>

View File

@ -6,6 +6,8 @@
padding-bottom: 62px;
width: 100%;
max-width: 460px;
overflow: inherit;
overflow-x: clip;
}
.title {

View File

@ -2,10 +2,17 @@ import Title from "@/components/Title";
import styles from "./styles.module.css";
import { useSelector } from "react-redux";
import { selectors } from "@/store";
import { getPriceFromTrial } from "@/services/price";
import { IPaywallProduct } from "@/api/resources/Paywall";
const getPrice = (product: IPaywallProduct | null) => {
if (!product) {
return 0;
}
return (product.trialPrice === 100 ? 99 : product.trialPrice || 0) / 100;
};
function PaymentDiscountTable() {
const activeSub = useSelector(selectors.selectActiveSubPlan);
const activeProduct = useSelector(selectors.selectActiveProduct);
return (
<div className={styles.container}>
@ -15,7 +22,11 @@ function PaymentDiscountTable() {
<p className={styles["no-pressure"]}>No pressure. Cancel anytime.</p>
<div className={styles.applied}>
<div className={styles.side}>
<img className={styles["present-image"]} src="/present.png" alt="Present" />
<img
className={styles["present-image"]}
src="/present.png"
alt="Present"
/>
<p className={styles.description}>Secret discount applied!</p>
</div>
<div className={styles.side}>
@ -27,14 +38,14 @@ function PaymentDiscountTable() {
<p>Your cost per 14 days after trial:</p>
<div className={styles.side}>
<span className={styles.discount}>$19</span>
<strong>$9</strong>
<strong>${(activeProduct?.price || 0) / 100}</strong>
</div>
</div>
<p className={styles.save}>You save $30</p>
<hr className={styles.line} />
<div className={styles["total-container"]}>
<p>Total today:</p>
{activeSub && <strong>${getPriceFromTrial(activeSub.trial)}</strong>}
{activeProduct && <strong>${getPrice(activeProduct)}</strong>}
</div>
</div>
);

View File

@ -4,19 +4,44 @@ import MainButton from "@/components/MainButton";
import PaymentDiscountTable from "./PaymentDiscountTable";
import Modal from "@/components/Modal";
import PaymentModal from "../TrialPayment/components/PaymentModal";
import { useState } from "react";
import { useEffect, useState } from "react";
import { actions, selectors } from "@/store";
import { useDispatch, useSelector } from "react-redux";
import { usePaywall } from "@/hooks/paywall/usePaywall";
import { EPlacementKeys } from "@/api/resources/Paywall";
function TrialPaymentWithDiscount() {
const dispatch = useDispatch();
const { products } = usePaywall({
placementKey: EPlacementKeys["aura.placement.secret.discount"],
});
const productFromStore = useSelector(selectors.selectActiveProduct);
const [isOpenPaymentModal, setIsOpenPaymentModal] = useState<boolean>(false);
const handleClose = () => {
setIsOpenPaymentModal(false);
};
useEffect(() => {
if (!products.length) return;
const activeProduct = products.find(
(p) => p.trialPrice === productFromStore?.trialPrice
);
if (!activeProduct) {
dispatch(actions.payment.update({ activeProduct: products[0] }));
}
if (activeProduct) {
dispatch(actions.payment.update({ activeProduct }));
}
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [dispatch, products]);
return (
<section className={`${styles.page} page`}>
<Modal open={isOpenPaymentModal} onClose={handleClose}>
<PaymentModal />
<PaymentModal
placementKey={EPlacementKeys["aura.placement.secret.discount"]}
/>
</Modal>
<img
className={styles["party-popper"]}
@ -35,10 +60,12 @@ function TrialPaymentWithDiscount() {
</MainButton>
<p className={styles.policy}>
By continuing you agree that if you don't cancel prior to the end of the
3-days trial, you will automatically be charged $9 for the introductory
period of 14 days thereafter the standard rate of $9 every 14 days until
you cancel in settings. Learn more about cancellation and refund policy
in Subscription terms.
3-days trial, you will automatically be charged $
{(productFromStore?.price || 0) / 100} for the introductory period of 14
days thereafter the standard rate of $
{(productFromStore?.price || 0) / 100} every 14 days until you cancel in
settings. Learn more about cancellation and refund policy in
Subscription terms.
</p>
</section>
);

View File

@ -10,12 +10,10 @@ import { SinglePayment, useApi, useApiCall } from "@/api";
import { useSelector } from "react-redux";
import { selectors } from "@/store";
import { useCallback, useState } from "react";
import {
ResponsePost,
} from "@/api/resources/SinglePayment";
import { ResponsePost } from "@/api/resources/SinglePayment";
import { createSinglePayment } from "@/services/singlePayment";
import Modal from "@/components/Modal";
import PaymentForm from "@/components/pages/PaymentWithEmailPage/PaymentForm";
import PaymentForm from "@/components/pages/SinglePaymentPage/PaymentForm";
import { getPriceCentsToDollars } from "@/services/price";
import Loader, { LoaderColor } from "@/components/Loader";
@ -25,9 +23,7 @@ function AddConsultationPage() {
const api = useApi();
const tokenFromStore = useSelector(selectors.selectToken);
const [isLoading, setIsLoading] = useState(false);
const [paymentIntent, setPaymentIntent] = useState<
ResponsePost | null
>(null);
const [paymentIntent, setPaymentIntent] = useState<ResponsePost | null>(null);
const [isError, setIsError] = useState(false);
const returnUrl = `${window.location.protocol}//${
window.location.host
@ -45,29 +41,34 @@ function AddConsultationPage() {
);
const handleClick = async () => {
if (!userFromStore || !currentProduct) return;
setIsLoading(true);
const { productId, key } = currentProduct;
const paymentInfo = {
productId,
key,
};
const paymentIntent = await createSinglePayment(
userFromStore,
paymentInfo,
tokenFromStore,
userFromStore.email,
userFromStore.profile.full_name,
userFromStore.profile.birthday,
returnUrl,
api
);
setPaymentIntent(paymentIntent);
setIsLoading(false);
if ("payment" in paymentIntent) {
if (paymentIntent.payment.status === "paid")
return navigate(routes.client.getInformationPartner());
return setIsError(true);
try {
if (!userFromStore || !currentProduct) return;
setIsLoading(true);
const { _id, key } = currentProduct;
const paymentInfo = {
productId: _id,
key,
};
const paymentIntent = await createSinglePayment(
userFromStore,
paymentInfo,
tokenFromStore,
userFromStore.email,
userFromStore.profile.full_name,
userFromStore.profile.birthday,
returnUrl,
api
);
setPaymentIntent(paymentIntent);
if ("payment" in paymentIntent) {
if (paymentIntent.payment.status === "paid")
return navigate(routes.client.getInformationPartner());
return setIsError(true);
}
} catch (error) {
setIsError(true);
} finally {
setIsLoading(false);
}
};
@ -86,7 +87,7 @@ function AddConsultationPage() {
onClose={() => setPaymentIntent(null)}
>
<Title variant="h1" className={styles["modal-title"]}>
{getPriceCentsToDollars(currentProduct?.amount || 0)}$
{getPriceCentsToDollars(currentProduct?.price || 0)}$
</Title>
<PaymentForm
stripePublicKey={paymentIntent.paymentIntent.data.public_key}

View File

@ -9,9 +9,7 @@ import FooterButton from "../../components/FooterButton";
import routes from "@/routes";
import PaymentAddress from "../../components/PaymentAddress";
import { createSinglePayment } from "@/services/singlePayment";
import {
ResponsePost,
} from "@/api/resources/SinglePayment";
import { ResponsePost } from "@/api/resources/SinglePayment";
import { useAuth } from "@/auth";
import { useSelector } from "react-redux";
import { selectors } from "@/store";
@ -19,16 +17,14 @@ import { SinglePayment, useApi, useApiCall } from "@/api";
import Loader, { LoaderColor } from "@/components/Loader";
import { getPriceCentsToDollars } from "@/services/price";
import Modal from "@/components/Modal";
import PaymentForm from "@/components/pages/PaymentWithEmailPage/PaymentForm";
import PaymentForm from "@/components/pages/SinglePaymentPage/PaymentForm";
function AddReportPage() {
const navigate = useNavigate();
const { user: userFromStore } = useAuth();
const api = useApi();
const tokenFromStore = useSelector(selectors.selectToken);
const [paymentIntent, setPaymentIntent] = useState<
ResponsePost | null
>(null);
const [paymentIntent, setPaymentIntent] = useState<ResponsePost | null>(null);
const [isLoading, setIsLoading] = useState(false);
const [isError, setIsError] = useState(false);
const [activeOffer, setActiveOffer] = useState(signUpOffers[0]);
@ -48,31 +44,36 @@ function AddReportPage() {
};
const handleClick = async () => {
if (!userFromStore || !activeOffer) return;
const currentProduct = getCurrentProduct(activeOffer?.productKey);
if (!currentProduct) return;
setIsLoading(true);
const { productId, key } = currentProduct;
const paymentInfo = {
productId,
key,
};
const paymentIntent = await createSinglePayment(
userFromStore,
paymentInfo,
tokenFromStore,
userFromStore.email,
userFromStore.profile.full_name,
userFromStore.profile.birthday,
returnUrl,
api
);
setPaymentIntent(paymentIntent);
setIsLoading(false);
if ("payment" in paymentIntent) {
if (paymentIntent.payment.status === "paid")
return navigate(routes.client.unlimitedReadings());
return setIsError(true);
try {
if (!userFromStore || !activeOffer) return;
const currentProduct = getCurrentProduct(activeOffer?.productKey);
if (!currentProduct) return;
setIsLoading(true);
const { _id, key } = currentProduct;
const paymentInfo = {
productId: _id,
key,
};
const paymentIntent = await createSinglePayment(
userFromStore,
paymentInfo,
tokenFromStore,
userFromStore.email,
userFromStore.profile.full_name,
userFromStore.profile.birthday,
returnUrl,
api
);
setPaymentIntent(paymentIntent);
if ("payment" in paymentIntent) {
if (paymentIntent.payment.status === "paid")
return navigate(routes.client.unlimitedReadings());
return setIsError(true);
}
} catch (error) {
setIsError(true);
} finally {
setIsLoading(false);
}
};

View File

@ -16,12 +16,10 @@ import { selectors } from "@/store";
import { useCallback, useState } from "react";
import { createSinglePayment } from "@/services/singlePayment";
import Loader, { LoaderColor } from "@/components/Loader";
import {
ResponsePost,
} from "@/api/resources/SinglePayment";
import { ResponsePost } from "@/api/resources/SinglePayment";
import Modal from "@/components/Modal";
import { getPriceCentsToDollars } from "@/services/price";
import PaymentForm from "@/components/pages/PaymentWithEmailPage/PaymentForm";
import PaymentForm from "@/components/pages/SinglePaymentPage/PaymentForm";
const sliderSettings = {
dots: false,
@ -40,9 +38,7 @@ function UnlimitedReadingsPage() {
const api = useApi();
const tokenFromStore = useSelector(selectors.selectToken);
const [isLoading, setIsLoading] = useState(false);
const [paymentIntent, setPaymentIntent] = useState<
ResponsePost | null
>(null);
const [paymentIntent, setPaymentIntent] = useState<ResponsePost | null>(null);
const [isError, setIsError] = useState(false);
const returnUrl = `${window.location.protocol}//${
window.location.host
@ -60,29 +56,34 @@ function UnlimitedReadingsPage() {
);
const handleClick = async () => {
if (!userFromStore || !currentProduct) return;
setIsLoading(true);
const { productId, key } = currentProduct;
const paymentInfo = {
productId,
key,
};
const paymentIntent = await createSinglePayment(
userFromStore,
paymentInfo,
tokenFromStore,
userFromStore.email,
userFromStore.profile.full_name,
userFromStore.profile.birthday,
returnUrl,
api
);
setPaymentIntent(paymentIntent);
setIsLoading(false);
if ("payment" in paymentIntent) {
if (paymentIntent.payment.status === "paid")
return navigate(routes.client.addConsultation());
return setIsError(true);
try {
if (!userFromStore || !currentProduct) return;
setIsLoading(true);
const { _id, key } = currentProduct;
const paymentInfo = {
productId: _id,
key,
};
const paymentIntent = await createSinglePayment(
userFromStore,
paymentInfo,
tokenFromStore,
userFromStore.email,
userFromStore.profile.full_name,
userFromStore.profile.birthday,
returnUrl,
api
);
setPaymentIntent(paymentIntent);
if ("payment" in paymentIntent) {
if (paymentIntent.payment.status === "paid")
return navigate(routes.client.addConsultation());
return setIsError(true);
}
} catch (error) {
setIsError(true);
} finally {
setIsLoading(false);
}
};
@ -102,7 +103,7 @@ function UnlimitedReadingsPage() {
onClose={() => setPaymentIntent(null)}
>
<Title variant="h1" className={styles["modal-title"]}>
{getPriceCentsToDollars(currentProduct?.amount || 0)}$
{getPriceCentsToDollars(currentProduct?.price || 0)}$
</Title>
<PaymentForm
stripePublicKey={paymentIntent.paymentIntent.data.public_key}

View File

@ -1,7 +1,13 @@
import Title from "@/components/Title";
import styles from "./styles.module.css";
function ComparePrices() {
function ComparePrices({
oldPrice,
newPrice,
}: {
oldPrice: string;
newPrice: string;
}) {
return (
<div className={styles.container}>
<div className={`${styles["old-price"]} ${styles["price-container"]}`}>
@ -11,7 +17,7 @@ function ComparePrices() {
</Title>
</div>
<div className={styles["main-container"]}>
<p className={styles.text}>up to $13.67</p>
<p className={styles.text}>{oldPrice}</p>
</div>
</div>
<div className={`${styles["new-price"]} ${styles["price-container"]}`}>
@ -22,7 +28,7 @@ function ComparePrices() {
</Title>
</div>
<div className={styles["main-container"]}>
<p className={styles.text}>$0</p>
<p className={styles.text}>${newPrice}</p>
</div>
</div>
</div>

View File

@ -1,13 +1,13 @@
import Title from "@/components/Title";
import styles from "./styles.module.css";
function SpecialOfferBanner() {
function SpecialOfferBanner({ title }: { title: string }) {
return (
<div className={styles.container}>
<img src="/wrapped-gift.webp" alt="Wrapped Gift" />
<div className="text-container">
<Title className={styles.title} variant="h3">
Special Offer!
{title}
</Title>
<p className={styles.text}>Everything for free. Trial include!</p>
</div>

View File

@ -15,11 +15,16 @@ import { selectors } from "@/store";
import { getZodiacSignByDate } from "@/services/zodiac-sign";
import { useNavigate } from "react-router-dom";
import routes from "@/routes";
import { usePaywall } from "@/hooks/paywall/usePaywall";
import { EPlacementKeys } from "@/api/resources/Paywall";
function MarketingLanding() {
const birthdate = useSelector(selectors.selectBirthdate);
const zodiacSign = getZodiacSignByDate(birthdate);
const navigate = useNavigate();
const { paywall, products, getText } = usePaywall({
placementKey: EPlacementKeys["aura.placement.email.marketing"],
});
const handleNext = () => {
navigate(routes.client.email("marketing-trial-payment"));
@ -27,7 +32,7 @@ function MarketingLanding() {
return (
<section className={`${styles.page} page`}>
<SpecialOfferBanner />
<SpecialOfferBanner title={paywall?.name || ""} />
<div className={styles.wrapper}>
<Title variant="h2" className={`${styles.title} ${styles["hi-title"]}`}>
Hey, {zodiacSign} Sun 👋
@ -66,7 +71,10 @@ function MarketingLanding() {
alt="Understanding"
style={{ minHeight: "323px" }}
/>
<ComparePrices />
<ComparePrices
oldPrice={getText("text.old.price", {}) as string}
newPrice={`${((products[0]?.trialPrice || 0) / 100).toFixed(2)}`}
/>
<PointsList
points={marketingLandingPointsList}
title="Your plan also includes:"

View File

@ -5,29 +5,22 @@ import MainButton from "@/components/MainButton";
import Modal from "@/components/Modal";
import PaymentModal from "../../TrialPayment/components/PaymentModal";
import { useEffect, useState } from "react";
import { ISubscriptionPlan } from "@/api/resources/SubscriptionPlans";
import { useApi } from "@/api";
import { useTranslation } from "react-i18next";
import { usePaywall } from "@/hooks/paywall/usePaywall";
import { EPlacementKeys } from "@/api/resources/Paywall";
import { useDispatch } from "react-redux";
import { actions } from "@/store";
function MarketingTrialPayment() {
const { i18n } = useTranslation();
const locale = i18n.language;
const api = useApi();
const dispatch = useDispatch();
const [isOpenPaymentModal, setIsOpenPaymentModal] = useState<boolean>(false);
const [freeTrialPlan, setFreeTrialPlan] = useState<
ISubscriptionPlan | undefined
>();
// get free trial plan
const { products } = usePaywall({
placementKey: EPlacementKeys["aura.placement.email.marketing"],
});
useEffect(() => {
(async () => {
const { sub_plans } = await api.getSubscriptionPlans({ locale });
const _freeTrialPlan = sub_plans.find(
(subPlan) => subPlan.trial?.is_free
);
setFreeTrialPlan(_freeTrialPlan);
})();
}, [api, locale]);
dispatch(actions.payment.update({ activeProduct: products[0] }));
}, [dispatch, products]);
const openStripeModal = () => {
setIsOpenPaymentModal(true);
@ -39,13 +32,17 @@ function MarketingTrialPayment() {
return (
<>
<Modal
containerClassName={styles.modal}
open={isOpenPaymentModal}
onClose={handleCloseModal}
>
<PaymentModal activeSubscriptionPlan={freeTrialPlan} />
</Modal>
{products[0] && (
<Modal
containerClassName={styles.modal}
open={isOpenPaymentModal}
onClose={handleCloseModal}
>
<PaymentModal
placementKey={EPlacementKeys["aura.placement.email.marketing"]}
/>
</Modal>
)}
<section className={`${styles.page} page`}>
<div className={styles.wrapper}>
<div className={styles.banner}>Special Offer</div>
@ -55,7 +52,7 @@ function MarketingTrialPayment() {
<p className={styles.description}>No pressure. Cancel anytime</p>
<div className={styles["total-today"]}>
<p className={styles.description}>Total today:</p>
<p className={styles.value}>$0</p>
<p className={styles.value}>${(products[0]?.trialPrice / 100).toFixed(2) || 0}</p>
</div>
<div className={styles.line} />
<div className={styles["code-container"]}>
@ -74,7 +71,7 @@ function MarketingTrialPayment() {
<p className={styles["sale-description"]}>Save $10 every period</p>
<div className={styles.line} />
<p className={styles["text-description"]}>
You will be charged only <b>$0 for your 7-day trial.</b>{" "}
You will be charged only <b>${(products[0]?.trialPrice / 100).toFixed(2) || 0} for your 7-day trial.</b>{" "}
Subscription <b>renews automatically</b> until cancelled. You{" "}
<b>can cancel at any time</b> before the end of the trial.
</p>

View File

@ -20,6 +20,11 @@ function GenderPage({ productKey }: IGenderPageProps): JSX.Element {
useEffect(() => {
const isShowTryApp = targetId === "i";
dispatch(actions.userConfig.addIsShowTryApp(isShowTryApp));
if (targetId && typeof window.ym === "function" && targetId !== "i") {
window.ym(95799066, "userParams", {
genderFrom: targetId,
});
}
}, [dispatch, targetId]);
const selectGender = (gender: Gender) => {

View File

@ -17,7 +17,13 @@ function GetInformationPartnerPage() {
return (
<section className={`${styles.page} page`}>
<video className={styles["background-video"]} loop autoPlay muted>
<video
className={styles["background-video"]}
loop={true}
autoPlay={true}
muted={true}
playsInline={true}
>
<source src="/videos/background-video-1.mp4" type="video/mp4" />
<source src="/videos/background-video-1.mp4" type="video/ogg" />
Your browser does not support the video tag.

View File

@ -4,6 +4,8 @@ import { useCallback, useEffect, useRef, useState } from "react";
import { onboardingTitles } from "@/data/onboarding";
import routes from "@/routes";
import { useNavigate } from "react-router-dom";
import { usePaywall } from "@/hooks/paywall/usePaywall";
import { EPlacementKeys } from "@/api/resources/Paywall";
function OnboardingPage() {
const navigate = useNavigate();
@ -11,6 +13,7 @@ function OnboardingPage() {
const [periodClassName, setPeriodClassName] = useState("");
const titleInterval = useRef<NodeJS.Timeout>();
const classNameTimeOut = useRef<NodeJS.Timeout>();
usePaywall({ placementKey: EPlacementKeys["aura.placement.main"] });
const handleNext = useCallback(() => {
navigate(routes.client.trialChoice());

View File

@ -1,248 +0,0 @@
import EmailInput from "@/components/EmailEnterPage/EmailInput";
import styles from "./styles.module.css";
import { useCallback, useEffect, useState } from "react";
import { useTranslation } from "react-i18next";
import { actions, selectors } from "@/store";
import { useDispatch, useSelector } from "react-redux";
import MainButton from "@/components/MainButton";
import Loader, { LoaderColor } from "@/components/Loader";
import { useAuth } from "@/auth";
import { ApiError, extractErrorMessage, useApi } from "@/api";
import { getClientTimezone } from "@/locales";
import ErrorText from "@/components/ErrorText";
import Title from "@/components/Title";
import NameInput from "@/components/EmailEnterPage/NameInput";
import { useParams } from "react-router-dom";
import routes from "@/routes";
import PaymentForm from "./PaymentForm";
import { getPriceCentsToDollars } from "@/services/price";
import { useSinglePayment } from "@/hooks/payment/useSinglePayment";
function PaymentWithEmailPage() {
const { productId } = useParams();
const { t, i18n } = useTranslation();
// const tokenFromStore = useSelector(selectors.selectToken);
const { signUp, user: userFromStore, token: tokenFromStore } = useAuth();
const api = useApi();
const timezone = getClientTimezone();
const dispatch = useDispatch();
const birthday = useSelector(selectors.selectBirthday);
const locale = i18n.language;
const [email, setEmail] = useState("");
const [name, setName] = useState("");
const [isValidEmail, setIsValidEmail] = useState(false);
const [isValidName, setIsValidName] = useState(productId !== "chat.aura");
const [isDisabled, setIsDisabled] = useState(true);
const [isAuth, setIsAuth] = useState(false);
const [apiError, setApiError] = useState<ApiError | null>(null);
const [error, setError] = useState<boolean>(false);
const returnUrl = `${window.location.protocol}//${
window.location.host
}${routes.client.paymentResult()}`;
const [isLoadingAuth, setIsLoadingAuth] = useState<boolean>(false);
const {
product,
paymentIntent,
createSinglePayment,
isLoading: isLoadingSinglePayment,
error: errorSinglePayment,
} = useSinglePayment();
useEffect(() => {
if (
isValidName &&
isValidEmail &&
!(error || apiError || errorSinglePayment?.error)
) {
setIsDisabled(false);
} else {
setIsDisabled(true);
}
}, [
isValidEmail,
email,
isValidName,
name,
error,
apiError,
errorSinglePayment?.error,
]);
const handleValidEmail = (email: string) => {
dispatch(actions.form.addEmail(email));
setEmail(email);
setIsValidEmail(true);
};
const handleValidName = (name: string) => {
setName(name);
setIsValidName(true);
};
const authorization = async () => {
try {
setIsLoadingAuth(true);
const auth = await api.auth({ email, timezone, locale });
const {
auth: { token, user },
} = auth;
signUp(token, user);
const payload = {
user: {
profile_attributes: {
birthday,
full_name: name,
},
},
token,
};
const updatedUser = await api.updateUser(payload).catch((error) => {
console.log("Error: ", error);
});
if (updatedUser?.user) {
dispatch(actions.user.update(updatedUser.user));
}
if (name) {
dispatch(
actions.user.update({
username: name,
})
);
}
dispatch(actions.status.update("registred"));
setIsAuth(true);
const userUpdated = await api.getUser({ token });
setIsLoadingAuth(false);
return { user: userUpdated?.user, token };
} catch (error) {
console.error(error);
if (error instanceof ApiError) {
setApiError(error as ApiError);
} else {
setError(true);
}
setIsLoadingAuth(false);
}
};
const handleClick = async () => {
const authData = await authorization();
if (!authData) {
return;
}
const { user, token } = authData;
if (typeof window.ym === "function")
window.ym(95799066, "reachGoal", "EnteredEmail");
await createSinglePayment({
user,
token,
targetProductKey: productId || "",
returnUrl,
});
};
const handleAuthUser = useCallback(async () => {
if (!tokenFromStore.length || !userFromStore) {
return;
}
await createSinglePayment({
user: userFromStore,
token: tokenFromStore,
targetProductKey: productId || "",
returnUrl,
});
}, [
createSinglePayment,
productId,
returnUrl,
tokenFromStore,
userFromStore,
]);
useEffect(() => {
handleAuthUser();
// eslint-disable-next-line react-hooks/exhaustive-deps
}, []);
return (
<div className={`${styles.page} page`}>
{(isLoadingSinglePayment || isLoadingSinglePayment) && (
<Loader color={LoaderColor.Black} />
)}
{!isLoadingSinglePayment &&
!isLoadingAuth &&
paymentIntent &&
"paymentIntent" in paymentIntent &&
!!tokenFromStore.length && (
<>
<Title variant="h1" className={styles.title}>
{getPriceCentsToDollars(product?.amount || 0)}$
</Title>
<PaymentForm
stripePublicKey={paymentIntent.paymentIntent.data.public_key}
clientSecret={paymentIntent.paymentIntent.data.client_secret}
returnUrl={`${returnUrl}?redirect_type=${product?.key}`}
/>
</>
)}
{(!tokenFromStore || !paymentIntent) &&
// || (productId !== "chat.aura" && !name.length)
!isLoadingSinglePayment &&
!isLoadingAuth && (
<>
<NameInput
value={name}
placeholder="Your name"
onValid={handleValidName}
onInvalid={() => setIsValidName(productId !== "chat.aura")}
/>
<EmailInput
name="email"
value={email}
placeholder={t("your_email")}
onValid={handleValidEmail}
onInvalid={() => setIsValidEmail(false)}
/>
<MainButton
className={styles.button}
onClick={handleClick}
disabled={isDisabled}
>
{isLoadingSinglePayment && <Loader color={LoaderColor.White} />}
{!isLoadingSinglePayment &&
!(!apiError && !error && !isLoadingSinglePayment && isAuth) &&
t("_continue")}
{!apiError && !error && !isLoadingSinglePayment && isAuth && (
<img
className={styles["success-icon"]}
src="/SuccessIcon.png"
alt="Success Icon"
/>
)}
</MainButton>
</>
)}
{(error || apiError || errorSinglePayment?.error) && (
<Title variant="h3" style={{ color: "red", margin: 0 }}>
Something went wrong:{" "}
{errorSinglePayment?.error?.length && errorSinglePayment?.error}
</Title>
)}
{apiError && (
<ErrorText
size="medium"
isShown={Boolean(apiError)}
message={apiError ? extractErrorMessage(apiError) : null}
/>
)}
</div>
);
}
export default PaymentWithEmailPage;

View File

@ -1,61 +0,0 @@
.page {
/* position: relative; */
position: static;
height: fit-content;
min-height: calc(100dvh - 103px);
/* max-height: -webkit-fill-available; */
display: flex;
justify-items: center;
justify-content: center;
align-items: center;
/* gap: 16px; */
}
.button {
border-radius: 12px;
margin-top: 0;
box-shadow: rgba(0, 0, 0, 0.25) 0px 4px 4px 0px;
height: 50px;
min-height: 0;
background: linear-gradient(
165.54deg,
rgb(20, 19, 51) -33.39%,
rgb(32, 34, 97) 15.89%,
rgb(84, 60, 151) 55.84%,
rgb(105, 57, 162) 74.96%
);
font-size: 18px;
line-height: 21px;
}
.payment-loader {
display: flex;
justify-content: center;
align-items: center;
}
.cross {
position: absolute;
top: -36px;
right: 28px;
width: 22px;
height: 22px;
cursor: pointer;
z-index: 9;
}
.title {
font-size: 27px;
font-weight: 700;
margin: 0;
}
.email {
font-size: 17px;
font-weight: 500;
margin: 0;
}
.success-icon {
height: 100%;
}

View File

@ -1,6 +1,6 @@
import { Elements } from "@stripe/react-stripe-js";
import styles from "./styles.module.css";
import CheckoutForm from "@/components/PaymentPage/methods/Stripe/CheckoutForm";
import CheckoutForm from "@/components/PaymentPage/methods/CheckoutForm";
import { useEffect, useState } from "react";
import { Stripe, loadStripe } from "@stripe/stripe-js";
import SecurityPayments from "../../TrialPayment/components/SecurityPayments";
@ -9,9 +9,15 @@ interface IPaymentFormProps {
stripePublicKey: string;
clientSecret: string;
returnUrl: string;
confirmType?: "payment" | "setup";
}
function PaymentForm({ stripePublicKey, clientSecret, returnUrl }: IPaymentFormProps) {
function PaymentForm({
stripePublicKey,
clientSecret,
returnUrl,
confirmType = "payment",
}: IPaymentFormProps) {
const [stripePromise, setStripePromise] =
useState<Promise<Stripe | null> | null>(null);
@ -23,7 +29,7 @@ function PaymentForm({ stripePublicKey, clientSecret, returnUrl }: IPaymentFormP
<div className={styles["payment-method-container"]}>
{stripePromise && clientSecret && (
<Elements stripe={stripePromise} options={{ clientSecret }}>
<CheckoutForm returnUrl={returnUrl} />
<CheckoutForm confirmType={confirmType} returnUrl={returnUrl} />
</Elements>
)}
</div>

View File

@ -1,6 +1,6 @@
import Title from "@/components/Title";
import styles from "./styles.module.css";
import PaymentForm from "../PaymentWithEmailPage/PaymentForm";
import PaymentForm from "./PaymentForm";
import { getPriceCentsToDollars } from "@/services/price";
import { useSinglePayment } from "@/hooks/payment/useSinglePayment";
import routes from "@/routes";
@ -59,7 +59,7 @@ function SinglePaymentPage({ productId, isForce = false }: ISinglePaymentPage) {
!!tokenFromStore.length && (
<>
<Title variant="h1" className={styles.title}>
{getPriceCentsToDollars(product?.amount || 0)}$
{getPriceCentsToDollars(product?.price || 0)}$
</Title>
<PaymentForm
stripePublicKey={paymentIntent.paymentIntent.data.public_key}

View File

@ -1,73 +1,36 @@
import PriceList from "@/components/PriceList";
import styles from "./styles.module.css";
import { useEffect, useMemo, useState } from "react";
import { ISubscriptionPlan } from "@/api/resources/SubscriptionPlans";
import { useTranslation } from "react-i18next";
import { useApi } from "@/api";
import { useEffect, useState } from "react";
import { useDispatch, useSelector } from "react-redux";
import { actions, selectors } from "@/store";
import { useNavigate } from "react-router-dom";
import routes from "@/routes";
import EmailsList from "@/components/EmailsList";
import MainButton from "@/components/MainButton";
interface IPlanKey {
[key: string]: number;
}
import { usePaywall } from "@/hooks/paywall/usePaywall";
import { EPlacementKeys } from "@/api/resources/Paywall";
import { getRandomArbitrary } from "@/services/random-value";
function TrialChoicePage() {
const { i18n } = useTranslation();
const locale = i18n.language;
const api = useApi();
const dispatch = useDispatch();
const navigate = useNavigate();
const selectedPrice = useSelector(selectors.selectSelectedPrice);
const homeConfig = useSelector(selectors.selectHome);
const email = useSelector(selectors.selectEmail);
const [subPlans, setSubPlans] = useState<ISubscriptionPlan[]>([]);
const [isDisabled, setIsDisabled] = useState(true);
const allowedPlans = useMemo(() => [""], []);
const [countUsers, setCountUsers] = useState(752);
useEffect(() => {
(async () => {
const { sub_plans } = await api.getSubscriptionPlans({ locale });
const plansWithoutTest = sub_plans.filter(
(plan: ISubscriptionPlan) => !plan.name.includes("(test)")
);
const plansKeys: IPlanKey = {};
const plans: ISubscriptionPlan[] = [];
for (const plan of plansWithoutTest) {
plansKeys[plan.name] = plansKeys[plan.name]
? plansKeys[plan.name] + 1
: 1;
if (
(plansKeys[plan.name] > 1 && !plan.trial?.is_free && !!plan.trial) ||
allowedPlans.includes(plan.id)
) {
const targetPlan = plansWithoutTest.find(
(item) => item.name === plan.name && item.id.includes("stripe")
);
plans.push(targetPlan as ISubscriptionPlan);
}
}
const randomDelay = getRandomArbitrary(3000, 5000);
const countUsersTimeOut = setTimeout(() => {
setCountUsers((prevState) => prevState + 1);
}, randomDelay);
return () => clearTimeout(countUsersTimeOut);
}, [countUsers]);
plans.sort((a, b) => {
if (!a.trial || !b.trial) {
return 0;
}
if (a.trial?.price_cents < b.trial?.price_cents) {
return -1;
}
if (a.trial?.price_cents > b.trial?.price_cents) {
return 1;
}
return 0;
});
setSubPlans(plans);
})();
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [api, locale]);
const { products, getText } = usePaywall({
placementKey: EPlacementKeys["aura.placement.main"],
});
const handlePriceItem = () => {
setIsDisabled(false);
@ -85,38 +48,49 @@ function TrialChoicePage() {
return (
<section className={`${styles.page} page`}>
<p className={styles.text}>
We've helped millions of people to have happier lives and better
relationships, and we want to help you too.
{getText("text.0", {
replacementSelector: "b",
color: "#1C38EA",
})}
</p>
<p className={`${styles.text} ${styles.bold}`}>
Money shouldnt stand in the way of finding astrology guidance that
finally works. So, choose an amount that you think is reasonable to try
us out for one week.
{getText("text.1", {
color: "#1C38EA",
})}
</p>
<p className={`${styles.text} ${styles.bold} ${styles.purple}`}>
It costs us $13.67 to offer a 3-day trial, but please choose the amount
you are comfortable with.
{getText("text.2", {
color: "#1C38EA",
})}
</p>
<div className={styles["price-container"]}>
<PriceList
subPlans={subPlans}
products={products}
activeItem={selectedPrice}
classNameItem={styles["price-item"]}
classNameItemActive={styles["price-item-active"]}
click={handlePriceItem}
/>
<p className={styles["auxiliary-text"]} style={{ maxWidth: "75%" }}>
This option will help us support those who need to select the lowest
trial prices!
{getText("text.3", {
color: "#1C38EA",
})}
</p>
<img
className={styles["arrow-image"]}
src="/arrow.svg"
alt={`Arrow to $${subPlans.at(-1)}`}
alt={`Arrow to $${products.at(-1)?.name}`}
/>
</div>
<div className={styles["emails-list-container"]}>
<EmailsList
title={getText("text.5", {
replacementSelector: "strong",
replacement: {
target: "${quantity}",
replacement: countUsers.toString(),
},
})}
classNameContainer={styles["emails-container"]}
classNameTitle={styles["emails-title"]}
classNameEmailItem={styles["email-item"]}
@ -129,10 +103,14 @@ function TrialChoicePage() {
disabled={isDisabled}
onClick={handleNext}
>
See my plan
{getText("text.button.1", {
color: "#1C38EA",
})}
</MainButton>
<p className={styles["auxiliary-text"]}>
*Cost of trial as of February 2024
{getText("text.4", {
color: "#1C38EA",
})}
</p>
</section>
);

View File

@ -4,48 +4,62 @@ import PaymentMethodsChoice from "../PaymentMethodsChoice";
import { useEffect, useMemo, useState } from "react";
import { EPaymentMethod, paymentMethods } from "@/data/paymentMethods";
import { Elements } from "@stripe/react-stripe-js";
import ApplePayButton from "@/components/StripePage/ApplePayButton";
import CheckoutForm from "@/components/PaymentPage/methods/Stripe/CheckoutForm";
import ApplePayButton from "@/components/PaymentPage/methods/ApplePayButton";
import CheckoutForm from "@/components/PaymentPage/methods/CheckoutForm";
import { Stripe, loadStripe } from "@stripe/stripe-js";
import { useSelector } from "react-redux";
import { selectors } from "@/store";
import { ISubscriptionPlan } from "@/api/resources/SubscriptionPlans";
import { useApi } from "@/api";
import { useNavigate } from "react-router-dom";
import routes from "@/routes";
import { useTranslation } from "react-i18next";
import { useAuth } from "@/auth";
import Loader from "@/components/Loader";
import { getPriceFromTrial } from "@/services/price";
import SecurityPayments from "../SecurityPayments";
import { EPlacementKeys, IPaywallProduct } from "@/api/resources/Paywall";
import { usePaywall } from "@/hooks/paywall/usePaywall";
import { useMakePayment } from "@/hooks/payment/useMakePayment";
interface IPaymentModalProps {
activeSubscriptionPlan?: ISubscriptionPlan;
activeProduct?: IPaywallProduct;
noTrial?: boolean;
returnUrl?: string;
placementKey?: EPlacementKeys;
}
const getPrice = (product: IPaywallProduct | null) => {
if (!product) {
return 0;
}
return (product.trialPrice === 100 ? 99 : product.trialPrice || 0) / 100;
};
function PaymentModal({
activeSubscriptionPlan,
activeProduct,
noTrial,
returnUrl,
placementKey = EPlacementKeys["aura.placement.main"],
}: IPaymentModalProps) {
const { i18n } = useTranslation();
const locale = i18n.language;
const api = useApi();
const { token } = useAuth();
const navigate = useNavigate();
const activeSubPlanFromStore = useSelector(selectors.selectActiveSubPlan);
const activeSubPlan = activeSubscriptionPlan
? activeSubscriptionPlan
: activeSubPlanFromStore;
const [stripePromise, setStripePromise] =
useState<Promise<Stripe | null> | null>(null);
const [clientSecret, setClientSecret] = useState<string>("");
const [subscriptionReceiptId, setSubscriptionReceiptId] =
useState<string>("");
const [isLoading, setIsLoading] = useState(true);
const [isError, setIsError] = useState<boolean>(false);
const { products } = usePaywall({
placementKey,
});
const activeProductFromStore = useSelector(selectors.selectActiveProduct);
const _activeProduct = activeProduct ? activeProduct : activeProductFromStore;
const {
paymentIntentId,
clientSecret,
returnUrl: checkoutUrl,
paymentType,
publicKey,
isLoading,
error,
} = useMakePayment({
productId: _activeProduct?._id || "",
returnPaidUrl: returnUrl,
});
if (checkoutUrl?.length) {
window.location.href = checkoutUrl;
}
const paymentMethodsButtons = useMemo(() => {
// return paymentMethods.filter(
@ -64,43 +78,10 @@ function PaymentModal({
useEffect(() => {
(async () => {
const siteConfig = await api.getAppConfig({ bundleId: "auraweb" });
setStripePromise(loadStripe(siteConfig.data.stripe_public_key));
const { sub_plans } = await api.getSubscriptionPlans({ locale });
const isActiveSubPlan = sub_plans.find(
(subPlan) => subPlan.id === activeSubPlan?.id
);
if (!activeSubPlan || !isActiveSubPlan) {
navigate(routes.client.priceList());
}
if (!products?.length || !publicKey) return;
setStripePromise(loadStripe(publicKey));
})();
}, [activeSubPlan, api, locale, navigate]);
useEffect(() => {
(async () => {
try {
const { subscription_receipt } = await api.createSubscriptionReceipt({
token,
way: "stripe",
subscription_receipt: {
sub_plan_id: activeSubPlan?.id || "stripe.7",
},
});
const { id } = subscription_receipt;
const { client_secret } = subscription_receipt.data;
const { checkout_url } = subscription_receipt.data;
if (checkout_url?.length) {
window.location.href = checkout_url;
}
setSubscriptionReceiptId(id);
setClientSecret(client_secret);
setIsLoading(false);
} catch (error) {
console.error(error);
setIsError(true);
}
})();
}, [activeSubPlan?.id, api, token]);
}, [products, publicKey]);
if (isLoading) {
return (
@ -112,7 +93,7 @@ function PaymentModal({
);
}
if (isError) {
if (error?.length) {
return (
<div className={styles["payment-modal"]}>
<Title variant="h3" className={styles.title}>
@ -132,16 +113,13 @@ function PaymentModal({
selectedPaymentMethod={selectedPaymentMethod}
onSelectPaymentMethod={onSelectPaymentMethod}
/>
{activeSubPlan && (
{_activeProduct && (
<div>
{!noTrial && (
<>
<p className={styles["sub-plan-description"]}>
You will be charged only{" "}
<b>
${getPriceFromTrial(activeSubPlan?.trial)} for your 3-day
trial.
</b>
<b>${getPrice(_activeProduct)} for your 3-day trial.</b>
</p>
<p className={styles["sub-plan-description"]}>
We`ll <b>email you a reminder</b> before your trial period ends.
@ -160,16 +138,17 @@ function PaymentModal({
{selectedPaymentMethod === EPaymentMethod.PAYMENT_BUTTONS && (
<div className={styles["payment-method"]}>
<ApplePayButton
activeSubPlan={activeSubPlan}
activeProduct={_activeProduct}
client_secret={clientSecret}
subscriptionReceiptId={subscriptionReceiptId}
subscriptionReceiptId={paymentIntentId}
/>
</div>
)}
{selectedPaymentMethod === EPaymentMethod.CREDIT_CARD && (
<CheckoutForm
subscriptionReceiptId={subscriptionReceiptId}
confirmType={paymentType}
subscriptionReceiptId={paymentIntentId}
returnUrl={returnUrl}
/>
)}

View File

@ -1,18 +1,21 @@
import Title from "@/components/Title";
import styles from "./styles.module.css";
import { getPriceFromTrial } from "@/services/price";
import { ISubscriptionPlan } from "@/api/resources/SubscriptionPlans";
import CustomButton from "../CustomButton";
import GuardPayments from "../GuardPayments";
import { useState } from "react";
import FullScreenModal from "@/components/FullScreenModal";
import { IPaywallProduct } from "@/api/resources/Paywall";
interface IPaymentTableProps {
subPlan: ISubscriptionPlan;
product: IPaywallProduct;
buttonClick: () => void;
}
function PaymentTable({ subPlan, buttonClick }: IPaymentTableProps) {
const getPrice = (product: IPaywallProduct) => {
return (product.trialPrice || 0) / 100;
};
function PaymentTable({ product, buttonClick }: IPaymentTableProps) {
const [isOpenPrivacyModal, setIsOpenPrivacyModal] = useState<boolean>(false);
const handleSubscriptionPolicyClick = (event: React.MouseEvent) => {
event.preventDefault();
@ -44,20 +47,18 @@ function PaymentTable({ subPlan, buttonClick }: IPaymentTableProps) {
<div className={styles["table-container"]}>
<Title variant="h3" className={styles.title}>
Personalized reading for{" "}
<span className={styles.purple}>
${getPriceFromTrial(subPlan?.trial)}
</span>
<span className={styles.purple}>${getPrice(product)}</span>
</Title>
<div className={styles["table-element"]}>
<p>Total today:</p>
<span>${getPriceFromTrial(subPlan?.trial)}</span>
<span>${getPrice(product)}</span>
</div>
<hr />
<div className={styles["table-element"]}>
<p>Your cost per 2 weeks after trial</p>
<div>
<span className={styles.discount}>$65</span>
<span>${subPlan.price_cents / 100}</span>
<span>${product.trialPrice / 100}</span>
</div>
</div>
</div>
@ -69,9 +70,9 @@ function PaymentTable({ subPlan, buttonClick }: IPaymentTableProps) {
<p className={styles.policy}>
You are enrolling in 2 weeks subscription. By continuing you agree that
if you don't cancel prior to the end of the 3-day trial for the $
{getPriceFromTrial(subPlan?.trial)} you will automatically be charged
$19 every 2 weeks until you cancel in settings. Learn more about
cancellation and refund policy in{" "}
{getPrice(product)} you will automatically be charged $19 every 2 weeks
until you cancel in settings. Learn more about cancellation and refund
policy in{" "}
<a onClick={handleSubscriptionPolicyClick}>Subscription policy</a>
</p>
</>

View File

@ -13,22 +13,17 @@ import YourReading from "./components/YourReading";
import Reviews from "./components/Reviews";
import PointsList from "./components/PointsList";
import OftenAsk from "./components/OftenAsk";
import { ISubscriptionPlan } from "@/api/resources/SubscriptionPlans";
import { useEffect, useState } from "react";
import { useApi } from "@/api";
import { getClientLocale } from "@/locales";
import { Locale } from "@/components/PaymentTable";
import WithPartnerInformation from "./components/WithPartnerInformation";
import Modal from "@/components/Modal";
import PaymentModal from "./components/PaymentModal";
import { trialPaymentPointsList } from "@/data/pointsLists";
import { trialPaymentReviews } from "@/data/reviews";
const locale = getClientLocale() as Locale;
import { usePaywall } from "@/hooks/paywall/usePaywall";
import { EPlacementKeys, IPaywallProduct } from "@/api/resources/Paywall";
function TrialPaymentPage() {
const dispatch = useDispatch();
const api = useApi();
const navigate = useNavigate();
const birthdate = useSelector(selectors.selectBirthdate);
const zodiacSign = getZodiacSignByDate(birthdate);
@ -42,55 +37,46 @@ function TrialPaymentPage() {
flowChoice,
} = useSelector(selectors.selectQuestionnaire);
const partnerZodiacSign = getZodiacSignByDate(partnerBirthdate);
const [subPlans, setSubPlans] = useState<ISubscriptionPlan[]>([]);
const activeSubPlanFromStore = useSelector(selectors.selectActiveSubPlan);
const [activeSubPlan, setActiveSubPlan] = useState<ISubscriptionPlan | null>(
activeSubPlanFromStore
);
const [isOpenPaymentModal, setIsOpenPaymentModal] = useState<boolean>(false);
const [marginTopTitle, setMarginTopTitle] = useState<number>(360);
const [singleOrWithPartner, setSingleOrWithPartner] = useState<
"single" | "partner"
>("single");
const { subPlan } = useParams();
useEffect(() => {
(async () => {
const { sub_plans } = await api.getSubscriptionPlans({ locale });
const plans = sub_plans
.filter((plan: ISubscriptionPlan) => plan.provider === "stripe")
.sort((a, b) => {
if (!a.trial || !b.trial) {
return 0;
}
if (a?.trial?.price_cents < b?.trial?.price_cents) {
return -1;
}
if (a?.trial?.price_cents > b?.trial?.price_cents) {
return 1;
}
return 0;
});
setSubPlans(plans);
})();
}, [api]);
const { products } = usePaywall({
placementKey: EPlacementKeys["aura.placement.main"],
});
const activeProductFromStore = useSelector(selectors.selectActiveProduct);
const [activeProduct, setActiveProduct] = useState<IPaywallProduct | null>(
activeProductFromStore
);
useEffect(() => {
if (subPlan) {
const targetSubPlan = subPlans.find(
(sub_plan) =>
const targetProduct = products.find(
(product) =>
String(
sub_plan?.trial?.price_cents
? Math.floor((sub_plan?.trial?.price_cents + 1) / 100)
: sub_plan.id.replace(".", "")
product?.trialPrice
? Math.floor((product?.trialPrice + 1) / 100)
: product.key.replace(".", "")
) === subPlan
);
if (targetSubPlan) {
setActiveSubPlan(targetSubPlan);
dispatch(actions.payment.update({ activeSubPlan: targetSubPlan }));
if (targetProduct) {
setActiveProduct(targetProduct);
dispatch(actions.payment.update({ activeProduct }));
}
}
}, [dispatch, subPlan, subPlans]);
}, [dispatch, subPlan, products, activeProduct]);
useEffect(() => {
if (!products.length) return;
const isActiveProduct = products.find(
(product) => product._id === activeProduct?._id
);
if (!activeProduct || !isActiveProduct) {
navigate(routes.client.trialChoice());
}
}, [activeProduct, navigate, products]);
useEffect(() => {
if (["relationship", "married"].includes(flowChoice)) {
@ -102,7 +88,7 @@ function TrialPaymentPage() {
setMarginTopTitle(340);
}, [flowChoice]);
if (!activeSubPlan) {
if (!activeProduct) {
return <Navigate to={routes.client.trialChoice()} />;
}
@ -157,7 +143,7 @@ function TrialPaymentPage() {
Your Personalized Clarity & Love Reading is ready!
</Title>
<Goal goal={goal} />
<PaymentTable subPlan={activeSubPlan} buttonClick={openStripeModal} />
<PaymentTable product={activeProduct} buttonClick={openStripeModal} />
<YourReading
gender={gender}
zodiacSign={zodiacSign}
@ -174,7 +160,7 @@ function TrialPaymentPage() {
<Reviews reviews={trialPaymentReviews} />
<PointsList title="What you get" points={trialPaymentPointsList} />
<OftenAsk />
<PaymentTable subPlan={activeSubPlan} buttonClick={openStripeModal} />
<PaymentTable product={activeProduct} buttonClick={openStripeModal} />
</section>
);
}

Some files were not shown because too many files have changed in this diff Show More