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: improve plan change dialog to show full plan comparison
Abdullah Attab43a8cbafe3d
diff --git a/apps/web/src/dialogs/buy-dialog/buy-dialog.tsx b/apps/web/src/dialogs/buy-dialog/buy-dialog.tsxindex a3be39966..034b8b1b1 100644--- a/apps/web/src/dialogs/buy-dialog/buy-dialog.tsx+++ b/apps/web/src/dialogs/buy-dialog/buy-dialog.tsx@@ -147,7 +147,8 @@ export const BuyDialog = DialogManager.register(function BuyDialog(</Text></Flex><PlansList- selectedPlan={user?.subscription.plan || SubscriptionPlan.FREE}+ selectedPlan={user?.subscription.productId}+ recommendedPlan={SubscriptionPlan.PRO}onPlanSelected={(plan) => selectPlan(plan)}/><Flexdiff --git a/apps/web/src/dialogs/buy-dialog/change-plan-dialog.tsx b/apps/web/src/dialogs/buy-dialog/change-plan-dialog.tsxindex 658105b5d..068e8ec17 100644--- a/apps/web/src/dialogs/buy-dialog/change-plan-dialog.tsx+++ b/apps/web/src/dialogs/buy-dialog/change-plan-dialog.tsx@@ -20,213 +20,109 @@ along with this program. If not, see <http://www.gnu.org/licenses/>.import { DialogManager } from "../../common/dialog-manager";import BaseDialog from "../../components/dialog";import { Flex, Text } from "@theme-ui/components";-import { getAllPlans, PERIOD_METADATA, PLAN_METADATA } from "./plans";-import { SelectComponent } from "../settings";+import { PLAN_METADATA } from "./plans";import { useStore as useUserStore } from "../../stores/user-store";import { db } from "../../common/db";-import { useCallback, useEffect, useState } from "react";-import dayjs from "dayjs";import { showToast } from "../../utils/toast";-import { usePromise } from "@notesnook/common";-import { ErrorText } from "../../components/error-text";-import { Loading } from "../../components/icons";-import { getCurrencySymbol } from "../../common/currencies";+import { ComparePlans, Footer, PlansList } from "./plan-list";+import { ConfirmDialog } from "../confirm";+import { TaskManager } from "../../common/task-manager";export type ChangePlanDialogProps = {onClose: () => void;- selectedPlan?: string;-};--type ChangePreviewResponse = {- update_summary?: {- result: {- action: "charge";- };- charge: {- amount: string;- };- credit: { amount: string };- };- immediate_transaction?: { details: Details };- recurring_transaction_details: Details;- next_transaction: {- billing_period: BillingPeriod;- details: Details;- };- currency_code: string;- billing_cycle: {- interval: "month" | "year";- };-};-type BillingPeriod = {- ends_at: string;- starts_at: string;-};-type Totals = {- total: number;- balance: number;-};-type Details = {- line_items: LineItem[];- totals: Totals;-};-type LineItem = {- proration: Proration;-};-type Proration = {- billing_period: BillingPeriod;};export const ChangePlanDialog = DialogManager.register(function ChangePlanDialog(props: ChangePlanDialogProps) {const { onClose } = props;- const plans = usePromise(() => getAllPlans(), []);const subscription = useUserStore((store) => store.user?.subscription);- const [changeSummary, setChangeSummary] = useState<- { title: string; amount: string }[]- >([]);- const [selectedPlan, setSelectedPlan] = useState(props.selectedPlan);- const [loading, setLoading] = useState(false);- const [error, setError] = useState<Error>();-- const changePlan = useCallback(async (id: string) => {- setLoading(true);- setChangeSummary([]);- try {- const response = (await db.subscriptions.preview(- id- )) as ChangePreviewResponse | null;- if (!response) return;-- const {- update_summary,- recurring_transaction_details,- currency_code: currencyCode- } = response;- const recurringTotal = recurring_transaction_details.totals.total;-- const planPrice = update_summary- ? parseInt(update_summary?.charge.amount || "0")- : recurringTotal;-- const summary: { title: string; amount: string }[] = [- {- title: "Plan price",- amount: formatPrice(planPrice, currencyCode)- }- ];- setChangeSummary(summary);- } catch (e) {- console.error(e);- setError(e as Error);- } finally {- setLoading(false);- }- }, []);-- useEffect(() => {- if (!props.selectedPlan || plans.status !== "fulfilled") return;- setSelectedPlan(props.selectedPlan);- changePlan(props.selectedPlan);- }, [props.selectedPlan, changePlan, plans]);return (<BaseDialog- title={`Change plan`}isOpen={true}onClose={onClose}- positiveButton={{- text: "Confirm",- disabled: !selectedPlan || loading,- loading,- onClick: async () => {- if (!selectedPlan) return;- setLoading(true);- try {- await db.subscriptions.change(selectedPlan);- showToast(- "success",- "Subscription changed successfully. It might take a couple of minutes for the changes to reflect in the app."- );- onClose();- } catch (e) {- showToast("error", (e as Error).message);- } finally {- setLoading(false);- }- }- }}- negativeButton={{- text: "Cancel",- onClick: onClose+ sx={{+ width: ["95%", "80%", "60%"],+ height: ["auto", "auto", "80vw"]}}>- {error ? (- <ErrorText error={error} />- ) : plans.status === "rejected" ? (- <ErrorText error={plans.reason} />- ) : (- <Flex sx={{ flexDirection: "column" }}>- <Flex- sx={{ alignItems: "center", justifyContent: "space-between" }}+ <Flex+ sx={{+ flexDirection: "column",+ flex: 1,+ px: 25,+ justifyContent: "center"+ }}+ >+ <Flex sx={{ flexDirection: "column", alignSelf: "center" }}>+ <Text+ id="select-plan"+ variant="heading"+ sx={{ fontSize: 32, textAlign: "center" }}+ >+ Change plan+ </Text>+ <Text+ variant="title"+ mt={1}+ sx={{+ fontSize: "title",+ color: "heading-secondary",+ textAlign: "center"+ }}>- <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={() => {- console.log(selectedPlan || subscription.productId);- return selectedPlan || subscription.productId;- }}- onSelectionChanged={async (id) => {- const plan = plans.value?.find((p) => p.id === id);- if (!plan) return;- setSelectedPlan(id);- await changePlan(id);- }}- />- )}- </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="body" sx={{ color: "paragraph-secondary" }}>- Note: You will receive a credit for unused time on your- previous plan, and you will only pay the prorated amount for- the new one.- </Text>- </Flex>- ) : null}+ You will only pay the prorated amount for the new subscription+ plan+ </Text></Flex>- )}+ <PlansList+ selectedPlan={subscription?.productId}+ loadAllPlans+ ignoreTrial+ onPlanSelected={async (plan) => {+ const result = await ConfirmDialog.show({+ title: "Confirm plan change",+ message: `Your plan will be switched to ${+ PLAN_METADATA[plan.plan].title+ } plan. You will receive a credit for unused time on your previous subscription, and you will only pay the prorated amount for your new subscription.`,+ positiveButtonText: "Confirm",+ negativeButtonText: "Cancel"+ });+ if (result) {+ onClose();+ await TaskManager.startTask({+ type: "modal",+ title: "Changing subscription plan",+ subtitle:+ "Please wait while we change your subscription plan...",+ action: async () => {+ try {+ await db.subscriptions.change(plan.id);+ showToast(+ "success",+ "Subscription changed successfully. It might take a couple of minutes for the changes to reflect in the app."+ );+ } catch (e) {+ showToast("error", (e as Error).message);+ }+ }+ });+ }+ }}+ />+ </Flex>+ <Flex+ sx={{+ flexDirection: "column",+ flex: 1,+ px: "5%",+ mt: 50+ }}+ >+ <ComparePlans />+ <Footer />+ </Flex></BaseDialog>);});--function formatPrice(amount: string | number, currency: string) {- return `${getCurrencySymbol(currency)}${- (typeof amount === "string" ? parseInt(amount) : amount) / 100- }`;-}diff --git a/apps/web/src/dialogs/buy-dialog/plan-list.tsx b/apps/web/src/dialogs/buy-dialog/plan-list.tsxindex b1d686137..87e16a951 100644--- a/apps/web/src/dialogs/buy-dialog/plan-list.tsx+++ b/apps/web/src/dialogs/buy-dialog/plan-list.tsx@@ -42,7 +42,10 @@ import { useStore as useUserStore } from "../../stores/user-store";import { getCurrencySymbol } from "../../common/currencies";type PlansListProps = {- selectedPlan: SubscriptionPlan;+ selectedPlan?: string;+ loadAllPlans?: boolean;+ ignoreTrial?: boolean;+ recommendedPlan?: SubscriptionPlan;onPlanSelected: (plan: Plan) => void;};@@ -118,8 +121,14 @@ const RECOMMENDED_BY = [];export function PlansList(props: PlansListProps) {- const { onPlanSelected, selectedPlan } = props;- const { isLoading, plans = [] } = usePlans();+ const {+ onPlanSelected,+ selectedPlan,+ loadAllPlans,+ ignoreTrial,+ recommendedPlan+ } = props;+ const { isLoading, plans = [] } = usePlans({ loadAllPlans });const [selectedPeriod, setPeriod] = useState<Period>("yearly");const user = useUserStore((store) => store.user);@@ -187,9 +196,10 @@ export function PlansList(props: PlansListProps) {textAlign: "start",display: "flex",flexDirection: "column",- border: metadata.recommended- ? "2px solid var(--accent)"- : "1px solid var(--border)",+ border:+ recommendedPlan === plan.plan+ ? "2px solid var(--accent)"+ : "1px solid var(--border)",borderRadius: "dialog"}}>@@ -208,7 +218,7 @@ export function PlansList(props: PlansListProps) {>{metadata.title}</Text>{" "}- {metadata.recommended ? (+ {recommendedPlan === plan.plan ? (<Textvariant="subBody"sx={{@@ -268,18 +278,20 @@ export function PlansList(props: PlansListProps) {);})}</Flex>- {selectedPlan === plan.plan ? (+ {selectedPlan === plan.id ? (<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"}+ variant={+ recommendedPlan === plan.plan ? "accent" : "secondary"+ }onClick={() => onPlanSelected(plan)}sx={{ mt: 2 }}>- {isTrialAvailableForPlan(plan.plan, user)+ {isTrialAvailableForPlan(plan.plan, user) && !ignoreTrial? "Start your free trial": "Select plan"}</Button>diff --git a/apps/web/src/dialogs/buy-dialog/plans.ts b/apps/web/src/dialogs/buy-dialog/plans.tsindex caed20670..0fdfe5686 100644--- a/apps/web/src/dialogs/buy-dialog/plans.ts+++ b/apps/web/src/dialogs/buy-dialog/plans.ts@@ -85,9 +85,11 @@ export async function getAllPlans(): Promise<Plan[] | null> {.sort((a, b) => a.plan - b.plan);}-export function usePlans() {+export function usePlans(options?: { loadAllPlans?: boolean }) {const result = usePromise(async () => {- const plans = await getPlans();+ const plans = options?.loadAllPlans+ ? await getAllPlans()+ : await getPlans();if (!plans) return;return {plans,diff --git a/apps/web/src/dialogs/buy-dialog/upgrade-dialog.tsx b/apps/web/src/dialogs/buy-dialog/upgrade-dialog.tsxindex fd8155fea..18047dcaf 100644--- a/apps/web/src/dialogs/buy-dialog/upgrade-dialog.tsx+++ b/apps/web/src/dialogs/buy-dialog/upgrade-dialog.tsx@@ -38,6 +38,7 @@ import { useStore as useUserStore } from "../../stores/user-store";import { ChangePlanDialog } from "./change-plan-dialog";import { Loading } from "../../components/icons";import { showToast } from "../../utils/toast";+import { isUserSubscribed } from "../../hooks/use-is-user-premium";export type UpgradeDialogProps = {feature: FeatureResult<any>;@@ -48,6 +49,7 @@ export const UpgradeDialog = DialogManager.register(function UpgradeDialog(props: UpgradeDialogProps) {const { onClose, feature } = props;+ const subscription = useUserStore((store) => store.user?.subscription);const plans = usePromise(() => getAllPlans(), []);const plan =plans.status === "fulfilled"@@ -133,47 +135,69 @@ export const UpgradeDialog = DialogManager.register(function UpgradeDialog(<strong>Cancel anytime.</strong> {PERIOD_METADATA.yearly.refundDays}-day money-back guarantee.</Text>- <Button- variant="accent"- disabled={!plan}- onClick={() => {- if (!plan) return;- onClose();- const subscription = useUserStore.getState().user?.subscription;- if (- subscription?.provider !== SubscriptionProvider.PADDLE &&- subscription?.provider !== SubscriptionProvider.STREETWRITERS- )- return showToast(- "error",- `You can only change your plan from the platform you originally bought the subscription from.`- );+ {!subscription || subscription.plan === SubscriptionPlan.FREE ? (+ <>+ <Button+ variant="accent"+ disabled={!plan}+ onClick={() => {+ if (!plan) return;+ onClose();- if (!subscription || subscription.plan === SubscriptionPlan.FREE) {- useCheckoutStore.getState().selectPlan(plan);- BuyDialog.show({});- } else ChangePlanDialog.show({ selectedPlan: plan.id });- }}- >- {plan ? (- <>- Upgrade to {metadata.title} {getCurrencySymbol(plan.currency)}- {plan.price.gross}- {formatRecurringPeriodShort(plan.period)}- </>- ) : (- <Loading size={16} color="accentForeground" />- )}- </Button>- <Button- variant="tertiary"- onClick={() => {- onClose();- BuyDialog.show({});- }}- >- Compare all plans- </Button>+ if (+ !subscription ||+ subscription.plan === SubscriptionPlan.FREE+ ) {+ useCheckoutStore.getState().selectPlan(plan);+ BuyDialog.show({});+ } else ChangePlanDialog.show({ selectedPlan: plan.id });+ }}+ >+ {plan ? (+ <>+ Upgrade to {metadata.title} {getCurrencySymbol(plan.currency)}+ {plan.price.gross}+ {formatRecurringPeriodShort(plan.period)}+ </>+ ) : (+ <Loading size={16} color="accentForeground" />+ )}+ </Button>+ <Button+ variant="tertiary"+ onClick={() => {+ onClose();+ BuyDialog.show({});+ }}+ >+ Compare all plans+ </Button>+ </>+ ) : (+ <Button+ variant="accent"+ disabled={!plan}+ onClick={() => {+ if (+ isUserSubscribed() &&+ subscription?.provider !== SubscriptionProvider.PADDLE &&+ subscription?.provider !== SubscriptionProvider.STREETWRITERS+ )+ return showToast(+ "error",+ `You can only change your plan from the platform you originally bought the subscription from.`+ );+ onClose();+ ChangePlanDialog.show({});+ }}+ >+ {plan ? (+ <>Change plan</>+ ) : (+ <Loading size={16} color="accentForeground" />+ )}+ </Button>+ )}</Flex></BaseDialog>);diff --git a/apps/web/src/views/plans.tsx b/apps/web/src/views/plans.tsxindex 5f66cf766..f6e68c647 100644--- a/apps/web/src/views/plans.tsx+++ b/apps/web/src/views/plans.tsx@@ -97,13 +97,13 @@ function Plans() {</Text></Flex><PlansList+ recommendedPlan={SubscriptionPlan.PRO}onPlanSelected={(plan) => {const url = new URLSearchParams({plan: Buffer.from(JSON.stringify(plan)).toString("base64")});hardNavigate(`/checkout`, url.toString());}}- selectedPlan={SubscriptionPlan.FREE}/></Flex><Flex