Skip to content

A fully open source & end-to-end encrypted note taking alternative to Evernote.

web: improve change plan ux

Abdullah Attae23c0f55b77f
diff --git a/apps/web/src/dialogs/buy-dialog/change-plan-dialog.tsx b/apps/web/src/dialogs/buy-dialog/change-plan-dialog.tsx
index 0317c93ac..9ed585b20 100644
--- a/apps/web/src/dialogs/buy-dialog/change-plan-dialog.tsx
+++ b/apps/web/src/dialogs/buy-dialog/change-plan-dialog.tsx
@@ -21,14 +21,16 @@ import { DialogManager } from "../../common/dialog-manager";
import BaseDialog from "../../components/dialog";
import { Flex, Text } from "@theme-ui/components";
import { getCurrencySymbol } from "./helpers";
-import { PERIOD_METADATA, PLAN_METADATA, usePlans } from "./plans";
+import { getAllPlans, PERIOD_METADATA, PLAN_METADATA } from "./plans";
import { SelectComponent } from "../settings";
import { useStore as useUserStore } from "../../stores/user-store";
import { db } from "../../common/db";
import { useState } from "react";
import dayjs from "dayjs";
-import { Loading } from "../../components/icons";
import { showToast } from "../../utils/toast";
+import { usePromise } from "@notesnook/common";
+import { ErrorText } from "../../components/error-text";
+import { Loading } from "../../components/icons";
export type ChangePlanDialogProps = {
onClose: () => void;
@@ -37,7 +39,7 @@ export type ChangePlanDialogProps = {
export const ChangePlanDialog = DialogManager.register(
function ChangePlanDialog(props: ChangePlanDialogProps) {
const { onClose } = props;
- const { plans } = usePlans();
+ const plans = usePromise(() => getAllPlans(), []);
const subscription = useUserStore((store) => store.user?.subscription);
const [changeSummary, setChangeSummary] = useState<
{ title: string; amount: string }[]
@@ -45,15 +47,9 @@ export const ChangePlanDialog = DialogManager.register(
const [selectedPlan, setSelectedPlan] = useState<string>();
const [loading, setLoading] = useState(false);
- const currentPlan = plans.find((p) => p.id === subscription?.productId);
- if (!subscription || !currentPlan) return null;
return (
<BaseDialog
title={`Change plan`}
- description={`You are currently on ${
- PLAN_METADATA[currentPlan.plan].title +
- ` (${PERIOD_METADATA[currentPlan.period].title})`
- } plan.`}
isOpen={true}
onClose={onClose}
positiveButton={{
@@ -78,142 +74,155 @@ export const ChangePlanDialog = DialogManager.register(
onClick: onClose
}}
>
- <Flex sx={{ flexDirection: "column" }}>
- <Flex sx={{ alignItems: "center", justifyContent: "space-between" }}>
- <Text variant="body">Select plan</Text>
- <SelectComponent
- options={plans.map((p) => ({
- title:
- PLAN_METADATA[p.plan].title +
- ` (${PERIOD_METADATA[p.period].title})`,
- value: p.id
- }))}
- selectedOption={() => selectedPlan || subscription.productId}
- onSelectionChanged={async (id) => {
- const plan = plans.find((p) => p.id === id);
- if (!plan) return;
- setSelectedPlan(id);
- setLoading(true);
- setChangeSummary([]);
- try {
- const {
- data: {
- update_summary,
- immediate_transaction,
- recurring_transaction_details,
- next_transaction,
- currency_code: currencyCode,
- billing_cycle
- }
- } = await db.subscriptions.preview(id);
- const proration =
- immediate_transaction.details.line_items.find(
- (l: any) => !!l.proration
- ).proration;
- const planPrice = parseInt(update_summary.charge.amount);
- const balance =
- recurring_transaction_details.totals.total -
- recurring_transaction_details.totals.balance +
- update_summary.credit.amount * -1;
- const charge = planPrice - balance;
- const recurringTotal = parseInt(
- recurring_transaction_details.totals.total
- );
- const summary: { title: string; amount: string }[] = [
- {
- title: "Plan price",
- amount: formatPrice(planPrice, currencyCode)
- },
- {
- title: "Balance from current subscription",
- amount: formatPrice(balance, currencyCode)
- }
- ];
- if (update_summary.result.action === "charge") {
- summary.push(
- {
- title: "Charged today",
- amount: formatPrice(charge, currencyCode)
- },
- {
- title: `Charged ${dayjs(
- next_transaction.billing_period.starts_at
- ).format("YYYY-MM-DD")}`,
- amount: formatPrice(recurringTotal, currencyCode)
- }
- );
- } else {
- const nextCharge = recurringTotal - charge;
- summary.push({
- title: "Charged today",
- amount: formatPrice(0, currencyCode)
- });
- if (nextCharge > 0 && proration) {
- summary.push({
- title: `Charged ${dayjs(
- proration.billing_period.ends_at
- ).format("YYYY-MM-DD")}`,
- amount: formatPrice(nextCharge, currencyCode)
- });
- summary.push({
- title: `Charged ${dayjs(
- proration.billing_period.ends_at
- )
- .add(1, billing_cycle.interval)
- .format("YYYY-MM-DD")}`,
- amount: formatPrice(planPrice, currencyCode)
- });
- } else {
- const freeIntervals = Math.floor(charge / planPrice);
- const amount =
- planPrice - (charge - planPrice * freeIntervals);
- const chargeStartDate = dayjs(
- next_transaction.billing_period.starts_at
- ).add(freeIntervals, billing_cycle.interval);
- summary.push(
+ {plans.status === "rejected" ? (
+ <ErrorText error={plans.reason} />
+ ) : (
+ <Flex sx={{ flexDirection: "column" }}>
+ <Flex
+ sx={{ alignItems: "center", justifyContent: "space-between" }}
+ >
+ <Text variant="body">Select plan</Text>
+ {plans.status === "pending" || !plans.value || !subscription ? (
+ <Loading size={16} />
+ ) : (
+ <SelectComponent
+ options={plans.value.map((p) => ({
+ title:
+ PLAN_METADATA[p.plan].title +
+ ` (${PERIOD_METADATA[p.period].title})`,
+ value: p.id
+ }))}
+ selectedOption={() => selectedPlan || subscription.productId}
+ onSelectionChanged={async (id) => {
+ const plan = plans.value?.find((p) => p.id === id);
+ if (!plan) return;
+ setSelectedPlan(id);
+ setLoading(true);
+ setChangeSummary([]);
+ try {
+ const {
+ data: {
+ update_summary,
+ immediate_transaction,
+ recurring_transaction_details,
+ next_transaction,
+ currency_code: currencyCode,
+ billing_cycle
+ }
+ } = await db.subscriptions.preview(id);
+ const proration =
+ immediate_transaction.details.line_items.find(
+ (l: any) => !!l.proration
+ ).proration;
+ const planPrice = parseInt(update_summary.charge.amount);
+ const balance =
+ recurring_transaction_details.totals.total -
+ recurring_transaction_details.totals.balance +
+ update_summary.credit.amount * -1;
+ const charge = planPrice - balance;
+ const recurringTotal = parseInt(
+ recurring_transaction_details.totals.total
+ );
+ const summary: { title: string; amount: string }[] = [
{
- title: `Charged ${chargeStartDate.format(
- "YYYY-MM-DD"
- )}`,
- amount: formatPrice(amount, currencyCode)
+ title: "Plan price",
+ amount: formatPrice(planPrice, currencyCode)
},
{
- title: `Charged ${chargeStartDate
- .add(1, billing_cycle.interval)
- .format("YYYY-MM-DD")}`,
- amount: formatPrice(planPrice, currencyCode)
+ title: "Balance from current subscription",
+ amount: formatPrice(balance, currencyCode)
}
- );
+ ];
+ if (update_summary.result.action === "charge") {
+ summary.push(
+ {
+ title: "Charged today",
+ amount: formatPrice(charge, currencyCode)
+ },
+ {
+ title: `Charged ${dayjs(
+ next_transaction.billing_period.starts_at
+ ).format("YYYY-MM-DD")}`,
+ amount: formatPrice(recurringTotal, currencyCode)
+ }
+ );
+ } else {
+ const nextCharge = recurringTotal - charge;
+ summary.push({
+ title: "Charged today",
+ amount: formatPrice(0, currencyCode)
+ });
+ if (nextCharge > 0 && proration) {
+ summary.push({
+ title: `Charged ${dayjs(
+ proration.billing_period.ends_at
+ ).format("YYYY-MM-DD")}`,
+ amount: formatPrice(nextCharge, currencyCode)
+ });
+ summary.push({
+ title: `Charged ${dayjs(
+ proration.billing_period.ends_at
+ )
+ .add(1, billing_cycle.interval)
+ .format("YYYY-MM-DD")}`,
+ amount: formatPrice(planPrice, currencyCode)
+ });
+ } else {
+ const freeIntervals = Math.floor(charge / planPrice);
+ const amount =
+ planPrice - (charge - planPrice * freeIntervals);
+ const chargeStartDate = dayjs(
+ next_transaction.billing_period.starts_at
+ ).add(freeIntervals, billing_cycle.interval);
+ summary.push(
+ {
+ title: `Charged ${chargeStartDate.format(
+ "YYYY-MM-DD"
+ )}`,
+ amount: formatPrice(amount, currencyCode)
+ },
+ {
+ title: `Charged ${chargeStartDate
+ .add(1, billing_cycle.interval)
+ .format("YYYY-MM-DD")}`,
+ amount: formatPrice(planPrice, currencyCode)
+ }
+ );
+ }
+ }
+ setChangeSummary(summary);
+ } finally {
+ setLoading(false);
}
- }
- setChangeSummary(summary);
- } finally {
- setLoading(false);
- }
- }}
- />
- </Flex>
- {changeSummary.length > 0 ? (
- <Flex sx={{ flexDirection: "column", gap: 1, mt: 1 }}>
- <Text variant="subtitle">Summary</Text>
- {changeSummary.map((item) => (
- <Flex
- key={item.title}
- sx={{ alignItems: "center", justifyContent: "space-between" }}
- >
- <Text variant="body">{item.title}</Text>
- <Text variant="body" sx={{ color: "paragraph-secondary" }}>
- {item.amount}
- </Text>
- </Flex>
- ))}
- <Text variant="subBody">
- Note: These are estimated amounts. The real amounts could differ
- slightly.
- </Text>
+ }}
+ />
+ )}
</Flex>
- ) : null}
- </Flex>
+ {changeSummary.length > 0 ? (
+ <Flex sx={{ flexDirection: "column", gap: 1, mt: 1 }}>
+ <Text variant="subtitle">Summary</Text>
+ {changeSummary.map((item) => (
+ <Flex
+ key={item.title}
+ sx={{
+ alignItems: "center",
+ justifyContent: "space-between"
+ }}
+ >
+ <Text variant="body">{item.title}</Text>
+ <Text variant="body" sx={{ color: "paragraph-secondary" }}>
+ {item.amount}
+ </Text>
+ </Flex>
+ ))}
+ <Text variant="subBody">
+ Note: These are estimated amounts. The real amounts could
+ differ slightly.
+ </Text>
+ </Flex>
+ ) : null}
+ </Flex>
+ )}
</BaseDialog>
);
}
diff --git a/apps/web/src/dialogs/buy-dialog/helpers.ts b/apps/web/src/dialogs/buy-dialog/helpers.ts
index 16608d996..338840292 100644
--- a/apps/web/src/dialogs/buy-dialog/helpers.ts
+++ b/apps/web/src/dialogs/buy-dialog/helpers.ts
@@ -24,6 +24,7 @@ import {
import { getFeature } from "@notesnook/common";
import { Period, Plan, SubscriptionPlan, User } from "@notesnook/core";
import { PricingInfo } from "./types";
+import dayjs from "dayjs";
export const IS_DEV = import.meta.env.DEV || IS_TESTING;
export function getCurrencySymbol(currency: string) {
diff --git a/apps/web/src/dialogs/buy-dialog/plan-list.tsx b/apps/web/src/dialogs/buy-dialog/plan-list.tsx
index 3a20eebd5..54d452ba1 100644
--- a/apps/web/src/dialogs/buy-dialog/plan-list.tsx
+++ b/apps/web/src/dialogs/buy-dialog/plan-list.tsx
@@ -122,7 +122,7 @@ const RECOMMENDED_BY = [
export function PlansList(props: PlansListProps) {
const { onPlanSelected, selectedPlan } = props;
- const { isLoading, plans } = usePlans();
+ const { isLoading, plans = [] } = usePlans();
const [selectedPeriod, setPeriod] = useState<Period>("yearly");
const user = useUserStore((store) => store.user);
@@ -166,126 +166,131 @@ export function PlansList(props: PlansListProps) {
justifyContent: "center"
}}
>
- {plans
- .filter(
- (p) =>
- p.plan !== SubscriptionPlan.EDUCATION &&
- p.period === selectedPeriod
- )
- .map((plan) => {
- const metadata = PLAN_METADATA[plan.plan];
- return (
- <Flex
- key={plan.id}
- data-test-id={`checkout-plan`}
- mt={1}
- sx={{
- maxWidth: 300,
- p: 2,
- flexShrink: 0,
- flex: 1,
- textAlign: "start",
- display: "flex",
- flexDirection: "column",
- border: metadata.recommended
- ? "2px solid var(--accent)"
- : "1px solid var(--border)",
- borderRadius: "dialog"
- }}
- >
+ {isLoading ? (
+ <Loading />
+ ) : (
+ plans
+ .filter(
+ (p) =>
+ p.plan !== SubscriptionPlan.EDUCATION &&
+ p.period === selectedPeriod
+ )
+ .map((plan) => {
+ const metadata = PLAN_METADATA[plan.plan];
+ return (
<Flex
- sx={{ justifyContent: "space-between", alignItems: "start" }}
+ key={plan.id}
+ data-test-id={`checkout-plan`}
+ mt={1}
+ sx={{
+ maxWidth: 300,
+ p: 2,
+ flexShrink: 0,
+ flex: 1,
+ textAlign: "start",
+ display: "flex",
+ flexDirection: "column",
+ border: metadata.recommended
+ ? "2px solid var(--accent)"
+ : "1px solid var(--border)",
+ borderRadius: "dialog"
+ }}
>
- <Text
- variant="title"
+ <Flex
sx={{
- color: "heading-secondary"
+ justifyContent: "space-between",
+ alignItems: "start"
}}
- data-test-id="title"
>
- {metadata.title}
- </Text>{" "}
- {metadata.recommended ? (
<Text
- variant="subBody"
+ variant="title"
sx={{
- bg: "accent",
- color: "accentForeground",
- borderRadius: 100,
- px: 1,
- py: "small"
+ color: "heading-secondary"
}}
+ data-test-id="title"
>
- Most popular
- </Text>
- ) : null}
- </Flex>
+ {metadata.title}
+ </Text>{" "}
+ {metadata.recommended ? (
+ <Text
+ variant="subBody"
+ sx={{
+ bg: "accent",
+ color: "accentForeground",
+ borderRadius: 100,
+ px: 1,
+ py: "small"
+ }}
+ >
+ Most popular
+ </Text>
+ ) : null}
+ </Flex>
- <Text
- variant="body"
- sx={{
- color: "paragraph-secondary"
- }}
- >
- {metadata.subtitle}
- </Text>
- <Text sx={{ mt: 1 }} variant="body">
- {isLoading ? (
- <Loading />
- ) : plan.recurring ? (
- <RecurringPricing plan={plan} />
+ <Text
+ variant="body"
+ sx={{
+ color: "paragraph-secondary"
+ }}
+ >
+ {metadata.subtitle}
+ </Text>
+ <Text sx={{ mt: 1 }} variant="body">
+ {plan.recurring ? (
+ <RecurringPricing plan={plan} />
+ ) : (
+ <OneTimePricing plan={plan} />
+ )}
+ </Text>
+ <Flex
+ sx={{
+ flexDirection: "column",
+ pt: 2,
+ mt: 1,
+ gap: 1,
+ borderTop: "1px solid var(--border)"
+ }}
+ >
+ {FEATURE_HIGHLIGHTS.map((feature) => {
+ const caption =
+ feature.availability[planToAvailability(plan.plan)]
+ .caption;
+ return (
+ <Flex
+ key={feature.id}
+ sx={{ justifyContent: "space-between" }}
+ >
+ <Text variant="body">{feature.title}</Text>
+ <Text
+ variant="body"
+ sx={{ color: "paragraph-secondary" }}
+ >
+ <FeatureCaption caption={caption} />
+ </Text>
+ </Flex>
+ );
+ })}
+ </Flex>
+ {selectedPlan === plan.plan ? (
+ <Flex sx={{ mt: 2, alignItems: "center", gap: 1 }}>
+ <CheckCircleOutline color="accent" size={16} />
+ <Text variant="subBody">You are on this plan.</Text>
+ </Flex>
) : (
- <OneTimePricing plan={plan} />
+ <Button
+ variant={metadata.recommended ? "accent" : "secondary"}
+ onClick={() => onPlanSelected(plan)}
+ sx={{ mt: 2 }}
+ >
+ {isTrialAvailableForPlan(plan.plan, user)
+ ? "Start your free trial"
+ : "Select plan"}
+ </Button>
)}
- </Text>
- <Flex
- sx={{
- flexDirection: "column",
- pt: 2,
- mt: 1,
- gap: 1,
- borderTop: "1px solid var(--border)"
- }}
- >
- {FEATURE_HIGHLIGHTS.map((feature) => {
- const caption =
- feature.availability[planToAvailability(plan.plan)]
- .caption;
- return (
- <Flex
- key={feature.id}
- sx={{ justifyContent: "space-between" }}
- >
- <Text variant="body">{feature.title}</Text>
- <Text
- variant="body"
- sx={{ color: "paragraph-secondary" }}
- >
- <FeatureCaption caption={caption} />
- </Text>
- </Flex>
- );
- })}
</Flex>
- {selectedPlan === plan.plan ? (
- <Flex sx={{ mt: 2, alignItems: "center", gap: 1 }}>
- <CheckCircleOutline color="accent" size={16} />
- <Text variant="subBody">You are on this plan.</Text>
- </Flex>
- ) : (
- <Button
- variant={metadata.recommended ? "accent" : "secondary"}
- onClick={() => onPlanSelected(plan)}
- sx={{ mt: 2 }}
- >
- {isTrialAvailableForPlan(plan.plan, user)
- ? "Start your free trial"
- : "Select plan"}
- </Button>
- )}
- </Flex>
- );
- })}
+ );
+ })
+ )}
</Flex>
<Text variant="body" sx={{ alignSelf: "center", mt: 2 }}>
@@ -313,7 +318,7 @@ export function PlansList(props: PlansListProps) {
width={f.size || 200}
css={`
[data-theme="dark"] & {
- filter: ${f.filter?.dark || "grayscale(1) invert(1)"};
+ filter: ${"grayscale(1) invert(1)"};
}
[data-theme="light"] & {
filter: ${f.filter?.light || "grayscale(1)"};
diff --git a/apps/web/src/dialogs/buy-dialog/plans.ts b/apps/web/src/dialogs/buy-dialog/plans.ts
index a77abf878..a41e838ed 100644
--- a/apps/web/src/dialogs/buy-dialog/plans.ts
+++ b/apps/web/src/dialogs/buy-dialog/plans.ts
@@ -19,9 +19,10 @@ along with this program. If not, see <http://www.gnu.org/licenses/>.
import { useEffect, useState } from "react";
import { Plan, PlanMetadata } from "./types";
-import { Period, SubscriptionPlan } from "@notesnook/core";
+import { Period, set, SubscriptionPlan } from "@notesnook/core";
import { strings } from "@notesnook/intl";
import { db } from "../../common/db";
+import { usePromise } from "@notesnook/common";
export const PLAN_METADATA: PlanMetadata = {
[SubscriptionPlan.FREE]: {
@@ -67,33 +68,42 @@ export const PERIOD_METADATA: Record<Period, PeriodMetadata> = {
}
};
-const PLANS = getPlans().catch(console.error);
export async function getPlans(): Promise<Plan[] | null> {
const user = await db.user.getUser();
const plans = await db.pricing.products(user?.subscription?.trialsAvailed);
return plans.sort((a, b) => a.plan - b.plan);
}
+export async function getAllPlans(): Promise<Plan[] | null> {
+ const user = await db.user.getUser();
+ const plans = await db.pricing.products();
+ const plansWithoutTrials = await db.pricing.products(
+ user?.subscription?.trialsAvailed
+ );
+
+ return set
+ .union(plans, plansWithoutTrials, (item) => `${item.plan}${item.period}`)
+ .sort((a, b) => a.plan - b.plan);
+}
+
export function usePlans() {
- const [isLoading, setIsLoading] = useState(false);
- const [plans, setPlans] = useState<Plan[]>([]);
- const [discount, setDiscount] = useState<number>();
- const [country, setCountry] = useState<string>();
- useEffect(() => {
- (async function () {
- try {
- setIsLoading(true);
- const plans = await PLANS;
- if (!plans) return;
- setPlans(plans);
- setDiscount(Math.max(...plans.map((p) => p.discount?.amount || 0)));
- setCountry(plans[0].country);
- } catch (e) {
- console.error(e);
- } finally {
- setIsLoading(false);
- }
- })();
- }, []);
- return { isLoading, plans, discount, country };
+ const result = usePromise(async () => {
+ const plans = await getPlans();
+ if (!plans) return;
+ return {
+ plans,
+ discount: Math.max(...plans.map((p) => p.discount?.amount || 0)),
+ country: plans[0].country
+ };
+ });
+
+ if (result.status === "pending") return { isLoading: true };
+ if (result.status === "rejected") return { isLoading: false };
+
+ return {
+ isLoading: false,
+ plans: result.value?.plans,
+ discount: result.value?.discount,
+ country: result.value?.country
+ };
}
diff --git a/apps/web/src/dialogs/settings/subscription-settings.ts b/apps/web/src/dialogs/settings/subscription-settings.ts
index eb47d0a31..fffef3dbe 100644
--- a/apps/web/src/dialogs/settings/subscription-settings.ts
+++ b/apps/web/src/dialogs/settings/subscription-settings.ts
@@ -104,16 +104,6 @@ export const SubscriptionSettings: SettingsGroup[] = [
variant: "secondary",
action: async () => {
ChangePlanDialog.show({});
- // try {
- // const urls = await db.subscriptions.urls();
- // if (!urls)
- // throw new Error(
- // "Failed to get subscription management urls. Please contact us at [email protected] so we can help you update your payment method."
- // );
- // window.open(urls?.update_payment_method, "_blank");
- // } catch (e) {
- // if (e instanceof Error) showToast("error", e.message);
- // }
}
}
]