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 support for changing plans
Abdullah Atta215ca2319045
diff --git a/apps/web/src/common/db.ts b/apps/web/src/common/db.tsindex 78e548ade..d62edef6a 100644--- a/apps/web/src/common/db.ts+++ b/apps/web/src/common/db.ts@@ -60,7 +60,8 @@ async function initializeDatabase(persistence: DatabasePersistence) {SSE_HOST: `${base}:7264`,ISSUES_HOST: `${base}:2624`,SUBSCRIPTIONS_HOST: `${base}:9264`,- MONOGRAPH_HOST: `${base}:6264`+ MONOGRAPH_HOST: `${base}:6264`,+ NOTESNOOK_HOST: `${base}:8788`});const storage = new NNStorage(diff --git a/apps/web/src/dialogs/buy-dialog/buy-dialog.tsx b/apps/web/src/dialogs/buy-dialog/buy-dialog.tsxindex 83c3080dd..2cdb1798a 100644--- a/apps/web/src/dialogs/buy-dialog/buy-dialog.tsx+++ b/apps/web/src/dialogs/buy-dialog/buy-dialog.tsx@@ -17,7 +17,7 @@ You should have received a copy of the GNU General Public Licensealong with this program. If not, see <http://www.gnu.org/licenses/>.*/-import { useCallback, useEffect, useState } from "react";+import { useCallback, useEffect } from "react";import { Text, Flex, Button, Box, Image } from "@theme-ui/components";import { Loading, Coupon } from "../../components/icons";import { useStore as useUserStore } from "../../stores/user-store";@@ -26,7 +26,7 @@ import Rocket from "../../assets/rocket.svg?url";import { hardNavigate } from "../../navigation";import { Features } from "./features";import { PaddleCheckout } from "./paddle";-import { Period, Plan, PricingInfo } from "./types";+import { Plan, PricingInfo } from "./types";import { getPlans, PERIOD_METADATA, PLAN_METADATA, usePlans } from "./plans";import {ComparePlans,@@ -42,7 +42,7 @@ import { isUserSubscribed } from "../../hooks/use-is-user-premium";import { SUBSCRIPTION_STATUS } from "../../common/constants";import BaseDialog from "../../components/dialog";import { ScopedThemeProvider } from "../../components/theme-provider";-import { SubscriptionPlan, User } from "@notesnook/core";+import { Period, SubscriptionPlan, User } from "@notesnook/core";import { BaseDialogProps, DialogManager } from "../../common/dialog-manager";import dayjs from "dayjs";import { PromptDialog } from "../prompt";@@ -83,14 +83,15 @@ export const BuyDialog = DialogManager.register(function BuyDialog(onClose={() => onClose(false)}noScroll={!!selectedPlan}sx={{- width: ["95%", "80%", "60%"]+ width: ["95%", "80%", "60%"],+ height: ["auto", "auto", "80vw"]}}>{selectedPlan ? (<Flexsx={{- // height: ["auto", "auto", "80vw"],width: "100%",+ height: "100%",overflow: "hidden",position: "relative",flexDirection: ["column", "column", "row"],@@ -231,98 +232,6 @@ export function CheckoutDetails({return <Features />;}-type TrialOrUpgradeProps = {- couponCode?: string;- user: User | undefined;- onShowPlans: () => void;- onTrialRequested: () => void | Promise<void>;-};-function TrialOrUpgrade(props: TrialOrUpgradeProps) {- const { user, onShowPlans, onTrialRequested, couponCode } = props;- const { isLoading, plans } = usePlans();- const plan = plans[0];-- return (- <>- <Image src={Rocket} style={{ flexShrink: 0, width: 200, height: 200 }} />- <Text variant="heading" mt={4} sx={{ textAlign: "center" }}>- Notesnook Pro- </Text>- <Text variant="body" mt={1} sx={{ textAlign: "center" }}>- Ready to take the next step in your private note taking journey?- </Text>- {isLoading || !plan ? (- <Loading sx={{ mt: 4 }} />- ) : (- <Text variant={"body"} mt={4} sx={{ fontSize: "title" }}>- {/* Starting from {getCurrencySymbol(plan.currency)}- {plan.price.gross}- {formatPeriod(plan.period)} */}- </Text>- )}- {isMacStoreApp() ? (- <>- <Text variant={"subBody"} mt={2} sx={{ textAlign: "center" }}>- You cannot upgrade from the macOS app.- </Text>- </>- ) : user ? (- <>- <Button- variant="accent"- mt={2}- sx={{ borderRadius: 100, px: 6 }}- onClick={onShowPlans}- data-test-id="see-all-plans"- >- See all plans- </Button>- {!user.subscription || !user.subscription.expiry ? (- <Button- variant="secondary"- mt={2}- sx={{ borderRadius: 100, px: 6 }}- onClick={onTrialRequested}- >- Try free for 14 days- </Button>- ) : null}- </>- ) : (- <>- <Button- variant="accent"- mt={4}- sx={{ borderRadius: 100, px: 6 }}- onClick={() => hardNavigate("/signup")}- >- Sign up for free- </Button>- <Text variant={"subBody"} mt={2} sx={{ textAlign: "center" }}>- After creating your account, you will be asked to activate your free- trial. <b>No credit card is required.</b>- </Text>- </>- )}-- {couponCode && (- <Text- variant="subBody"- bg="shade"- mt={4}- p={1}- sx={{ borderRadius: "default", color: "accent" }}- >- {user- ? "Please select a plan to use your coupon:"- : `Please sign up or login to use your coupon:`}{" "}- <b>{couponCode}</b>- </Text>- )}- </>- );-}-type AlreadyPremiumProps = {isCanceled?: boolean;onShowPlans: () => void;diff --git a/apps/web/src/dialogs/buy-dialog/change-plan-dialog.tsx b/apps/web/src/dialogs/buy-dialog/change-plan-dialog.tsxnew file mode 100644index 000000000..0317c93ac--- /dev/null+++ b/apps/web/src/dialogs/buy-dialog/change-plan-dialog.tsx@@ -0,0 +1,226 @@+/*+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 { 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 { 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";++export type ChangePlanDialogProps = {+ onClose: () => void;+};++export const ChangePlanDialog = DialogManager.register(+ function ChangePlanDialog(props: ChangePlanDialogProps) {+ const { onClose } = props;+ const { plans } = usePlans();+ const subscription = useUserStore((store) => store.user?.subscription);+ const [changeSummary, setChangeSummary] = useState<+ { title: string; amount: string }[]+ >([]);+ 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={{+ text: "Confirm",+ disabled: !selectedPlan || loading,+ loading,+ onClick: async () => {+ if (!selectedPlan) return;+ setLoading(true);+ try {+ await db.subscriptions.change(selectedPlan);+ onClose();+ } catch (e) {+ showToast("error", (e as Error).message);+ } finally {+ setLoading(false);+ }+ }+ }}+ negativeButton={{+ text: "Cancel",+ 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(+ {+ 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);+ }+ }}+ />+ </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>+ );+ }+);++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/helpers.ts b/apps/web/src/dialogs/buy-dialog/helpers.tsindex 7f1b30a57..6dcd609de 100644--- a/apps/web/src/dialogs/buy-dialog/helpers.ts+++ b/apps/web/src/dialogs/buy-dialog/helpers.ts@@ -22,8 +22,9 @@ import {ICurrencySymbols} from "@brixtol/currency-symbols";import { getFeature } from "@notesnook/common";-import { Plan } from "@notesnook/core";+import { Period, Plan, SubscriptionPlan, User } from "@notesnook/core";import { PricingInfo } from "./types";+import { useStore as useUserStore } from "../../stores/user-store";export const IS_DEV = import.meta.env.DEV || IS_TESTING;export function getCurrencySymbol(currency: string) {@@ -49,6 +50,12 @@ export const FEATURE_HIGHLIGHTS = [getFeature("appLock")];+const TRIAL_PERIODS: Record<Period, number> = {+ yearly: 14,+ monthly: 7,+ "5-year": 30+};+export function toPricingInfo(plan: Plan): PricingInfo {return {country: plan.country,@@ -59,7 +66,12 @@ export function toPricingInfo(plan: Plan): PricingInfo {period: plan.period,subtotal: `${getCurrencySymbol(plan.currency)}${plan.price.net}`,tax: `${getCurrencySymbol(plan.currency)}${plan.price.tax}`,- total: `${getCurrencySymbol(plan.currency)}${plan.price.gross}`+ total: `${getCurrencySymbol(plan.currency)}${plan.price.gross}`,+ trial_period: isTrialAvailableForPlan(plan.plan)+ ? {+ frequency: TRIAL_PERIODS[plan.period]+ }+ : undefined},discount: plan.discount,coupon: plan.discount?.code,@@ -73,3 +85,11 @@ export function toPricingInfo(plan: Plan): PricingInfo {}};}++export function isTrialAvailableForPlan(plan: SubscriptionPlan) {+ const user = useUserStore.getState().user;+ return (+ !user?.subscription.trialsAvailed ||+ !user?.subscription.trialsAvailed?.includes(plan)+ );+}diff --git a/apps/web/src/dialogs/buy-dialog/paddle.tsx b/apps/web/src/dialogs/buy-dialog/paddle.tsxindex a99f15861..cbe9ff2bf 100644--- a/apps/web/src/dialogs/buy-dialog/paddle.tsx+++ b/apps/web/src/dialogs/buy-dialog/paddle.tsx@@ -20,7 +20,7 @@ along with this program. If not, see <http://www.gnu.org/licenses/>.import { useEffect, useState, useRef, useCallback } from "react";import { Flex } from "@theme-ui/components";import { Loader } from "../../components/loader";-import { PaddleEvent, Period, Plan, Price, PricingInfo } from "./types";+import { PaddleEvent, Plan, Price, PricingInfo } from "./types";import { ScrollContainer } from "@notesnook/ui";import useMobile from "../../hooks/use-mobile";import {@@ -37,6 +37,7 @@ import { isFeatureSupported } from "../../utils/feature-check";import { IS_DEV, parseAmount } from "./helpers";import { CheckoutCustomerUserInfo } from "@paddle/paddle-js/types/checkout/customer";import { logger } from "../../utils/logger";+import { Period } from "@notesnook/core";export const SELLER_ID = IS_DEV ? 1506 : 128190;export const CLIENT_PADDLE_TOKEN = IS_DEV@@ -101,7 +102,11 @@ export function PaddleCheckout(props: PaddleCheckoutProps) {createCheckout({ theme, user, coupon, plan }).then(async (checkoutData) => {if (!checkoutData) return;- const pricingInfo = await getPrice(plan, checkoutData);+ const pricingInfo = await getPrice(plan, {+ currencyCode: checkoutData.currency_code,+ discount: checkoutData.discount,+ countryCode: checkoutData.customer.address?.country_code+ });if (!pricingInfo) return;addressRef.current = checkoutData.customer.address || undefined;@@ -116,7 +121,7 @@ export function PaddleCheckout(props: PaddleCheckoutProps) {useEffect(() => {async function onMessage(ev: MessageEvent<PaddleEvent>) {- if (ev.origin !== PADDLE_ORIGIN) return;+ if (ev.origin !== PADDLE_ORIGIN || !ev.data) return;logger.debug("Paddle event received", { data: ev.data });const { event_name, callback_data } = ev.data;@@ -140,7 +145,11 @@ export function PaddleCheckout(props: PaddleCheckoutProps) {console.log(callback_data);addressRef.current = callback_data.data.customer.address || undefined;- const pricingInfo = await getPrice(plan, callback_data.data);+ const pricingInfo = await getPrice(plan, {+ currencyCode: callback_data.data.currency_code,+ discount: callback_data.data.discount,+ countryCode: callback_data.data.customer.address?.country_code+ });if (!pricingInfo) return;pricingInfo.invalidCoupon =@@ -205,7 +214,12 @@ function getCheckoutURL(id: string, theme: PaddleCheckoutProps["theme"]) {)}`;}-async function getPrice(plan: Plan, checkoutData: CheckoutEventsData) {+type PriceOptions = {+ currencyCode: string;+ discount?: { id: string; code: string };+ countryCode?: string;+};+export async function getPrice(plan: Plan, data: PriceOptions) {const response = await fetch(`${PADDLE_API}/pricing-preview`, {method: "POST",body: JSON.stringify({@@ -215,14 +229,8 @@ async function getPrice(plan: Plan, checkoutData: CheckoutEventsData) {price_id: plan.id}],- currency_code: checkoutData.currency_code,- address: checkoutData.customer.address- ? {- postal_code: checkoutData.customer.address?.postal_code,- country_code: checkoutData.customer.address?.country_code- }- : undefined,- discount_id: checkoutData.discount?.id+ currency_code: data.currencyCode,+ discount_id: data.discount?.id}),headers: {"Content-Type": "application/json",@@ -233,13 +241,13 @@ async function getPrice(plan: Plan, checkoutData: CheckoutEventsData) {if (!response.ok) return false;const json = (await response.json()) as PricePreviewResponse;console.log(json);- return getPricingInfo(json.data, plan.period, checkoutData);+ return getPricingInfo(json.data, plan.period, data);}function getPricingInfo(price: PricePreviewResponse["data"],period: Period,- checkoutData: CheckoutEventsData+ options: PriceOptions): PricingInfo {const {discounts,@@ -262,7 +270,7 @@ function getPricingInfo(totalsWithoutDiscount.total = `${symbol}${(total / 100).toFixed(2)}`;}return {- country: checkoutData.customer.address?.country_code || "US",+ country: options.countryCode || "US",discount: discount? {recurring: isRecurring,@@ -274,17 +282,17 @@ function getPricingInfo(price: {id: _price.id,period,- currency: checkoutData.currency_code,+ currency: options.currencyCode,...totals,trial_period: _price.trial_period},recurringPrice: {id: _price.id,period,- currency: checkoutData.currency_code,+ currency: options.currencyCode,...totalsWithoutDiscount},- coupon: checkoutData.discount?.code+ coupon: options.discount?.code};}diff --git a/apps/web/src/dialogs/buy-dialog/plan-list.tsx b/apps/web/src/dialogs/buy-dialog/plan-list.tsxindex e61cc5bec..6113ce337 100644--- a/apps/web/src/dialogs/buy-dialog/plan-list.tsx+++ b/apps/web/src/dialogs/buy-dialog/plan-list.tsx@@ -18,18 +18,17 @@ along with this program. If not, see <http://www.gnu.org/licenses/>.*/import { Text, Flex, Button, Image, Link, Box } from "@theme-ui/components";-import {- Check,- CheckCircleOutline,- Cross,- Loading-} from "../../components/icons";-import { Period, Plan } from "./types";+import { CheckCircleOutline, Loading } from "../../components/icons";+import { Plan } from "./types";import { PERIOD_METADATA, PLAN_METADATA, usePlans } from "./plans";import { useState } from "react";-import { FEATURE_HIGHLIGHTS, getCurrencySymbol } from "./helpers";+import {+ FEATURE_HIGHLIGHTS,+ getCurrencySymbol,+ isTrialAvailableForPlan+} from "./helpers";import { strings } from "@notesnook/intl";-import { SubscriptionPlan } from "@notesnook/core";+import { Period, SubscriptionPlan } from "@notesnook/core";import Cameron from "../../assets/testimonials/cameron.jpg";import AndroidPolice from "../../assets/featured/android-police.svg";import AppleInsider from "../../assets/featured/appleinsider.svg";@@ -40,13 +39,10 @@ import PrivacyGuides from "../../assets/featured/privacy-guides.svg";import Techlore from "../../assets/featured/techlore.svg";import TheVerge from "../../assets/featured/theverge.svg";import FreedomPress from "../../assets/featured/freedom-press.svg";-import {- getFeature,- getFeaturesTable,- planToAvailability-} from "@notesnook/common";+import { getFeaturesTable, planToAvailability } from "@notesnook/common";import { FeatureCaption } from "./feature-caption";import Accordion from "../../components/accordion";+import { useStore as useUserStore } from "../../stores/user-store";type PlansListProps = {selectedPlan: SubscriptionPlan;@@ -126,7 +122,7 @@ const RECOMMENDED_BY = [export function PlansList(props: PlansListProps) {const { onPlanSelected, selectedPlan } = props;- const { isLoading, plans, discount, country } = usePlans();+ const { isLoading, plans } = usePlans();const [selectedPeriod, setPeriod] = useState<Period>("yearly");return (@@ -154,7 +150,7 @@ export function PlansList(props: PlansListProps) {borderRadius: 100,py: 1}}- onClick={() => setPeriod(id)}+ onClick={() => setPeriod(id as Period)}>{period.title}</Button>@@ -281,7 +277,9 @@ export function PlansList(props: PlansListProps) {onClick={() => onPlanSelected(plan)}sx={{ mt: 2 }}>- Select plan+ {isTrialAvailableForPlan(plan.plan)+ ? "Start your free trial"+ : "Select plan"}</Button>)}</Flex>diff --git a/apps/web/src/dialogs/buy-dialog/plans.ts b/apps/web/src/dialogs/buy-dialog/plans.tsindex 31a570958..5016f3738 100644--- a/apps/web/src/dialogs/buy-dialog/plans.ts+++ b/apps/web/src/dialogs/buy-dialog/plans.ts@@ -19,29 +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 { IS_DEV } from "./helpers";import { Period, SubscriptionPlan } from "@notesnook/core";import { strings } from "@notesnook/intl";import { db } from "../../common/db";-function createPlan(- id: string,- plan: SubscriptionPlan,- period: Period,- price: number,- recurring = true-): Plan {- return {- plan,- id,- price: { gross: price, net: price, tax: 0 },- currency: "USD",- country: "US",- period: period,- recurring- };-}-export const PLAN_METADATA: PlanMetadata = {[SubscriptionPlan.FREE]: {title: "Free",@@ -82,101 +63,23 @@ export const PERIOD_METADATA: Record<Period, PeriodMetadata> = {}};-export const DEFAULT_PLANS: Plan[] = [- createPlan(- IS_DEV- ? "pri_01j00cf6v5kqqvchcpgapr7123"- : "pri_01j02dbe7btgk6ta3ctper2161",- SubscriptionPlan.ESSENTIAL,- "monthly",- 1.99- ),- createPlan(- IS_DEV- ? "pri_01j00d1qq3bart3w1rvt0q8bkt"- : "pri_01j02dckdey85cgmrdknd2f4zx",- SubscriptionPlan.ESSENTIAL,- "yearly",- 19.99- ),- createPlan(- IS_DEV- ? "pri_01j00fnbzth05aafjb05kcahvq"- : "pri_01h9qprh1xvvxbs8vcpcg7qacm",- SubscriptionPlan.PRO,- "monthly",- 6.99- ),- createPlan(- IS_DEV- ? "pri_01j00fpawjwkrqxy2faqhzts9m"- : "pri_01h9qpqyjwbm3m2xy7834t3azt",- SubscriptionPlan.PRO,- "yearly",- 69.99- ),- createPlan(- IS_DEV- ? "pri_01j00fr72gn40xzk9cdcfpzevw"- : "pri_01j02da6n9c1xmzq15kjhjxngn",- SubscriptionPlan.PRO,- "5-year",- 299.99- ),- createPlan(- IS_DEV- ? "pri_01j00fxsryh5jfyfjqq5tsx4c7"- : "pri_01j02ddzyc1m63s3b1kq6g4bnn",- SubscriptionPlan.BELIEVER,- "monthly",- 8.99- ),- createPlan(- IS_DEV- ? "pri_01j00fzbz01rfn3f30crwxc7y9"- : "pri_01j02dezv9v5ncw3e16ncvz7x7",- SubscriptionPlan.BELIEVER,- "yearly",- 89.99- ),- createPlan(- IS_DEV- ? "pri_01j00g0wpmj6m9vcvpjq97jwpp"- : "pri_01j02dfxz6y8hghfbr5p8cqtgb",- SubscriptionPlan.BELIEVER,- "5-year",- 399.99- )-];--export const EDUCATION_PLAN: Plan = createPlan(- IS_DEV ? "pri_01j00g6asxjskghjcrbxpbd26e" : "pri_01j02dh4mwkbsvpygyf1bd9whs",- SubscriptionPlan.EDUCATION,- "yearly",- 19.99,- false-);--let CACHED_PLANS: Plan[];+const PLANS = getPlans().catch(console.error);export async function getPlans(): Promise<Plan[] | null> {- // if (IS_TESTING || import.meta.env.DEV) return DEFAULT_PLANS;- if (CACHED_PLANS) return CACHED_PLANS;-- const plans = await db.pricing.products();- CACHED_PLANS = plans.sort((a, b) => a.plan - b.plan);- return plans;+ 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 function usePlans() {const [isLoading, setIsLoading] = useState(false);- const [plans, setPlans] = useState<Plan[]>(DEFAULT_PLANS);+ const [plans, setPlans] = useState<Plan[]>([]);const [discount, setDiscount] = useState<number>();const [country, setCountry] = useState<string>();useEffect(() => {(async function () {try {setIsLoading(true);- const plans = await getPlans();+ const plans = await PLANS;if (!plans) return;setPlans(plans);setDiscount(Math.max(...plans.map((p) => p.discount?.amount || 0)));diff --git a/apps/web/src/dialogs/buy-dialog/store.ts b/apps/web/src/dialogs/buy-dialog/store.tsindex 826474309..5a58c6c20 100644--- a/apps/web/src/dialogs/buy-dialog/store.ts+++ b/apps/web/src/dialogs/buy-dialog/store.ts@@ -17,10 +17,9 @@ You should have received a copy of the GNU General Public Licensealong with this program. If not, see <http://www.gnu.org/licenses/>.*/-import { Plan, Price, PricingInfo } from "./types";+import { Plan, PricingInfo } from "./types";import { create } from "zustand";import { create as produce } from "mutative";-import { DEFAULT_PLANS } from "./plans";interface ICheckoutStore {selectedPlan?: Plan;diff --git a/apps/web/src/dialogs/settings/components/billing-history.tsx b/apps/web/src/dialogs/settings/components/billing-history.tsxindex 422f0ffcd..30272c385 100644--- a/apps/web/src/dialogs/settings/components/billing-history.tsx+++ b/apps/web/src/dialogs/settings/components/billing-history.tsx@@ -76,6 +76,10 @@ export function BillingHistory() {{error.stack}</Text></Flex>+ ) : transactions.length === 0 ? (+ <Text variant="body" sx={{ mt: 2, color: "paragraph-secondary" }}>+ You have not been billed yet.+ </Text>) : (<tablestyle={{ tableLayout: "fixed", borderCollapse: "collapse" }}diff --git a/apps/web/src/dialogs/settings/components/subscription-status.tsx b/apps/web/src/dialogs/settings/components/subscription-status.tsxindex 3a6419170..6c064af98 100644--- a/apps/web/src/dialogs/settings/components/subscription-status.tsx+++ b/apps/web/src/dialogs/settings/components/subscription-status.tsx@@ -39,13 +39,16 @@ export function SubscriptionStatus() {const { title, autoRenew, expiryDate, trial, legacy } =getSubscriptionInfo(user);- const subtitle = trial- ? "Your free trial is on-going."- : autoRenew- ? `Your subscription will auto renew on ${expiryDate}.`- : expiryDate- ? `Your account will automatically downgrade to the Free plan on ${expiryDate}.`- : "";+ const subtitle =+ title === "Free"+ ? ""+ : trial+ ? `Your free trial is on-going. Your subscription will start on ${expiryDate}.`+ : autoRenew+ ? `Your subscription will auto renew on ${expiryDate}.`+ : expiryDate+ ? `Your account will automatically downgrade to the Free plan on ${expiryDate}.`+ : "";if (!user) return null;return (@@ -82,7 +85,10 @@ export function SubscriptionStatus() {<Gridsx={{gridTemplateRows: "1fr ".repeat(featuresUsage.value.length),- gridTemplateColumns: "1fr 2fr 1fr"+ gridTemplateColumns: "1fr 3fr 1fr",+ borderTop: "1px solid var(--border)",+ pt: 2,+ width: "100%"}}>{featuresUsage.value.map((feature, index) => (@@ -90,19 +96,16 @@ export function SubscriptionStatus() {<Text sx={{ gridRow: index + 1, gridColumn: 1 }} variant="body">{getFeature(feature.id).title}</Text>- <Progress- sx={{ gridRow: index + 1, gridColumn: 2 }}- max={feature.total}- value={feature.used}- /><Text- sx={{ gridRow: index + 1, gridColumn: 3 }}+ sx={{ gridRow: index + 1, gridColumn: 3, textAlign: "right" }}variant="subBody">{feature.id === "storage"? `${formatBytes(feature.used)}/${formatBytes(feature.total)}`+ : feature.total === Infinity+ ? "Unlimited": `${feature.used} of ${feature.total}`}</Text></>diff --git a/apps/web/src/dialogs/settings/index.tsx b/apps/web/src/dialogs/settings/index.tsxindex a713ec2c6..5b1638f47 100644--- a/apps/web/src/dialogs/settings/index.tsx+++ b/apps/web/src/dialogs/settings/index.tsx@@ -437,7 +437,7 @@ function SettingItem(props: { item: Setting }) {useEffect(() => {if (!item.onStateChange) return;- const unsubscribe = item.onStateChange(setState);+ const unsubscribe = item.onStateChange((state) => setState(state));return () => {unsubscribe?.();};@@ -615,7 +615,7 @@ function SettingItem(props: { item: Setting }) {);}-function SelectComponent(props: DropdownSettingComponent) {+export function SelectComponent(props: Omit<DropdownSettingComponent, "type">) {const { onSelectionChanged, options } = props;const selectedOption = usePromise(() => props.selectedOption(), [props]);@@ -638,7 +638,11 @@ function SelectComponent(props: DropdownSettingComponent) {}>{options.map((option) => (- <option key={option.value} value={option.value}>+ <option+ key={option.value}+ value={option.value}+ disabled={option.disabled}+ >{option.title}</option>))}diff --git a/apps/web/src/dialogs/settings/subscription-settings.ts b/apps/web/src/dialogs/settings/subscription-settings.tsindex eccb67cda..c1921a7cf 100644--- a/apps/web/src/dialogs/settings/subscription-settings.ts+++ b/apps/web/src/dialogs/settings/subscription-settings.ts@@ -17,13 +17,16 @@ You should have received a copy of the GNU General Public Licensealong with this program. If not, see <http://www.gnu.org/licenses/>.*/-import { SettingsGroup } from "./types";+import { SettingComponent, SettingsGroup } from "./types";import { SubscriptionStatus } from "./components/subscription-status";import { showToast } from "../../utils/toast";import { db } from "../../common/db";import { BillingHistory } from "./components/billing-history";import { useStore as useUserStore } from "../../stores/user-store";-import { isUserSubscribed } from "../../hooks/use-is-user-premium";+import {+ isActiveSubscription,+ isUserSubscribed+} from "../../hooks/use-is-user-premium";import { strings } from "@notesnook/intl";import {SubscriptionPlan,@@ -32,6 +35,7 @@ import {} from "@notesnook/core";import { TaskManager } from "../../common/task-manager";import { ConfirmDialog } from "../confirm";+import { ChangePlanDialog } from "../buy-dialog/change-plan-dialog";export const SubscriptionSettings: SettingsGroup[] = [{@@ -52,28 +56,23 @@ export const SubscriptionSettings: SettingsGroup[] = [return (user?.subscription.provider !== SubscriptionProvider.PADDLE ||!isUserSubscribed(user) ||- status === SubscriptionStatusEnum.CANCELED ||- status === SubscriptionStatusEnum.EXPIRED+ status === SubscriptionStatusEnum.EXPIRED ||+ status === SubscriptionStatusEnum.TRIAL ||+ status === SubscriptionStatusEnum.CANCELED);},components: [{type: "toggle",- isToggled: () =>- useUserStore.getState().user?.subscription.status ===- SubscriptionStatusEnum.ACTIVE,+ isToggled: () => isActiveSubscription(),async toggle() {try {- const user = useUserStore.getState().user;- const status = user?.subscription.status;- if (status === SubscriptionStatusEnum.ACTIVE)- await db.subscriptions.pause();+ if (isActiveSubscription()) await db.subscriptions.pause();else await db.subscriptions.resume();useUserStore.setState((state) => {- state.user!.subscription.status =- status === SubscriptionStatusEnum.ACTIVE- ? SubscriptionStatusEnum.PAUSED- : SubscriptionStatusEnum.ACTIVE;+ state.user!.subscription.status = isActiveSubscription()+ ? SubscriptionStatusEnum.PAUSED+ : SubscriptionStatusEnum.ACTIVE;});} catch (e) {showToast("error", (e as Error).message);@@ -82,15 +81,53 @@ export const SubscriptionSettings: SettingsGroup[] = [}]},+ {+ key: "change-plan",+ title: "Change plan",+ description: "Change your subscription plan.",+ isHidden: () => {+ const user = useUserStore.getState().user;+ const status = user?.subscription.status;+ return (+ user?.subscription.provider !== SubscriptionProvider.PADDLE ||+ !isUserSubscribed(user) ||+ status === SubscriptionStatusEnum.CANCELED ||+ status === SubscriptionStatusEnum.EXPIRED+ );+ },+ components: [+ {+ type: "button",+ title: "Change",+ 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);+ // }+ }+ }+ ]+ },{key: "payment-method",title: strings.paymentMethod(),description: strings.changePaymentMethodDescription(),isHidden: () => {const user = useUserStore.getState().user;+ const status = user?.subscription.status;return (user?.subscription.provider !== SubscriptionProvider.PADDLE ||- !isUserSubscribed(user)+ !isUserSubscribed(user) ||+ status === SubscriptionStatusEnum.CANCELED ||+ status === SubscriptionStatusEnum.EXPIRED);},components: [@@ -114,49 +151,46 @@ export const SubscriptionSettings: SettingsGroup[] = []},{- key: "cancel-subscription",- title: "Cancel subscription",+ key: "cancel-trial",+ title: "Cancel trial",onStateChange: (listener) =>useUserStore.subscribe((s) => s.user, listener),- description: `Cancel your subscription to stop all future charges permanently. You will automatically be downgraded to the Free plan at the end of your billing period.--Canceled subscriptions cannot be resumed/renewed which is why it is recommended that you disable auto renew instead.`,+ description: `Cancel your trial to stop all future charges permanently. You will be immediately downgraded to the Free plan.`,isHidden: () => {const user = useUserStore.getState().user;const status = user?.subscription.status;return (user?.subscription.provider !== SubscriptionProvider.PADDLE ||!isUserSubscribed(user) ||- status === SubscriptionStatusEnum.CANCELED ||- status === SubscriptionStatusEnum.EXPIRED+ status !== SubscriptionStatusEnum.TRIAL);},components: [{type: "button",title: "Cancel",+ variant: "error",async action() {- const cancelSubscription = await ConfirmDialog.show({- title: "Cancel subscription?",+ const cancelTrial = await ConfirmDialog.show({+ title: "Cancel trial?",message:- "Cancel your subscription to stop all future charges permanently. You will automatically be downgraded to the Free plan at the end of your billing period.",+ "Cancel your trial to stop all future charges permanently. You will be immediately downgraded to the Free plan.",negativeButtonText: "No",positiveButtonText: "Yes"});- if (cancelSubscription) {+ if (cancelTrial) {await TaskManager.startTask({type: "modal",- title: "Cancelling your subscription",+ title: "Cancelling your trial",subtitle: "Please wait...",action: () => db.subscriptions.cancel()}).catch((e) => showToast("error", e.message)).then(() =>- showToast("success", "Your subscription has been canceled.")+ showToast("success", "Your trial has been canceled."));}- },- variant: "error"+ }}]},@@ -187,19 +221,20 @@ Canceled subscriptions cannot be resumed/renewed which is why it is recommendedpositiveButtonText: "Yes"});if (refundSubscription) {- await TaskManager.startTask({+ const result = await TaskManager.startTask({type: "modal",title: "Requesting refund for your subscription",subtitle: "Please wait...",action: () => db.subscriptions.refund()- })- .catch((e) => showToast("error", e.message))- .then(() =>- showToast(- "success",- "Your refund request has been sent. If you are eligible for a refund, you'll receive your funds within 24 hours. Please wait at least 24 hours before reaching out to us in case there is any problem."- )- );+ });+ if (result instanceof Error) {+ showToast("error", result.message);+ return;+ }+ showToast(+ "success",+ "Your refund request has been sent. If you are eligible for a refund, you'll receive your funds within 24 hours. Please wait at least 24 hours before reaching out to us in case there is any problem."+ );}},variant: "error"diff --git a/apps/web/src/dialogs/settings/types.ts b/apps/web/src/dialogs/settings/types.tsindex 1152a77fe..26a1a572b 100644--- a/apps/web/src/dialogs/settings/types.ts+++ b/apps/web/src/dialogs/settings/types.ts@@ -70,7 +70,7 @@ export type SettingsGroup = {header: string | ((props: any) => JSX.Element | null);isHidden?: () => boolean;onStateChange?: (- listener: (state: unknown, prevState: unknown) => void+ listener: (state: any, prevState: unknown) => void) => () => void;onRender?: () => void | Promise<void>;};@@ -79,9 +79,9 @@ export type Setting = {key: string;keywords?: string[];title: string;- description?: string | ((state?: unknown) => string);- components: SettingComponent[] | ((state?: unknown) => SettingComponent[]);- isHidden?: (state?: unknown) => boolean;+ description?: string | ((state?: any) => string);+ components: SettingComponent[] | ((state?: any) => SettingComponent[]);+ isHidden?: (state?: any) => boolean;onStateChange?: (listener: (state: unknown, prevState: unknown) => void) => () => void;@@ -126,7 +126,7 @@ export type ToggleSettingComponent = BaseSettingComponent<"toggle"> & {};export type DropdownSettingComponent = BaseSettingComponent<"dropdown"> & {- options: { value: string | number; title: string }[];+ options: { value: string | number; title: string; disabled?: boolean }[];selectedOption: () => string | number | Promise<string | number>;onSelectionChanged: (value: string) => void | Promise<void>;};diff --git a/apps/web/src/hooks/use-is-user-premium.ts b/apps/web/src/hooks/use-is-user-premium.tsindex d805e9c66..448053620 100644--- a/apps/web/src/hooks/use-is-user-premium.ts+++ b/apps/web/src/hooks/use-is-user-premium.ts@@ -17,7 +17,12 @@ You should have received a copy of the GNU General Public Licensealong with this program. If not, see <http://www.gnu.org/licenses/>.*/-import { SubscriptionPlan, SubscriptionType, User } from "@notesnook/core";+import {+ SubscriptionPlan,+ SubscriptionStatus,+ SubscriptionType,+ User+} from "@notesnook/core";import { SUBSCRIPTION_STATUS } from "../common/constants";import {useStore as useUserStore,@@ -43,14 +48,44 @@ export function isUserPremium(user?: User) {);}+export function isActiveSubscription(user?: User) {+ user = user || userstore.get().user;+ if (!user) return false;++ const { status } = user?.subscription || {};++ return (+ status === SubscriptionStatus.ACTIVE || status === SubscriptionStatus.TRIAL+ );+}export function isUserSubscribed(user?: User) {- if (!user) user = userstore.get().user;+ user = user || userstore.get().user;if (!user) return false;- const { type, plan } = user.subscription || {};+ const { type, expiry, plan, status } = user?.subscription || {};+ if (!expiry) return false;+ const isLegacyPro =+ type !== undefined &&+ (type === SubscriptionType.BETA ||+ type === SubscriptionType.PREMIUM ||+ type === SubscriptionType.PREMIUM_CANCELED ||+ type === SubscriptionType.TRIAL);++ if (isLegacyPro) {+ return (+ type === SubscriptionType.PREMIUM ||+ type === SubscriptionType.PREMIUM_CANCELED+ );+ }+return (- (type === SubscriptionType.PREMIUM ||- type === SubscriptionType.PREMIUM_CANCELED) &&- plan !== SubscriptionPlan.FREE+ plan !== SubscriptionPlan.FREE && status !== SubscriptionStatus.EXPIRED);++ // const { type, plan } = user.subscription || {};+ // return (+ // (type === SubscriptionType.TRIAL || type === SubscriptionType.PREMIUM ||+ // type === SubscriptionType.PREMIUM_CANCELED) &&+ // plan !== SubscriptionPlan.FREE+ // );}diff --git a/packages/core/src/api/index.ts b/packages/core/src/api/index.tsindex 4a1da7f50..1261bd66f 100644--- a/packages/core/src/api/index.ts+++ b/packages/core/src/api/index.ts@@ -450,6 +450,7 @@ class Database {hosts.SUBSCRIPTIONS_HOST || Hosts.SUBSCRIPTIONS_HOST;Hosts.ISSUES_HOST = hosts.ISSUES_HOST || Hosts.ISSUES_HOST;Hosts.MONOGRAPH_HOST = hosts.MONOGRAPH_HOST || Hosts.MONOGRAPH_HOST;+ Hosts.NOTESNOOK_HOST = hosts.NOTESNOOK_HOST || Hosts.NOTESNOOK_HOST;}version() {diff --git a/packages/core/src/api/pricing.ts b/packages/core/src/api/pricing.tsindex b332238dd..7fa45a310 100644--- a/packages/core/src/api/pricing.ts+++ b/packages/core/src/api/pricing.ts@@ -18,6 +18,7 @@ along with this program. If not, see <http://www.gnu.org/licenses/>.*/import { SubscriptionPlan, SubscriptionPlanId } from "../types.js";+import hosts from "../utils/constants.js";import http from "../utils/http.js";export type SKUResponse = {@@ -57,7 +58,6 @@ export interface Plan {country: string;}-const BASE_URL = `https://notesnook.com/api/v2/prices`;export class Pricing {static sku(platform: "android" | "ios" | "web",@@ -65,11 +65,14 @@ export class Pricing {plan: SubscriptionPlanId): Promise<SKUResponse> {return http.get(- `${BASE_URL}/skus?platform=${platform}&period=${period}&plan=${plan}`+ `${hosts.NOTESNOOK_HOST}/api/v2/prices/skus?platform=${platform}&period=${period}&plan=${plan}`);}- static products(): Promise<Plan[]> {- return http.get(`${BASE_URL}/products`);+ static products(trialsAvailed?: SubscriptionPlan[]): Promise<Plan[]> {+ const url = new URL(`${hosts.NOTESNOOK_HOST}/api/v2/prices/products`);+ if (trialsAvailed)+ url.searchParams.set("trialsAvailed", trialsAvailed.join(","));+ return http.get(url.toString());}}diff --git a/packages/core/src/api/subscriptions.ts b/packages/core/src/api/subscriptions.tsindex aaf395d01..5f91e4d5d 100644--- a/packages/core/src/api/subscriptions.ts+++ b/packages/core/src/api/subscriptions.ts@@ -90,12 +90,12 @@ export default class Subscriptions {);}- async refund() {+ async refund(reason?: string) {const token = await this.db.tokenManager.getAccessToken();if (!token) return;await http.post(`${hosts.SUBSCRIPTIONS_HOST}/subscriptions/v2/refund`,- null,+ { reason },token);}@@ -145,8 +145,32 @@ export default class Subscriptions {async checkoutUrl(plan: SubscriptionPlan, period: Period) {const user = await this.db.user.getUser();if (!user) return;- return `https://notesnook.com/api/v2/checkout?userId=${user.id}&email=${+ return `${hosts.NOTESNOOK_HOST}/api/v2/checkout?userId=${user.id}&email=${user.email}&plan=${planToId(plan)}&period=${period}`;}++ async preview(productId: string) {+ const token = await this.db.tokenManager.getAccessToken();+ if (!token) return;+ return http.post(+ `${hosts.SUBSCRIPTIONS_HOST}/subscriptions/v2/preview`,+ {+ productId: productId+ },+ token+ );+ }++ async change(productId: string) {+ const token = await this.db.tokenManager.getAccessToken();+ if (!token) return;+ return http.post(+ `${hosts.SUBSCRIPTIONS_HOST}/subscriptions/v2/change`,+ {+ productId: productId+ },+ token+ );+ }}diff --git a/packages/core/src/types.ts b/packages/core/src/types.tsindex 005056577..d55d3d378 100644--- a/packages/core/src/types.ts+++ b/packages/core/src/types.ts@@ -617,6 +617,7 @@ export type User = {type: SubscriptionType;plan: SubscriptionPlan;status: SubscriptionStatus;+ trialsAvailed?: SubscriptionPlan[];updateURL: string | null;};};diff --git a/packages/core/src/utils/constants.ts b/packages/core/src/utils/constants.tsindex 34e053f45..8eb0bffb0 100644--- a/packages/core/src/utils/constants.ts+++ b/packages/core/src/utils/constants.ts@@ -48,7 +48,12 @@ export const hosts = {ISSUES_HOST: isProduction()? "https://issues.streetwriters.co": "http://localhost:2624",- MONOGRAPH_HOST: isProduction() ? "https://monogr.ph" : "http://localhost:6264"+ MONOGRAPH_HOST: isProduction()+ ? "https://monogr.ph"+ : "http://localhost:6264",+ NOTESNOOK_HOST: isProduction()+ ? "https://notesnook.com"+ : "http://localhost:8787"};export default hosts;