Skip to content

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

mobile: handle web payments

Ammar Ahmed1a544754efa0
diff --git a/apps/mobile/app/components/premium/paywall.tsx b/apps/mobile/app/components/premium/paywall.tsx
index 157ca0bf3..767090387 100644
--- a/apps/mobile/app/components/premium/paywall.tsx
+++ b/apps/mobile/app/components/premium/paywall.tsx
@@ -52,6 +52,7 @@ import { Button } from "../ui/button";
import { IconButton } from "../ui/icon-button";
import Heading from "../ui/typography/heading";
import Paragraph from "../ui/typography/paragraph";
+import { db } from "../../common/database";
const Steps = {
select: 1,
@@ -97,11 +98,7 @@ const PayWall = (props: NavigationProps<"PayWall">) => {
);
const [ctaButtonVisible, setCtaButtonVisible] = useState(false);
const [step, setStep] = useState(
- routeParams.state
- ? isGithubRelease
- ? Steps.buyWeb
- : Steps.buy
- : Steps.select
+ routeParams.state ? Steps.buy : Steps.select
);
const isFocused = useNavigationFocus(props.navigation, {
onBlur: () => true,
@@ -518,7 +515,11 @@ After trying all the privacy security oriented note taking apps, for the price a
planId={pricingPlans.currentPlan?.id as string}
productId={
annualBilling
- ? `notesnook.${pricingPlans?.currentPlan?.id as string}.yearly`
+ ? Config.GITHUB_RELEASE === "true"
+ ? "yearly"
+ : `notesnook.${pricingPlans?.currentPlan?.id as string}.yearly`
+ : Config.GITHUB_RELEASE === "true"
+ ? "monthly"
: `notesnook.${pricingPlans?.currentPlan?.id as string}.monthly`
}
canActivateTrial={pricingPlans.userCanRequestTrial}
@@ -537,7 +538,11 @@ After trying all the privacy security oriented note taking apps, for the price a
>
<WebView
source={{
- uri: webUrl
+ html: `
+ <button onclick="function() { window.ReactNativeWebView.postMessage(JSON.stringify({
+ success:true
+ })) }" />
+ `
}}
/>
</View>
@@ -878,11 +883,10 @@ const PricingPlanCard = ({
annualBilling
);
- const DefaultPricing = {
- essential: "$2.99",
- pro: "$5.99",
- believer: "$6.99"
- };
+ const WebPlan = pricingPlans?.getWebPlan(
+ plan.id,
+ annualBilling ? "yearly" : "monthly"
+ );
return (
<TouchableOpacity
@@ -999,7 +1003,7 @@ const PricingPlanCard = ({
{isFreePlan
? "0.00"
: price ||
- DefaultPricing[plan.id as keyof typeof DefaultPricing]}{" "}
+ `${WebPlan?.price.currency} ${WebPlan?.price.gross}`}{" "}
<Paragraph>/month</Paragraph>
</Paragraph>
diff --git a/apps/mobile/app/components/sheets/buy-plan/index.tsx b/apps/mobile/app/components/sheets/buy-plan/index.tsx
index e3f9ac21a..626fe07c1 100644
--- a/apps/mobile/app/components/sheets/buy-plan/index.tsx
+++ b/apps/mobile/app/components/sheets/buy-plan/index.tsx
@@ -18,7 +18,7 @@ along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
import { useThemeColors } from "@notesnook/theme";
import dayjs from "dayjs";
-import React from "react";
+import React, { useState } from "react";
import { ScrollView, Text, TouchableOpacity, View } from "react-native";
import * as RNIap from "react-native-iap";
import Icon from "react-native-vector-icons/MaterialCommunityIcons";
@@ -30,7 +30,11 @@ import { DefaultAppStyles } from "../../../utils/styles";
import { Button } from "../../ui/button";
import Heading from "../../ui/typography/heading";
import Paragraph from "../../ui/typography/paragraph";
-
+import Config from "react-native-config";
+import { Plan } from "@notesnook/core";
+import { db } from "../../../common/database";
+import { WebView } from "react-native-webview";
+const isGithubRelease = Config.GITHUB_RELEASE === "true";
export const BuyPlan = (props: {
planId: string;
productId: string;
@@ -40,6 +44,7 @@ export const BuyPlan = (props: {
}) => {
const { colors } = useThemeColors();
const insets = useGlobalSafeAreaInsets();
+ const [checkoutUrl, setCheckoutUrl] = useState<string>();
const pricingPlans = usePricingPlans({
planId: props.planId,
productId: props.productId,
@@ -54,10 +59,58 @@ export const BuyPlan = (props: {
0,
true
);
- const is5YearPlanSelected =
- pricingPlans.selectedProduct?.productId.includes("5year");
+ const is5YearPlanSelected = (
+ isGithubRelease
+ ? (pricingPlans.selectedProduct as Plan)?.period
+ : (pricingPlans.selectedProduct as RNIap.Product)?.productId
+ )?.includes("5");
- return (
+ return checkoutUrl ? (
+ <View
+ style={{
+ flex: 1
+ }}
+ >
+ <WebView
+ source={{
+ html: `<!DOCTYPE html>
+<html lang="en">
+ <head>
+ <meta charset="UTF-8" />
+ <meta name="viewport" content="width=device-width, initial-scale=1.0" />
+ <title>Basic HTML Page with Button</title>
+ </head>
+ <body>
+ <h1>Welcome to My Page</h1>
+ <p>This is a simple example of an HTML page with a button.</p>
+
+ <button
+ type="button"
+ onclick="window.ReactNativeWebView.postMessage(JSON.stringify({
+ success:true
+ }));"
+ >
+ Click Me!
+ </button>
+ </body>
+</html>
+`
+ }}
+ onMessage={(message) => {
+ const data = JSON.parse(message.nativeEvent.data);
+ if (data.success) {
+ props.goNext();
+ }
+ return;
+ }}
+ domStorageEnabled
+ javaScriptEnabled
+ style={{
+ flex: 1
+ }}
+ />
+ </View>
+ ) : (
<ScrollView
contentContainerStyle={{
marginTop: DefaultAppStyles.GAP_VERTICAL
@@ -72,11 +125,19 @@ export const BuyPlan = (props: {
}}
>
{[
- `notesnook.${props.planId}.yearly`,
- `notesnook.${props.planId}.monthly`,
+ Config.GITHUB_RELEASE === "true"
+ ? "yearly"
+ : `notesnook.${props.planId}.yearly`,
+ Config.GITHUB_RELEASE === "true"
+ ? "monthly"
+ : `notesnook.${props.planId}.monthly`,
...(props.planId === "essential"
? []
- : [`notesnook.${props.planId}.5year`])
+ : [
+ Config.GITHUB_RELEASE === "true"
+ ? "5-year"
+ : `notesnook.${props.planId}.5year`
+ ])
].map((item) => (
<ProductItem
key={item}
@@ -103,7 +164,7 @@ export const BuyPlan = (props: {
color: colors.primary.accent
}}
>
- ({billingDuration.duration} days free)
+ ({billingDuration?.duration} days free)
</Text>
) : null}
</Heading>
@@ -130,7 +191,9 @@ export const BuyPlan = (props: {
>
<Paragraph color={colors.secondary.paragraph}>
Due{" "}
- {dayjs().add(billingDuration.duration, "day").format("DD MMMM")}
+ {dayjs()
+ .add(billingDuration?.duration || 0, "day")
+ .format("DD MMMM")}
</Paragraph>
<Paragraph color={colors.secondary.paragraph}>
{pricingPlans.getStandardPrice(
@@ -156,7 +219,7 @@ export const BuyPlan = (props: {
"Pay once and use for 5 years"
]
: [
- `Free ${billingDuration.duration} day trial, cancel any time`,
+ `Free ${billingDuration?.duration} day trial, cancel any time`,
"Google will remind you before your trial ends"
]
).map((item) => (
@@ -184,13 +247,23 @@ export const BuyPlan = (props: {
type="accent"
loading={pricingPlans.loading}
title={
- pricingPlans.selectedProduct?.productId.includes("5year")
+ is5YearPlanSelected
? "Purchase"
: pricingPlans?.userCanRequestTrial
? "Subscribe and start free trial"
: "Subscribe"
}
- onPress={() => {
+ onPress={async () => {
+ if (isGithubRelease) {
+ setCheckoutUrl(
+ await db.subscriptions.checkoutUrl(
+ (pricingPlans.selectedProduct as Plan).plan,
+ (pricingPlans.selectedProduct as Plan).period
+ )
+ );
+ return;
+ }
+
const offerToken = pricingPlans.getOfferTokenAndroid(
pricingPlans.selectedProduct as RNIap.SubscriptionAndroid,
0
@@ -256,10 +329,27 @@ const ProductItem = (props: {
const { colors } = useThemeColors();
const product =
props.pricingPlans?.currentPlan?.subscriptions?.[props.productId] ||
- props.pricingPlans?.currentPlan?.products?.[props.productId];
- const isAnnual = product?.productId.includes("yearly");
- const isSelected =
- product?.productId === props.pricingPlans.selectedProduct?.productId;
+ props.pricingPlans?.currentPlan?.products?.[props.productId] ||
+ props.pricingPlans?.getWebPlan(
+ props.pricingPlans?.currentPlan?.id as string,
+ props.productId as "monthly" | "yearly"
+ );
+
+ const isAnnual = isGithubRelease
+ ? (product as Plan)?.period === "yearly"
+ : (product as RNIap.Subscription)?.productId.includes("yearly");
+
+ const isSelected = isGithubRelease
+ ? (product as Plan)?.period ===
+ (props.pricingPlans.selectedProduct as Plan)?.period
+ : (product as RNIap.Subscription)?.productId ===
+ (props.pricingPlans.selectedProduct as RNIap.Subscription)?.productId;
+
+ const is5YearProduct = (
+ isGithubRelease
+ ? (product as Plan)?.period
+ : (product as RNIap.Product)?.productId
+ )?.includes("5");
return (
<TouchableOpacity
@@ -270,7 +360,11 @@ const ProductItem = (props: {
activeOpacity={0.9}
onPress={() => {
if (!product) return;
- props.pricingPlans.selectProduct(product?.productId);
+ props.pricingPlans.selectProduct(
+ isGithubRelease
+ ? (product as Plan)?.period
+ : (product as RNIap.Subscription)?.productId
+ );
}}
>
<Icon
@@ -288,12 +382,13 @@ const ProductItem = (props: {
<Heading size={AppFontSize.md}>
{isAnnual
? "Yearly"
- : product?.productId.includes("5year")
+ : is5YearProduct
? "5 year plan (One time purchase)"
: "Monthly"}
</Heading>
- {isAnnual ? (
+ {(isAnnual && !isGithubRelease) ||
+ (isGithubRelease && (product as Plan)?.discount?.amount) ? (
<View
style={{
backgroundColor: colors.static.red,
@@ -305,11 +400,13 @@ const ProductItem = (props: {
>
<Heading color={colors.static.white} size={AppFontSize.xs}>
Best value -{" "}
- {props.pricingPlans.compareProductPrice(
- props.pricingPlans.currentPlan?.id as string,
- `notesnook.${props.pricingPlans.currentPlan?.id}.yearly`,
- `notesnook.${props.pricingPlans.currentPlan?.id}.monthly`
- )}
+ {isGithubRelease
+ ? (product as Plan).discount?.amount
+ : props.pricingPlans.compareProductPrice(
+ props.pricingPlans.currentPlan?.id as string,
+ `notesnook.${props.pricingPlans.currentPlan?.id}.yearly`,
+ `notesnook.${props.pricingPlans.currentPlan?.id}.monthly`
+ )}
% Off
</Heading>
</View>
@@ -317,17 +414,20 @@ const ProductItem = (props: {
</View>
<Paragraph size={AppFontSize.md}>
- {isAnnual || product?.productId.includes("5year")
+ {isAnnual || is5YearProduct
? `${props.pricingPlans.getPrice(
product as RNIap.Subscription,
- props.pricingPlans.hasTrialOffer(undefined, product?.productId)
+ props.pricingPlans.hasTrialOffer(
+ undefined,
+ (product as RNIap.Subscription)?.productId
+ )
? 1
: 0,
isAnnual
)}/month`
: null}
- {!isAnnual && !product?.productId.includes("5year")
+ {!isAnnual && !is5YearProduct
? `${props.pricingPlans.getStandardPrice(
product as RNIap.Subscription
)}/month`
diff --git a/apps/mobile/app/components/sheets/paywall/index.tsx b/apps/mobile/app/components/sheets/paywall/index.tsx
index 2b99044db..228d8fe53 100644
--- a/apps/mobile/app/components/sheets/paywall/index.tsx
+++ b/apps/mobile/app/components/sheets/paywall/index.tsx
@@ -2,6 +2,7 @@ import { FeatureId, FeatureResult } from "@notesnook/common";
import { useThemeColors } from "@notesnook/theme";
import { useEffect, useState } from "react";
import { View } from "react-native";
+import Config from "react-native-config";
import usePricingPlans from "../../../hooks/use-pricing-plans";
import {
eSendEvent,
@@ -18,8 +19,7 @@ import AppIcon from "../../ui/AppIcon";
import { Button } from "../../ui/button";
import Heading from "../../ui/typography/heading";
import Paragraph from "../../ui/typography/paragraph";
-import { BuyPlan } from "../buy-plan";
-
+const isGithubRelease = Config.GITHUB_RELEASE === "true";
const INDEX_TO_PLAN = {
1: "essential",
2: "pro",
@@ -48,7 +48,9 @@ export default function PaywallSheet<Tid extends FeatureId>(props: {
if (!plan) return;
pricingPlans.selectPlan(plan?.id);
pricingPlans.selectProduct(
- plan?.subscriptionSkuList?.find((sku) => sku.includes("year"))
+ isGithubRelease
+ ? "yearly"
+ : plan?.subscriptionSkuList?.find((sku) => sku.includes("year"))
);
}, []);
@@ -64,180 +66,148 @@ export default function PaywallSheet<Tid extends FeatureId>(props: {
paddingBottom: DefaultAppStyles.GAP
}}
>
- {step === Steps.Select ? (
- <>
- <View
- style={{
- width: "100%",
- paddingHorizontal: DefaultAppStyles.GAP,
- gap: DefaultAppStyles.GAP_VERTICAL
- }}
- >
- {/* <View
+ <>
+ <View
style={{
- backgroundColor: colors.secondary.background,
- borderRadius: 10,
- height: 150,
width: "100%",
- justifyContent: "center",
- alignItems: "center"
+ paddingHorizontal: DefaultAppStyles.GAP,
+ gap: DefaultAppStyles.GAP_VERTICAL
}}
>
- <Heading>{pricingPlans.currentPlan?.name}</Heading>
- </View> */}
+ <Paragraph>
+ <AppIcon
+ name="crown"
+ size={AppFontSize.md}
+ color={colors.static.orange}
+ />{" "}
+ Upgrade plan to {pricingPlans.currentPlan?.name} to use this
+ feature.
+ </Paragraph>
+
+ <View
+ style={{
+ gap: DefaultAppStyles.GAP_VERTICAL_SMALL,
+ width: "100%"
+ }}
+ >
+ <Heading>Try it for free</Heading>
- <Paragraph>
- <AppIcon
- name="crown"
- size={AppFontSize.md}
- color={colors.static.orange}
- />{" "}
- Upgrade plan to {pricingPlans.currentPlan?.name} to use this
- feature.
- </Paragraph>
+ <Heading size={AppFontSize.sm}>Get this and so much more:</Heading>
<View
style={{
- gap: DefaultAppStyles.GAP_VERTICAL_SMALL,
- width: "100%"
+ gap: DefaultAppStyles.GAP_SMALL,
+ flexDirection: "row"
}}
>
- <Heading>Try it for free</Heading>
-
- <Heading size={AppFontSize.sm}>
- Get this and so much more:
- </Heading>
-
- <View
+ <AppIcon name="cloud" size={AppFontSize.xxl} />
+ <Paragraph
style={{
- gap: DefaultAppStyles.GAP_SMALL,
- flexDirection: "row"
+ flexShrink: 1
}}
>
- <AppIcon name="cloud" size={AppFontSize.xxl} />
- <Paragraph
- style={{
- flexShrink: 1
- }}
- >
- <Heading size={AppFontSize.sm}>25 GB</Heading> cloud storage
- space for storing images and files upto 5 GB every month.
- </Paragraph>
- </View>
+ <Heading size={AppFontSize.sm}>25 GB</Heading> cloud storage
+ space for storing images and files upto 5 GB every month.
+ </Paragraph>
+ </View>
- <View
+ <View
+ style={{
+ gap: DefaultAppStyles.GAP_SMALL,
+ flexDirection: "row"
+ }}
+ >
+ <AppIcon name="lock" size={AppFontSize.xxl} />
+ <Paragraph
style={{
- gap: DefaultAppStyles.GAP_SMALL,
- flexDirection: "row"
+ flexShrink: 1
}}
>
- <AppIcon name="lock" size={AppFontSize.xxl} />
- <Paragraph
- style={{
- flexShrink: 1
- }}
- >
- <Heading size={AppFontSize.sm}>App lock</Heading> for locking
- your notes as soon as app enters background
- </Paragraph>
- </View>
+ <Heading size={AppFontSize.sm}>App lock</Heading> for locking
+ your notes as soon as app enters background
+ </Paragraph>
+ </View>
- <View
+ <View
+ style={{
+ gap: DefaultAppStyles.GAP_SMALL,
+ flexDirection: "row"
+ }}
+ >
+ <AppIcon name="vector-link" size={AppFontSize.xxl} />
+ <Paragraph
style={{
- gap: DefaultAppStyles.GAP_SMALL,
- flexDirection: "row"
+ flexShrink: 1
}}
>
- <AppIcon name="vector-link" size={AppFontSize.xxl} />
- <Paragraph
- style={{
- flexShrink: 1
- }}
- >
- Use advanced note taking features like{" "}
- <Heading size={AppFontSize.sm}>
- tables, outlines, block level note linking
- </Heading>{" "}
- and much more.
- </Paragraph>
- </View>
+ Use advanced note taking features like{" "}
+ <Heading size={AppFontSize.sm}>
+ tables, outlines, block level note linking
+ </Heading>{" "}
+ and much more.
+ </Paragraph>
</View>
</View>
+ </View>
- <View
+ <View
+ style={{
+ width: "100%",
+ paddingHorizontal: DefaultAppStyles.GAP
+ }}
+ >
+ <Paragraph
style={{
- width: "100%",
- paddingHorizontal: DefaultAppStyles.GAP
+ marginVertical: 10
}}
+ size={AppFontSize.xs}
>
- <Paragraph
- style={{
- marginVertical: 10
- }}
- size={AppFontSize.xs}
- >
- <Heading size={AppFontSize.xs}>Cancel anytime.</Heading> Google
- will remind you 2 days before your trial ends.
- </Paragraph>
-
- <Button
- type="accent"
- title="Upgrade"
- style={{
- marginVertical: DefaultAppStyles.GAP_VERTICAL,
- width: "100%"
- }}
- onPress={() => {
- if (!useUserStore.getState().user) {
- eSendEvent(eCloseSheet);
- Navigation.navigate("Auth", {
- mode: AuthMode.login
- });
- return;
- }
- setStep(Steps.Buy);
- }}
- />
- </View>
+ <Heading size={AppFontSize.xs}>Cancel anytime.</Heading> Google will
+ remind you 2 days before your trial ends.
+ </Paragraph>
<Button
- type="plain"
- title="Explore all plans"
- icon="arrow-right"
- iconPosition="right"
+ type="accent"
+ title="Upgrade"
+ style={{
+ marginVertical: DefaultAppStyles.GAP_VERTICAL,
+ width: "100%"
+ }}
onPress={() => {
eSendEvent(eCloseSheet);
+ if (!useUserStore.getState().user) {
+ Navigation.navigate("Auth", {
+ mode: AuthMode.login
+ });
+ return;
+ }
Navigation.navigate("PayWall", {
- context: useUserStore.getState().user
- ? "logged-in"
- : "logged-out"
+ context: "logged-in",
+ state: {
+ planId: pricingPlans.currentPlan?.id,
+ productId: isGithubRelease
+ ? "yearly"
+ : (pricingPlans.selectProduct as any).productId,
+ billingType: "annual"
+ }
});
}}
/>
- </>
- ) : null}
-
- {pricingPlans.currentPlan &&
- pricingPlans.selectedProduct &&
- step === Steps.Buy ? (
- <>
- <View
- style={{
- width: "100%",
- paddingHorizontal: DefaultAppStyles.GAP
- }}
- >
- <Heading>{pricingPlans.currentPlan.name} plan</Heading>
- <Paragraph>{pricingPlans.currentPlan.description}</Paragraph>
- </View>
- <BuyPlan
- planId={pricingPlans.currentPlan?.id}
- productId={pricingPlans.selectedProduct?.productId}
- goBack={() => {}}
- goNext={() => {}}
- />
- </>
- ) : null}
+ </View>
+
+ <Button
+ type="plain"
+ title="Explore all plans"
+ icon="arrow-right"
+ iconPosition="right"
+ onPress={() => {
+ eSendEvent(eCloseSheet);
+ Navigation.navigate("PayWall", {
+ context: useUserStore.getState().user ? "logged-in" : "logged-out"
+ });
+ }}
+ />
+ </>
</View>
);
}
diff --git a/apps/mobile/app/components/sheets/plan-limits/index.tsx b/apps/mobile/app/components/sheets/plan-limits/index.tsx
index 34387e1cd..d98affe82 100644
--- a/apps/mobile/app/components/sheets/plan-limits/index.tsx
+++ b/apps/mobile/app/components/sheets/plan-limits/index.tsx
@@ -59,34 +59,15 @@ export function PlanLimits() {
{getFeature(item.id).title}
</Paragraph>
<Paragraph size={AppFontSize.sm}>
- {item.id === "storage"
+ {item.total === Infinity
+ ? "Unlimited"
+ : item.id === "storage"
? `${formatBytes(item.used)}/${formatBytes(
item.total
)} ${strings.used()}`
: `${item.used}/${item.total} ${strings.used()}`}
</Paragraph>
</View>
- <View
- style={{
- backgroundColor: colors.secondary.background,
- width: "100%",
- height: 5,
- borderRadius: 10
- }}
- >
- <View
- style={{
- backgroundColor: colors.primary.accent,
- height: 5,
- width: `${
- ((item.used > item.total ? item.total : item.used) /
- item.total) *
- 100
- }%`,
- borderRadius: 10
- }}
- />
- </View>
</View>
))}
diff --git a/apps/mobile/app/hooks/use-pricing-plans.ts b/apps/mobile/app/hooks/use-pricing-plans.ts
index 80d240930..2a33fedd2 100644
--- a/apps/mobile/app/hooks/use-pricing-plans.ts
+++ b/apps/mobile/app/hooks/use-pricing-plans.ts
@@ -16,14 +16,15 @@ 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 { Plan } from "@notesnook/core";
import { useEffect, useState } from "react";
import { Platform } from "react-native";
+import Config from "react-native-config";
import * as RNIap from "react-native-iap";
import { DatabaseLogger, db } from "../common/database";
import PremiumService from "../services/premium";
import { useSettingStore } from "../stores/use-setting-store";
import { useUserStore } from "../stores/use-user-store";
-
function numberWithCommas(x: string) {
const parts = x.toString().split(".");
parts[0] = parts[0].replace(/\B(?=(\d{3})+(?!\d))/g, ",");
@@ -140,8 +141,13 @@ type PricingPlansOptions = {
productId?: string;
onBuy?: () => void;
};
-
+const planIdToIndex = (planId: string) => {
+ const planIndex = planId === "essential" ? 1 : planId === "pro" ? 2 : 3;
+ return planIndex;
+};
+let WebPlanCache: Plan[];
const usePricingPlans = (options?: PricingPlansOptions) => {
+ const isGithubRelease = Config.GITHUB_RELEASE === "true";
const user = useUserStore((state) => state.user);
const [currentPlan, setCurrentPlan] = useState<string>(
options?.planId || pricingPlans[2].id
@@ -155,8 +161,14 @@ const usePricingPlans = (options?: PricingPlansOptions) => {
const [isPromoOffer, setIsPromoOffer] = useState(false);
const [cancelPromo, setCancelPromo] = useState(false);
const [userCanRequestTrial, setUserCanRequestTrial] = useState(false);
+ const [webPricingPlans, setWebPricingPlans] = useState<Plan[]>([]);
const getProduct = (planId: string, skuId: string) => {
+ if (isGithubRelease)
+ return webPricingPlans.find(
+ (plan) => planIdToIndex(planId) === plan.plan && skuId === plan.period
+ );
+
return (
plans.find((p) => p.id === planId)?.subscriptions?.[skuId] ||
plans.find((p) => p.id === planId)?.products?.[skuId]
@@ -164,6 +176,10 @@ const usePricingPlans = (options?: PricingPlansOptions) => {
};
const getProductAndroid = (planId: string, skuId: string) => {
+ if (isGithubRelease)
+ return webPricingPlans.find(
+ (plan) => planIdToIndex(planId) === plan.plan && skuId === plan.period
+ );
return getProduct(planId, skuId) as RNIap.SubscriptionAndroid;
};
@@ -209,6 +225,13 @@ const usePricingPlans = (options?: PricingPlansOptions) => {
});
setPlans([...pricingPlans]);
setUserCanRequestTrial(hasTrialOffer());
+ if (Config.GITHUB_RELEASE === "true") {
+ try {
+ const products = WebPlanCache || (await db.pricing.products());
+ WebPlanCache = products;
+ setWebPricingPlans(products);
+ } catch (e) {}
+ }
setLoadingPlans(false);
};
@@ -243,10 +266,21 @@ const usePricingPlans = (options?: PricingPlansOptions) => {
loadPlans().then(() => loadPromoOffer());
}, [options?.promoOffer, cancelPromo]);
- function getLocalizedPrice(product: RNIap.Subscription | RNIap.Product) {
+ function getLocalizedPrice(
+ product: RNIap.Subscription | RNIap.Product | Plan
+ ) {
if (!product) return;
if (Platform.OS === "android") {
+ if (isGithubRelease)
+ return `${(product as Plan).price.currency} ${
+ (product as Plan).period === "yearly"
+ ? ((product as Plan).price.gross / 12).toFixed(2)
+ : (product as Plan).period === "5-year"
+ ? ((product as Plan).price.gross / (12 * 5)).toFixed(2)
+ : (product as Plan).price.gross
+ }`;
+
const pricingPhaseListItem = (product as RNIap.SubscriptionAndroid)
?.subscriptionOfferDetails?.[0]?.pricingPhases?.pricingPhaseList?.[1];
@@ -272,7 +306,7 @@ const usePricingPlans = (options?: PricingPlansOptions) => {
product: RNIap.Subscription,
androidOfferToken?: string
) {
- if (loading || !product) return;
+ if (loading || !product || isGithubRelease) return;
setLoading(true);
try {
if (!user) {
@@ -366,9 +400,13 @@ const usePricingPlans = (options?: PricingPlansOptions) => {
}
const getBillingPeriod = (
- product: RNIap.Subscription,
+ product: RNIap.Subscription | Plan,
offerIndex: number
) => {
+ if (isGithubRelease) {
+ return (product as Plan).period;
+ }
+
if (Platform.OS === "android") {
const period = (product as RNIap.SubscriptionAndroid)
?.subscriptionOfferDetails?.[offerIndex]?.pricingPhases
@@ -386,12 +424,21 @@ const usePricingPlans = (options?: PricingPlansOptions) => {
};
const getBillingDuration = (
- product: RNIap.Subscription,
+ product: RNIap.Subscription | Plan,
offerIndex: number,
phaseIndex: number,
trialDurationIos?: boolean
) => {
- if (product.productId.includes("5year")) {
+ if (!product) return;
+
+ if (isGithubRelease) {
+ return {
+ duration: 1,
+ type: (product as Plan).period
+ };
+ }
+
+ if ((product as RNIap.Subscription)?.productId.includes("5year")) {
return {
type: "year",
duration: 5
@@ -520,17 +567,25 @@ const usePricingPlans = (options?: PricingPlansOptions) => {
};
const getPrice = (
- product: RNIap.Subscription | RNIap.Product,
+ product: RNIap.Subscription | RNIap.Product | Plan,
phaseIndex: number,
annualBilling?: boolean
) => {
if (!product) return null;
+ if (isGithubRelease)
+ return `${(product as Plan).price.currency} ${
+ (product as Plan).period === "yearly"
+ ? ((product as Plan).price.gross / 12).toFixed(2)
+ : (product as Plan).period === "5-year"
+ ? ((product as Plan).price.gross / (12 * 5)).toFixed(2)
+ : (product as Plan).price.gross
+ }`;
+
const androidPricingPhase = (product as RNIap.SubscriptionAndroid)
?.subscriptionOfferDetails?.[0].pricingPhases?.pricingPhaseList?.[
phaseIndex
];
- console.log(product as RNIap.Product);
const { localizedPrice, priceSymbol, priceValue } = getPriceParts(
Platform.OS === "android"
@@ -549,7 +604,8 @@ const usePricingPlans = (options?: PricingPlansOptions) => {
: (product as RNIap.SubscriptionIOS).localizedPrice
);
- return !annualBilling && !product?.productId.includes("5year")
+ return !annualBilling &&
+ !(product as RNIap.Subscription)?.productId.includes("5year")
? getLocalizedPrice(product as RNIap.Subscription)
: convertPrice(
priceValue,
@@ -622,204 +678,14 @@ const usePricingPlans = (options?: PricingPlansOptions) => {
return plans.find((p) => p.id === "pro")?.products?.[
`notesnook.${currentPlan}.5year`
];
+ },
+ getWebPlan(plan: string, period: "monthly" | "yearly") {
+ const planIndex = planIdToIndex(plan);
+ return webPricingPlans.find(
+ (plan) => plan.plan === planIndex && plan.period === period
+ );
}
};
};
-// const usePricingPlans = (options?: {
-// promo?: {
-// promoCode?: string;
-// };
-// }) => {
-// const user = useUserStore((state) => state.user);
-// const [product, setProduct] = useState<{
-// type: string;
-// offerType: "monthly" | "yearly";
-// data: RNIap.Subscription;
-// cycleText: string;
-// info: string;
-// }>();
-
-// const [buying, setBuying] = useState(false);
-// const [loading, setLoading] = useState(false);
-// const userCanRequestTrial =
-// user && (!user.subscription || !user.subscription.expiry) ? true : false;
-// const yearlyPlan = usePricing("yearly");
-// const monthlyPlan = usePricing("monthly");
-// const promoCode = options?.promo?.promoCode;
-
-// const getSkus = useCallback(async () => {
-// try {
-// setLoading(true);
-// if (promoCode) {
-// getPromo(promoCode);
-// }
-// setLoading(false);
-// } catch (e) {
-// setLoading(false);
-// console.log("error getting sku", e);
-// }
-// }, [promoCode]);
-
-// const getPromo = async (code: string) => {
-// try {
-// let skuId: string;
-// if (code.startsWith("com.streetwriters.notesnook")) {
-// skuId = code;
-// } else {
-// skuId = await db.offers?.getCode(
-// code.split(":")[0],
-// Platform.OS as "ios" | "android" | "web"
-// );
-// }
-
-// const products = await PremiumService.getProducts();
-// const product = products.find((p) => p.productId === skuId);
-// if (!product) return false;
-// const isMonthly = product.productId.indexOf(".mo") > -1;
-
-// const cycleText = isMonthly
-// ? promoCyclesMonthly[
-// (Platform.OS === "android"
-// ? (product as RNIap.SubscriptionAndroid)
-// .subscriptionOfferDetails[0]?.pricingPhases
-// .pricingPhaseList?.[0].billingCycleCount
-// : parseInt(
-// (product as RNIap.SubscriptionIOS)
-// .introductoryPriceNumberOfPeriodsIOS as string
-// )) as keyof typeof promoCyclesMonthly
-// ]
-// : promoCyclesYearly[
-// (Platform.OS === "android"
-// ? (product as RNIap.SubscriptionAndroid)
-// .subscriptionOfferDetails[0]?.pricingPhases
-// .pricingPhaseList?.[0].billingCycleCount
-// : parseInt(
-// (product as RNIap.SubscriptionIOS)
-// .introductoryPriceNumberOfPeriodsIOS as string
-// )) as keyof typeof promoCyclesYearly
-// ];
-
-// setProduct({
-// type: "promo",
-// offerType: isMonthly ? "monthly" : "yearly",
-// data: product,
-// cycleText: cycleText,
-// info: `Pay ${isMonthly ? "monthly" : "yearly"}, cancel anytime`
-// });
-// return true;
-// } catch (e) {
-// console.log("PROMOCODE ERROR:", code, e);
-// return false;
-// }
-// };
-
-// useEffect(() => {
-// getSkus();
-// }, [getSkus]);
-
-// const buySubscription = async (product: RNIap.Subscription) => {
-// if (buying || !product) return;
-// setBuying(true);
-// try {
-// if (!user) {
-// setBuying(false);
-// return;
-// }
-// useSettingStore.getState().setAppDidEnterBackgroundForAction(true);
-// const androidOfferToken =
-// Platform.OS === "android"
-// ? (product as RNIap.SubscriptionAndroid).subscriptionOfferDetails[0]
-// .offerToken
-// : null;
-
-// DatabaseLogger.info(
-// `Subscription Requested initiated for user ${toUUID(user.id)}`
-// );
-
-// await RNIap.requestSubscription({
-// sku: product?.productId,
-// obfuscatedAccountIdAndroid: user.id,
-// obfuscatedProfileIdAndroid: user.id,
-// appAccountToken: toUUID(user.id),
-// andDangerouslyFinishTransactionAutomaticallyIOS: false,
-// subscriptionOffers: androidOfferToken
-// ? [
-// {
-// offerToken: androidOfferToken,
-// sku: product?.productId
-// }
-// ]
-// : undefined
-// });
-// useSettingStore.getState().setAppDidEnterBackgroundForAction(false);
-// setBuying(false);
-// eSendEvent(eCloseSheet);
-// eSendEvent(eClosePremiumDialog);
-// await sleep(500);
-// presentSheet({
-// title: "Thank you for subscribing!",
-// paragraph:
-// "Your Notesnook Pro subscription will be activated soon. If your account is not upgraded to Notesnook Pro, your money will be refunded to you. In case of any issues, please reach out to us at [email protected]",
-// action: async () => {
-// eSendEvent(eCloseSheet);
-// },
-// icon: "check",
-// actionText: "Continue"
-// });
-// } catch (e) {
-// setBuying(false);
-// console.log(e);
-// }
-// };
-
-// function getStandardPrice(
-// type: "monthly" | "yearly",
-// product: RNIap.Subscription
-// ) {
-// if (!product) return;
-// const productType = type;
-
-// if (Platform.OS === "android") {
-// const pricingPhaseListItem = (product as RNIap.SubscriptionAndroid)
-// ?.subscriptionOfferDetails?.[0]?.pricingPhases?.pricingPhaseList?.[1];
-
-// if (!pricingPhaseListItem) {
-// const product =
-// productType === "monthly"
-// ? monthlyPlan?.product
-// : yearlyPlan?.product;
-// return (product as RNIap.SubscriptionAndroid)
-// ?.subscriptionOfferDetails?.[0]?.pricingPhases?.pricingPhaseList?.[0]
-// ?.formattedPrice;
-// }
-
-// return pricingPhaseListItem?.formattedPrice;
-// } else {
-// const productDefault =
-// productType === "monthly" ? monthlyPlan?.product : yearlyPlan?.product;
-// return (
-// (product as RNIap.SubscriptionIOS)?.localizedPrice ||
-// (productDefault as RNIap.SubscriptionIOS)?.localizedPrice
-// );
-// }
-// }
-
-// return {
-// product,
-// buySubscription,
-// getStandardPrice,
-// loading,
-// userCanRequestTrial,
-// buying,
-// setBuying,
-// setLoading,
-// user,
-// setProduct,
-// monthlyPlan,
-// yearlyPlan,
-// getPromo
-// };
-// };
-
export default usePricingPlans;