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
feat: improve checkout reliability and add regional pricing
thecodrr1db3e1b8d007
diff --git a/apps/web/__e2e__/checkout.test.js b/apps/web/__e2e__/checkout.test.jsindex 23c929e21..02e4fb15d 100644--- a/apps/web/__e2e__/checkout.test.js+++ b/apps/web/__e2e__/checkout.test.js@@ -40,6 +40,7 @@ async function getPrices() {* @param {string} prices*/function roundOffPrices(prices) {+ console.log(prices);return prices.replaceAll(/(\d+.\d+)/gm, (str, price) => {price = parseFloat(price);return isNaN(price) ? 0 : Math.ceil(Math.round(price) / 10) * 10;@@ -57,7 +58,14 @@ async function getPaddleFrame(selector = "inlineComplianceBarContainer") {return paddleFrame;}-async function changeCountry(paddleFrame, countryCode, pinCode) {+/**+ *+ * @param {Page} page+ * @param {*} paddleFrame+ * @param {*} countryCode+ * @param {*} pinCode+ */+async function changeCountry(page, paddleFrame, countryCode, pinCode) {await paddleFrame.selectOption(getPaddleTestId("countriesSelect"),countryCode,@@ -72,6 +80,11 @@ async function changeCountry(paddleFrame, countryCode, pinCode) {await paddleFrame.waitForSelector(getPaddleTestId("inlineComplianceBarContainer"));++ await page.waitForSelector(+ getTestId(`checkout-plan-country-${countryCode}`),+ { state: "attached" }+ );}async function forEachPlan(action) {@@ -91,10 +104,18 @@ async function forEachPlan(action) {}}-test("change plans", async ({ page }) => {+test("change plans", async ({ page }, info) => {+ info.setTimeout(0);+await loginUser();- await page.goto("/#/buy/");+ await page.waitForNavigation({ url: /notes/ });++ await page.goto("/notes/#/buy/");++ await page.waitForSelector(getTestId("see-all-plans"));++ await page.click(getTestId("see-all-plans"));await forEachPlan(async (plan) => {await expect(@@ -108,21 +129,31 @@ test("confirm plan prices", async ({ page }) => {await page.goto("/#/buy/");+ await page.waitForSelector(getTestId("see-all-plans"));++ await page.click(getTestId("see-all-plans"));+await forEachPlan(async (plan) => {const prices = roundOffPrices((await getPrices()).join("\n"));expect(prices).toMatchSnapshot(`checkout-${plan.key}-prices.txt`);});});-test("changing locale should show localized prices", async ({ page }) => {+test("changing locale should show localized prices", async ({ page }, info) => {+ info.setTimeout(0);+await loginUser();await page.goto("/#/buy/");+ await page.waitForSelector(getTestId("see-all-plans"));++ await page.click(getTestId("see-all-plans"));+await forEachPlan(async (plan) => {const paddleFrame = await getPaddleFrame();- await changeCountry(paddleFrame, "IN", "110001");+ await changeCountry(page, paddleFrame, "IN", "110001");const prices = roundOffPrices((await getPrices()).join("\n"));expect(prices).toMatchSnapshot(`checkout-${plan.key}-IN-prices.txt`);@@ -132,12 +163,16 @@ test("changing locale should show localized prices", async ({ page }) => {test("applying coupon should change discount & total price", async ({ page }, {setTimeout,}) => {- setTimeout(60 * 1000);+ setTimeout(0);await loginUser();await page.goto("/#/buy/");+ await page.waitForSelector(getTestId("see-all-plans"));++ await page.click(getTestId("see-all-plans"));+await forEachPlan(async (plan) => {await getPaddleFrame();@@ -146,6 +181,10 @@ test("applying coupon should change discount & total price", async ({ page }, {await getPaddleFrame();+ await page.waitForSelector(getTestId(`checkout-plan-coupon-applied`), {+ state: "attached",+ });+const prices = roundOffPrices((await getPrices()).join("\n"));expect(prices).toMatchSnapshot(@@ -154,7 +193,8 @@ test("applying coupon should change discount & total price", async ({ page }, {});});-test("apply coupon through url", async ({ page }) => {+test("apply coupon through url", async ({ page }, { setTimeout }) => {+ setTimeout(0);await loginUser();for (let plan of plans) {@@ -162,6 +202,10 @@ test("apply coupon through url", async ({ page }) => {await getPaddleFrame();+ await page.waitForSelector(getTestId(`checkout-plan-coupon-applied`), {+ state: "attached",+ });+const prices = roundOffPrices((await getPrices()).join("\n"));expect(prices).toMatchSnapshot(`checkout-${plan.key}-discounted-prices.txt`@@ -172,22 +216,30 @@ test("apply coupon through url", async ({ page }) => {test("apply coupon after changing country", async ({ page }, {setTimeout,}) => {- setTimeout(60 * 1000);+ setTimeout(0);await loginUser();await page.goto("/#/buy/");+ await page.waitForSelector(getTestId("see-all-plans"));++ await page.click(getTestId("see-all-plans"));+await forEachPlan(async (plan) => {const paddleFrame = await getPaddleFrame();- await changeCountry(paddleFrame, "IN", "110001");+ await changeCountry(page, paddleFrame, "IN", "110001");await page.fill(getTestId("checkout-coupon-code"), plan.coupon);await page.press(getTestId("checkout-coupon-code"), "Enter");await getPaddleFrame();+ await page.waitForSelector(getTestId(`checkout-plan-coupon-applied`), {+ state: "attached",+ });+const prices = roundOffPrices((await getPrices()).join("\n"));expect(prices).toMatchSnapshot(`checkout-${plan.key}-IN-discounted-prices.txt`diff --git a/apps/web/__e2e__/checkout.test.js-snapshots/checkout-monthly-IN-discounted-prices-Chromium-linux.txt b/apps/web/__e2e__/checkout.test.js-snapshots/checkout-monthly-IN-discounted-prices-Chromium-linux.txtindex 5511cc82b..fa9c192dc 100644--- a/apps/web/__e2e__/checkout.test.js-snapshots/checkout-monthly-IN-discounted-prices-Chromium-linux.txt+++ b/apps/web/__e2e__/checkout.test.js-snapshots/checkout-monthly-IN-discounted-prices-Chromium-linux.txt@@ -1,5 +1,5 @@-subtotal: ₹410-tax: ₹40+subtotal: ₹350+tax: ₹70discount: -₹210-total: ₹240-then ₹470/mo\ No newline at end of file+total: ₹210+then ₹410/mo\ No newline at end of filediff --git a/apps/web/__e2e__/checkout.test.js-snapshots/checkout-monthly-IN-discounted-prices-Firefox-linux.txt b/apps/web/__e2e__/checkout.test.js-snapshots/checkout-monthly-IN-discounted-prices-Firefox-linux.txtdeleted file mode 100644index 5511cc82b..000000000--- a/apps/web/__e2e__/checkout.test.js-snapshots/checkout-monthly-IN-discounted-prices-Firefox-linux.txt+++ /dev/null@@ -1,5 +0,0 @@-subtotal: ₹410-tax: ₹40-discount: -₹210-total: ₹240-then ₹470/mo\ No newline at end of filediff --git a/apps/web/__e2e__/checkout.test.js-snapshots/checkout-monthly-IN-discounted-prices-WebKit-linux.txt b/apps/web/__e2e__/checkout.test.js-snapshots/checkout-monthly-IN-discounted-prices-WebKit-linux.txtdeleted file mode 100644index 5d13e5e3d..000000000--- a/apps/web/__e2e__/checkout.test.js-snapshots/checkout-monthly-IN-discounted-prices-WebKit-linux.txt+++ /dev/null@@ -1,5 +0,0 @@-subtotal: ₹410-tax: ₹40-discount: -₹210-total: ₹240-then ₹470/modiff --git a/apps/web/__e2e__/checkout.test.js-snapshots/checkout-monthly-IN-prices-Chromium-linux.txt b/apps/web/__e2e__/checkout.test.js-snapshots/checkout-monthly-IN-prices-Chromium-linux.txtindex 76abca1c0..4fe57ada1 100644--- a/apps/web/__e2e__/checkout.test.js-snapshots/checkout-monthly-IN-prices-Chromium-linux.txt+++ b/apps/web/__e2e__/checkout.test.js-snapshots/checkout-monthly-IN-prices-Chromium-linux.txt@@ -1,4 +1,4 @@-subtotal: ₹410+subtotal: ₹350tax: ₹70discount: ₹0-total: ₹470/mo\ No newline at end of file+total: ₹410/mo\ No newline at end of filediff --git a/apps/web/__e2e__/checkout.test.js-snapshots/checkout-monthly-IN-prices-Firefox-linux.txt b/apps/web/__e2e__/checkout.test.js-snapshots/checkout-monthly-IN-prices-Firefox-linux.txtdeleted file mode 100644index 76abca1c0..000000000--- a/apps/web/__e2e__/checkout.test.js-snapshots/checkout-monthly-IN-prices-Firefox-linux.txt+++ /dev/null@@ -1,4 +0,0 @@-subtotal: ₹410-tax: ₹70-discount: ₹0-total: ₹470/mo\ No newline at end of filediff --git a/apps/web/__e2e__/checkout.test.js-snapshots/checkout-monthly-IN-prices-WebKit-linux.txt b/apps/web/__e2e__/checkout.test.js-snapshots/checkout-monthly-IN-prices-WebKit-linux.txtdeleted file mode 100644index 660cfc41f..000000000--- a/apps/web/__e2e__/checkout.test.js-snapshots/checkout-monthly-IN-prices-WebKit-linux.txt+++ /dev/null@@ -1,4 +0,0 @@-subtotal: ₹410-tax: ₹70-discount: ₹0-total: ₹470/modiff --git a/apps/web/__e2e__/checkout.test.js-snapshots/checkout-monthly-discounted-prices-Firefox-linux.txt b/apps/web/__e2e__/checkout.test.js-snapshots/checkout-monthly-discounted-prices-Firefox-linux.txtdeleted file mode 100644index 3e6ce3205..000000000--- a/apps/web/__e2e__/checkout.test.js-snapshots/checkout-monthly-discounted-prices-Firefox-linux.txt+++ /dev/null@@ -1,5 +0,0 @@-subtotal: $10-tax: $0-discount: -$10-total: $10-then $10/mo\ No newline at end of filediff --git a/apps/web/__e2e__/checkout.test.js-snapshots/checkout-monthly-discounted-prices-WebKit-linux.txt b/apps/web/__e2e__/checkout.test.js-snapshots/checkout-monthly-discounted-prices-WebKit-linux.txtdeleted file mode 100644index ba4b6d366..000000000--- a/apps/web/__e2e__/checkout.test.js-snapshots/checkout-monthly-discounted-prices-WebKit-linux.txt+++ /dev/null@@ -1,5 +0,0 @@-subtotal: $10-tax: $0-discount: -$10-total: $10-then $10/modiff --git a/apps/web/__e2e__/checkout.test.js-snapshots/checkout-monthly-prices-Firefox-linux.txt b/apps/web/__e2e__/checkout.test.js-snapshots/checkout-monthly-prices-Firefox-linux.txtdeleted file mode 100644index 3c65aafcb..000000000--- a/apps/web/__e2e__/checkout.test.js-snapshots/checkout-monthly-prices-Firefox-linux.txt+++ /dev/null@@ -1,4 +0,0 @@-subtotal: $10-tax: $0-discount: $0-total: $10/mo\ No newline at end of filediff --git a/apps/web/__e2e__/checkout.test.js-snapshots/checkout-monthly-prices-WebKit-linux.txt b/apps/web/__e2e__/checkout.test.js-snapshots/checkout-monthly-prices-WebKit-linux.txtdeleted file mode 100644index e9391ad34..000000000--- a/apps/web/__e2e__/checkout.test.js-snapshots/checkout-monthly-prices-WebKit-linux.txt+++ /dev/null@@ -1,4 +0,0 @@-subtotal: $10-tax: $0-discount: $0-total: $10/modiff --git a/apps/web/__e2e__/checkout.test.js-snapshots/checkout-yearly-IN-discounted-prices-Chromium-linux.txt b/apps/web/__e2e__/checkout.test.js-snapshots/checkout-yearly-IN-discounted-prices-Chromium-linux.txtindex 8cc760564..222d63398 100644--- a/apps/web/__e2e__/checkout.test.js-snapshots/checkout-yearly-IN-discounted-prices-Chromium-linux.txt+++ b/apps/web/__e2e__/checkout.test.js-snapshots/checkout-yearly-IN-discounted-prices-Chromium-linux.txt@@ -1,5 +1,5 @@-subtotal: ₹4510-tax: ₹590-discount: -₹680-total: ₹4420-then ₹5190/yr\ No newline at end of file+subtotal: ₹3850+tax: ₹700+discount: -₹690+total: ₹3860+then ₹4540/yr\ No newline at end of filediff --git a/apps/web/__e2e__/checkout.test.js-snapshots/checkout-yearly-IN-discounted-prices-Firefox-linux.txt b/apps/web/__e2e__/checkout.test.js-snapshots/checkout-yearly-IN-discounted-prices-Firefox-linux.txtdeleted file mode 100644index 8cc760564..000000000--- a/apps/web/__e2e__/checkout.test.js-snapshots/checkout-yearly-IN-discounted-prices-Firefox-linux.txt+++ /dev/null@@ -1,5 +0,0 @@-subtotal: ₹4510-tax: ₹590-discount: -₹680-total: ₹4420-then ₹5190/yr\ No newline at end of filediff --git a/apps/web/__e2e__/checkout.test.js-snapshots/checkout-yearly-IN-discounted-prices-WebKit-linux.txt b/apps/web/__e2e__/checkout.test.js-snapshots/checkout-yearly-IN-discounted-prices-WebKit-linux.txtdeleted file mode 100644index 8d79581c3..000000000--- a/apps/web/__e2e__/checkout.test.js-snapshots/checkout-yearly-IN-discounted-prices-WebKit-linux.txt+++ /dev/null@@ -1,5 +0,0 @@-subtotal: ₹4510-tax: ₹590-discount: -₹680-total: ₹4420-then ₹5190/yrdiff --git a/apps/web/__e2e__/checkout.test.js-snapshots/checkout-yearly-IN-prices-Chromium-linux.txt b/apps/web/__e2e__/checkout.test.js-snapshots/checkout-yearly-IN-prices-Chromium-linux.txtindex 624436abe..25b1f9a4f 100644--- a/apps/web/__e2e__/checkout.test.js-snapshots/checkout-yearly-IN-prices-Chromium-linux.txt+++ b/apps/web/__e2e__/checkout.test.js-snapshots/checkout-yearly-IN-prices-Chromium-linux.txt@@ -1,4 +1,4 @@-subtotal: ₹4510-tax: ₹690+subtotal: ₹770+tax: ₹140discount: ₹0-total: ₹5190/yr\ No newline at end of file+total: ₹910/yr\ No newline at end of filediff --git a/apps/web/__e2e__/checkout.test.js-snapshots/checkout-yearly-IN-prices-Firefox-linux.txt b/apps/web/__e2e__/checkout.test.js-snapshots/checkout-yearly-IN-prices-Firefox-linux.txtdeleted file mode 100644index 624436abe..000000000--- a/apps/web/__e2e__/checkout.test.js-snapshots/checkout-yearly-IN-prices-Firefox-linux.txt+++ /dev/null@@ -1,4 +0,0 @@-subtotal: ₹4510-tax: ₹690-discount: ₹0-total: ₹5190/yr\ No newline at end of filediff --git a/apps/web/__e2e__/checkout.test.js-snapshots/checkout-yearly-IN-prices-WebKit-linux.txt b/apps/web/__e2e__/checkout.test.js-snapshots/checkout-yearly-IN-prices-WebKit-linux.txtdeleted file mode 100644index a17b2eda2..000000000--- a/apps/web/__e2e__/checkout.test.js-snapshots/checkout-yearly-IN-prices-WebKit-linux.txt+++ /dev/null@@ -1,4 +0,0 @@-subtotal: ₹4510-tax: ₹690-discount: ₹0-total: ₹5190/yrdiff --git a/apps/web/__e2e__/checkout.test.js-snapshots/checkout-yearly-discounted-prices-Firefox-linux.txt b/apps/web/__e2e__/checkout.test.js-snapshots/checkout-yearly-discounted-prices-Firefox-linux.txtdeleted file mode 100644index d8ca4d5cd..000000000--- a/apps/web/__e2e__/checkout.test.js-snapshots/checkout-yearly-discounted-prices-Firefox-linux.txt+++ /dev/null@@ -1,5 +0,0 @@-subtotal: $50-tax: $0-discount: -$10-total: $50-then $50/yr\ No newline at end of filediff --git a/apps/web/__e2e__/checkout.test.js-snapshots/checkout-yearly-discounted-prices-WebKit-linux.txt b/apps/web/__e2e__/checkout.test.js-snapshots/checkout-yearly-discounted-prices-WebKit-linux.txtdeleted file mode 100644index 0aa1e9a79..000000000--- a/apps/web/__e2e__/checkout.test.js-snapshots/checkout-yearly-discounted-prices-WebKit-linux.txt+++ /dev/null@@ -1,5 +0,0 @@-subtotal: $50-tax: $0-discount: -$10-total: $50-then $50/yrdiff --git a/apps/web/__e2e__/checkout.test.js-snapshots/checkout-yearly-prices-Firefox-linux.txt b/apps/web/__e2e__/checkout.test.js-snapshots/checkout-yearly-prices-Firefox-linux.txtdeleted file mode 100644index a9b5bd67e..000000000--- a/apps/web/__e2e__/checkout.test.js-snapshots/checkout-yearly-prices-Firefox-linux.txt+++ /dev/null@@ -1,4 +0,0 @@-subtotal: $50-tax: $0-discount: $0-total: $50/yr\ No newline at end of filediff --git a/apps/web/__e2e__/checkout.test.js-snapshots/checkout-yearly-prices-WebKit-linux.txt b/apps/web/__e2e__/checkout.test.js-snapshots/checkout-yearly-prices-WebKit-linux.txtdeleted file mode 100644index 935d93119..000000000--- a/apps/web/__e2e__/checkout.test.js-snapshots/checkout-yearly-prices-WebKit-linux.txt+++ /dev/null@@ -1,4 +0,0 @@-subtotal: $50-tax: $0-discount: $0-total: $50/yrdiff --git a/apps/web/__e2e__/utils/index.js b/apps/web/__e2e__/utils/index.jsindex 9ba445c26..d27b50d21 100644--- a/apps/web/__e2e__/utils/index.js+++ b/apps/web/__e2e__/utils/index.js@@ -19,7 +19,7 @@ async function loginUser(user = USER, navigate = true) {await page.click(getTestId("submitButton"));- await page.waitForSelector(getTestId("navitem-sync"));+ await page.waitForSelector(getTestId("sync-status-synced"));}const NOTEBOOK = {diff --git a/apps/web/src/common/checkout b/apps/web/src/common/checkoutnew file mode 100644index 000000000..7a224cd07--- /dev/null+++ b/apps/web/src/common/checkout@@ -0,0 +1,242 @@+// import { ANALYTICS_EVENTS, trackEvent } from "../utils/analytics";+// import fetchJsonp from "fetch-jsonp";+// import Config from "../utils/config";+// import { db } from "./db";++// type Period = "monthly" | "yearly";+// const isDev = false; // process.env.NODE_ENV === "development";++// const VENDOR_ID = isDev ? 1506 : 128190;++// const PRODUCT_ID = async (plan: Period) => {+// const pricingPlan = await db.pricing?.sku("web", plan);+// if (!pricingPlan) throw new Error("Could not get SKU.");+// return pricingPlan.sku;+// };++// declare global {++// type PaddleOptions = {+// vendor: number;+// debug?: boolean;+// enableTracking?: boolean;+// poweredByBadge?: boolean;+// loadMethod?: "Direct";+// eventCallback?: null;+// sdk?: boolean;+// sdkAttributes?: {+// bundleIdentifier?: string;+// appName?: string;+// };+// completeDetails?: boolean;+// upsellCheckbox?: boolean;+// checkoutVariant?: null;+// };+// type Price = { currency: string; price: string; auth: string };+// type PaddleOpenOptions = {+// product: string;+// coupon?: string;+// method?: "overlay" | "window" | "inline" | "sdk";+// prices?: Price[];+// recurringPrices?: Price[];+// referring_domain?: string;+// passthrough?: string;+// checkoutVersion?: string;+// marketingConsent?: "0" | "1";+// email?: string;+// country?: string;+// postcode?: string;+// trialDays?: number;+// trialDaysAuth?: string;+// allowQuantity?: boolean;+// title?: string;+// message?: string;+// disableLogout?: boolean;+// displayModeTheme?: "dark" | "light";+// theme?: "none" | "green" | "light" | "dark";+// upsell?: string;+// upsellTitle?: string;+// upsellText?: string;+// upsellAction?: string;+// upsellPassthrough?: string;+// upsellCoupon?: string;+// frameInitialHeight?: number;+// frameTarget?: string;+// frameStyle?: string;+// override?: string;+// success?: string;+// successCallback?: string | Function;+// closeCallback?: string | Function;+// loadCallback?: string | Function;+// locale?: string;+// quantity?: string | number;+// };+// type CallbackParams = {+// event: PaddleEvents;+// eventData: any;+// checkoutData: any;+// campaignData: any;+// };+// interface Window {+// Paddle: {+// Options: (options: PaddleOptions) => void;+// Setup: (options: PaddleOptions) => void;+// Checkout: {+// open: (options: PaddleOpenOptions) => void;+// };+// Environment: {+// set: (+// env: "production" | "staging" | "sandbox" | "dev" | "local"+// ) => void;+// get: () => string;+// detect: () => void;+// defaults: () => string;+// };+// };+// }+// }++// function loadPaddle(eventCallback) {+// return new Promise((resolve) => {+// if (window.Paddle) {+// window.Paddle.Options({+// vendor: VENDOR_ID,+// eventCallback,+// debug: true,+// poweredByBadge: false,+// enableTracking: false,+// });+// resolve();+// return;+// }++// var script = document.createElement("script");+// script.src = "https://cdn.paddle.com/paddle/paddle.js";+// script.async = true;+// var firstScriptElement = document.getElementsByTagName("script")[0];+// script.onload = function () {+// if (isDev) window.Paddle.Environment.set("sandbox");+// window.Paddle.Setup({+// vendor: VENDOR_ID,+// eventCallback,+// });+// resolve();+// };+// firstScriptElement.parentNode.insertBefore(script, firstScriptElement);+// });+// }++// type InlineCheckoutParams = {+// user: User;+// plan: Period;+// coupon?: string;+// country?: string;+// onCheckoutLoaded?: () => void;+// };+// function inlineCheckout({+// user,+// plan,+// coupon,+// country,+// onCheckoutLoaded,+// }: InlineCheckoutParams) {+// return new Promise(async (resolve) => {+// await loadPaddle((e) => {+// const data = e.eventData;+// switch (e.event) {+// case "Checkout.Loaded":+// case "Checkout.Location.Submit":+// case "Checkout.Coupon.Applied":+// case "Checkout.Coupon.Remove":+// onCheckoutLoaded && onCheckoutLoaded(data);+// resolve();+// break;+// default:+// break;+// }+// });++// const { Paddle } = window;+// if (!Paddle) return;++// const container = document.getElementsByClassName("checkout-container")[0];+// if (!container) return;++// if (coupon) {+// trackEvent(ANALYTICS_EVENTS.offerClaimed, `[${coupon}] redeemed!`);+// } else {+// trackEvent(ANALYTICS_EVENTS.checkoutStarted, `Checkout requested`);+// }++// Paddle.Checkout.open({+// frameTarget: "checkout-container",+// frameStyle: "position: relative; width: 100%; border: 0;",+// frameInitialHeight: 416,+// disableLogout: true,+// allowQuantity: false,+// method: "inline",+// displayModeTheme: Config.get("theme", "light"),+// product: await PRODUCT_ID(plan),+// country,+// email: user.email,+// coupon,+// passthrough: JSON.stringify({+// userId: user.id,+// }),+// });+// });+// }++// // async function upgrade(user, coupon, plan) {+// // if (!window.Paddle) {+// // await loadPaddle();+// // }++// // const { Paddle } = window;+// // if (!Paddle) return;++// // if (coupon) {+// // trackEvent(ANALYTICS_EVENTS.offerClaimed, `[${coupon}] redeemed!`);+// // } else {+// // trackEvent(ANALYTICS_EVENTS.checkoutStarted, `Checkout requested`);+// // }++// // Paddle.Checkout.open({+// // product: PRODUCT_ID(plan),+// // email: user.email,+// // coupon,+// // passthrough: JSON.stringify({+// // userId: user.id,+// // }),+// // });+// // }++// async function openPaddleDialog(overrideUrl) {+// if (!window.Paddle) {+// await loadPaddle();+// }++// const { Paddle } = window;+// if (!Paddle) return;++// Paddle.Checkout.open({+// override: overrideUrl,+// product: PRODUCT_ID,+// });+// }++// async function getPlan(plan) {+// const productId = await PRODUCT_ID(plan);+// const url = `https://checkout.paddle.com/api/2.0/prices?product_ids=${productId}&callback=getPlan`;+// const response = await fetchJsonp(url, {+// timeout: 30000,+// jsonpCallback: "callback",+// jsonpCallbackFunction: "getPlan",+// });+// const json = await response.json();+// if (!json || !json.success || !json.response?.products?.length)+// throw new Error("Failed to get prices.");+// return json.response.products[0];+// }++// export { openPaddleDialog, getPlans, getPlan, inlineCheckout };diff --git a/apps/web/src/common/checkout.js b/apps/web/src/common/checkout.jsdeleted file mode 100644index 7f0a8e2c2..000000000--- a/apps/web/src/common/checkout.js+++ /dev/null@@ -1,161 +0,0 @@-import { ANALYTICS_EVENTS, trackEvent } from "../utils/analytics";-import fetchJsonp from "fetch-jsonp";-import Config from "../utils/config";--const isDev = false; // process.env.NODE_ENV === "development";--const VENDOR_ID = isDev ? 1506 : 128190;--/**- *- * @param {"yearly"|"monthly"} plan- * @returns- */-const PRODUCT_ID = (plan) => {- if (isDev) return plan === "monthly" ? 9822 : 0;- else return plan === "monthly" ? 648884 : 658759;-};--function loadPaddle(eventCallback) {- return new Promise((resolve) => {- if (window.Paddle) {- window.Paddle.Options({- vendor: VENDOR_ID,- eventCallback,- });- resolve();- return;- }-- var script = document.createElement("script");- script.src = "https://cdn.paddle.com/paddle/paddle.js";- script.async = true;- var firstScriptElement = document.getElementsByTagName("script")[0];- script.onload = function () {- if (isDev) window.Paddle.Environment.set("sandbox");- window.Paddle.Setup({- vendor: VENDOR_ID,- eventCallback,- });- resolve();- };- firstScriptElement.parentNode.insertBefore(script, firstScriptElement);- });-}--function inlineCheckout({ user, plan, coupon, country, onCheckoutLoaded }) {- return new Promise(async (resolve) => {- await loadPaddle((e) => {- const data = e.eventData;- switch (e.event) {- case "Checkout.Loaded":- case "Checkout.Location.Submit":- case "Checkout.Coupon.Applied":- case "Checkout.Coupon.Remove":- onCheckoutLoaded && onCheckoutLoaded(data);- resolve();- break;- default:- break;- }- });-- const { Paddle } = window;- if (!Paddle) return;-- const container = document.getElementsByClassName("checkout-container")[0];- if (!container) return;-- if (coupon) {- trackEvent(ANALYTICS_EVENTS.offerClaimed, `[${coupon}] redeemed!`);- } else {- trackEvent(ANALYTICS_EVENTS.checkoutStarted, `Checkout requested`);- }-- Paddle.Checkout.open({- frameTarget: "checkout-container",- frameStyle: "position: relative; width: 100%; border: 0;",- frameInitialHeight: 416,- disableLogout: true,- allowQuantity: false,- method: "inline",- displayModeTheme: Config.get("theme", "light"),- product: PRODUCT_ID(plan),- country,- email: user.email,- coupon,- passthrough: JSON.stringify({- userId: user.id,- }),- });- });-}--async function upgrade(user, coupon, plan) {- if (!window.Paddle) {- await loadPaddle();- }-- const { Paddle } = window;- if (!Paddle) return;-- if (coupon) {- trackEvent(ANALYTICS_EVENTS.offerClaimed, `[${coupon}] redeemed!`);- } else {- trackEvent(ANALYTICS_EVENTS.checkoutStarted, `Checkout requested`);- }-- Paddle.Checkout.open({- product: PRODUCT_ID(plan),- email: user.email,- coupon,- passthrough: JSON.stringify({- userId: user.id,- }),- });-}--async function openPaddleDialog(overrideUrl) {- if (!window.Paddle) {- await loadPaddle();- }-- const { Paddle } = window;- if (!Paddle) return;-- Paddle.Checkout.open({- override: overrideUrl,- product: PRODUCT_ID,- });-}--async function getPlans() {- const monthlyProductId = PRODUCT_ID("monthly");- const yearlyProductId = PRODUCT_ID("yearly");- const url = `https://checkout.paddle.com/api/2.0/prices?product_ids=${yearlyProductId},${monthlyProductId}&callback=getPrices`;- const response = await fetchJsonp(url, {- timeout: 30000,- jsonpCallback: "callback",- jsonpCallbackFunction: "getPrices",- });- const json = await response.json();- if (!json || !json.success || !json.response?.products?.length)- throw new Error("Failed to get prices.");- return json.response.products;-}--async function getPlan(plan) {- const productId = PRODUCT_ID(plan);- const url = `https://checkout.paddle.com/api/2.0/prices?product_ids=${productId}&callback=getPlan`;- const response = await fetchJsonp(url, {- timeout: 30000,- jsonpCallback: "callback",- jsonpCallbackFunction: "getPlan",- });- const json = await response.json();- if (!json || !json.success || !json.response?.products?.length)- throw new Error("Failed to get prices.");- return json.response.products[0];-}--export { upgrade, openPaddleDialog, getPlans, getPlan, inlineCheckout };diff --git a/apps/web/src/common/dialogcontroller.js b/apps/web/src/common/dialogcontroller.jsindex 54e21a5c9..3195ae3eb 100644--- a/apps/web/src/common/dialogcontroller.js+++ b/apps/web/src/common/dialogcontroller.js@@ -21,27 +21,21 @@ import { getChangelog } from "../utils/version";import { isDesktop } from "../utils/platform";function showDialog(dialog) {- const root = document.getElementById("dialogContainer");-- if (root) {- return new Promise((resolve, reject) => {- const perform = (result) => {- ReactDOM.unmountComponentAtNode(root);- hashNavigate("/", { replace: true });- resolve(result);- };- const PropDialog = dialog(Dialogs, perform);-- ReactDOM.render(<ThemeProvider>{PropDialog}</ThemeProvider>, root);- });- }- return Promise.reject("No element with id 'dialogContainer'");+ return new Promise((resolve, reject) => {+ const container = document.createElement("div");+ const perform = (result) => {+ ReactDOM.unmountComponentAtNode(container);+ hashNavigate("/", { replace: true, notify: false });+ resolve(result);+ };+ const PropDialog = dialog(Dialogs, perform);+ ReactDOM.render(<ThemeProvider>{PropDialog}</ThemeProvider>, container);+ });}export function closeOpenedDialog() {- const root = document.getElementById("ReactModalPortal");- if (!root) return;- ReactDOM.unmountComponentAtNode(root);+ const dialogs = document.querySelectorAll(".ReactModalPortal");+ dialogs.forEach((elem) => elem.remove());}export function showEditNotebookDialog(notebookId) {diff --git a/apps/web/src/components/accent-item/index.js b/apps/web/src/components/accent-item/index.jsindex a154d78fb..ccdd70a55 100644--- a/apps/web/src/components/accent-item/index.js+++ b/apps/web/src/components/accent-item/index.js@@ -15,10 +15,11 @@ function AccentItem(props) {variant="rowCenter"sx={{ position: "relative" }}onClick={async () => {- if (isUserPremium()) setAccent(code);- else {- await showBuyDialog();- }+ await showBuyDialog();+ // if (isUserPremium()) setAccent(code);+ // else {+ // await showBuyDialog();+ // }}}key={label}>diff --git a/apps/web/src/components/dialogs/buy-dialog/buy-dialog.tsx b/apps/web/src/components/dialogs/buy-dialog/buy-dialog.tsxnew file mode 100644index 000000000..136f4c6ef--- /dev/null+++ b/apps/web/src/components/dialogs/buy-dialog/buy-dialog.tsx@@ -0,0 +1,529 @@+import { useCallback, useEffect, useRef, useState } from "react";+import { Text, Flex, Button } from "rebass";+import * as Icon from "../../icons";+import { useStore as useUserStore } from "../../../stores/user-store";+import { useStore as useThemeStore } from "../../../stores/theme-store";+import getSymbolFromCurrency from "currency-symbol-map";+import Modal from "react-modal";+import { useTheme } from "emotion-theming";+import { ReactComponent as Rocket } from "../../../assets/rocket.svg";+import { ReactComponent as WorkAnywhere } from "../../../assets/workanywhere.svg";+import { ReactComponent as WorkLate } from "../../../assets/worklate.svg";+import Field from "../../field";+import { hardNavigate } from "../../../navigation";+import { Features } from "./features";+import { PaddleCheckout } from "./paddle";+import { Period, Plan, PricingInfo } from "./types";+import { PLAN_METADATA, usePlans } from "./plans";+import { formatPeriod, PlansList } from "./plan-list";+import { showToast } from "../../../utils/toast";+import { TaskManager } from "../../../common/task-manager";+import { db } from "../../../common/db";+import { useCheckoutStore } from "./store";++type BuyDialogProps = {+ couponCode?: string;+ plan?: "monthly" | "yearly";+ onClose: () => void;+};++export function BuyDialog(props: BuyDialogProps) {+ const { onClose, couponCode, plan } = props;+ const theme: any = useTheme();++ useEffect(() => {+ return () => {+ useCheckoutStore.getState().reset();+ };+ }, []);++ return (+ <Modal+ isOpen={true}+ onRequestClose={props.onClose}+ shouldCloseOnEsc+ shouldReturnFocusAfterClose+ shouldFocusAfterRender+ onAfterOpen={(e: any) => {+ if (!onClose) return;+ // we need this work around because ReactModal content spreads over the overlay+ const child = e.contentEl.firstElementChild;+ e.contentEl.onmousedown = function (e: any) {+ if (!e.screenX && !e.screenY) return;+ if (+ e.x < child.offsetLeft ||+ e.x > child.offsetLeft + child.clientWidth ||+ e.y < child.offsetTop ||+ e.y > child.offsetTop + child.clientHeight+ ) {+ onClose();+ }+ };+ }}+ style={{+ content: {+ top: 0,+ left: 0,+ right: 0,+ bottom: 0,+ display: "flex",+ justifyContent: "center",+ backgroundColor: undefined,+ padding: 0,+ overflowY: "hidden",+ border: 0,+ zIndex: 0,+ },+ overlay: {+ zIndex: 999,+ background: theme.colors.overlay,+ },+ }}+ >+ <Flex+ flexDirection={["column", "column", "row"]}+ width={["95%", "80%", "60%"]}+ maxHeight={["95%", "80%", "80%"]}+ bg="transparent"+ alignSelf={"center"}+ overflowY={["scroll", "scroll", "hidden"]}+ sx={{+ position: "relative",+ overflow: "hidden",+ boxShadow: "4px 5px 18px 2px #00000038",+ borderRadius: "dialog",+ }}+ >+ <Flex+ flexDirection="column"+ justifyContent="center"+ alignItems="center"+ flexShrink={0}+ sx={{+ borderTopLeftRadius: "dialog",+ borderBottomLeftRadius: [0, 0, "dialog"],+ overflow: "hidden",+ bg: "bgSecondary",+ "@supports ((-webkit-backdrop-filter: none) or (backdrop-filter: none))":+ {+ bg: "bgTransparent",+ backdropFilter: "blur(8px)",+ },+ }}+ width={["100%", "100%", 350]}+ p={4}+ py={50}+ >+ <SideBar+ onClose={onClose}+ couponCode={couponCode}+ initialPlan={plan}+ />+ </Flex>+ <Details initialCouponCode={couponCode} />+ </Flex>+ </Modal>+ );+}++type SideBarProps = {+ couponCode?: string;+ initialPlan?: Period;+ onClose: () => void;+};+function SideBar(props: SideBarProps) {+ const { couponCode, initialPlan, onClose } = props;+ const [showPlans, setShowPlans] = useState(!!initialPlan);+ const onPlanSelected = useCheckoutStore((state) => state.onPlanSelected);+ const selectedPlan = useCheckoutStore((state) => state.selectedPlan);+ const pricingInfo = useCheckoutStore((state) => state.pricingInfo);+ const user = useUserStore((store) => store.user);++ if (user && selectedPlan)+ return (+ <SelectedPlan+ plan={selectedPlan}+ pricingInfo={pricingInfo}+ onChangePlan={initialPlan ? undefined : () => onPlanSelected(undefined)}+ />+ );++ if (user && showPlans)+ return (+ <PlansList+ onPlansLoaded={(plans) => {+ if (!initialPlan) return;+ const plan = plans.find((p) => p.period === initialPlan);+ onPlanSelected(plan);+ }}+ onPlanSelected={onPlanSelected}+ />+ );++ return (+ <TrialOrUpgrade+ couponCode={couponCode}+ user={user}+ onShowPlans={() => setShowPlans(true)}+ onTrialRequested={async () => {+ try {+ const result = await TaskManager.startTask({+ type: "status",+ id: "trialActivation",+ action: (report) => {+ report({+ text: "Activating trial",+ });+ return db.user?.activateTrial();+ },+ });+ if (result) onClose();+ } catch (e) {+ if (e instanceof Error)+ showToast(+ "error",+ `Could not activate trial. Please try again. Error: ${e.message}`+ );+ }+ }}+ />+ );+}++type DetailsProps = {+ initialCouponCode?: string;+};+function Details(props: DetailsProps) {+ const { initialCouponCode } = props;+ const user = useUserStore((store) => store.user);+ const selectedPlan = useCheckoutStore((state) => state.selectedPlan);+ const onPriceUpdated = useCheckoutStore((state) => state.onPriceUpdated);+ const couponCode = useCheckoutStore((store) => store.couponCode);+ const onApplyCoupon = useCheckoutStore((store) => store.onApplyCoupon);+ const setIsApplyingCoupon = useCheckoutStore(+ (store) => store.setIsApplyingCoupon+ );+ const theme = useThemeStore((store) => store.theme);++ if (selectedPlan && user)+ return (+ <PaddleCheckout+ plan={selectedPlan}+ theme={theme}+ user={user}+ coupon={couponCode}+ onCouponApplied={() => setIsApplyingCoupon(true)}+ onPriceUpdated={(pricingInfo) => {+ onPriceUpdated(pricingInfo);+ console.log(initialCouponCode, "applying coupon", couponCode);++ if (!initialCouponCode || initialCouponCode === couponCode) return;+ console.log(initialCouponCode, "applying coupon");+ onApplyCoupon(initialCouponCode);+ }}+ />+ );++ 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 (+ <>+ <Rocket width={200} />+ <Text variant="heading" textAlign="center" mt={4}>+ Notesnook Pro+ </Text>+ <Text variant="body" textAlign="center" mt={1}>+ Ready to take the next step in your private note taking journey?+ </Text>+ {isLoading || !plan ? (+ <Icon.Loading sx={{ mt: 4 }} />+ ) : (+ <Text variant={"body"} fontSize="title" mt={4}>+ Starting from {getSymbolFromCurrency(plan.currency)}+ {plan.price.gross}+ {formatPeriod(plan.period)}+ </Text>+ )}+ {user ? (+ <>+ <Button+ variant="primary"+ 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="primary"+ mt={4}+ sx={{ borderRadius: 100, px: 6 }}+ onClick={() => hardNavigate("/signup")}+ >+ Sign up for free+ </Button>+ <Text variant={"subBody"} textAlign="center" mt={2}>+ 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"+ color="primary"+ mt={4}+ p={1}+ sx={{ borderRadius: "default" }}+ >+ Please sign up or login to use your coupon: <b>{couponCode}</b>+ </Text>+ )}+ </>+ );+}++type SelectedPlanProps = {+ plan: Plan;+ pricingInfo: PricingInfo | undefined;+ onChangePlan?: () => void;+};+function SelectedPlan(props: SelectedPlanProps) {+ const { plan, pricingInfo, onChangePlan } = props;+ const metadata = PLAN_METADATA[plan.period];+ const [isInvalidCoupon, setIsInvalidCoupon] = useState(false);+ const [isApplyingCoupon, setIsApplyingCoupon] = useCheckoutStore((store) => [+ store.isApplyingCoupon,+ store.setIsApplyingCoupon,+ ]);++ const onApplyCoupon = useCheckoutStore((store) => store.onApplyCoupon);+ const couponInputRef = useRef<HTMLInputElement>();++ const applyCoupon = useCallback(() => {+ const coupon = couponInputRef.current?.value;+ if (!coupon) return;+ setIsApplyingCoupon(true);+ onApplyCoupon(coupon);+ }, [onApplyCoupon, setIsApplyingCoupon]);++ const removeCoupon = useCallback(() => {+ setIsApplyingCoupon(true);+ onApplyCoupon(undefined);+ }, [onApplyCoupon, setIsApplyingCoupon]);++ useEffect(() => {+ if (!couponInputRef.current) return;+ setIsApplyingCoupon(false);++ const couponValue = couponInputRef.current.value;++ const isInvalidCoupon =+ !!couponValue && couponValue !== pricingInfo?.coupon;+ setIsInvalidCoupon(isInvalidCoupon);+ if (isInvalidCoupon) return;++ const pricingInfoCoupon = pricingInfo?.coupon || "";+ if (couponValue !== pricingInfoCoupon) {+ couponInputRef.current.value = pricingInfoCoupon;+ onApplyCoupon(pricingInfo?.coupon);+ }+ }, [pricingInfo, onApplyCoupon, setIsApplyingCoupon]);++ return (+ <>+ {plan.period === "monthly" ? (+ <WorkAnywhere width={180} />+ ) : (+ <WorkLate width={180} />+ )}+ <Text variant="heading" textAlign="center" mt={4}>+ Notesnook Pro+ </Text>+ <Text+ data-test-id="checkout-plan-title"+ variant="body"+ fontSize="subheading"+ textAlign="center"+ mt={1}+ >+ {metadata.title}+ </Text>++ {pricingInfo ? (+ <>+ <Text data-test-id={`checkout-plan-country-${pricingInfo.country}`} />+ {pricingInfo.coupon && (+ <Text data-test-id={`checkout-plan-coupon-applied`} />+ )}++ <Field+ inputRef={couponInputRef}+ variant={isInvalidCoupon ? "error" : "input"}+ sx={{ alignSelf: "stretch", my: 2 }}+ styles={{ input: { fontSize: "body" } }}+ data-test-id="checkout-coupon-code"+ id="coupon"+ name="coupon"+ placeholder={+ isApplyingCoupon ? "Applying coupon code..." : "Coupon code"+ }+ autoFocus={isInvalidCoupon}+ disabled={!!pricingInfo?.coupon}+ onKeyUp={(e: KeyboardEvent) => {+ if (e.code === "Enter") applyCoupon();+ }}+ action={{+ icon: isApplyingCoupon+ ? Icon.Loading+ : pricingInfo?.coupon+ ? Icon.Cross+ : Icon.Check,+ onClick: () =>+ pricingInfo?.coupon ? removeCoupon() : applyCoupon(),+ }}+ />+ <CheckoutPricing pricingInfo={pricingInfo} />+ {onChangePlan && (+ <Button+ data-test-id="checkout-plan-change"+ variant="secondary"+ mt={4}+ px={4}+ onClick={onChangePlan}+ >+ Change plan+ </Button>+ )}+ </>+ ) : (+ <Icon.Loading sx={{ mt: 4 }} />+ )}+ </>+ );+}++type CheckoutPricingProps = {+ pricingInfo: PricingInfo;+};+function CheckoutPricing(props: CheckoutPricingProps) {+ const { pricingInfo } = props;+ const { currency, price, discount, period, recurringPrice } = pricingInfo;+ const fields = [+ {+ key: "subtotal",+ label: "Subtotal",+ value: formatPrice(currency, price.net.toFixed(2), null),+ },+ {+ key: "tax",+ label: "Sales tax",+ color: "error",+ value: formatPrice(currency, price.tax.toFixed(2), null),+ },+ {+ key: "discount",+ label: "Discount",+ color: "primary",+ value: formatPrice(+ currency,+ discount.amount.toFixed(2),+ null,+ discount.amount > 0+ ),+ },+ ];++ const isDiscounted = discount.recurring || discount.amount <= 0;+ const currentTotal = formatPrice(+ currency,+ (price.gross - discount.amount).toFixed(2),+ isDiscounted ? period : undefined+ );+ const recurringTotal = formatPrice(+ currency,+ recurringPrice.gross.toFixed(2),+ period+ );+ return (+ <>+ {fields.map((field) => (+ <Flex+ key={field.key}+ justifyContent="space-between"+ alignSelf="stretch"+ mt={1}+ >+ <Text variant="body" fontSize="subtitle">+ {field.label}+ </Text>+ <Text+ data-test-id={`checkout-price-${field.key}`}+ variant="body"+ fontSize="subtitle"+ color={field.color || "text"}+ >+ {field.value}+ </Text>+ </Flex>+ ))}+ <Flex justifyContent="space-between" alignSelf="stretch" mt={1}>+ <Text variant="body" fontSize="heading">+ Total+ </Text>+ <Text+ data-test-id={`checkout-price-total`}+ variant="body"+ fontSize="heading"+ color={"text"}+ textAlign="end"+ >+ {currentTotal}+ {isDiscounted ? null : (+ <Text fontSize="body">{`then ${recurringTotal}`}</Text>+ )}+ </Text>+ </Flex>+ </>+ );+}++function formatPrice(+ currency: string,+ price: string,+ period?: Period | null,+ negative = false+) {+ const formattedPeriod = period ? formatPeriod(period) : "";+ const currencySymbol = getSymbolFromCurrency(currency);+ const prefix = negative ? "-" : "";+ return `${prefix}${currencySymbol}${price}${formattedPeriod}`;+}diff --git a/apps/web/src/components/dialogs/buy-dialog/features.tsx b/apps/web/src/components/dialogs/buy-dialog/features.tsxnew file mode 100644index 000000000..93c32310d--- /dev/null+++ b/apps/web/src/components/dialogs/buy-dialog/features.tsx@@ -0,0 +1,334 @@+import { Text, Flex, Box } from "rebass";+import * as Icon from "../../icons";++type Feature = {+ title?: string;+ icon?: (props: any) => JSX.Element;+ pro?: boolean;+};++type Section = {+ title: string;+ detail: string;+ columns?: number;+ info?: string;+ pro?: boolean;+ features?: Feature[];+};++const sections: Section[] = [+ {+ title: "Focused on privacy",+ detail:+ "Everything you do in Notesnook stays private. We use XChaCha20-Poly1305-IETF and Argon2 to encrypt your notes.",+ features: [+ {+ title: "Zero ads & zero trackers",+ icon: Icon.Billboard,+ },+ {+ title: "On device encryption",+ icon: Icon.Cellphone,+ },+ {+ title: "Secure app lock for all",+ icon: Icon.CellphoneLock,+ },+ {+ title: "100% end-to-end encrypted",+ icon: Icon.Lock,+ },+ {+ title: "Private vault for notes",+ icon: Icon.ShieldLock,+ pro: true,+ },+ ],+ },+ {+ title: "Instant syncing",+ detail:+ "Seemlessly work from anywhere. Every change is synced instantly everywhere.",+ pro: true,+ },+ {+ title: "100% cross platform",+ detail: "Notesnook is available on all major platforms — for everyone.",+ columns: 8,+ features: [+ {+ icon: Icon.iOS,+ },+ {+ icon: Icon.Android,+ },+ {+ icon: Icon.Windows,+ },+ {+ icon: Icon.Linux,+ },+ {+ icon: Icon.MacOS,+ },+ {+ icon: Icon.Chrome,+ },+ {+ icon: Icon.Firefox,+ },+ {+ icon: Icon.Safari,+ },+ ],+ },+ {+ title: "Attach files & images",+ detail:+ "Add your documents, PDFs, images and videos, and keep them safe and organized.",+ pro: true,+ features: [+ {+ title: "Bulletproof encryption",+ icon: Icon.Lock,+ },+ {+ title: "High quality 4K images",+ icon: Icon.ImageMultiple,+ },+ {+ title: "Unlimited storage",+ icon: Icon.Harddisk,+ },+ {+ title: "Upto 500 MB per file",+ icon: Icon.FileCabinet,+ },+ {+ title: "All file types supported",+ icon: Icon.File,+ },+ ],+ },+ {+ title: "No limit on notes",+ detail:+ "We don't have nonsense like blocks and whatnot. You can create as many notes as you want — no limits.",+ },+ {+ title: "Safe publishing to the Internet",+ detail:+ "Publishing is nothing new but we offer fully encrypted, anonymous publishing. Take any note & share it with the world.",+ features: [+ {+ title: "Anonymous publishing",+ icon: Icon.Anonymous,+ },+ {+ title: "Password protection",+ icon: Icon.CloudLock,+ },+ {+ title: "Self destructable notes",+ icon: Icon.Timebomb,+ },+ ],+ },+ {+ title: "Organize yourself in the best way",+ detail:+ "We offer multiple ways to keep you organized. The only limit is your imagination.",+ features: [+ {+ title: "Unlimited notebooks*",+ icon: Icon.Notebook2,+ pro: true,+ },+ {+ title: "Colors & tags*",+ icon: Icon.Palette,+ pro: true,+ },+ {+ title: "Side menu shortcuts",+ icon: Icon.Shortcut,+ },+ {+ title: "Pins & favorites",+ icon: Icon.Pin,+ },+ ],+ info: "* Free users can only create 3 notebooks (no limit on topics) and 5 tags.",+ },++ {+ title: "Rich tools for rich editing",+ detail:+ "Having the right tool at the right time is crucial for note taking. Lists, tables, codeblocks — you name it, we have it.",+ pro: true,+ features: [+ {+ title: "Lists & tables",+ icon: Icon.Table,+ },+ {+ title: "Images & embeds",+ icon: Icon.Embed,+ },+ {+ title: "Checklists",+ icon: Icon.CheckCircleOutline,+ },+ {+ title: "Markdown shortcuts",+ icon: Icon.Markdown,+ },+ ],+ },+ {+ title: "Export and take your notes anywhere",+ detail:+ "You own your notes, not us. No proprietary formats. No vendor lock in. No waiting for hours to download your notes.",+ // info: "* Free users can export notes in well formatted plain text.",+ features: [+ {+ title: "Export as Markdown",+ icon: Icon.Markdown,+ pro: true,+ },+ {+ title: "Export as PDF",+ icon: Icon.PDF,+ pro: true,+ },+ {+ title: "Export as HTML",+ icon: Icon.HTML,+ pro: true,+ },+ {+ title: "Export as text",+ icon: Icon.Text,+ },+ {+ title: "Bulk exports",+ icon: Icon.Export,+ },+ ],+ },+ {+ title: "Backup & keep your notes safe",+ detail:+ "Do not worry about losing your data. Turn on automatic backups on weekly or daily basis.",+ features: [+ {+ title: "Automatic monthly, weekly & daily backups",+ icon: Icon.Backup,+ pro: true,+ },+ {+ title: "Backup encryption",+ icon: Icon.EncryptedBackup,+ pro: true,+ },+ ],+ },+ {+ title: "Personalize & make Notesnook your own",+ detail:+ "Change app themes to match your style. Custom themes are coming soon.",+ pro: true,+ features: [+ {+ title: "10+ themes",+ icon: Icon.Accent,+ },+ {+ title: "Automatic dark mode",+ icon: Icon.Theme,+ },+ {+ title: "Change default home page",+ icon: Icon.Home,+ },+ ],+ },+];++export function Features() {+ return (+ <Flex+ flexDirection="column"+ flex={1}+ overflowY={["hidden", "hidden", "auto"]}+ flexShrink={0}+ sx={{ position: "relative" }}+ pt={6}+ bg="background"+ >+ {sections.map((section) => (+ <Flex flexDirection="column" px={6} pb={50}>+ {section.pro && (+ <Flex+ bg="bgSecondary"+ alignSelf="start"+ px={2}+ py="2px"+ sx={{ borderRadius: 50 }}+ mb={1}+ >+ <Icon.Pro color="primary" size={16} />+ <Text variant="body" color="primary" ml={"2px"}>+ Pro+ </Text>+ </Flex>+ )}+ <Text variant="body" fontSize={"1.3rem"}>+ {section.title}+ </Text>+ <Text variant="body" mt={1} fontSize="title" color="fontTertiary">+ {section.detail}+ </Text>+ {section.features && (+ <Box+ sx={{+ display: "grid",+ gridTemplateColumns: section.columns+ ? "1fr ".repeat(section.columns)+ : "1fr 1fr 1fr",+ gap: 3,+ }}+ mt={4}+ >+ {section.features.map((feature) => (+ <Flex alignItems="start" flexDirection="column">+ {feature.icon && (+ <feature.icon size={20} color="text" sx={{ mb: 1 }} />+ )}+ {feature.pro && (+ <Flex justifyContent="center" alignItems="center">+ <Icon.Pro color="primary" size={14} />+ <Text variant="subBody" color="primary" ml={"2px"}>+ Pro+ </Text>+ </Flex>+ )}+ {feature.title && (+ <Text variant="body" fontSize="subtitle">+ {feature.title}+ </Text>+ )}+ </Flex>+ ))}+ </Box>+ )}+ {section.info && (+ <Text mt={1} variant="subBody">+ {section.info}+ </Text>+ )}+ </Flex>+ ))}+ </Flex>+ );+}diff --git a/apps/web/src/components/dialogs/buy-dialog/index.ts b/apps/web/src/components/dialogs/buy-dialog/index.tsnew file mode 100644index 000000000..8079239c2--- /dev/null+++ b/apps/web/src/components/dialogs/buy-dialog/index.ts@@ -0,0 +1 @@+export { BuyDialog as default } from "./buy-dialog";diff --git a/apps/web/src/components/dialogs/buy-dialog/paddle.tsx b/apps/web/src/components/dialogs/buy-dialog/paddle.tsxnew file mode 100644index 000000000..86c100e12--- /dev/null+++ b/apps/web/src/components/dialogs/buy-dialog/paddle.tsx@@ -0,0 +1,263 @@+import { useEffect, useState, useRef, useCallback } from "react";+import { Box, Flex } from "rebass";+import Loader from "../../loader";+import {+ CheckoutData,+ CheckoutDataResponse,+ CheckoutPrices,+ PaddleEvent,+ PaddleEvents,+ Plan,+ Price,+ PricingInfo,+} from "./types";++// const isDev = false; // process.env.NODE_ENV === "development";+// const VENDOR_ID = isDev ? 1506 : 128190;+const PADDLE_ORIGIN = "https://buy.paddle.com";++const SUBSCRIBED_EVENTS: PaddleEvents[] = [+ PaddleEvents["Checkout.Loaded"],+ PaddleEvents["Checkout.Coupon.Applied"],+ PaddleEvents["Checkout.Coupon.Remove"],+ PaddleEvents["Checkout.Location.Submit"],+];++type PaddleCheckoutProps = {+ user: { id: string; email: string };+ theme: "dark" | "light";+ plan: Plan;+ onPriceUpdated?: (pricingInfo: PricingInfo) => void;+ onCouponApplied?: () => void;+ coupon?: string;+};+export function PaddleCheckout(props: PaddleCheckoutProps) {+ const { plan, onPriceUpdated, coupon, onCouponApplied } = props;+ const [sourceUrl, setSourceUrl] = useState<string>();+ const [isLoading, setIsLoading] = useState(true);+ const [checkoutId, setCheckoutId] = useState<string>();+ const appliedCouponCode = useRef<string>();+ const checkoutRef = useRef<HTMLIFrameElement>();++ const reloadCheckout = useCallback(() => {+ if (!checkoutRef.current) return;+ setIsLoading(true);+ checkoutRef.current.src = `https://buy.paddle.com/checkout/?checkout_id=${checkoutId}&display_mode=inline&apple_pay_enabled=false`;+ }, [checkoutId]);++ const updatePrice = useCallback(+ async (checkoutId: string) => {+ const checkoutData = await getCheckoutData(checkoutId);+ if (!checkoutData) return;+ const pricingInfo = getPricingInfo(plan, checkoutData);+ if (onPriceUpdated) onPriceUpdated(pricingInfo);+ return pricingInfo;+ },+ [onPriceUpdated, plan]+ );++ useEffect(() => {+ (async function () {+ const url = await getCheckoutURL(props);+ setSourceUrl(url);+ })();+ }, [props]);++ useEffect(() => {+ async function onMessage(ev: MessageEvent<PaddleEvent>) {+ if (ev.origin !== PADDLE_ORIGIN) return;+ const { event_name, callback_data } = ev.data;+ const { checkout } = callback_data;++ if (+ !checkout ||+ !checkout.id ||+ SUBSCRIBED_EVENTS.indexOf(event_name) === -1+ )+ return;++ if (event_name === PaddleEvents["Checkout.Loaded"]) setIsLoading(false);++ const pricingInfo = await updatePrice(checkout.id);+ if (!pricingInfo) return;++ appliedCouponCode.current = pricingInfo.coupon;+ setCheckoutId(checkout.id);+ }+ window.addEventListener("message", onMessage);+ return () => {+ window.removeEventListener("message", onMessage);+ };+ }, [onPriceUpdated, updatePrice, plan]);++ useEffect(() => {+ if (+ !checkoutId ||+ appliedCouponCode.current === coupon ||+ !appliedCouponCode.current === !coupon+ )+ return;+ if (onCouponApplied) onCouponApplied();++ (async function () {+ const checkoutData = coupon+ ? await applyCoupon(checkoutId, coupon)+ : await removeCoupon(checkoutId);+ if (!checkoutData) {+ await updatePrice(checkoutId);+ return;+ }+ appliedCouponCode.current = coupon;+ reloadCheckout();+ })();+ }, [+ coupon,+ onCouponApplied,+ checkoutId,+ onPriceUpdated,+ plan,+ reloadCheckout,+ updatePrice,+ ]);++ return (+ <Flex+ className="checkout-container"+ sx={{ bg: "background", flex: 1, overflowY: "auto" }}+ >+ {isLoading ? (+ <Loader+ text={""}+ title={+ coupon+ ? "Applying coupon code..."+ : "Loading checkout. Please wait..."+ }+ />+ ) : null}+ <Box+ ref={checkoutRef}+ as="iframe"+ src={sourceUrl}+ sx={{+ m: 6,+ display: isLoading ? "none" : "block",+ flex: 1,+ outline: "none",+ border: "none",+ minHeight: 500,+ }}+ />+ </Flex>+ );+}++async function getCheckoutURL(params: PaddleCheckoutProps) {+ const { plan, theme, user } = params;+ const BASE_URL = `https://create-checkout.paddle.com/checkout/product/${plan.id}`;+ const queryParams = new URLSearchParams();+ queryParams.set("product", plan.id);+ queryParams.set("passthrough", JSON.stringify({ userId: user.id }));+ queryParams.set("guest_email", user.email);+ queryParams.set("quantity_variable", "0");+ queryParams.set("disable_logout", "true");+ queryParams.set("display_mode_theme", theme);+ queryParams.set("display_mode", "inline");+ queryParams.set("apple_pay_enabled", "false");+ queryParams.set("paddlejs-version", "2.0.14");+ queryParams.set("popup", "true");+ queryParams.set("paddle_js", "true");+ queryParams.set("is_popup", "true");+ queryParams.set("parent_url", window.location.href);+ const fullURL = `${BASE_URL}?${queryParams.toString()}`;+ return fullURL;+}++function getPricingInfo(plan: Plan, checkoutData: CheckoutData): PricingInfo {+ const { prices, recurring } = checkoutData.items[0];+ const price = prices[0];+ const recurringPrice = recurring.prices[0];+ const discount = price.discounts.length > 0 ? price.discounts[0] : undefined;+ const isRecurringDiscount = recurringPrice.discounts.length > 0;++ return {+ country: checkoutData.customer.country_code,+ currency: price.currency,+ discount: {+ amount: discount?.gross_discount || 0,+ recurring: isRecurringDiscount,+ },+ period: plan.period,+ price: normalizeCheckoutPrice(price),+ recurringPrice: normalizeCheckoutPrice(recurringPrice),+ coupon: discount?.code,+ };+}++function normalizeCheckoutPrice(prices: CheckoutPrices): Price {+ const price = prices.unit_price;+ return {+ gross: price.gross,+ net: price.net,+ tax: price.tax,+ currency: prices.currency,+ };+}++async function applyCoupon(+ checkoutId: string,+ couponCode: string+): Promise<CheckoutData | false> {+ const url = ` https://checkout-service.paddle.com/checkout/${checkoutId}/coupon`;+ const body = { data: { coupon_code: couponCode } };+ const headers = new Headers();+ headers.set("content-type", "application/json");+ const response = await fetch(url, {+ body: JSON.stringify(body),+ headers,+ method: "POST",+ });+ if (!response.ok) return false;+ const json = (await response.json()) as CheckoutDataResponse;++ await sendCheckoutEvent(checkoutId, PaddleEvents["Checkout.Coupon.Applied"]);++ return json.data;+}++async function removeCoupon(checkoutId: string): Promise<CheckoutData | false> {+ const url = ` https://checkout-service.paddle.com/checkout/${checkoutId}/coupon`;++ const response = await fetch(url, {+ method: "DELETE",+ });+ if (!response.ok) return false;+ const json = (await response.json()) as CheckoutDataResponse;++ await sendCheckoutEvent(checkoutId, PaddleEvents["Checkout.Coupon.Remove"]);++ return json.data;+}++async function sendCheckoutEvent(checkoutId: string, eventName: PaddleEvents) {+ const url = ` https://checkout-service.paddle.com/checkout/${checkoutId}/event`;+ const body = { data: { event_name: eventName } };+ const headers = new Headers();+ headers.set("content-type", "application/json");+ const response = await fetch(url, {+ body: JSON.stringify(body),+ headers,+ method: "POST",+ });+ return response.ok;+}++async function getCheckoutData(+ checkoutId: string+): Promise<CheckoutData | undefined> {+ const url = `https://checkout-service.paddle.com/checkout/${checkoutId}`;+ const response = await fetch(url);+ if (!response.ok) return undefined;+ const json = (await response.json()) as CheckoutDataResponse;+ return json.data;+}diff --git a/apps/web/src/components/dialogs/buy-dialog/plan-list.tsx b/apps/web/src/components/dialogs/buy-dialog/plan-list.tsxnew file mode 100644index 000000000..4221fd31a--- /dev/null+++ b/apps/web/src/components/dialogs/buy-dialog/plan-list.tsx@@ -0,0 +1,112 @@+import { Text, Flex, Button } from "rebass";+import * as Icon from "../../icons";+import getSymbolFromCurrency from "currency-symbol-map";+import { ReactComponent as Nomad } from "../../../assets/nomad.svg";+import { Period, Plan } from "./types";+import { PLAN_METADATA, usePlans } from "./plans";+import { useEffect } from "react";++type PlansListProps = {+ onPlanSelected: (plan: Plan) => void;+ onPlansLoaded?: (plans: Plan[]) => void;+};+export function PlansList(props: PlansListProps) {+ const { onPlanSelected, onPlansLoaded } = props;+ const { isLoading, plans, discount, country } = usePlans();++ useEffect(() => {+ if (isLoading || !onPlansLoaded) return;+ onPlansLoaded(plans);+ }, [isLoading, onPlansLoaded, plans]);++ return (+ <>+ <Nomad width={200} />+ <Text variant="heading" textAlign="center" mt={4}>+ Choose a plan+ </Text>+ <Text variant="body" textAlign="center" mt={1}>+ {discount ? (+ <>+ We are giving a special <b>{discount}% discount</b> to all users+ from {country}.+ </>+ ) : (+ "Notesnook profits when you purchase a subscription — not by selling your data."+ )}+ </Text>+ <Flex flexDirection="column" alignSelf="stretch" mt={2}>+ {plans.map((plan) => {+ const metadata = PLAN_METADATA[plan.period];+ return (+ <Button+ disabled={isLoading}+ data-test-id={`checkout-plan-${plan.period}`}+ variant="tool"+ display="flex"+ textAlign="start"+ justifyContent="space-between"+ alignItems="center"+ flex={1}+ mt={1}+ bg="transparent"+ // sx={+ // {+ // // bg: selectedPlan?.key === plan.key ? "border" : "transparent",+ // // border:+ // // selectedPlan?.key === plan.key ? "1px solid var(--primary)" : "none",+ // }+ // }+ onClick={() => onPlanSelected(plan)}+ >+ <Text variant="subtitle" fontWeight="normal">+ {metadata.title}+ <Text variant="body" fontWeight="normal" color="fontTertiary">+ {metadata.subtitle}+ </Text>+ </Text>+ {isLoading ? <Icon.Loading /> : <RecurringPricing plan={plan} />}+ </Button>+ );+ })}+ </Flex>+ </>+ );+}++type RecurringPricingProps = {+ plan: Plan;+};+function RecurringPricing(props: RecurringPricingProps) {+ const { plan } = props;+ return (+ <Text+ sx={{ flexShrink: 0 }}+ variant="body"+ fontSize="subBody"+ textAlign={"end"}+ >+ {plan.originalPrice && (+ <Text+ color="fontTertiary"+ fontSize={"body"}+ sx={{ textDecorationLine: "line-through" }}+ >+ {getSymbolFromCurrency(plan.currency)}+ {plan.originalPrice.gross}+ </Text>+ )}+ <Text>+ <Text as="span" fontSize="subtitle">+ {getSymbolFromCurrency(plan.currency)}+ {plan.price.gross}+ </Text>+ {formatPeriod(plan.period)}+ </Text>+ </Text>+ );+}++export function formatPeriod(period: Period) {+ return period === "monthly" ? "/mo" : period === "yearly" ? "/yr" : "";+}diff --git a/apps/web/src/components/dialogs/buy-dialog/plans.ts b/apps/web/src/components/dialogs/buy-dialog/plans.tsnew file mode 100644index 000000000..f62cbf222--- /dev/null+++ b/apps/web/src/components/dialogs/buy-dialog/plans.ts@@ -0,0 +1,69 @@+import { useEffect, useState } from "react";+import { isTesting } from "../../../utils/platform";+import { Period, Plan } from "./types";++type PlanMetadata = {+ title: string;+ subtitle: string;+};++export const DEFAULT_PLANS: Plan[] = [+ {+ period: "monthly",+ country: "PK",+ currency: "USD",+ discount: 0,+ id: "648884",+ price: { gross: 4.49, net: 0, tax: 0 },+ },+ {+ period: "yearly",+ country: "PK",+ currency: "USD",+ discount: 0,+ id: "658759",+ price: { gross: 49.99, net: 0, tax: 0 },+ },+];++export const PLAN_METADATA: Record<Period, PlanMetadata> = {+ monthly: { title: "Monthly", subtitle: `Pay once a month.` },+ yearly: { title: "Yearly", subtitle: `Pay once a year.` },+};++var CACHED_PLANS: Plan[];+export async function getPlans(): Promise<Plan[] | null> {+ if (isTesting()) return DEFAULT_PLANS;+ if (CACHED_PLANS) return CACHED_PLANS;++ const url = `https://notesnook.com/api/v1/prices/products/web`;+ const response = await fetch(url);+ if (!response.ok) return null;+ const plans = (await response.json()) as Plan[];+ CACHED_PLANS = plans;+ return plans;+}++export function usePlans() {+ const [isLoading, setIsLoading] = useState(false);+ const [plans, setPlans] = useState<Plan[]>(DEFAULT_PLANS);+ const [discount, setDiscount] = useState<number>();+ const [country, setCountry] = useState<string>();+ useEffect(() => {+ (async function () {+ try {+ setIsLoading(true);+ let plans = await getPlans();+ if (!plans) return;+ setPlans(plans);+ setDiscount(Math.max(...plans.map((p) => p.discount)));+ setCountry(plans[0].country);+ } catch (e) {+ console.error(e);+ } finally {+ setIsLoading(false);+ }+ })();+ }, []);+ return { isLoading, plans, discount, country };+}diff --git a/apps/web/src/components/dialogs/buy-dialog/store.ts b/apps/web/src/components/dialogs/buy-dialog/store.tsnew file mode 100644index 000000000..a566c1437--- /dev/null+++ b/apps/web/src/components/dialogs/buy-dialog/store.ts@@ -0,0 +1,57 @@+import { Plan, PricingInfo } from "./types";+import create from "zustand";+import produce from "immer";++interface ICheckoutStore {+ selectedPlan?: Plan;+ onPlanSelected: (plan?: Plan) => void;+ pricingInfo?: PricingInfo;+ onPriceUpdated: (pricingInfo?: PricingInfo) => void;+ isApplyingCoupon: boolean;+ setIsApplyingCoupon: (isApplyingCoupon: boolean) => void;+ couponCode?: string;+ onApplyCoupon: (couponCode?: string) => void;+ reset: () => void;+}+export const useCheckoutStore = create<ICheckoutStore>((set, get) => ({+ selectedPlan: undefined,+ pricingInfo: undefined,+ couponCode: undefined,+ isApplyingCoupon: false,+ onPlanSelected: (plan) =>+ set(+ produce((state: ICheckoutStore) => {+ state.selectedPlan = plan;+ state.pricingInfo = undefined;+ })+ ),+ onPriceUpdated: (pricingInfo) =>+ set(+ produce((state: ICheckoutStore) => {+ state.pricingInfo = pricingInfo;+ })+ ),+ onApplyCoupon: (couponCode) =>+ set(+ produce((state: ICheckoutStore) => {+ console.log("SETTING coupon", couponCode);+ state.couponCode = couponCode;+ })+ ),+ setIsApplyingCoupon: (isApplyingCoupon) =>+ set(+ produce((state: ICheckoutStore) => {+ state.isApplyingCoupon = isApplyingCoupon;+ })+ ),+ reset: () => {+ set(+ produce((state: ICheckoutStore) => {+ state.selectedPlan = undefined;+ state.pricingInfo = undefined;+ state.couponCode = undefined;+ state.isApplyingCoupon = false;+ })+ );+ },+}));diff --git a/apps/web/src/components/dialogs/buy-dialog/types.ts b/apps/web/src/components/dialogs/buy-dialog/types.tsnew file mode 100644index 000000000..de5bd8872--- /dev/null+++ b/apps/web/src/components/dialogs/buy-dialog/types.ts@@ -0,0 +1,199 @@+export type Period = "monthly" | "yearly";++export enum PaddleEvents {+ /** Checkout has been initialized on the page **/+ "Checkout.Loaded" = "Checkout.Loaded",+ /** Checkout has been closed on the page. This is equivalent to when the "closeCallback" checkout parameter is fired . **/+ "Checkout.Close" = "Checkout.Close",+ /** Checkout has been completed successfully. This is equivalent to when the "successCallback" checkout parameter is fired . **/+ "Checkout.Complete" = "Checkout.Complete",+ /** User has opted into/out of marketing emails in the checkout **/+ "Checkout.User.Subscribed" = "Checkout.User.Subscribed",+ /** User has changed the quantity in the checkout **/+ "Checkout.Quantity.Change" = "Checkout.Quantity.Change",+ /** User has proceeded past the email checkout step **/+ "Checkout.Login" = "Checkout.Login",+ /** User selected 'Not you? Change' in bottom right of checkout **/+ "Checkout.Logout" = "Checkout.Logout",+ /** Payment method has been selected **/+ "Checkout.PaymentMethodSelected" = "Checkout.PaymentMethodSelected",+ /** User clicked 'Add Coupon' **/+ "Checkout.Coupon.Add" = "Checkout.Coupon.Add",+ /** User has submitted a coupon **/+ "Checkout.Coupon.Submit" = "Checkout.Coupon.Submit",+ /** User has cancelled the coupon page **/+ "Checkout.Coupon.Cancel" = "Checkout.Coupon.Cancel",+ /** Valid coupon applied to purchase **/+ "Checkout.Coupon.Applied" = "Checkout.Coupon.Applied",+ /** Coupon has been removed **/+ "Checkout.Coupon.Remove" = "Checkout.Coupon.Remove",+ /** Any generic checkout error, like an invalid VAT number or payment failure **/+ "Checkout.Error" = "Checkout.Error",+ /** User proceeded past the location page **/+ "Checkout.Location.Submit" = "Checkout.Location.Submit",+ /** Language has been changed in the bottom right **/+ "Checkout.Language.Change" = "Checkout.Language.Change",+ /** User clicked 'Add VAT Number' **/+ "Checkout.Vat.Add" = "Checkout.Vat.Add",+ /** VAT screen cancelled **/+ "Checkout.Vat.Cancel" = "Checkout.Vat.Cancel",+ /** VAT number was submitted **/+ "Checkout.Vat.Submit" = "Checkout.Vat.Submit",+ /** VAT number was accepted and applied **/+ "Checkout.Vat.Applied" = "Checkout.Vat.Applied",+ /** VAT number was removed **/+ "Checkout.Vat.Remove" = "Checkout.Vat.Remove",+ /** Wire transfer details have been completed **/+ "Checkout.WireTransfer.Complete" = "Checkout.WireTransfer.Complete",+ /** Payment has been completed successfully. **/+ "Checkout.PaymentComplete" = "Checkout.PaymentComplete",+ /** User has selected "Change Payment Method" when on the payment screen **/+ "Checkout.PaymentMethodChange" = "Checkout.PaymentMethodChange",+ /** User has selected "Change Payment Method" when on the Wire Transfer screen **/+ "Checkout.WireTransfer.PaymentMethodChange" = "Checkout.WireTransfer.PaymentMethodChange",+}++export interface CallbackData {+ checkout?: Checkout;+}++export interface Checkout {+ id?: string;+}++export type PaddleEvent = {+ action: "event";+ event_name: PaddleEvents;+ callback_data: CallbackData;+};++export interface Plan {+ id: string;+ period: Period;+ price: Price;+ currency: string;+ originalPrice?: Price;+ discount: number;+ country: string;+}++export type PricingInfo = {+ country: string;+ currency: string;+ price: Price;+ period: Period;+ recurringPrice: Price;+ discount: Discount;+ coupon?: string;+};++export type Discount = {+ recurring: boolean;+ amount: number;+};++export interface Price {+ gross: number;+ net: number;+ tax: number;+ currency?: string;+}++export interface CheckoutDataResponse {+ data: CheckoutData;+}++export interface CheckoutData {+ public_checkout_id: string;+ type: string;+ uuid: string;+ vendor: Vendor;+ display_currency: string;+ charge_currency: string;+ customer: Customer;+ items: Item[];+ available_payment_methods: any[];+ total: TotalPrice[];+ pending_payment: boolean;+ completed: boolean;+ payment_method_type: null;+ flagged_for_review: boolean;+ ip_geo_country_code: string;+ tax: null;+ name: null;+ image_url: null;+ message: null;+ passthrough: string;+ redirect_url: null;+ created_at: Date;+}++export interface Customer {+ id: number;+ email: string;+ country_code: string;+ postcode: null;+ audience_opt_in: boolean;+}++export interface Item {+ checkout_product_id: number;+ product_id: number;+ name: string;+ custom_message: string;+ quantity: number;+ allow_quantity: boolean;+ min_quantity: number;+ max_quantity: number;+ icon_url: string;+ prices: CheckoutPrices[];+ recurring: Recurring;+ webhook_url: null;+}++export interface CheckoutPrices {+ currency: string;+ unit_price: CheckoutPrice;+ line_price: CheckoutPrice;+ discounts: CheckoutDiscount[];+ tax_rate: number;+}++export interface CheckoutDiscount {+ rank: number;+ type: string;+ net_discount: number;+ gross_discount: number;+ code: string;+ description: string;+}++export interface CheckoutPrice {+ net: number;+ gross: number;+ net_discount: number;+ gross_discount: number;+ net_after_discount: number;+ gross_after_discount: number;+ tax: number;+ tax_after_discount: number;+}++export interface Recurring {+ period: string;+ interval: number;+ trial_days: number;+ prices: CheckoutPrices[];+}++export type TotalPrice = CheckoutPrice & {+ currency: string;+ is_free: boolean;+ includes_tax: boolean;+ tax_rate: number;+};++export interface Vendor {+ id: number;+ name: string;+}diff --git a/apps/web/src/components/dialogs/buydialog.js b/apps/web/src/components/dialogs/buydialog.jsdeleted file mode 100644index 90f1779a2..000000000--- a/apps/web/src/components/dialogs/buydialog.js+++ /dev/null@@ -1,894 +0,0 @@-import { useCallback, useEffect, useState } from "react";-import { Text, Flex, Button, Box } from "rebass";-import * as Icon from "../icons";-import { useStore as useUserStore } from "../../stores/user-store";-import { getPlans, getPlan, inlineCheckout } from "../../common/checkout";-import getSymbolFromCurrency from "currency-symbol-map";-import { ANALYTICS_EVENTS, trackEvent } from "../../utils/analytics";-import Modal from "react-modal";-import { useTheme } from "emotion-theming";-import { ReactComponent as Rocket } from "../../assets/rocket.svg";-import { ReactComponent as Nomad } from "../../assets/nomad.svg";-import { ReactComponent as WorkAnywhere } from "../../assets/workanywhere.svg";-import { ReactComponent as WorkLate } from "../../assets/worklate.svg";-import Loader from "../loader";-import Field from "../field";-import { useSessionState } from "../../utils/hooks";-import { hardNavigate } from "../../navigation";--const sections = [- {- title: "Focused on privacy",- detail:- "Everything you do in Notesnook stays private. We use XChaCha20-Poly1305-IETF and Argon2 to encrypt your notes.",- features: [- {- title: "Zero ads & zero trackers",- icon: Icon.Billboard,- },- {- title: "On device encryption",- icon: Icon.Cellphone,- },- {- title: "Secure app lock for all",- icon: Icon.CellphoneLock,- },- {- title: "100% end-to-end encrypted",- icon: Icon.Lock,- },- {- title: "Private vault for notes",- icon: Icon.ShieldLock,- pro: true,- },- ],- },- {- title: "Instant syncing",- detail:- "Seemlessly work from anywhere. Every change is synced instantly everywhere.",- pro: true,- },- {- title: "100% cross platform",- detail: "Notesnook is available on all major platforms — for everyone.",- columns: 8,- features: [- {- icon: Icon.iOS,- },- {- icon: Icon.Android,- },- {- icon: Icon.Windows,- },- {- icon: Icon.Linux,- },- {- icon: Icon.MacOS,- },- {- icon: Icon.Chrome,- },- {- icon: Icon.Firefox,- },- {- icon: Icon.Safari,- },- ],- },- {- title: "Attach files & images",- detail:- "Add your documents, PDFs, images and videos, and keep them safe and organized.",- pro: true,- features: [- {- title: "Bulletproof encryption",- icon: Icon.Lock,- },- {- title: "High quality 4K images",- icon: Icon.ImageMultiple,- },- {- title: "Unlimited storage",- icon: Icon.Harddisk,- },- {- title: "Upto 500 MB per file",- icon: Icon.FileCabinet,- },- {- title: "All file types supported",- icon: Icon.File,- },- ],- },- {- title: "No limit on notes",- detail:- "We don't have nonsense like blocks and whatnot. You can create as many notes as you want — no limits.",- },- {- title: "Safe publishing to the Internet",- detail:- "Publishing is nothing new but we offer fully encrypted, anonymous publishing. Take any note & share it with the world.",- features: [- {- title: "Anonymous publishing",- icon: Icon.Anonymous,- },- {- title: "Password protection",- icon: Icon.CloudLock,- },- {- title: "Self destructable notes",- icon: Icon.Timebomb,- },- ],- },- {- title: "Organize yourself in the best way",- detail:- "We offer multiple ways to keep you organized. The only limit is your imagination.",- features: [- {- title: "Unlimited notebooks*",- icon: Icon.Notebook2,- pro: true,- },- {- title: "Colors & tags*",- icon: Icon.Palette,- pro: true,- },- {- title: "Side menu shortcuts",- icon: Icon.Shortcut,- },- {- title: "Pins & favorites",- icon: Icon.Pin,- },- ],- info: "* Free users can only create 3 notebooks (no limit on topics) and 5 tags.",- },-- {- title: "Rich tools for rich editing",- detail:- "Having the right tool at the right time is crucial for note taking. Lists, tables, codeblocks — you name it, we have it.",- pro: true,- features: [- {- title: "Lists & tables",- icon: Icon.Table,- },- {- title: "Images & embeds",- icon: Icon.Embed,- },- {- title: "Checklists",- icon: Icon.CheckCircleOutline,- },- {- title: "Markdown shortcuts",- icon: Icon.Markdown,- },- ],- },- {- title: "Export and take your notes anywhere",- detail:- "You own your notes, not us. No proprietary formats. No vendor lock in. No waiting for hours to download your notes.",- // info: "* Free users can export notes in well formatted plain text.",- features: [- {- title: "Export as Markdown",- icon: Icon.Markdown,- pro: true,- },- {- title: "Export as PDF",- icon: Icon.PDF,- pro: true,- },- {- title: "Export as HTML",- icon: Icon.HTML,- pro: true,- },- {- title: "Export as text",- icon: Icon.Text,- },- {- title: "Bulk exports",- icon: Icon.Export,- },- ],- },- {- title: "Backup & keep your notes safe",- detail:- "Do not worry about losing your data. Turn on automatic backups on weekly or daily basis.",- features: [- {- title: "Automatic monthly, weekly & daily backups",- icon: Icon.Backup,- pro: true,- },- {- title: "Backup encryption",- icon: Icon.EncryptedBackup,- pro: true,- },- ],- },- {- title: "Personalize & make Notesnook your own",- detail:- "Change app themes to match your style. Custom themes are coming soon.",- pro: true,- features: [- {- title: "10+ themes",- icon: Icon.Accent,- },- {- title: "Automatic dark mode",- icon: Icon.Theme,- },- {- title: "Change default home page",- icon: Icon.Home,- },- ],- },-];--function BuyDialog(props) {- const { couponCode, plan } = props;- const user = useUserStore((store) => store.user);- const isLoggedIn = useUserStore((store) => store.isLoggedIn);- const [selectedPlan, setSelectedPlan] = useState();- const [discount, setDiscount] = useState();- const theme = useTheme();-- useEffect(() => {- trackEvent(ANALYTICS_EVENTS.purchaseInitiated, "Buy dialog opened.");- }, []);-- useEffect(() => {- if (!plan) return;- (async function () {- const product = await getPlan(plan);- setDiscount({ isApplyingCoupon: !!couponCode });- setSelectedPlan({- ...productToPlan(product),- coupon: couponCode,- });- })();- }, [plan, couponCode]);-- const onCheckoutLoaded = useCallback((data) => {- setSelectedPlan((plan) => {- const pricingInfo = getPricingInfoFromCheckout(plan, data);- if (plan.country !== pricingInfo.country) {- return { ...plan, ...pricingInfo };- }- setDiscount(pricingInfo);- return plan;- });- }, []);-- return (- <Modal- isOpen={true}- onRequestClose={props.onClose}- shouldCloseOnEsc- shouldReturnFocusAfterClose- shouldFocusAfterRender- onAfterOpen={(e) => {- if (!props.onClose) return;- // we need this work around because ReactModal content spreads over the overlay- const child = e.contentEl.firstElementChild;- e.contentEl.onmousedown = function (e) {- if (!e.screenX && !e.screenY) return;- if (- e.x < child.offsetLeft ||- e.x > child.offsetLeft + child.clientWidth ||- e.y < child.offsetTop ||- e.y > child.offsetTop + child.clientHeight- ) {- props.onClose();- }- };- if (props.onOpen) props.onOpen();- }}- style={{- content: {- top: 0,- left: 0,- right: 0,- bottom: 0,- display: "flex",- justifyContent: "center",- backgroundColor: undefined,- padding: 0,- overflowY: "hidden",- border: 0,- zIndex: 0,- },- overlay: {- zIndex: 999,- background: theme.colors.overlay,- },- }}- >- <Flex- flexDirection={["column", "column", "row"]}- width={["95%", "80%", "60%"]}- maxHeight={["95%", "80%", "80%"]}- bg="transparent"- alignSelf={"center"}- overflowY={["scroll", "scroll", "auto"]}- sx={{- position: "relative",- // overflow: "hidden",- boxShadow: "4px 5px 18px 2px #00000038",- borderRadius: "dialog",- }}- >- <Flex- flexDirection="column"- justifyContent="center"- alignItems="center"- flexShrink={0}- sx={{- borderTopLeftRadius: "dialog",- borderBottomLeftRadius: [0, 0, "dialog"],- overflow: "hidden",- bg: "bgSecondary",- "@supports ((-webkit-backdrop-filter: none) or (backdrop-filter: none))":- {- bg: "bgTransparent",- backdropFilter: "blur(8px)",- },- }}- width={["100%", "100%", 350]}- p={4}- py={50}- >- {isLoggedIn ? (- selectedPlan ? (- <SelectedPlan- plan={{ ...selectedPlan, ...discount }}- onPlanChangeRequest={() => {- setSelectedPlan();- setDiscount();- }}- isPlanChangeable={!plan}- onCouponApplied={(coupon) => {- setDiscount({- isApplyingCoupon: true,- });- setSelectedPlan((plan) => ({- ...plan,- coupon,- }));- }}- />- ) : plan ? (- <Loader title="Please wait..." />- ) : (- <ChooseAPlan- selectedPlan={selectedPlan}- onPlanChanged={(plan) => setSelectedPlan(plan)}- />- )- ) : (- <TryForFree couponCode={couponCode} />- )}- </Flex>- {isLoggedIn ? (- selectedPlan ? (- <Checkout- user={user}- planId={selectedPlan.key}- coupon={selectedPlan.coupon}- country={selectedPlan.country}- onCheckoutLoaded={onCheckoutLoaded}- />- ) : plan ? null : (- <FeaturesList />- )- ) : (- <FeaturesList />- )}- </Flex>- </Modal>- );-}-export default BuyDialog;--function RecurringPricing(props) {- const { plan } = props;- // if (product.prices.total === prices.recurring_prices.total) return null;- return (- <Text variant="body" fontSize="subBody">- <Text as="span" fontSize="subtitle">- <Price currency={plan.currency} price={plan.price} />- </Text>- {formatPeriod(plan.key)}- </Text>- );-}--function Price(props) {- const { currency, price } = props;- return (- <>- {getSymbolFromCurrency(currency)}- {price}- </>- );-}--function FeaturesList() {- return (- <Flex- flexDirection="column"- flex={1}- overflowY={["hidden", "hidden", "auto"]}- flexShrink={0}- sx={{ position: "relative" }}- pt={6}- bg="background"- >- {sections.map((section) => (- <Flex flexDirection="column" px={6} pb={50}>- {section.pro && (- <Flex- bg="bgSecondary"- alignSelf="start"- px={2}- py="2px"- sx={{ borderRadius: 50 }}- mb={1}- >- <Icon.Pro color="primary" size={16} />- <Text variant="body" color="primary" ml={"2px"}>- Pro- </Text>- </Flex>- )}- <Text variant="body" fontSize={"1.3rem"}>- {section.title}- </Text>- <Text variant="body" mt={1} fontSize="title" color="fontTertiary">- {section.detail}- </Text>- {section.features && (- <Box- sx={{- display: "grid",- gridTemplateColumns: section.columns- ? "1fr ".repeat(section.columns)- : "1fr 1fr 1fr",- gap: 3,- }}- mt={4}- >- {section.features.map((feature) => (- <Flex alignItems="start" flexDirection="column">- <feature.icon size={20} color="text" sx={{ mb: 1 }} />- {feature.pro && (- <Flex justifyContent="center" alignItems="center">- <Icon.Pro color="primary" size={14} />- <Text variant="subBody" color="primary" ml={"2px"}>- Pro- </Text>- </Flex>- )}- {feature.title && (- <Text variant="body" fontSize="subtitle">- {feature.title}- </Text>- )}- </Flex>- ))}- </Box>- )}- {section.info && (- <Text mt={1} variant="subBody">- {section.info}- </Text>- )}- </Flex>- ))}- </Flex>- );-}--function Checkout({ user, planId, coupon, country, onCheckoutLoaded }) {- const [isLoaded, setIsLoaded] = useState(false);- useEffect(() => {- (async () => {- setIsLoaded(false);- await inlineCheckout({- user,- plan: planId,- coupon,- country,- onCheckoutLoaded,- });- setIsLoaded(true);- })();- // eslint-disable-next-line react-hooks/exhaustive-deps- }, [planId, coupon]);-- return (- <Flex- bg="background"- //width="100%"- flex={1}- padding={40}- flexShrink={[0, 0, 1]}- overflowY={["hidden", "hidden", "auto"]}- alignItems={isLoaded ? "stretch" : "center"}- >- {!isLoaded ? (- <Loader- title={- coupon- ? "Applying coupon code. Please wait..."- : "Loading checkout. Please wait..."- }- />- ) : null}- <Box- flex={1}- className="checkout-container"- display={!isLoaded ? "none" : "block"}- />- </Flex>- );-}--const CACHED_PLANS = [- {- key: "monthly",- title: "Monthly",- subtitle: `Pay once a month.`,- },- {- key: "yearly",- title: "Yearly",- subtitle: `Pay once a year.`,- },-];-function PlansList({ selectedPlan, onPlanChanged }) {- const [isLoading, setIsLoading] = useState(false);- const [plans, setPlans] = useSessionState("PlansList:plans", CACHED_PLANS);-- useEffect(() => {- if (plans && plans !== CACHED_PLANS) return;- (async function () {- try {- setIsLoading(true);- let plans = await getPlans();- plans = plans.map((product) => {- return productToPlan(product);- });- setPlans(plans);- } catch (e) {- console.error(e);- } finally {- setIsLoading(false);- }- })();- }, [plans, setPlans]);-- return plans.map((plan) => (- <Button- disabled={isLoading}- data-test-id={`checkout-plan-${plan.key}`}- variant="tool"- display="flex"- textAlign="start"- justifyContent="space-between"- alignItems="center"- flex={1}- mt={1}- sx={{- bg: selectedPlan?.key === plan.key ? "border" : "transparent",- border:- selectedPlan?.key === plan.key ? "1px solid var(--primary)" : "none",- }}- onClick={() => onPlanChanged(plan)}- >- <Text variant="subtitle" fontWeight="normal">- {plan.title}- <Text variant="body" fontWeight="normal" color="fontTertiary">- {plan.subtitle}- </Text>- </Text>- {isLoading ? <Icon.Loading /> : <RecurringPricing plan={plan} />}- </Button>- ));-}--function ChooseAPlan({ selectedPlan, onPlanChanged }) {- return (- <>- <Nomad width={200} />- <Text variant="heading" textAlign="center" mt={4}>- Choose a plan- </Text>- <Text variant="body" textAlign="center" mt={1}>- Every day we spend hours improving Notesnook. You are what makes that- possible.- </Text>- <Flex flexDirection="column" alignSelf="stretch" mt={2}>- <PlansList selectedPlan={selectedPlan} onPlanChanged={onPlanChanged} />- </Flex>- </>- );-}--function TryForFree({ couponCode }) {- return (- <>- <Rocket width={200} />- <Text variant="heading" textAlign="center" mt={4}>- Notesnook Pro- </Text>- <Text variant="body" textAlign="center" mt={1}>- Ready to take the next step in your private note taking journey?- </Text>- <Button variant="primary" mt={4} onClick={() => hardNavigate("/signup")}>- {couponCode ? "Claim my discount" : "Try free for 14 days"}- </Button>- {couponCode && (- <Text- variant="subBody"- bg="shade"- color="primary"- mt={4}- p={1}- sx={{ borderRadius: "default" }}- >- Please sign up or login to use your coupon: <b>{couponCode}</b>- </Text>- )}- </>- );-}--function SelectedPlan({- plan,- isPlanChangeable,- onPlanChangeRequest,- onCouponApplied,-}) {- useEffect(() => {- const couponInput = document.getElementById("coupon");- couponInput.value = plan.coupon ? plan.coupon : couponInput.value;- }, [plan.coupon]);-- return (- <>- {plan.key === "monthly" ? (- <WorkAnywhere width={180} />- ) : (- <WorkLate width={180} />- )}- <Text variant="heading" textAlign="center" mt={4}>- Notesnook Pro- </Text>- <Text- data-test-id="checkout-plan-title"- variant="body"- fontSize="subheading"- textAlign="center"- mt={1}- >- {plan.title}- </Text>- <Field- variant={plan.isInvalidCoupon ? "error" : "input"}- sx={{ alignSelf: "stretch", my: 2 }}- styles={{ input: { fontSize: "body" } }}- data-test-id="checkout-coupon-code"- id="coupon"- name="coupon"- placeholder="Coupon code"- autoFocus={plan.isInvalidCoupon}- disabled={!!plan.coupon}- onKeyUp={(e) => {- if (e.code === "Enter") {- const couponInput = document.getElementById("coupon");- if (!!plan.coupon) couponInput.value = "";- onCouponApplied(couponInput.value);- }- }}- action={{- icon: plan.isApplyingCoupon- ? Icon.Loading- : plan.coupon- ? Icon.Cross- : Icon.Check,- onClick: () => {- const couponInput = document.getElementById("coupon");- if (!!plan.coupon) couponInput.value = "";- onCouponApplied(couponInput.value);- },- }}- />- <CheckoutPricing- currency={plan.currency}- period={plan.key}- subtotal={plan.price}- discountedPrice={plan.discount || 0.0}- tax={plan.tax || 0.0}- recurringTax={plan.recurringTax || 0.0}- isRecurringDiscount={plan.isRecurringDiscount}- />- {isPlanChangeable && (- <Button- data-test-id="checkout-plan-change"- variant="secondary"- mt={4}- px={4}- onClick={onPlanChangeRequest}- >- Change plan- </Button>- )}- </>- );-}--function CheckoutPricing({- currency,- period,- subtotal,- discountedPrice,- tax,- recurringTax,- isRecurringDiscount,-}) {- const fields = [- {- key: "subtotal",- label: "Subtotal",- value: formatPrice(currency, subtotal.toFixed(2)),- },- {- key: "tax",- label: "Sales tax",- color: "error",- value: formatPrice(currency, tax.toFixed(2), null),- },- {- key: "discount",- label: "Discount",- color: "primary",- value: formatPrice(- currency,- discountedPrice.toFixed(2),- null,- discountedPrice > 0- ),- },- ];- const currentTotal = (subtotal + tax - discountedPrice).toFixed(2);- const recurringTotal = (subtotal + recurringTax).toFixed(2);- const isDiscounted = isRecurringDiscount || discountedPrice <= 0;- return (- <>- {fields.map((field) => (- <Flex- key={field.key}- justifyContent="space-between"- alignSelf="stretch"- mt={1}- >- <Text variant="body" fontSize="subtitle">- {field.label}- </Text>- <Text- data-test-id={`checkout-price-${field.key}`}- variant="body"- fontSize="subtitle"- color={field.color || "text"}- >- {field.value}- </Text>- </Flex>- ))}- <Flex justifyContent="space-between" alignSelf="stretch" mt={1}>- <Text variant="body" fontSize="heading">- Total- </Text>- <Text- data-test-id={`checkout-price-total`}- variant="body"- fontSize="heading"- color={"text"}- textAlign="end"- >- {formatPrice(currency, currentTotal, isDiscounted ? period : "null")}- <Text fontSize="body">- {isDiscounted- ? ""- : `then ${formatPrice(currency, recurringTotal, period)}`}- </Text>- </Text>- </Flex>- </>- );-}--function formatPrice(currency, price, period, negative = false) {- return `${negative ? "-" : ""}${getSymbolFromCurrency(- currency- )}${price}${formatPeriod(period)}`;-}--function formatPeriod(period) {- return period === "monthly" ? "/mo" : period === "yearly" ? "/yr" : "";-}--function getPricingInfoFromCheckout(plan, eventData) {- const {- checkout,- user: { country },- } = eventData;- const { prices, recurring_prices, coupon } = checkout;- const { currency, total, total_tax } = prices.customer;-- const couponCode = coupon.coupon_code ? coupon.coupon_code : undefined;- const price = parseFloat(total);- const recurringPrice = parseFloat(recurring_prices.customer.total);- const tax = parseFloat(total_tax);- const recurringTax = parseFloat(recurring_prices.customer.total_tax);- const isCouponApplied = !!couponCode;-- const isCurrencyChanged = plan.currency !== currency;- return {- country,- currency,- price: isCurrencyChanged ? price : plan.price,- tax,- recurringTax,- discount: isCouponApplied ? plan.price - price : 0,- coupon: couponCode,- isRecurringDiscount: couponCode && price === recurringPrice,- isInvalidCoupon: plan.coupon && plan.coupon !== couponCode,- };-}--function productToPlan(product) {- return {- key: `${product.subscription.interval}ly`,- // country: product.customer_country,- currency: product.currency,- price: product.price.net,- id: product.product_id,- title: product.subscription.interval === "month" ? "Monthly" : "Yearly",- subtitle: `Pay once a ${product.subscription.interval}.`,-- tax: product.price.tax,- recurringTax: product.subscription.price.tax,- };-}diff --git a/apps/web/src/components/dialogs/feature-dialog.tsx b/apps/web/src/components/dialogs/feature-dialog.tsxindex 53a799991..ad9eb7fcc 100644--- a/apps/web/src/components/dialogs/feature-dialog.tsx+++ b/apps/web/src/components/dialogs/feature-dialog.tsx@@ -85,7 +85,11 @@ type FeatureDialogProps = {function FeatureDialog(props: FeatureDialogProps) {const { featureName } = props;const feature = features[featureName];- if (!feature || (feature.shouldShow && !feature.shouldShow())) return null;+ if (!feature || (feature.shouldShow && !feature.shouldShow())) {+ props.onClose(false);+ return null;+ }+return (<DialogisOpen={true}diff --git a/apps/web/src/components/dialogs/onboarding-dialog.js b/apps/web/src/components/dialogs/onboarding-dialog.jsindex f61e9bcbf..f229fdb8d 100644--- a/apps/web/src/components/dialogs/onboarding-dialog.js+++ b/apps/web/src/components/dialogs/onboarding-dialog.js@@ -122,7 +122,11 @@ function OnboardingDialog({ onClose: _onClose, type }) {else setStep((s) => ++s);}, []);- if (!steps || !steps[step] || !type) return null;+ if (!steps || !steps[step] || !type) {+ onClose();+ return null;+ }+const {title,subtitle,diff --git a/apps/web/src/navigation/hash-routes.js b/apps/web/src/navigation/hash-routes.jsindex 7fcac4ae0..ec627c7e3 100644--- a/apps/web/src/navigation/hash-routes.js+++ b/apps/web/src/navigation/hash-routes.js@@ -5,7 +5,6 @@ import {showCreateTagDialog,showEditTagDialog,showEmailVerificationDialog,- showError,showFeatureDialog,showOnboardingDialog,} from "../common/dialog-controller";@@ -28,7 +27,6 @@ import { hashNavigate } from ".";import { Suspense } from "react";import EditorLoading from "../components/editor/loading";import EditorPlaceholder from "../components/editor/-placeholder";-import { db } from "../common/db";const Editor = React.lazy(() => import("../components/editor"));const hashroutes = {diff --git a/apps/web/src/views/auth.tsx b/apps/web/src/views/auth.tsxindex d70a77c3c..d23f0e98a 100644--- a/apps/web/src/views/auth.tsx+++ b/apps/web/src/views/auth.tsx@@ -22,9 +22,10 @@ import { showToast } from "../utils/toast";import AuthContainer from "../components/auth-container";import { isTesting } from "../utils/platform";import { AuthenticatorType } from "../components/dialogs/multi-factor-dialog";-import { RequestError } from "notes-core/utils/http";import { useTimer } from "../hooks/use-timer";import { ANALYTICS_EVENTS, trackEvent } from "../utils/analytics";+// @ts-ignore+import { RequestError } from "notes-core/utils/http";type LoginFormData = {email: string;@@ -910,9 +911,10 @@ async function login(Config.set("sessionExpired", false);openURL("/");} catch (e) {- if (e instanceof RequestError && e.code === "mfa_required") {+ const error = e as any;+ if (error.code === "mfa_required") {const { primaryMethod, phoneNumber, secondaryMethod, token } =- e.data as MFAErrorData;+ error.data as MFAErrorData;if (!primaryMethod)throw new Error(diff --git a/apps/web/src/views/settings.js b/apps/web/src/views/settings.jsindex 849d78184..414e77d14 100644--- a/apps/web/src/views/settings.js+++ b/apps/web/src/views/settings.js@@ -33,7 +33,6 @@ import { showToast } from "../utils/toast";import { hardNavigate, hashNavigate } from "../navigation";import { appVersion } from "../utils/version";import { CHECK_IDS } from "notes-core/common";-import { openPaddleDialog } from "../common/checkout";import Tip from "../components/tip";import Toggle from "../components/toggle";import { isDesktop } from "../utils/platform";@@ -908,7 +907,7 @@ function AccountStatus(props) {"error","Failed to update. Please reach out to us at [email protected] so we can help you resolve the issue.");- await openPaddleDialog(user.subscription.updateURL);+ window.open(user.subscription.updateURL, "_blank");}}><Tip@@ -925,7 +924,7 @@ function AccountStatus(props) {"error","Failed to cancel subscription. Please reach out to us at [email protected] so we can help you resolve the issue.");- await openPaddleDialog(user.subscription.cancelURL);+ window.open(user.subscription.cancelURL, "_blank");}}><Tip