A fully open source & end-to-end encrypted note taking alternative to Evernote.
TypeScript asp-net-coredotnet-coreelectronfosshacktoberfestnote-managmentnote-takingnote-taking-appnotebooknotesnotes-appopen-sourceopensourceprivacyproductivityreactreact-nativereactjsself-hosted
web: add quick checkout (#6811)
Abdullah Atta9e9ef157375d
diff --git a/apps/web/src/bootstrap.tsx b/apps/web/src/bootstrap.tsxindex 8e99c2d02..c930b1735 100644--- a/apps/web/src/bootstrap.tsx+++ b/apps/web/src/bootstrap.tsx@@ -50,6 +50,10 @@ export type Routes = keyof typeof routes;// | "default";const routes = {+ "/checkout": {+ component: () => import("./views/checkout"),+ props: {}+ },"/account/recovery": {component: () => import("./views/recovery"),props: { route: "methods" }diff --git a/apps/web/src/components/icons/index.tsx b/apps/web/src/components/icons/index.tsxindex 0656d844f..11afa98bd 100644--- a/apps/web/src/components/icons/index.tsx+++ b/apps/web/src/components/icons/index.tsx@@ -216,7 +216,9 @@ import {mdiFileMusicOutline,mdiBroom,mdiServerSecurity,- mdiOpenInNew+ mdiOpenInNew,+ mdiTagOutline,+ mdiChatQuestionOutline} from "@mdi/js";import { useTheme } from "@emotion/react";import { Theme } from "@notesnook/theme";@@ -554,3 +556,5 @@ export const WindowRestore = createIcon(export const WindowClose = createIcon(mdiWindowClose);export const ClearCache = createIcon(mdiBroom);export const OpenInNew = createIcon(mdiOpenInNew);+export const Coupon = createIcon(mdiTagOutline);+export const Support = createIcon(mdiChatQuestionOutline);diff --git a/apps/web/src/dialogs/buy-dialog/buy-dialog.tsx b/apps/web/src/dialogs/buy-dialog/buy-dialog.tsxindex 376a9223e..4473352bc 100644--- a/apps/web/src/dialogs/buy-dialog/buy-dialog.tsx+++ b/apps/web/src/dialogs/buy-dialog/buy-dialog.tsx@@ -18,11 +18,10 @@ along with this program. If not, see <http://www.gnu.org/licenses/>.*/import { useCallback, useEffect, useRef, useState } from "react";-import { Text, Flex, Button, Link } from "@theme-ui/components";+import { Text, Flex, Button, Link, Box } from "@theme-ui/components";import { Cross, Check, Loading } from "../../components/icons";import { useStore as useUserStore } from "../../stores/user-store";import { useStore as useThemeStore } from "../../stores/theme-store";-import { useTheme } from "@emotion/react";import Rocket from "../../assets/rocket.svg?react";import WorkAnywhere from "../../assets/workanywhere.svg?react";import WorkLate from "../../assets/worklate.svg?react";@@ -38,7 +37,6 @@ import { TaskManager } from "../../common/task-manager";import { db } from "../../common/db";import { useCheckoutStore } from "./store";import { getCurrencySymbol } from "./helpers";-import { Theme } from "@notesnook/theme";import { isMacStoreApp } from "../../utils/platform";import { isUserSubscribed } from "../../hooks/use-is-user-premium";import { SUBSCRIPTION_STATUS } from "../../common/constants";@@ -57,10 +55,10 @@ export const BuyDialog = DialogManager.register(function BuyDialog(props: BuyDialogProps) {const { onClose, couponCode, plan } = props;- const theme = useTheme() as Theme;const onApplyCoupon = useCheckoutStore((store) => store.applyCoupon);const isCheckoutCompleted = useCheckoutStore((store) => store.isCompleted);+ const user = useUserStore((store) => store.user);useEffect(() => {return () => {@@ -110,9 +108,13 @@ export const BuyDialog = DialogManager.register(function BuyDialog(py: 50}}>- <SideBar onClose={() => onClose(false)} initialPlan={plan} />+ <CheckoutSideBar+ onClose={() => onClose(false)}+ initialPlan={plan}+ user={user}+ /></ScopedThemeProvider>- <Details />+ <CheckoutDetails user={user} /></Flex></BaseDialog>);@@ -121,14 +123,14 @@ export const BuyDialog = DialogManager.register(function BuyDialog(type SideBarProps = {initialPlan?: Period;onClose: () => void;+ user?: User;};-function SideBar(props: SideBarProps) {- const { initialPlan, onClose } = props;+export function CheckoutSideBar(props: SideBarProps) {+ const { initialPlan, onClose, user } = props;const [showPlans, setShowPlans] = useState(false);const onPlanSelected = useCheckoutStore((state) => state.selectPlan);const selectedPlan = useCheckoutStore((state) => state.selectedPlan);const pricingInfo = useCheckoutStore((state) => state.pricingInfo);- const user = useUserStore((store) => store.user);const couponCode = useCheckoutStore((store) => store.couponCode);const onApplyCoupon = useCheckoutStore((store) => store.applyCoupon);const isCheckoutCompleted = useCheckoutStore((store) => store.isCompleted);@@ -150,7 +152,12 @@ function SideBar(props: SideBarProps) {if (user && !showPlans && isUserSubscribed(user)) {return (- <AlreadyPremium user={user} onShowPlans={() => setShowPlans(true)} />+ <AlreadyPremium+ isCanceled={+ user?.subscription?.type === SUBSCRIPTION_STATUS.PREMIUM_CANCELED+ }+ onShowPlans={() => setShowPlans(true)}+ />);}@@ -194,8 +201,11 @@ function SideBar(props: SideBarProps) {);}-function Details() {- const user = useUserStore((store) => store.user);+export function CheckoutDetails({+ user+}: {+ user?: { id: string; email: string };+}) {const selectedPlan = useCheckoutStore((state) => state.selectedPlan);const onPriceUpdated = useCheckoutStore((state) => state.updatePrice);const completeCheckout = useCheckoutStore((state) => state.completeCheckout);@@ -205,7 +215,6 @@ function Details() {(store) => store.setIsApplyingCoupon);const theme = useThemeStore((store) => store.colorScheme);-if (isCheckoutCompleted) return null;if (selectedPlan && user)@@ -329,15 +338,11 @@ function TrialOrUpgrade(props: TrialOrUpgradeProps) {}type AlreadyPremiumProps = {- user: User | undefined;+ isCanceled?: boolean;onShowPlans: () => void;};function AlreadyPremium(props: AlreadyPremiumProps) {- const { user, onShowPlans } = props;-- const isCanceled =- user?.subscription?.type === SUBSCRIPTION_STATUS.PREMIUM_CANCELED;-+ const { isCanceled, onShowPlans } = props;return (<><Rocket style={{ flexShrink: 0, width: 200, height: 200 }} />@@ -369,17 +374,20 @@ function AlreadyPremium(props: AlreadyPremiumProps) {);}-function CheckoutCompleted(props: { onClose: () => void }) {- const { onClose } = props;+export function CheckoutCompleted(props: {+ onClose: () => void;+ buttonText?: string;+}) {+ const { onClose, buttonText } = props;return (<><Rocket style={{ flexShrink: 0, width: 200, height: 200 }} /><Text variant="heading" mt={4} sx={{ textAlign: "center" }}>- Thank you!+ You are awesome!</Text><Text variant="body" mt={1} sx={{ textAlign: "center" }}>- You have successfully subscribed to Notesnook Pro.+ Thank you for supporting privacy! Your subscription is now active.</Text><Buttonvariant="accent"@@ -388,7 +396,7 @@ function CheckoutCompleted(props: { onClose: () => void }) {onClick={onClose}data-test-id="see-all-plans">- Continue+ {buttonText || "Continue"}</Button></>);@@ -527,7 +535,7 @@ function SelectedPlan(props: SelectedPlanProps) {type CheckoutPricingProps = {pricingInfo: PricingInfo;};-function CheckoutPricing(props: CheckoutPricingProps) {+export function CheckoutPricing(props: CheckoutPricingProps) {const { pricingInfo } = props;const { currency, price, discount, period, recurringPrice } = pricingInfo;const fields = [@@ -577,40 +585,44 @@ function CheckoutPricing(props: CheckoutPricingProps) {><Textvariant="body"- sx={{ fontSize: "subtitle" }}data-test-id={`label`}+ sx={{ fontWeight: "bold" }}>{field.label}</Text><Textdata-test-id={`value`}variant="body"- sx={{ fontSize: "subtitle", color: field.color || "paragraph" }}+ sx={{ color: field.color || "paragraph" }}>{field.value}</Text></Flex>))}+ <Box sx={{ my: 2, height: 1, bg: "separator" }} /><Flexmt={1}sx={{ justifyContent: "space-between", alignSelf: "stretch" }}data-test-id={`checkout-price-item`}>- <Text- variant="body"- sx={{ fontSize: "heading" }}- data-test-id={`label`}- >+ <Text variant="title" data-test-id={`label`}>Total</Text>- <Text as="div" variant="body" sx={{ textAlign: "end" }}>+ <Text as="div" variant="title" sx={{ textAlign: "end" }}><Textdata-test-id={`value`}- sx={{ fontSize: "heading", color: "paragraph" }}+ sx={{ fontSize: "title", color: "paragraph" }}>{currentTotal}</Text>- <Text as="div" sx={{ fontSize: "body", color: "paragraph" }}>+ <Text+ as="div"+ sx={{+ fontSize: "body",+ color: "paragraph-secondary",+ fontWeight: "body"+ }}+ >{period === "education" && discount.amount > 0? "for one year": isDiscounteddiff --git a/apps/web/src/dialogs/buy-dialog/paddle.tsx b/apps/web/src/dialogs/buy-dialog/paddle.tsxindex dd7525ae4..5729fb419 100644--- a/apps/web/src/dialogs/buy-dialog/paddle.tsx+++ b/apps/web/src/dialogs/buy-dialog/paddle.tsx@@ -55,7 +55,8 @@ const SUBSCRIBED_EVENTS: PaddleEvents[] = [PaddleEvents["Checkout.Coupon.Applied"],PaddleEvents["Checkout.Coupon.Remove"],PaddleEvents["Checkout.Location.Submit"],- PaddleEvents["Checkout.Complete"]+ PaddleEvents["Checkout.Complete"],+ PaddleEvents["Checkout.Customer.Details"]];type PaddleCheckoutProps = {@@ -68,19 +69,20 @@ type PaddleCheckoutProps = {coupon?: string;};export function PaddleCheckout(props: PaddleCheckoutProps) {- const { plan, onPriceUpdated, coupon, onCouponApplied, onCompleted } = props;+ const { plan, onPriceUpdated, coupon, onCouponApplied, onCompleted, user } =+ props;const [sourceUrl, setSourceUrl] = useState<string>();const [isLoading, setIsLoading] = useState(true);- const [checkoutId, setCheckoutId] = useState<string>();const appliedCouponCode = useRef<string>();+ const checkoutId = useRef<string>();const checkoutRef = useRef<HTMLIFrameElement>(null);const isMobile = useMobile();const reloadCheckout = useCallback(() => {if (!checkoutRef.current) return;setIsLoading(true);- checkoutRef.current.src = `${PADDLE_ORIGIN}/checkout/?checkout_id=${checkoutId}&display_mode=inline&apple_pay_enabled=false`;- }, [checkoutId]);+ checkoutRef.current.src = `${PADDLE_ORIGIN}/checkout/?checkout_id=${checkoutId.current}&display_mode=inline&apple_pay_enabled=false`;+ }, []);const updatePrice = useCallback(async (checkoutId: string, isInvalidCoupon?: boolean) => {@@ -105,39 +107,68 @@ export function PaddleCheckout(props: PaddleCheckoutProps) {async function onMessage(ev: MessageEvent<PaddleEvent>) {if (ev.origin !== PADDLE_ORIGIN) return;logger.debug("Paddle event received", { data: ev.data });- const { event_name, callback_data } = ev.data;+ const { event, event_name, callback_data } = ev.data;const { checkout } = callback_data;+ if (event === PaddleEvents["Checkout.RemoveSpinner"]) {+ setIsLoading(false);+ return;+ }+if (!checkout ||!checkout.id ||- SUBSCRIBED_EVENTS.indexOf(event_name) === -1+ (SUBSCRIBED_EVENTS.indexOf(event_name) === -1 &&+ SUBSCRIBED_EVENTS.indexOf(event) === -1)) {- logger.debug("Ignoring paddle event", { event_name });+ logger.debug("Ignoring paddle event", { event_name, event });return;}+ if (+ event_name === PaddleEvents["Checkout.Customer.Details"] &&+ !checkoutId.current+ ) {+ submitCustomerInfo(+ checkout.id,+ user.email,+ callback_data.user?.country || "US"+ ).finally(() => {+ checkoutId.current = checkout.id;+ reloadCheckout();+ });+ }+if (event_name === PaddleEvents["Checkout.Complete"]) {onCompleted && onCompleted();return;}- if (event_name === PaddleEvents["Checkout.Loaded"]) setIsLoading(false);+ if (event_name === PaddleEvents["Checkout.Loaded"] && checkoutId.current)+ setIsLoading(false);const pricingInfo = await updatePrice(checkout.id);if (!pricingInfo) return;appliedCouponCode.current = pricingInfo.coupon;- setCheckoutId(checkout.id);+ checkoutId.current = checkout.id;}window.addEventListener("message", onMessage, false);return () => {window.removeEventListener("message", onMessage, false);};- }, [onPriceUpdated, updatePrice, plan, onCompleted]);+ }, [+ onPriceUpdated,+ updatePrice,+ plan,+ onCompleted,+ user.email,+ reloadCheckout+ ]);useEffect(() => {+ const checkout_id = checkoutId.current;if (- !checkoutId ||+ !checkout_id ||appliedCouponCode.current === coupon ||!appliedCouponCode.current === !coupon)@@ -146,10 +177,10 @@ export function PaddleCheckout(props: PaddleCheckoutProps) {(async function () {const checkoutData = coupon- ? await applyCoupon(checkoutId, coupon)- : await removeCoupon(checkoutId);+ ? await applyCoupon(checkout_id, coupon).catch(() => false)+ : await removeCoupon(checkout_id).catch(() => false);if (!checkoutData) {- await updatePrice(checkoutId, true);+ await updatePrice(checkout_id, true);return;}appliedCouponCode.current = coupon;@@ -158,7 +189,6 @@ export function PaddleCheckout(props: PaddleCheckoutProps) {}, [coupon,onCouponApplied,- checkoutId,onPriceUpdated,plan,reloadCheckout,@@ -250,7 +280,9 @@ function getPricingInfo(plan: Plan, checkoutData: CheckoutData): PricingInfo {currency: price.currency,discount: {amount: discount?.gross_discount || 0,- recurring: isRecurringDiscount+ recurring: isRecurringDiscount,+ code: discount?.code,+ type: "promo"},period: plan.period,price: normalizeCheckoutPrice(price),@@ -291,6 +323,36 @@ async function applyCoupon(return json.data;}+async function submitCustomerInfo(+ checkoutId: string,+ email: string,+ country: string+): Promise<CheckoutData | false> {+ if (IS_TESTING) return false;++ const url = ` ${CHECKOUT_SERVICE_ORIGIN}/checkout/${checkoutId}/customer-info`;+ const body = {+ data: {+ email,+ country_code: country,+ audience_optin: false,+ postcode: "1123212"+ }+ };+ const headers = new Headers();+ headers.set("content-type", "application/json");+ const response = await fetch(url, {+ body: JSON.stringify(body),+ headers,+ method: "POST"+ });++ if (!response.ok) return false;+ const json = (await response.json()) as CheckoutDataResponse;++ return json.data;+}+async function removeCoupon(checkoutId: string): Promise<CheckoutData | false> {const url = ` ${CHECKOUT_SERVICE_ORIGIN}/checkout/${checkoutId}/coupon`;diff --git a/apps/web/src/dialogs/buy-dialog/plan-list.tsx b/apps/web/src/dialogs/buy-dialog/plan-list.tsxindex 44390465d..7debd11d2 100644--- a/apps/web/src/dialogs/buy-dialog/plan-list.tsx+++ b/apps/web/src/dialogs/buy-dialog/plan-list.tsx@@ -117,7 +117,7 @@ function RecurringPricing(props: RecurringPricingProps) {sx={{ flexShrink: 0, fontSize: "subBody", textAlign: "end" }}variant="body">- {plan.originalPrice && (+ {plan.originalPrice && plan.originalPrice.gross !== plan.price.gross ? (<Textsx={{textDecorationLine: "line-through",@@ -128,7 +128,7 @@ function RecurringPricing(props: RecurringPricingProps) {{getCurrencySymbol(plan.currency)}{plan.originalPrice.gross}</Text>- )}+ ) : null}<Text><Text as="span" sx={{ fontSize: "subtitle" }}>{getCurrencySymbol(plan.currency)}diff --git a/apps/web/src/dialogs/buy-dialog/plans.ts b/apps/web/src/dialogs/buy-dialog/plans.tsindex 6f8038586..16ef8f9c7 100644--- a/apps/web/src/dialogs/buy-dialog/plans.ts+++ b/apps/web/src/dialogs/buy-dialog/plans.ts@@ -31,8 +31,9 @@ export const EDUCATION_PLAN: Plan = {period: "education",country: "US",currency: "USD",- discount: 0,- price: { gross: 9.99, net: 0, tax: 0 }+ discount: { type: "regional", amount: 0, recurring: false },+ price: { gross: 9.99, net: 0, tax: 0 },+ originalPrice: { gross: 9.99, net: 0, tax: 0 }};export const DEFAULT_PLANS: Plan[] = [@@ -40,7 +41,8 @@ export const DEFAULT_PLANS: Plan[] = [period: "monthly",country: "PK",currency: "USD",- discount: 0,+ discount: { type: "regional", amount: 0, recurring: false },+ originalPrice: { gross: 4.49, net: 0, tax: 0 },id: import.meta.env.DEV || IS_TESTING ? "9822" : "648884",price: { gross: 4.49, net: 0, tax: 0 }},@@ -48,9 +50,10 @@ export const DEFAULT_PLANS: Plan[] = [period: "yearly",country: "PK",currency: "USD",- discount: 0,+ discount: { type: "regional", amount: 0, recurring: false },id: import.meta.env.DEV || IS_TESTING ? "50305" : "658759",- price: { gross: 49.99, net: 0, tax: 0 }+ price: { gross: 49.99, net: 0, tax: 0 },+ originalPrice: { gross: 49.99, net: 0, tax: 0 }},EDUCATION_PLAN];@@ -90,7 +93,7 @@ export function usePlans() {const plans = await getPlans();if (!plans) return;setPlans(plans);- setDiscount(Math.max(...plans.map((p) => p.discount)));+ setDiscount(Math.max(...plans.map((p) => p.discount?.amount || 0)));setCountry(plans[0].country);} catch (e) {console.error(e);diff --git a/apps/web/src/dialogs/buy-dialog/types.ts b/apps/web/src/dialogs/buy-dialog/types.tsindex c9a491e07..b3e5f6c66 100644--- a/apps/web/src/dialogs/buy-dialog/types.ts+++ b/apps/web/src/dialogs/buy-dialog/types.ts@@ -69,11 +69,19 @@ export enum PaddleEvents {/** User has selected "Change Payment Method" when on the payment screen **/"Checkout.PaymentMethodChange" = "Checkout.PaymentMethodChange",/** User has selected "Change Payment Method" when on the Wire Transfer screen **/- "Checkout.WireTransfer.PaymentMethodChange" = "Checkout.WireTransfer.PaymentMethodChange"+ "Checkout.WireTransfer.PaymentMethodChange" = "Checkout.WireTransfer.PaymentMethodChange",++ "Checkout.Customer.Details" = "Checkout.Customer.Details",+ "Checkout.RemoveSpinner" = "Checkout.RemoveSpinner"}export interface CallbackData {checkout?: Checkout;+ user?: {+ email: string;+ id: string;+ country: string;+ };}export interface Checkout {@@ -82,6 +90,7 @@ export interface Checkout {export type PaddleEvent = {action: "event";+ event: PaddleEvents;event_name: PaddleEvents;callback_data: CallbackData;};@@ -91,8 +100,9 @@ export interface Plan {period: Period;price: Price;currency: string;- originalPrice?: Price;- discount: number;+ currencySymbol?: string;+ originalPrice: Price;+ discount?: Discount;country: string;}@@ -108,6 +118,8 @@ export type PricingInfo = {};export type Discount = {+ type: "regional" | "promo";+ code?: string;recurring: boolean;amount: number;};diff --git a/apps/web/src/views/auth.tsx b/apps/web/src/views/auth.tsxindex c3c11cefe..de873a87a 100644--- a/apps/web/src/views/auth.tsx+++ b/apps/web/src/views/auth.tsx@@ -43,6 +43,7 @@ import { AuthenticatorType, User } from "@notesnook/core";import { showLogoutConfirmation } from "../dialogs/confirm";import { TaskManager } from "../common/task-manager";import { strings } from "@notesnook/intl";+import { ScrollContainer } from "@notesnook/ui";type EmailFormData = {email: string;@@ -97,11 +98,17 @@ type BaseFormData =| AccountRecoveryFormData| SignupFormData;+type OpenURLFunction = (+ url: string,+ context?: { authenticated: boolean }+) => void;type NavigateFunction = <TRoute extends AuthRoutes>(route: TRoute,formData?: AuthFormData[TRoute]) => void;type BaseAuthComponentProps<TRoute extends AuthRoutes> = {+ canSkip?: boolean;+ openURL: OpenURLFunction;navigate: NavigateFunction;formData?: AuthFormData[TRoute];};@@ -113,7 +120,12 @@ type AuthRoutes =| "recover"| "mfa:code"| "mfa:select";-export type AuthProps = { route: AuthRoutes };+export type AuthProps = {+ route: AuthRoutes;+ isolated?: boolean;+ canSkip?: boolean;+ openURL?: OpenURLFunction;+};type AuthComponent<TRoute extends AuthRoutes> = (props: BaseAuthComponentProps<TRoute>@@ -161,6 +173,16 @@ const authorizedRoutes: AuthRoutes[] = [];function Auth(props: AuthProps) {+ return (+ <AuthContainer>+ <HeadlessAuth {...props} />+ </AuthContainer>+ );+}+export default Auth;++export function HeadlessAuth(props: AuthProps) {+ const { openURL = _openURL, isolated } = props;const [route, setRoute] = useState(props.route);const [isReady, setIsReady] = useState(false);const [storedFormData, setStoredFormData] = useState<@@ -168,52 +190,55 @@ function Auth(props: AuthProps) {>();const Route = useMemo(() => getRouteComponent(route), [route]);useEffect(() => {+ if (isolated) return;window.history.replaceState({}, "", makeURL(routePaths[route]));- }, [route]);+ }, [route, isolated]);useEffect(() => {db.user.getUser().then((user) => {if (user && authorizedRoutes.includes(route) && !isSessionExpired())- return openURL("/");+ return openURL("/", { authenticated: true });setIsReady(true);});- }, [route]);+ }, [route, openURL]);if (!isReady) return <></>;return (- <AuthContainer>- <Flex- sx={{- zIndex: 1,- flex: 1,- overflowY: "auto",- flexDirection: "column"- }}- >- {Route && (- <Route- navigate={(route, formData) => {- setStoredFormData(formData);- setRoute(route);- }}- formData={storedFormData}- />- )}- </Flex>- </AuthContainer>+ <ScrollContainer+ className="auth-scroll-container"+ style={{+ display: "flex",+ flexDirection: "column",+ zIndex: 1,+ flex: 1,+ flexShrink: 0+ }}+ >+ {Route && (+ <Route+ openURL={openURL}+ canSkip={props.canSkip}+ navigate={(route, formData) => {+ setStoredFormData(formData);+ setRoute(route);+ }}+ formData={storedFormData}+ />+ )}+ </ScrollContainer>);}-export default Auth;function LoginEmail(props: BaseAuthComponentProps<"login:email">) {- const { navigate } = props;+ const { navigate, canSkip = true, openURL } = props;return (<AuthFormtype="login:email"title={strings.welcomeBack()}- canSkip+ canSkip={canSkip}+ openURL={openURL}subtitle={<SubtitleWithActiontext={strings.dontHaveAccount()}@@ -267,10 +292,10 @@ function LoginEmail(props: BaseAuthComponentProps<"login:email">) {}function LoginPassword(props: BaseAuthComponentProps<"login:password">) {- const { navigate, formData } = props;+ const { navigate, formData, openURL } = props;if (!formData) {- openURL("/");+ openURL("/", { authenticated: false });return null;}@@ -284,6 +309,7 @@ function LoginPassword(props: BaseAuthComponentProps<"login:password">) {title: strings.loggingIn(),subtitle: strings.authWait()}}+ openURL={openURL}onSubmit={async (form) => {await userstore.login({@@ -294,7 +320,7 @@ function LoginPassword(props: BaseAuthComponentProps<"login:password">) {Config.get("sessionExpired", false));Config.set("sessionExpired", false);- openURL("/");+ openURL("/", { authenticated: true });}}>{(form?: PasswordFormData) => (@@ -325,13 +351,13 @@ function LoginPassword(props: BaseAuthComponentProps<"login:password">) {}function Signup(props: BaseAuthComponentProps<"signup">) {- const { navigate } = props;+ const { navigate, canSkip = true, openURL } = props;return (<AuthFormtype="signup"title={strings.createAccount()}- canSkip+ canSkip={canSkip}subtitle={<SubtitleWithActiontext={strings.alreadyHaveAccount()}@@ -345,13 +371,14 @@ function Signup(props: BaseAuthComponentProps<"signup">) {title: strings.creatingAccount(),subtitle: strings.creatingAccountDesc()}}+ openURL={openURL}onSubmit={async (form) => {if (form.password !== form["confirm-password"]) {throw new Error(strings.passwordNotMatched());}await userstore.signup(form);- openURL("/notes/#/welcome");+ openURL("/notes/#/welcome", { authenticated: true });}}>{(form?: SignupFormData) => (@@ -410,7 +437,7 @@ function Signup(props: BaseAuthComponentProps<"signup">) {}function SessionExpiry(props: BaseAuthComponentProps<"sessionExpiry">) {- const { navigate } = props;+ const { navigate, openURL } = props;const [user, setUser] = useState<User | undefined>();useEffect(() => {@@ -420,10 +447,10 @@ function SessionExpiry(props: BaseAuthComponentProps<"sessionExpiry">) {setUser(user);} else if (!user) {Config.set("sessionExpired", false);- openURL("/login");- } else openURL("/");+ navigate("login:email");+ } else openURL("/", { authenticated: true });})();- }, []);+ }, [navigate, openURL]);return (<AuthForm@@ -440,6 +467,7 @@ function SessionExpiry(props: BaseAuthComponentProps<"sessionExpiry">) {title: strings.loggingIn(),subtitle: strings.pleaseWaitLogin()}}+ openURL={openURL}onSubmit={async () => {if (!user) return;@@ -494,7 +522,7 @@ function SessionExpiry(props: BaseAuthComponentProps<"sessionExpiry">) {action: () => db.user.logout(true),subtitle: strings.loggingOutDesc()});- openURL("/login");+ navigate("login:email");}}}>@@ -505,7 +533,7 @@ function SessionExpiry(props: BaseAuthComponentProps<"sessionExpiry">) {}function AccountRecovery(props: BaseAuthComponentProps<"recover">) {- const { navigate, formData } = props;+ const { navigate, formData, openURL } = props;const [success, setSuccess] = useState<string>();return (@@ -525,6 +553,7 @@ function AccountRecovery(props: BaseAuthComponentProps<"recover">) {title: strings.sendingRecoveryEmail(),subtitle: strings.sendingRecoveryEmailDesc()}}+ openURL={openURL}onSubmit={async (form) => {if (!form.email) {setSuccess(undefined);@@ -598,7 +627,7 @@ function getTexts(formData: MFAFormData) {}function MFACode(props: BaseAuthComponentProps<"mfa:code">) {- const { navigate, formData } = props;+ const { navigate, formData, openURL } = props;const [isSending, setIsSending] = useState(false);const { elapsed, enabled, setEnabled } = useTimer(`2fa.${formData?.primaryMethod}`,@@ -637,7 +666,7 @@ function MFACode(props: BaseAuthComponentProps<"mfa:code">) {}, [formData, sendCode]);if (!formData) {- openURL("/");+ openURL("/", { authenticated: false });return null;}@@ -655,6 +684,7 @@ function MFACode(props: BaseAuthComponentProps<"mfa:code">) {title: strings.verifying2faCode(),subtitle: strings.authWait()}}+ openURL={openURL}onSubmit={async (form) => {if (!form.code) throw new Error(strings.coreRequired());@@ -728,7 +758,7 @@ const MFAMethods: MFAMethod[] = [{ type: "recoveryCode", title: strings.recoveryCode(), icon: MfaRecoveryCode }];function MFASelector(props: BaseAuthComponentProps<"mfa:select">) {- const { navigate, formData } = props;+ const { navigate, formData, openURL } = props;const [selected, setSelected] = useState(0);const isValidMethod = useCallback((method: MFAMethodType) => {@@ -741,7 +771,7 @@ function MFASelector(props: BaseAuthComponentProps<"mfa:select">) {[formData]);if (!formData) {- openURL("/");+ openURL("/", { authenticated: false });return null;}@@ -754,6 +784,7 @@ function MFASelector(props: BaseAuthComponentProps<"mfa:select">) {title: strings.loggingIn(),subtitle: strings.authWait()}}+ openURL={openURL}onSubmit={async () => {const selectedType = MFAMethods[selected];formData.selectedMethod = selectedType.type;@@ -816,6 +847,7 @@ type AuthFormProps<TType extends AuthRoutes> = {loading: { title: string; subtitle: string };type: TType;onSubmit: (form: AuthFormData[TType]) => Promise<void>;+ openURL: OpenURLFunction;loadForever?: boolean;canSkip?: boolean;children?:@@ -824,7 +856,7 @@ type AuthFormProps<TType extends AuthRoutes> = {};export function AuthForm<T extends AuthRoutes>(props: AuthFormProps<T>) {- const { title, subtitle, children, canSkip, loadForever } = props;+ const { title, subtitle, children, canSkip, loadForever, openURL } = props;const [isSubmitting, setIsSubmitting] = useState(false);const [error, setError] = useState<string>();const formRef = useRef<HTMLFormElement>(null);@@ -867,7 +899,7 @@ export function AuthForm<T extends AuthRoutes>(props: AuthFormProps<T>) {flexDirection: "column",alignItems: "center",justifyContent: "center",- width: ["95%", "45%"],+ width: ["95%", "95%", "45%"],alignSelf: "center"}}>@@ -897,7 +929,7 @@ export function AuthForm<T extends AuthRoutes>(props: AuthFormProps<T>) {textDecoration: "none"}}onClick={() => {- openURL("/notes/");+ openURL("/notes/", { authenticated: false });}}>{strings.skipAndGoToApp()}@@ -986,11 +1018,11 @@ export function SubmitButton(props: SubmitButtonProps) {);}-function openURL(url: string, force?: boolean) {+function _openURL(url: string, _context?: any) {const queryParams = getQueryParams();const redirect = queryParams?.redirect;Config.set("skipInitiation", true);- hardNavigate(force ? url : redirect || url);+ hardNavigate(redirect || url);}function maskEmail(email: string) {diff --git a/apps/web/src/views/checkout.tsx b/apps/web/src/views/checkout.tsxnew file mode 100644index 000000000..8d5d206b3--- /dev/null+++ b/apps/web/src/views/checkout.tsx@@ -0,0 +1,456 @@+/*+This file is part of the Notesnook project (https://notesnook.com/)++Copyright (C) 2023 Streetwriters (Private) Limited++This program is free software: you can redistribute it and/or modify+it under the terms of the GNU General Public License as published by+the Free Software Foundation, either version 3 of the License, or+(at your option) any later version.++This program is distributed in the hope that it will be useful,+but WITHOUT ANY WARRANTY; without even the implied warranty of+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the+GNU General Public License for more details.++You should have received a copy of the GNU General Public License+along with this program. If not, see <http://www.gnu.org/licenses/>.+*/++import "../app.css";+import { useEffect, useState } from "react";+import { Box, Button, Flex, Text } from "@theme-ui/components";+import { hardNavigate, useQueryParams } from "../navigation";+import { Check, Coupon, Support } from "../components/icons";+import { HeadlessAuth } from "./auth";+import {+ CheckoutCompleted,+ CheckoutDetails,+ CheckoutPricing+} from "../dialogs/buy-dialog";+import { useCheckoutStore } from "../dialogs/buy-dialog/store";+import { useStore as useUserStore } from "../stores/user-store";+import { z } from "zod";+import { PricingInfo } from "../dialogs/buy-dialog/types";+import IconTag from "../components/icon-tag";+import { SUBSCRIPTION_STATUS } from "../common/constants";++export type Period = "yearly" | "monthly" | "education";+export type Plan = z.infer<typeof PlanSchema>;++const PlanSchema = z.object({+ id: z.string(),+ period: z.enum(["yearly", "monthly", "education"]),+ price: z.object({+ gross: z.number(),+ net: z.number(),+ tax: z.number(),+ currency: z.string().optional()+ }),+ currency: z.string(),+ currencySymbol: z.string().optional(),+ originalPrice: z.object({+ gross: z.number(),+ net: z.number(),+ tax: z.number(),+ currency: z.string().optional()+ }),+ discount: z+ .object({+ type: z.enum(["regional", "promo"]),+ code: z.string().optional(),+ recurring: z.boolean(),+ amount: z.number()+ })+ .optional(),+ country: z.string()+});++function toPricingInfo(plan: Plan): PricingInfo {+ return {+ country: plan.country,+ currency: plan.currency,+ discount: plan.discount+ ? {+ amount: plan.originalPrice.gross - plan.price.gross,+ recurring: plan.discount.recurring,+ type: plan.discount.type,+ code: plan.discount.code+ }+ : { amount: 0, recurring: false, type: "promo" },+ period: plan.period,+ price: plan.originalPrice,+ recurringPrice: plan.originalPrice,+ coupon: plan.discount?.code,+ invalidCoupon: false+ };+}++const CHECKOUT_STEPS = ["Account", "Payment", "Complete"];+function Checkout() {+ const [{ plan }] = useQueryParams();++ const [currentStep, setCurrentStep] = useState(0);+ const [error, setError] = useState<string>();+ const user = useUserStore((store) => store.user);+ const isCheckoutCompleted = useCheckoutStore((store) => store.isCompleted);++ useEffect(() => {+ if (isCheckoutCompleted) {+ setCurrentStep(2);+ }+ }, [isCheckoutCompleted]);++ useEffect(() => {+ useUserStore.getState().init();+ }, []);++ useEffect(() => {+ const pricingInfo = PlanSchema.safeParse(+ JSON.parse(Buffer.from(plan, "base64").toString("utf-8"))+ );+ if (!pricingInfo.success) {+ hardNavigate("/");+ return;+ }+ useCheckoutStore.getState().selectPlan(pricingInfo.data);+ useCheckoutStore.getState().updatePrice(toPricingInfo(pricingInfo.data));+ useCheckoutStore.getState().applyCoupon(pricingInfo.data.discount?.code);+ }, [plan]);++ if (!plan) {+ hardNavigate("/");+ return null;+ }++ return (+ <Flex+ sx={{+ bg: "background",+ flexDirection: "column",+ height: "100%",+ overflowY: "auto"+ }}+ >+ <Flex+ sx={{+ alignItems: "center",+ justifyContent: "space-between",+ borderBottom: "1px solid var(--border)",+ px: 2+ }}+ >+ <Flex sx={{ alignItems: "center", justifyContent: "center", gap: 2 }}>+ <svg+ style={{+ borderRadius: "default",+ height: 50,+ width: 30,+ alignSelf: "start"+ }}+ >+ <use href="#full-logo" />+ </svg>+ <Text variant="heading" sx={{ fontSize: 20 }}>+ Notesnook+ </Text>+ </Flex>+ <Button+ variant="secondary"+ sx={{ display: "flex", alignItems: "center", gap: 1 }}+ >+ <Support size={18} />+ <span>Contact support</span>+ </Button>+ </Flex>+ <Flex sx={{ flex: 1 }}>+ <Flex sx={{ flexDirection: "column", flex: 1 }}>+ <Flex+ sx={{+ justifyContent: "center",+ alignItems: "center",+ gap: 2,+ mt: 2,+ pb: 2+ }}+ >+ {CHECKOUT_STEPS.map((step, index) => (+ <>+ <Flex key={step} sx={{ alignItems: "center", gap: 2 }}>+ <Flex+ sx={{+ bg:+ currentStep >= index+ ? "accent"+ : "background-secondary",+ height: 25,+ width: 25,+ borderRadius: 100,+ alignItems: "center",+ justifyContent: "center",+ flexShrink: 0+ }}+ >+ <Text+ variant="subBody"+ sx={{+ color:+ currentStep >= index+ ? "accentForeground"+ : "paragraph-secondary",+ textAlign: "center"+ }}+ >+ {index + 1}+ </Text>+ </Flex>+ <Text variant="body">{step}</Text>+ </Flex>+ {index < CHECKOUT_STEPS.length - 1 ? (+ <Box+ sx={{+ display: ["none", "none", "block"],+ height: 2,+ width: 100,+ bg: "separator"+ }}+ />+ ) : null}+ </>+ ))}+ </Flex>++ <Flex+ sx={{+ flex: 1,+ // pr: 300,+ position: "relative",+ overflow: "hidden",+ m: 2,+ gap: 2,+ ".auth-scroll-container form": {+ width: ["95%", "95%", "35%"]+ }+ }}+ >+ {currentStep === 0 ? (+ <HeadlessAuth+ route="signup"+ canSkip={false}+ isolated+ openURL={async (url, ctx) => {+ if (ctx?.authenticated) {+ await useUserStore.getState().init();+ const user = useUserStore.getState().user;+ setCurrentStep(+ user?.subscription.type === SUBSCRIPTION_STATUS.PREMIUM+ ? 2+ : 1+ );+ } else setError("Failed to create account.");+ }}+ />+ ) : currentStep === 1 ? (+ <Flex+ sx={{ flexDirection: "column", overflow: "hidden", flex: 1 }}+ >+ <Text variant="heading" sx={{ mx: 2 }}>+ Final step, make the payment.+ </Text>+ <Text+ variant="body"+ sx={{+ mx: 2,+ fontSize: "title",+ color: "paragraph-secondary",+ mt: 1,+ mb: 4+ }}+ >+ You are one step away from unlocking the full potential of+ Notesnook.+ </Text>+ <CheckoutDetails user={user} />+ </Flex>+ ) : currentStep === 2 ? (+ <Flex+ sx={{+ flexDirection: "column",+ flex: 1,+ alignItems: "center",+ justifyContent: "center"+ }}+ >+ <CheckoutCompleted+ onClose={() => hardNavigate("/notes")}+ buttonText="Start your journey"+ />+ </Flex>+ ) : null}+ </Flex>+ </Flex>+ {currentStep === 2 ? null : (+ <Flex+ sx={{+ display: ["none", "none", "flex"],+ width: "300px",+ border: "1px solid var(--border)",+ borderTop: "none",+ p: 3,+ flexDirection: "column",+ justifyContent: "space-between",+ bg: "background"+ }}+ >+ <CheckoutSummary />+ </Flex>+ )}+ </Flex>++ {currentStep === 2 ? null : (+ <Flex+ sx={{+ display: ["flex", "flex", "none"],+ width: "100%",+ bg: "background",+ zIndex: 999,+ borderTop: "1px solid var(--border)",+ p: 3,+ flexDirection: "column",+ mt: 4+ }}+ >+ <CheckoutSummaryMobile />+ </Flex>+ )}+ </Flex>+ );+}+export default Checkout;++function CheckoutSummaryMobile() {+ const selectedPlan = useCheckoutStore((state) => state.selectedPlan);+ const pricingInfo = useCheckoutStore((state) => state.pricingInfo);+ const couponCode = useCheckoutStore((store) => store.couponCode);++ console.log(pricingInfo);+ if (!selectedPlan || !pricingInfo) return null;+ return (+ <>+ <Flex+ sx={{+ flexDirection: "column"+ }}+ >+ <Text variant="title" sx={{}}>+ Summary+ </Text>+ <Box sx={{ my: 2, height: 1, bg: "separator" }} />+ <CheckoutPricing pricingInfo={pricingInfo} />+ {couponCode && pricingInfo.discount.amount > 0 ? (+ <IconTag+ icon={Coupon}+ text={couponCode}+ styles={{ container: { alignSelf: "end", mt: 2 } }}+ />+ ) : null}+ </Flex>+ </>+ );+}++function CheckoutSummary() {+ const selectedPlan = useCheckoutStore((state) => state.selectedPlan);+ const pricingInfo = useCheckoutStore((state) => state.pricingInfo);+ const couponCode = useCheckoutStore((store) => store.couponCode);++ console.log(pricingInfo);+ if (!selectedPlan || !pricingInfo) return null;+ return (+ <>+ <Flex+ sx={{+ flexDirection: "column"+ }}+ >+ <Text variant="title" sx={{}}>+ Summary+ </Text>+ <Box sx={{ my: 2, height: 1, bg: "separator" }} />+ <Text variant="subtitle" sx={{}}>+ Notesnook Pro+ </Text>+ <Box as="ul" sx={{ paddingInlineStart: 30, mt: 1 }}>+ {[+ "Unlimited real time sync",+ "Unlimited storage",+ "Exports in PDF, HTML & Markdown",+ "Unlimited devices",+ "Recurring reminders",+ "Unlimited notebooks & tags",+ "Automatic backups"+ ].map((feature) => (+ <Text+ as="li"+ key={feature}+ variant="body"+ sx={{ color: "paragraph-secondary", mt: 1 }}+ >+ {feature}+ </Text>+ ))}+ </Box>+ <Box sx={{ my: 2, height: 1, bg: "separator" }} />+ <CheckoutPricing pricingInfo={pricingInfo} />++ {couponCode && pricingInfo.discount.amount > 0 ? (+ <IconTag+ icon={Coupon}+ text={couponCode}+ styles={{ container: { alignSelf: "end", mt: 2 } }}+ />+ ) : null}+ </Flex>+ <Flex sx={{ flexDirection: "column", gap: 2, mt: 2 }}>+ <Flex+ sx={{+ p: 2,+ bg: "background-secondary",+ borderRadius: "default",+ border: "1px solid var(--border)",+ flexDirection: "column"+ }}+ >+ <Text variant="body" sx={{ fontWeight: "bold" }}>+ Privacy seems expensive until you get hacked!+ </Text>+ <Text variant="subBody">+ Hey there! We're a small team of developers focused on bringing+ you the best note-taking experience. Your support helps us keep the+ lights on.+ </Text>+ </Flex>+ <Flex+ sx={{+ p: 2,+ bg: "black",+ borderRadius: 10,+ border: "1px solid var(--border)",+ gap: 2+ }}+ >+ <Check size={16} color="white" />+ <Text+ variant="body"+ sx={{+ color: "white"+ }}+ >+ {pricingInfo.period === "yearly" ? "30" : "7"}-day money-back+ guarantee+ </Text>+ </Flex>+ </Flex>+ </>+ );+}