📈 Open source, privacy-first web analytics — a cookie-less Google Analytics alternative with built-in error tracking and performance monitoring. Self-host it or use our cloud. Get started for free!
TypeScript chartsclickhousedockergdprgoogle-analyticsmetricsmonitoringmysqlnestjsprivacyredisself-hostedselfhostedstatisticstailwindcssweb-analyticswebanalyticswebsite
Move Billing to user settings
Blue Mousec748c12665be
diff --git a/web/app/components/pricing/BillingPricing.tsx b/web/app/components/pricing/BillingPricing.tsxindex 020ccdbbb..5096aa916 100644--- a/web/app/components/pricing/BillingPricing.tsx+++ b/web/app/components/pricing/BillingPricing.tsx@@ -1,9 +1,8 @@-import { Label, Radio, RadioGroup } from '@headlessui/react'-import cx from 'clsx'import dayjs from 'dayjs'import _includes from 'lodash/includes'import _isNil from 'lodash/isNil'import _map from 'lodash/map'+import _round from 'lodash/round'import { QuestionIcon } from '@phosphor-icons/react'import React, { memo, useEffect, useMemo, useState } from 'react'import { Trans, useTranslation } from 'react-i18next'@@ -22,11 +21,12 @@ import {import { Metainfo, DEFAULT_METAINFO } from '~/lib/models/Metainfo'import { useAuth } from '~/providers/AuthProvider'import { useTheme } from '~/providers/ThemeProvider'-import type { BillingActionData } from '~/routes/billing'+import type { UserSettingsActionData } from '~/routes/user-settings'import { Badge } from '~/ui/Badge'import Button from '~/ui/Button'import Loader from '~/ui/Loader'import Modal from '~/ui/Modal'+import { Switch } from '~/ui/Switch'import Tooltip from '~/ui/Tooltip'import { cn } from '~/utils/generic'import routes from '~/utils/routes'@@ -50,8 +50,8 @@ const BillingPricing = ({const { isAuthenticated, user, loadUser } = useAuth()const { theme } = useTheme()- const previewFetcher = useFetcher<BillingActionData>()- const changePlanFetcher = useFetcher<BillingActionData>()+ const previewFetcher = useFetcher<UserSettingsActionData>()+ const changePlanFetcher = useFetcher<UserSettingsActionData>()const [planCodeLoading, setPlanCodeLoading] = useState<string | null>(null)const [@@ -174,7 +174,7 @@ const BillingPricing = ({setIsNewPlanConfirmationModalOpened(true)previewFetcher.submit({ intent: 'preview-subscription-update', planId: String(planId) },- { method: 'POST', action: '/billing' },+ { method: 'POST', action: '/user-settings' },)}@@ -230,7 +230,7 @@ const BillingPricing = ({const updateSubscription = () => {changePlanFetcher.submit({ intent: 'change-subscription-plan', planId: String(newPlanId) },- { method: 'POST', action: '/billing' },+ { method: 'POST', action: '/user-settings' },)}@@ -292,48 +292,53 @@ const BillingPricing = ({return validCodes.map((code) => PLAN_LIMITS[code])}, [PLAN_CODES_ARRAY])+ const yearlyDiscount = useMemo(() => {+ const firstTier = tiers[0]+ if (!firstTier) return 0++ const monthlyPrice = firstTier.price[currencyCode]?.monthly ?? 0+ const yearlyPrice = firstTier.price[currencyCode]?.yearly ?? 0++ if (monthlyPrice === 0) return 0++ const annualCostIfMonthly = monthlyPrice * 12+ const savings = annualCostIfMonthly - yearlyPrice+ const discountPercentage = (savings / annualCostIfMonthly) * 100++ return _round(discountPercentage, 0)+ }, [tiers, currencyCode])+return (<><div className='rounded-xl border border-gray-200 p-4 sm:p-6 dark:border-white/10'>- <div className='mb-3 flex justify-between'>+ <div className='mb-3 flex items-center justify-between'><h2 className='text-2xl font-bold text-black dark:text-gray-50'>{t('common.billing')}</h2>- <RadioGroup- value={billingFrequency}- onChange={setBillingFrequency}- className='grid grid-cols-2 gap-x-1 rounded-md p-1 text-center text-xs leading-5 font-semibold ring-1 ring-gray-200 dark:ring-white/20'+ <button+ type='button'+ onClick={() =>+ setBillingFrequency(+ billingFrequency === BillingFrequency.yearly+ ? BillingFrequency.monthly+ : BillingFrequency.yearly,+ )+ }+ className='flex cursor-pointer items-center gap-2 rounded-lg bg-gray-100 px-3 py-2 transition-colors hover:bg-gray-200 dark:bg-slate-800 dark:hover:bg-slate-700'>- <Label className='sr-only'>{t('pricing.frequency')}</Label>- <Radio- key={BillingFrequency.monthly}- value={BillingFrequency.monthly}- className={({ checked }) =>- cx(- checked- ? 'bg-slate-900 text-gray-50 dark:bg-white/90 dark:text-slate-900'- : 'text-slate-700 hover:bg-slate-200 dark:text-gray-200 dark:hover:bg-white/30 dark:hover:text-white',- 'flex cursor-pointer items-center justify-center rounded-md px-2.5 py-1 transition-all',- )- }- >- <span>{t('pricing.monthlyBilling')}</span>- </Radio>- <Radio- key={BillingFrequency.yearly}- value={BillingFrequency.yearly}- className={({ checked }) =>- cx(- checked- ? 'bg-slate-900 text-gray-50 dark:bg-white/90 dark:text-slate-900'- : 'text-slate-700 hover:bg-slate-200 dark:text-gray-200 dark:hover:bg-white/30 dark:hover:text-white',- 'flex cursor-pointer items-center justify-center rounded-md px-2.5 py-1 transition-all',- )- }- >- <span>{t('pricing.yearlyBilling')}</span>- </Radio>- </RadioGroup>+ <span className='text-sm font-medium text-gray-700 dark:text-gray-200'>+ {t('pricing.billedYearly')}+ </span>+ {yearlyDiscount > 0 ? (+ <span className='rounded-md bg-emerald-100 px-1.5 py-0.5 text-xs font-semibold text-emerald-700 dark:bg-emerald-900/50 dark:text-emerald-400'>+ -{yearlyDiscount} %+ </span>+ ) : null}+ <Switch+ checked={billingFrequency === BillingFrequency.yearly}+ onChange={() => {}}+ />+ </button></div><div className='space-y-2'>diff --git a/web/app/components/pricing/MarketingPricing.tsx b/web/app/components/pricing/MarketingPricing.tsxindex 11aeaf3ff..6703ef43b 100644--- a/web/app/components/pricing/MarketingPricing.tsx+++ b/web/app/components/pricing/MarketingPricing.tsx@@ -1,8 +1,7 @@-import { Label, Radio, RadioGroup } from '@headlessui/react'-import cx from 'clsx'import _map from 'lodash/map'+import _round from 'lodash/round'import { ArrowRightIcon, QuestionIcon, CheckIcon } from '@phosphor-icons/react'-import { useState } from 'react'+import { useState, useMemo } from 'react'import { useTranslation } from 'react-i18next'import { Link } from 'react-router'@@ -15,6 +14,7 @@ import {} from '~/lib/constants'import { DEFAULT_METAINFO, Metainfo } from '~/lib/models/Metainfo'import { useAuth } from '~/providers/AuthProvider'+import { Switch } from '~/ui/Switch'import Tooltip from '~/ui/Tooltip'import routes from '~/utils/routes'@@ -40,6 +40,22 @@ const MarketingPricing = ({(code) => PLAN_LIMITS[code as keyof typeof PLAN_LIMITS],)+ const yearlyDiscount = useMemo(() => {+ const firstPlan = plans[0]+ if (!firstPlan) return 0++ const monthlyPrice = firstPlan.price[currencyCode]?.monthly ?? 0+ const yearlyPrice = firstPlan.price[currencyCode]?.yearly ?? 0++ if (monthlyPrice === 0) return 0++ const annualCostIfMonthly = monthlyPrice * 12+ const savings = annualCostIfMonthly - yearlyPrice+ const discountPercentage = (savings / annualCostIfMonthly) * 100++ return _round(discountPercentage, 0)+ }, [plans, currencyCode])+return (<section id='pricing' className='relative p-2'><div className='rounded-xl bg-slate-900 py-16 sm:py-20'>@@ -142,41 +158,30 @@ const MarketingPricing = ({<div className='col-span-12 lg:col-span-7'><div className='mb-3 flex justify-end'>- <RadioGroup- value={billingFrequency}- onChange={setBillingFrequency}- className='grid grid-cols-2 gap-x-1 rounded-md p-1 text-center text-xs leading-5 font-semibold ring-1 ring-white/20'+ <button+ type='button'+ onClick={() =>+ setBillingFrequency(+ billingFrequency === BillingFrequency.yearly+ ? BillingFrequency.monthly+ : BillingFrequency.yearly,+ )+ }+ className='flex cursor-pointer items-center gap-2 rounded-lg bg-white/10 px-3 py-2 transition-colors hover:bg-white/20'>- <Label className='sr-only'>{t('pricing.frequency')}</Label>- <Radio- key={BillingFrequency.monthly}- value={BillingFrequency.monthly}- className={({ checked }) =>- cx(- checked- ? 'bg-white/90 text-slate-900'- : 'text-gray-200 hover:bg-white/30 hover:text-white',- 'flex cursor-pointer items-center justify-center rounded-md px-2.5 py-1 transition-all',- )- }- >- <span>{t('pricing.monthlyBilling')}</span>- </Radio>- <Radio- key={BillingFrequency.yearly}- value={BillingFrequency.yearly}- className={({ checked }) =>- cx(- checked- ? 'bg-white/90 text-slate-900'- : 'text-gray-200 hover:bg-white/30 hover:text-white',- 'flex cursor-pointer items-center justify-center rounded-md px-2.5 py-1 transition-all',- )- }- >- <span>{t('pricing.yearlyBilling')}</span>- </Radio>- </RadioGroup>+ <span className='text-sm font-medium text-gray-100'>+ {t('pricing.billedYearly')}+ </span>+ {yearlyDiscount > 0 ? (+ <span className='rounded-md bg-emerald-500/20 px-1.5 py-0.5 text-xs font-semibold text-emerald-300'>+ -{yearlyDiscount} %+ </span>+ ) : null}+ <Switch+ checked={billingFrequency === BillingFrequency.yearly}+ onChange={() => {}}+ />+ </button></div><div className='space-y-3'>{_map(plans, (tier) => (diff --git a/web/app/pages/Billing/index.tsx b/web/app/pages/Billing/index.tsxdeleted file mode 100644index f564c88ce..000000000--- a/web/app/pages/Billing/index.tsx+++ /dev/null@@ -1,553 +0,0 @@-import { WarningOctagonIcon, InfoIcon } from '@phosphor-icons/react'-import dayjs from 'dayjs'-import duration from 'dayjs/plugin/duration'-import utc from 'dayjs/plugin/utc'-import _round from 'lodash/round'-import { useMemo, useState, useEffect } from 'react'-import { useTranslation, Trans } from 'react-i18next'-import { useLoaderData, useFetcher } from 'react-router'-import { toast } from 'sonner'--import FAQ from '~/components/marketing/FAQ'-import BillingPricing from '~/components/pricing/BillingPricing'-import {- PADDLE_JS_URL,- PADDLE_VENDOR_ID,- CONTACT_EMAIL,- paddleLanguageMapping,-} from '~/lib/constants'-import { DEFAULT_METAINFO } from '~/lib/models/Metainfo'-import { UsageInfo } from '~/lib/models/Usageinfo'-import { useAuth } from '~/providers/AuthProvider'-import { useTheme } from '~/providers/ThemeProvider'-import type { BillingActionData, BillingLoaderData } from '~/routes/billing'-import Button from '~/ui/Button'-import Loader from '~/ui/Loader'-import Modal from '~/ui/Modal'-import MultiProgress from '~/ui/MultiProgress'-import { loadScript } from '~/utils/generic'--dayjs.extend(utc)-dayjs.extend(duration)--const DEFAULT_USAGE_INFO: UsageInfo = {- total: 0,- traffic: 0,- errors: 0,- customEvents: 0,- captcha: 0,- trafficPerc: 0,- errorsPerc: 0,- customEventsPerc: 0,- captchaPerc: 0,-}--const Billing = () => {- const loaderData = useLoaderData<BillingLoaderData>()- const metainfoFetcher = useFetcher<BillingActionData>()-- const [isCancelSubModalOpened, setIsCancelSubModalOpened] = useState(false)- const [lastEvent, setLastEvent] = useState<{ event: string } | null>(null)-- const { user, isLoading: authLoading } = useAuth()- const { theme } = useTheme()-- const metainfo = useMemo(() => {- if (metainfoFetcher.data?.success && metainfoFetcher.data.data) {- return metainfoFetcher.data.data as typeof DEFAULT_METAINFO- }- return loaderData?.metainfo ?? DEFAULT_METAINFO- }, [loaderData?.metainfo, metainfoFetcher.data])-- const usageInfo = useMemo(- () => loaderData?.usageInfo ?? DEFAULT_USAGE_INFO,- [loaderData?.usageInfo],- )- const isLoading = !loaderData-- const {- t,- i18n: { language },- } = useTranslation('common')-- const {- nextBillDate,- planCode,- subUpdateURL,- trialEndDate,- timeFormat,- cancellationEffectiveDate,- subCancelURL,- maxEventsCount = 0,- } = user || {}-- const isSubscriber = !['none', 'trial', 'free'].includes(planCode || '')- const isTrial = planCode === 'trial'- const isNoSub = planCode === 'none'-- const totalUsage = maxEventsCount- ? _round((usageInfo.total / maxEventsCount) * 100, 2)- : 0- const remainingUsage = _round(100 - totalUsage, 2)-- // Paddle (payment processor) set-up- useEffect(() => {- loadScript(PADDLE_JS_URL)-- const interval = setInterval(paddleSetup, 200)-- function paddleSetup() {- if ((window as any)?.Paddle) {- ;(window as any).Paddle.Setup({- vendor: PADDLE_VENDOR_ID,- eventCallback: setLastEvent,- })- clearInterval(interval)- }- }- }, [])-- const isTrialEnded = (() => {- if (!trialEndDate) {- return false- }-- const now = dayjs.utc()- const future = dayjs.utc(trialEndDate)- const diff = future.diff(now)-- return diff < 0- })()-- const trialEndsOnMessage = (() => {- if (!trialEndDate || !isTrial) {- return null- }-- if (isTrialEnded) {- return t('pricing.trialEnded')- }-- let date-- if (language === 'en') {- if (timeFormat === '12-hour') {- date = dayjs(trialEndDate).locale(language).format('MMMM D, h:mm A')- } else {- date = dayjs(trialEndDate).locale(language).format('MMMM D, HH:mm')- }- } else if (timeFormat === '12-hour') {- date = dayjs(trialEndDate).locale(language).format('D MMMM, h:mm A')- } else {- date = dayjs(trialEndDate).locale(language).format('D MMMM, HH:mm')- }-- return t('billing.trialEnds', {- date,- })- })()-- const onSubscriptionCancel = () => {- if (!subCancelURL) {- toast.error(t('apiNotifications.somethingWentWrong'))- return- }-- if (!window.Paddle) {- window.location.replace(subCancelURL)- return- }-- window.Paddle.Checkout.open({- override: subCancelURL,- method: 'inline',- frameTarget: 'checkout-container',- frameInitialHeight: 416,- frameStyle:- 'width:100%; min-width:312px; background-color: #f9fafb; border: none; border-radius: 10px; margin-top: 10px;',- locale: paddleLanguageMapping[language] || language,- displayModeTheme: theme,- country: metainfo.country,- })- setTimeout(() => {- document.querySelector('#checkout-container')?.scrollIntoView()- }, 500)- }-- const onUpdatePaymentDetails = () => {- if (!subUpdateURL) {- toast.error(t('apiNotifications.somethingWentWrong'))- return- }-- if (!window.Paddle) {- window.location.replace(subUpdateURL)- return- }-- window.Paddle.Checkout.open({- override: subUpdateURL,- method: 'inline',- frameTarget: 'checkout-container',- frameInitialHeight: 416,- frameStyle:- 'width:100%; min-width:312px; background-color: #f9fafb; border: none; border-radius: 10px; margin-top: 10px;',- locale: paddleLanguageMapping[language] || language,- displayModeTheme: theme,- country: metainfo.country,- })- setTimeout(() => {- document.querySelector('#checkout-container')?.scrollIntoView()- }, 500)- }-- return (- <div className='min-h-page bg-gray-50 dark:bg-slate-900'>- <div className='mx-auto px-4 pt-12 whitespace-pre-line sm:px-6 md:w-11/12'>- <h1 className='text-4xl font-extrabold text-gray-900 dark:text-gray-50'>- {t('billing.title')}- </h1>- </div>-- <div className='mx-auto mt-5 grid gap-x-10 gap-y-8 px-4 pb-4 whitespace-pre-line sm:px-6 md:w-11/12 lg:grid-cols-3'>- <div className='lg:col-span-2'>- <h2- id='billing'- className='mb-2 text-2xl font-medium text-gray-900 dark:text-gray-50'- >- {t('billing.subscription')}- </h2>- <p className='mt-1 text-base text-gray-900 dark:text-gray-50'>- {isSubscriber ? t('billing.selectPlan') : t('billing.changePlan')}- </p>- <p className='max-w-prose text-base text-gray-900 dark:text-gray-50'>- {t('billing.membersNotification')}- </p>- {isSubscriber && nextBillDate ? (- <div className='mt-5 max-w-prose rounded-md bg-blue-50 p-4 dark:bg-blue-600/30'>- <div className='flex'>- <div className='shrink-0'>- <InfoIcon- aria-hidden='true'- className='h-5 w-5 text-blue-400 dark:text-blue-100'- />- </div>- <p className='ml-3 text-sm font-medium text-blue-700 dark:text-blue-100'>- {t('billing.nextBillDateIs', {- date:- language === 'en'- ? dayjs(nextBillDate)- .locale(language)- .format('MMMM D, YYYY')- : dayjs(nextBillDate)- .locale(language)- .format('D MMMM, YYYY'),- })}- </p>- </div>- </div>- ) : null}- {cancellationEffectiveDate ? (- <div className='mt-5 max-w-prose rounded-md bg-blue-50 p-4 dark:bg-blue-600/30'>- <div className='flex'>- <div className='shrink-0'>- <InfoIcon- aria-hidden='true'- className='h-5 w-5 text-blue-400 dark:text-blue-100'- />- </div>- <div className='ml-3'>- <h3 className='text-sm font-medium text-blue-700 dark:text-blue-100'>- {t('billing.subscriptionCancelled')}- </h3>- <p className='mt-2 text-sm text-blue-700 dark:text-blue-100'>- {t('billing.subscriptionCancelledDescription', {- date:- language === 'en'- ? dayjs(cancellationEffectiveDate)- .locale(language)- .format('MMMM D, YYYY')- : dayjs(cancellationEffectiveDate)- .locale(language)- .format('D MMMM, YYYY'),- })}- </p>- </div>- </div>- </div>- ) : null}- {isTrial && trialEndsOnMessage ? (- <div className='mt-5 max-w-prose rounded-md bg-amber-400/10 p-4 dark:bg-amber-600/20'>- <div className='flex'>- <div className='shrink-0'>- <InfoIcon- aria-hidden='true'- className='h-5 w-5 text-amber-400 dark:text-amber-50'- />- </div>- <div className='ml-3'>- <h3 className='text-sm font-medium text-amber-700 dark:text-amber-50'>- {trialEndsOnMessage}- </h3>- <p className='mt-1 text-sm text-amber-700 dark:text-amber-50'>- {t('billing.trialDescription')}- </p>- </div>- </div>- </div>- ) : null}- {isNoSub ? (- <div className='mt-5 max-w-prose rounded-md bg-red-50 p-4 dark:bg-red-600/20'>- <div className='flex'>- <div className='shrink-0'>- <WarningOctagonIcon- aria-hidden='true'- className='h-5 w-5 text-red-400 dark:text-red-100'- />- </div>- <div className='ml-3'>- <h3 className='text-sm font-medium text-red-800 dark:text-red-100'>- {t('billing.noActiveSubscription')}- </h3>- <p className='mt-2 text-sm text-red-700 dark:text-red-100'>- {t('billing.noActiveSubscriptionDescription')}- </p>- </div>- </div>- </div>- ) : null}-- {isLoading || authLoading ? (- <Loader />- ) : (- <div className='mt-8 flex flex-col'>- <BillingPricing lastEvent={lastEvent} metainfo={metainfo} />- <div className='mt-2 space-y-2'>- {subUpdateURL && !cancellationEffectiveDate ? (- <Button- className='mr-2'- onClick={onUpdatePaymentDetails}- type='button'- primary- large- >- {t('billing.update')}- </Button>- ) : null}- {subCancelURL && !cancellationEffectiveDate ? (- <Button- onClick={() => setIsCancelSubModalOpened(true)}- type='button'- semiDanger- large- >- {t('billing.cancelSub')}- </Button>- ) : null}- </div>- </div>- )}- </div>-- <div className='lg:col-span-1'>- <h2- id='usage'- className='mb-2 text-2xl font-medium text-gray-900 dark:text-gray-50'- >- {t('billing.planUsage')}- </h2>- <p className='mt-1 max-w-prose text-base text-gray-900 dark:text-gray-50'>- {t('billing.planUsageDesc')}- </p>-- {isLoading || authLoading ? (- <Loader />- ) : (- <div className='mt-4 text-gray-900 dark:text-gray-50'>- {totalUsage >= 80 ? (- <div className='mb-4 rounded-md bg-amber-50 p-4 dark:bg-amber-600/30'>- <div className='flex'>- <div className='shrink-0'>- <WarningOctagonIcon- aria-hidden='true'- className='h-5 w-5 text-amber-400 dark:text-amber-100'- />- </div>- <div className='ml-3'>- <p className='text-sm text-amber-800 dark:text-amber-100'>- {totalUsage >= 90- ? t('billing.usageWarningCritical', {- percentage: totalUsage,- })- : t('billing.usageWarningHigh', {- percentage: totalUsage,- })}- </p>- </div>- </div>- </div>- ) : null}-- <p className='mb-4 max-w-prose text-base text-gray-900 dark:text-gray-50'>- {t('billing.usageOverview', {- tracked: (usageInfo.total || 0).toLocaleString(),- trackedPerc: totalUsage || 0,- maxEvents: (maxEventsCount || 0).toLocaleString(),- })}- </p>-- <div className='mb-4 space-y-2'>- <div className='flex items-center justify-between'>- <div className='flex items-center'>- <div className='size-2 rounded-full bg-blue-600 dark:bg-blue-500' />- <span className='ml-2 text-sm'>- {t('billing.pageviews', {- quantity: usageInfo.traffic || 0,- percentage: usageInfo.trafficPerc || 0,- })}- </span>- </div>- </div>-- <div className='flex items-center justify-between'>- <div className='flex items-center'>- <div className='size-2 rounded-full bg-fuchsia-600 dark:bg-fuchsia-500' />- <span className='ml-2 text-sm'>- {t('billing.customEvents', {- quantity: usageInfo.customEvents || 0,- percentage: usageInfo.customEventsPerc || 0,- })}- </span>- </div>- </div>-- <div className='flex items-center justify-between'>- <div className='flex items-center'>- <div className='size-2 rounded-full bg-lime-600 dark:bg-lime-500' />- <span className='ml-2 text-sm'>- {t('billing.captcha', {- quantity: usageInfo.captcha || 0,- percentage: usageInfo.captchaPerc || 0,- })}- </span>- </div>- </div>-- <div className='flex items-center justify-between'>- <div className='flex items-center'>- <div className='size-2 rounded-full bg-red-600 dark:bg-red-500' />- <span className='ml-2 text-sm'>- {t('billing.errors', {- quantity: usageInfo.errors || 0,- percentage: usageInfo.errorsPerc || 0,- })}- </span>- </div>- </div>- </div>-- <p className='mb-2 text-lg font-medium text-gray-900 dark:text-gray-50'>- {t('billing.xofy', {- x: (usageInfo.total || 0).toLocaleString(),- y: (maxEventsCount || 0).toLocaleString(),- })}- </p>-- <MultiProgress- className='w-full'- progress={[- {- value:- usageInfo.traffic === 0- ? 0- : (usageInfo.traffic / maxEventsCount) * 100,- lightColour: '#2563eb',- darkColour: '#1d4ed8',- },- {- value:- usageInfo.customEvents === 0- ? 0- : (usageInfo.customEvents / maxEventsCount) * 100,- lightColour: '#c026d3',- darkColour: '#a21caf',- },- {- value:- usageInfo.captcha === 0- ? 0- : (usageInfo.captcha / maxEventsCount) * 100,- lightColour: '#65a30d',- darkColour: '#4d7c0f',- },- {- value:- usageInfo.errors === 0- ? 0- : (usageInfo.errors / maxEventsCount) * 100,- lightColour: '#dc2626',- darkColour: '#b91c1c',- },- ]}- />-- <div className='mt-2 flex items-center justify-between'>- <p className='text-sm text-gray-600 dark:text-gray-400'>- {t('billing.xPercentUsed', { percentage: totalUsage })}- </p>- <p className='text-sm text-gray-600 dark:text-gray-400'>- {t('billing.xPercentRemaining', {- percentage: remainingUsage,- })}- </p>- </div>-- <p className='mt-4 text-sm text-gray-600 dark:text-gray-400'>- {t('billing.resetDate', {- days: Math.ceil(- (new Date(- new Date().getFullYear(),- new Date().getMonth() + 1,- 1,- ).getTime() -- new Date().getTime()) /- (1000 * 60 * 60 * 24),- ),- })}- </p>- </div>- )}- </div>- </div>-- <FAQ />-- <Modal- onClose={() => {- setIsCancelSubModalOpened(false)- }}- onSubmit={() => {- setIsCancelSubModalOpened(false)- onSubscriptionCancel()- }}- submitText={t('common.yes')}- closeText={t('common.no')}- title={t('pricing.cancelTitle')}- submitType='danger'- type='error'- message={- <Trans- t={t}- i18nKey='pricing.cancelDesc'- values={{- email: CONTACT_EMAIL,- }}- />- }- isOpened={isCancelSubModalOpened}- />- </div>- )-}--export default Billingdiff --git a/web/app/pages/UserSettings/UserSettings.tsx b/web/app/pages/UserSettings/UserSettings.tsxindex 069b2050b..82f23a5c6 100644--- a/web/app/pages/UserSettings/UserSettings.tsx+++ b/web/app/pages/UserSettings/UserSettings.tsx@@ -17,10 +17,17 @@ import {TranslateIcon,LockIcon,CaretDownIcon,+ CreditCardIcon,} from '@phosphor-icons/react'+import _round from 'lodash/round'import React, { useState, useEffect, memo, useMemo, useRef } from 'react'-import { useTranslation } from 'react-i18next'-import { useNavigate, useFetcher, useSearchParams } from 'react-router'+import { useTranslation, Trans } from 'react-i18next'+import {+ useNavigate,+ useFetcher,+ useSearchParams,+ useLoaderData,+} from 'react-router'import { toast } from 'sonner'import {@@ -32,17 +39,30 @@ import {whitelist,languages,languageFlag,+ PADDLE_JS_URL,+ PADDLE_VENDOR_ID,+ CONTACT_EMAIL,+ paddleLanguageMapping,} from '~/lib/constants'+import BillingPricing from '~/components/pricing/BillingPricing'import { changeLanguage } from '~/i18n'+import { DEFAULT_METAINFO } from '~/lib/models/Metainfo'+import { UsageInfo } from '~/lib/models/Usageinfo'import { User } from '~/lib/models/User'import PaidFeature from '~/modals/PaidFeature'import { useAuth } from '~/providers/AuthProvider'-import type { UserSettingsActionData } from '~/routes/user-settings'+import { useTheme } from '~/providers/ThemeProvider'+import type {+ UserSettingsActionData,+ UserSettingsLoaderData,+} from '~/routes/user-settings'import Alert from '~/ui/Alert'import Button from '~/ui/Button'import Checkbox from '~/ui/Checkbox'import Input from '~/ui/Input'+import Loader from '~/ui/Loader'import Modal from '~/ui/Modal'+import MultiProgress from '~/ui/MultiProgress'import PasswordStrength from '~/ui/PasswordStrength'import Select from '~/ui/Select'import { TabHeader } from '~/ui/TabHeader'@@ -50,6 +70,7 @@ import { Text } from '~/ui/Text'import Textarea from '~/ui/Textarea'import Flag from '~/ui/Flag'import TimezonePicker from '~/ui/TimezonePicker'+import { loadScript } from '~/utils/generic'import { getCookie, setCookie } from '~/utils/cookie'import routes from '~/utils/routes'import {@@ -73,6 +94,7 @@ const timeFormatArray = _map(TimeFormat, (key) => key)const TAB_MAPPING = {ACCOUNT: 'account',PASSWORD_AUTH: 'password-auth',+ BILLING: 'billing',INTERFACE: 'interface',COMMUNICATIONS: 'communications',LANGUAGE: 'language',@@ -130,6 +152,12 @@ const getTabs = (t: typeof i18next.t): TabConfig[] => {icon: LockIcon,description: t('profileSettings.passwordAuthDesc'),},+ {+ id: TAB_MAPPING.BILLING,+ label: t('profileSettings.billingTab'),+ icon: CreditCardIcon,+ description: t('profileSettings.billingTabDesc'),+ },{id: TAB_MAPPING.COMMUNICATIONS,label: t('profileSettings.communications'),@@ -157,8 +185,10 @@ const getTabIconColor = (tabId: string): string => {return 'text-blue-500'case TAB_MAPPING.PASSWORD_AUTH:return 'text-indigo-500'- case TAB_MAPPING.COMMUNICATIONS:+ case TAB_MAPPING.BILLING:return 'text-emerald-500'+ case TAB_MAPPING.COMMUNICATIONS:+ return 'text-teal-500'case TAB_MAPPING.INTERFACE:return 'text-purple-500'default:@@ -166,6 +196,18 @@ const getTabIconColor = (tabId: string): string => {}}+const DEFAULT_USAGE_INFO: UsageInfo = {+ total: 0,+ traffic: 0,+ errors: 0,+ customEvents: 0,+ captcha: 0,+ trafficPerc: 0,+ errorsPerc: 0,+ customEventsPerc: 0,+ captchaPerc: 0,+}+interface SettingsSectionProps {title: stringdescription?: string@@ -202,7 +244,9 @@ interface Form extends Partial<User> {}const UserSettings = () => {- const { user, logout, mergeUser } = useAuth()+ const { user, logout, mergeUser, isLoading: authLoading } = useAuth()+ const loaderData = useLoaderData<UserSettingsLoaderData>()+ const { theme } = useTheme()const navigate = useNavigate()const {@@ -210,9 +254,157 @@ const UserSettings = () => {i18n: { language },} = useTranslation('common')const fetcher = useFetcher<UserSettingsActionData>()+ const metainfoFetcher = useFetcher<UserSettingsActionData>()const [searchParams, setSearchParams] = useSearchParams()+ const [isCancelSubModalOpened, setIsCancelSubModalOpened] = useState(false)+ const [lastEvent, setLastEvent] = useState<{ event: string } | null>(null)++ const metainfo = useMemo(() => {+ if (metainfoFetcher.data?.success && metainfoFetcher.data.data) {+ return metainfoFetcher.data.data as typeof DEFAULT_METAINFO+ }+ return loaderData?.metainfo ?? DEFAULT_METAINFO+ }, [loaderData?.metainfo, metainfoFetcher.data])++ const usageInfo = useMemo(+ () => loaderData?.usageInfo ?? DEFAULT_USAGE_INFO,+ [loaderData?.usageInfo],+ )++ const isBillingLoading = !loaderData++ const {+ nextBillDate,+ planCode,+ subUpdateURL,+ trialEndDate,+ timeFormat: userTimeFormat,+ cancellationEffectiveDate,+ subCancelURL,+ maxEventsCount = 0,+ } = user || {}++ const isSubscriber = !['none', 'trial', 'free'].includes(planCode || '')+ const isTrial = planCode === 'trial'+ const isNoSub = planCode === 'none'++ const totalUsage = maxEventsCount+ ? _round((usageInfo.total / maxEventsCount) * 100, 2)+ : 0+ const remainingUsage = _round(100 - totalUsage, 2)++ useEffect(() => {+ loadScript(PADDLE_JS_URL)++ const interval = setInterval(paddleSetup, 200)++ function paddleSetup() {+ if ((window as any)?.Paddle) {+ ;(window as any).Paddle.Setup({+ vendor: PADDLE_VENDOR_ID,+ eventCallback: setLastEvent,+ })+ clearInterval(interval)+ }+ }+ }, [])++ const isTrialEnded = (() => {+ if (!trialEndDate) {+ return false+ }++ const now = dayjs.utc()+ const future = dayjs.utc(trialEndDate)+ const diff = future.diff(now)++ return diff < 0+ })()++ const trialEndsOnMessage = (() => {+ if (!trialEndDate || !isTrial) {+ return null+ }++ if (isTrialEnded) {+ return t('pricing.trialEnded')+ }++ let date++ if (language === 'en') {+ if (userTimeFormat === '12-hour') {+ date = dayjs(trialEndDate).locale(language).format('MMMM D, h:mm A')+ } else {+ date = dayjs(trialEndDate).locale(language).format('MMMM D, HH:mm')+ }+ } else if (userTimeFormat === '12-hour') {+ date = dayjs(trialEndDate).locale(language).format('D MMMM, h:mm A')+ } else {+ date = dayjs(trialEndDate).locale(language).format('D MMMM, HH:mm')+ }++ return t('billing.trialEnds', {+ date,+ })+ })()++ const onSubscriptionCancel = () => {+ if (!subCancelURL) {+ toast.error(t('apiNotifications.somethingWentWrong'))+ return+ }++ if (!(window as any).Paddle) {+ window.location.replace(subCancelURL)+ return+ }++ ;(window as any).Paddle.Checkout.open({+ override: subCancelURL,+ method: 'inline',+ frameTarget: 'checkout-container',+ frameInitialHeight: 416,+ frameStyle:+ 'width:100%; min-width:312px; background-color: #f9fafb; border: none; border-radius: 10px; margin-top: 10px;',+ locale: paddleLanguageMapping[language] || language,+ displayModeTheme: theme,+ country: metainfo.country,+ })+ setTimeout(() => {+ document.querySelector('#checkout-container')?.scrollIntoView()+ }, 500)+ }++ const onUpdatePaymentDetails = () => {+ if (!subUpdateURL) {+ toast.error(t('apiNotifications.somethingWentWrong'))+ return+ }++ if (!(window as any).Paddle) {+ window.location.replace(subUpdateURL)+ return+ }++ ;(window as any).Paddle.Checkout.open({+ override: subUpdateURL,+ method: 'inline',+ frameTarget: 'checkout-container',+ frameInitialHeight: 416,+ frameStyle:+ 'width:100%; min-width:312px; background-color: #f9fafb; border: none; border-radius: 10px; margin-top: 10px;',+ locale: paddleLanguageMapping[language] || language,+ displayModeTheme: theme,+ country: metainfo.country,+ })+ setTimeout(() => {+ document.querySelector('#checkout-container')?.scrollIntoView()+ }, 500)+ }+const tabs = getTabs(t)const activeTab = useMemo<SettingsTab>(() => {@@ -1042,6 +1234,303 @@ const UserSettings = () => {</>) : null}+ {activeTab === TAB_MAPPING.BILLING &&+ !isSelfhosted &&+ activeTabConfig ? (+ <>+ <TabHeader+ icon={activeTabConfig.icon}+ label={activeTabConfig.label}+ description={activeTabConfig.description}+ iconColorClass={getTabIconColor(activeTabConfig.id)}+ />++ {isBillingLoading || authLoading ? (+ <div className='flex justify-center py-12'>+ <Loader />+ </div>+ ) : (+ <>+ {/* Trial info alert */}+ {isTrial && trialEndsOnMessage ? (+ <Alert+ variant='info'+ title={t('profileSettings.trialActive')}+ className='mb-6'+ >+ {trialEndsOnMessage} {t('billing.trialDescription')}+ </Alert>+ ) : null}++ {/* Subscription cancelled alert */}+ {cancellationEffectiveDate ? (+ <Alert+ variant='warning'+ title={t('billing.subscriptionCancelled')}+ className='mb-6'+ >+ {t('billing.subscriptionCancelledDescription', {+ date:+ language === 'en'+ ? dayjs(cancellationEffectiveDate)+ .locale(language)+ .format('MMMM D, YYYY')+ : dayjs(cancellationEffectiveDate)+ .locale(language)+ .format('D MMMM, YYYY'),+ })}+ </Alert>+ ) : null}++ {/* No active subscription alert */}+ {isNoSub ? (+ <Alert+ variant='error'+ title={t('billing.noActiveSubscription')}+ className='mb-6'+ >+ {t('billing.noActiveSubscriptionDescription')}+ </Alert>+ ) : null}++ {/* Next bill date info */}+ {isSubscriber && nextBillDate ? (+ <Alert+ variant='info'+ title={t('profileSettings.nextBilling')}+ className='mb-6'+ >+ {t('billing.nextBillDateIs', {+ date:+ language === 'en'+ ? dayjs(nextBillDate)+ .locale(language)+ .format('MMMM D, YYYY')+ : dayjs(nextBillDate)+ .locale(language)+ .format('D MMMM, YYYY'),+ })}+ </Alert>+ ) : null}++ {/* Plan Usage Section */}+ <SettingsSection+ title={t('billing.planUsage')}+ description={t('billing.planUsageDesc')}+ >+ {totalUsage >= 80 ? (+ <Alert variant='warning' className='mb-4'>+ {totalUsage >= 90+ ? t('billing.usageWarningCritical', {+ percentage: totalUsage,+ })+ : t('billing.usageWarningHigh', {+ percentage: totalUsage,+ })}+ </Alert>+ ) : null}++ <div className='rounded-xl border border-gray-200 bg-white p-5 dark:border-slate-700 dark:bg-slate-800'>+ <Text+ as='p'+ size='sm'+ colour='secondary'+ className='mb-4'+ >+ {t('billing.usageOverview', {+ tracked: (usageInfo.total || 0).toLocaleString(),+ trackedPerc: totalUsage || 0,+ maxEvents: (maxEventsCount || 0).toLocaleString(),+ })}+ </Text>++ <div className='mb-4 grid grid-cols-2 gap-3'>+ <div className='flex items-center'>+ <div className='size-2 rounded-full bg-blue-600 dark:bg-blue-500' />+ <Text+ as='span'+ size='sm'+ colour='secondary'+ className='ml-2'+ >+ {t('billing.pageviews', {+ quantity: usageInfo.traffic || 0,+ percentage: usageInfo.trafficPerc || 0,+ })}+ </Text>+ </div>+ <div className='flex items-center'>+ <div className='size-2 rounded-full bg-fuchsia-600 dark:bg-fuchsia-500' />+ <Text+ as='span'+ size='sm'+ colour='secondary'+ className='ml-2'+ >+ {t('billing.customEvents', {+ quantity: usageInfo.customEvents || 0,+ percentage: usageInfo.customEventsPerc || 0,+ })}+ </Text>+ </div>+ <div className='flex items-center'>+ <div className='size-2 rounded-full bg-lime-600 dark:bg-lime-500' />+ <Text+ as='span'+ size='sm'+ colour='secondary'+ className='ml-2'+ >+ {t('billing.captcha', {+ quantity: usageInfo.captcha || 0,+ percentage: usageInfo.captchaPerc || 0,+ })}+ </Text>+ </div>+ <div className='flex items-center'>+ <div className='size-2 rounded-full bg-red-600 dark:bg-red-500' />+ <Text+ as='span'+ size='sm'+ colour='secondary'+ className='ml-2'+ >+ {t('billing.errors', {+ quantity: usageInfo.errors || 0,+ percentage: usageInfo.errorsPerc || 0,+ })}+ </Text>+ </div>+ </div>++ <Text+ as='p'+ size='base'+ weight='semibold'+ className='mb-2'+ >+ {t('billing.xofy', {+ x: (usageInfo.total || 0).toLocaleString(),+ y: (maxEventsCount || 0).toLocaleString(),+ })}+ </Text>++ <MultiProgress+ className='w-full'+ progress={[+ {+ value:+ usageInfo.traffic === 0+ ? 0+ : (usageInfo.traffic / maxEventsCount) * 100,+ lightColour: '#2563eb',+ darkColour: '#1d4ed8',+ },+ {+ value:+ usageInfo.customEvents === 0+ ? 0+ : (usageInfo.customEvents / maxEventsCount) *+ 100,+ lightColour: '#c026d3',+ darkColour: '#a21caf',+ },+ {+ value:+ usageInfo.captcha === 0+ ? 0+ : (usageInfo.captcha / maxEventsCount) * 100,+ lightColour: '#65a30d',+ darkColour: '#4d7c0f',+ },+ {+ value:+ usageInfo.errors === 0+ ? 0+ : (usageInfo.errors / maxEventsCount) * 100,+ lightColour: '#dc2626',+ darkColour: '#b91c1c',+ },+ ]}+ />++ <div className='mt-2 flex items-center justify-between'>+ <Text as='p' size='sm' colour='muted'>+ {t('billing.xPercentUsed', {+ percentage: totalUsage,+ })}+ </Text>+ <Text as='p' size='sm' colour='muted'>+ {t('billing.xPercentRemaining', {+ percentage: remainingUsage,+ })}+ </Text>+ </div>++ <Text as='p' size='sm' colour='muted' className='mt-3'>+ {t('billing.resetDate', {+ days: Math.ceil(+ (new Date(+ new Date().getFullYear(),+ new Date().getMonth() + 1,+ 1,+ ).getTime() -+ new Date().getTime()) /+ (1000 * 60 * 60 * 24),+ ),+ })}+ </Text>+ </div>+ </SettingsSection>++ {/* Subscription Plans Section */}+ <SettingsSection+ title={t('billing.subscription')}+ description={+ isSubscriber+ ? t('billing.changePlan')+ : t('billing.selectPlan')+ }+ >+ <Text as='p' size='sm' colour='muted' className='mb-4'>+ {t('billing.membersNotification')}+ </Text>++ <BillingPricing+ lastEvent={lastEvent}+ metainfo={metainfo}+ />++ <div className='mt-4 flex flex-wrap gap-3'>+ {subUpdateURL && !cancellationEffectiveDate ? (+ <Button+ onClick={onUpdatePaymentDetails}+ type='button'+ primary+ large+ >+ {t('billing.update')}+ </Button>+ ) : null}+ {subCancelURL && !cancellationEffectiveDate ? (+ <Button+ onClick={() => setIsCancelSubModalOpened(true)}+ type='button'+ semiDanger+ large+ >+ {t('billing.cancelSub')}+ </Button>+ ) : null}+ </div>++ <div id='checkout-container' className='mt-4' />+ </SettingsSection>+ </>+ )}+ </>+ ) : null}+{activeTab === TAB_MAPPING.COMMUNICATIONS &&!isSelfhosted &&activeTabConfig ? (@@ -1250,6 +1739,30 @@ const UserSettings = () => {message={t('profileSettings.passwordChangeWarningModal.body')}isOpened={isPasswordChangeModalOpened}/>+ <Modal+ onClose={() => {+ setIsCancelSubModalOpened(false)+ }}+ onSubmit={() => {+ setIsCancelSubModalOpened(false)+ onSubscriptionCancel()+ }}+ submitText={t('common.yes')}+ closeText={t('common.no')}+ title={t('pricing.cancelTitle')}+ submitType='danger'+ type='error'+ message={+ <Trans+ t={t}+ i18nKey='pricing.cancelDesc'+ values={{+ email: CONTACT_EMAIL,+ }}+ />+ }+ isOpened={isCancelSubModalOpened}+ /></div>)}diff --git a/web/app/routes/billing.tsx b/web/app/routes/billing.tsxindex 33e3a96c0..7618d9fe9 100644--- a/web/app/routes/billing.tsx+++ b/web/app/routes/billing.tsx@@ -1,44 +1,13 @@-import { useTranslation } from 'react-i18next'-import {- type ActionFunctionArgs,- type LoaderFunctionArgs,- type MetaFunction,- redirect,- data,-} from 'react-router'+import { type LoaderFunctionArgs, redirect } from 'react-router'import type { SitemapFunction } from 'remix-sitemap'-import { serverFetch } from '~/api/api.server'import { isSelfhosted } from '~/lib/constants'-import { Metainfo } from '~/lib/models/Metainfo'-import { UsageInfo } from '~/lib/models/Usageinfo'-import Billing from '~/pages/Billing'-import { getDescription, getPreviewImage, getTitle } from '~/utils/seo'-import {- redirectIfNotAuthenticated,- createHeadersWithCookies,-} from '~/utils/session.server'--export const meta: MetaFunction = () => {- // eslint-disable-next-line react-hooks/rules-of-hooks- const { t } = useTranslation('common')-- return [- ...getTitle(t('titles.billing')),- ...getDescription(t('description.default')),- ...getPreviewImage(),- ]-}+import { redirectIfNotAuthenticated } from '~/utils/session.server'export const sitemap: SitemapFunction = () => ({exclude: true,})-export interface BillingLoaderData {- metainfo: Metainfo | null- usageInfo: UsageInfo | null-}-export async function loader({ request }: LoaderFunctionArgs) {if (isSelfhosted) {return redirect('/login', 302)@@ -46,102 +15,9 @@ export async function loader({ request }: LoaderFunctionArgs) {redirectIfNotAuthenticated(request)- const [metainfoResult, usageInfoResult] = await Promise.all([- serverFetch<Metainfo>(request, 'user/metainfo'),- serverFetch<UsageInfo>(request, 'user/usageinfo'),- ])-- const cookies = [...metainfoResult.cookies, ...usageInfoResult.cookies]-- return data<BillingLoaderData>(- {- metainfo: metainfoResult.data,- usageInfo: usageInfoResult.data,- },- { headers: createHeadersWithCookies(cookies) },- )-}--export interface BillingActionData {- success?: boolean- intent?: string- error?: string- data?: unknown-}--export async function action({ request }: ActionFunctionArgs) {- redirectIfNotAuthenticated(request)-- const formData = await request.formData()- const intent = formData.get('intent')?.toString()-- switch (intent) {- case 'preview-subscription-update': {- const planId = Number(formData.get('planId'))-- const result = await serverFetch(request, 'user/preview-plan', {- method: 'POST',- body: { planId },- })-- if (result.error) {- return data<BillingActionData>(- { intent, error: result.error as string },- { status: 400 },- )- }-- return data<BillingActionData>(- { intent, success: true, data: result.data },- { headers: createHeadersWithCookies(result.cookies) },- )- }-- case 'change-subscription-plan': {- const planId = Number(formData.get('planId'))-- const result = await serverFetch(request, 'user/change-plan', {- method: 'POST',- body: { planId },- })-- if (result.error) {- return data<BillingActionData>(- { intent, error: result.error as string },- { status: 400 },- )- }-- return data<BillingActionData>(- { intent, success: true, data: result.data },- { headers: createHeadersWithCookies(result.cookies) },- )- }-- case 'get-metainfo': {- const result = await serverFetch<Metainfo>(request, 'user/metainfo')-- if (result.error) {- return data<BillingActionData>(- { intent, error: result.error as string },- { status: 400 },- )- }-- return data<BillingActionData>(- { intent, success: true, data: result.data },- { headers: createHeadersWithCookies(result.cookies) },- )- }-- default:- return data<BillingActionData>(- { error: 'Unknown action' },- { status: 400 },- )- }+ return redirect('/user-settings?tab=billing', 302)}export default function BillingRoute() {- return <Billing />+ return null}diff --git a/web/app/routes/user-settings.tsx b/web/app/routes/user-settings.tsxindex b9c78462d..c48095ca4 100644--- a/web/app/routes/user-settings.tsx+++ b/web/app/routes/user-settings.tsx@@ -8,6 +8,9 @@ import { data } from 'react-router'import type { SitemapFunction } from 'remix-sitemap'import { serverFetch } from '~/api/api.server'+import { isSelfhosted } from '~/lib/constants'+import { Metainfo } from '~/lib/models/Metainfo'+import { UsageInfo } from '~/lib/models/Usageinfo'import { User } from '~/lib/models/User'import UserSettings from '~/pages/UserSettings'import { getDescription, getPreviewImage, getTitle } from '~/utils/seo'@@ -38,9 +41,35 @@ export const sitemap: SitemapFunction = () => ({exclude: true,})+export interface UserSettingsLoaderData {+ metainfo: Metainfo | null+ usageInfo: UsageInfo | null+}+export async function loader({ request }: LoaderFunctionArgs) {redirectIfNotAuthenticated(request)- return null++ if (isSelfhosted) {+ return data<UserSettingsLoaderData>({+ metainfo: null,+ usageInfo: null,+ })+ }++ const [metainfoResult, usageInfoResult] = await Promise.all([+ serverFetch<Metainfo>(request, 'user/metainfo'),+ serverFetch<UsageInfo>(request, 'user/usageinfo'),+ ])++ const cookies = [...metainfoResult.cookies, ...usageInfoResult.cookies]++ return data<UserSettingsLoaderData>(+ {+ metainfo: metainfoResult.data,+ usageInfo: usageInfoResult.data,+ },+ { headers: createHeadersWithCookies(cookies) },+ )}export interface UserSettingsActionData {@@ -59,6 +88,7 @@ export interface UserSettingsActionData {otpauthUrl?: stringtwoFactorRecoveryCode?: string}+ data?: unknown}export async function action({ request }: ActionFunctionArgs) {@@ -441,6 +471,64 @@ export async function action({ request }: ActionFunctionArgs) {)}+ case 'preview-subscription-update': {+ const planId = Number(formData.get('planId'))++ const result = await serverFetch(request, 'user/preview-plan', {+ method: 'POST',+ body: { planId },+ })++ if (result.error) {+ return data<UserSettingsActionData>(+ { intent, error: result.error as string },+ { status: 400 },+ )+ }++ return data<UserSettingsActionData>(+ { intent, success: true, data: result.data },+ { headers: createHeadersWithCookies(result.cookies) },+ )+ }++ case 'change-subscription-plan': {+ const planId = Number(formData.get('planId'))++ const result = await serverFetch(request, 'user/change-plan', {+ method: 'POST',+ body: { planId },+ })++ if (result.error) {+ return data<UserSettingsActionData>(+ { intent, error: result.error as string },+ { status: 400 },+ )+ }++ return data<UserSettingsActionData>(+ { intent, success: true, data: result.data },+ { headers: createHeadersWithCookies(result.cookies) },+ )+ }++ case 'get-metainfo': {+ const result = await serverFetch<Metainfo>(request, 'user/metainfo')++ if (result.error) {+ return data<UserSettingsActionData>(+ { intent, error: result.error as string },+ { status: 400 },+ )+ }++ return data<UserSettingsActionData>(+ { intent, success: true, data: result.data },+ { headers: createHeadersWithCookies(result.cookies) },+ )+ }+case 'accept-organisation-invitation': {const membershipId = formData.get('membershipId')?.toString()diff --git a/web/public/locales/en.json b/web/public/locales/en.jsonindex a0cfee2bb..071c24db3 100644--- a/web/public/locales/en.json+++ b/web/public/locales/en.json@@ -820,6 +820,10 @@"changeLanguage": "Change your language","interfaceDesc": "Customize how Swetrix displays information to you.","communicationsDesc": "Configure how you receive updates and notifications.",+ "billingTab": "Subscription & Billing",+ "billingTabDesc": "Manage your subscription plan and view usage details.",+ "trialActive": "You're on a free trial",+ "nextBilling": "Next billing date","changeEmail": "Change email address","changeEmailDesc": "Change your account email address. You need this email to sign in and verify your identity.","currentEmail": "Current email address",@@ -1936,15 +1940,12 @@}},"billing": {- "title": "Billing & Plans","update": "Update payment details",- "nextBillDate": "Next bill date:","nextBillDateIs": "Your next bill date is {{date}}","trialEnds": "Trial ends {{date}}","cancelSub": "Cancel subscription","noActiveSubscription": "You don't have an active subscription.","noActiveSubscriptionDescription": "Don't worry, we still collect your analytics data. But if you want to continue using Swetrix, please upgrade your account to one of our subscription tiers.",- "inactive": "Inactive","subscriptionCancelled": "Subscription cancelled","subscriptionCancelledDescription": "Your subscription is active until {{date}}. After that, you will not be able to access your analytics data. Don't worry, we will still store incoming events and pageviews for your projects in case you change your mind.","planUsage": "Plan usage",@@ -2015,6 +2016,7 @@"upgrade": "Upgrade","monthlyBilling": "Monthly","yearlyBilling": "Yearly",+ "billedYearly": "Billed yearly","switchToMonthly": "Switch to monthly billing","frequency": "Payment frequency","eventsPerMonth": "events / month",