📈 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
(improvement) Pro-rata subscription upgrades (#331)
Andrii Romasiun59098ae4112f
diff --git a/app/api/index.ts b/app/api/index.tsindex 09614ffdd..c20ad5f28 100644--- a/app/api/index.ts+++ b/app/api/index.ts@@ -1069,9 +1069,27 @@ export const resetFilters = (pid: string, type: string, filters: string[]) =>throw error})-export const reciveLoginNotification = (recive: boolean) =>+export const receiveLoginNotification = (receiveLoginNotifications: boolean) =>api- .post('user/recieve-login-notifications', { receiveLoginNotifications: recive })+ .post('user/recieve-login-notifications', { receiveLoginNotifications })+ .then((response) => response.data)+ .catch((error) => {+ debug('%s', error)+ throw error+ })++export const previewSubscriptionUpdate = (planId: number) =>+ api+ .post('user/preview-plan', { planId })+ .then((response) => response.data)+ .catch((error) => {+ debug('%s', error)+ throw error+ })++export const changeSubscriptionPlan = (planId: number) =>+ api+ .post('user/change-plan', { planId }).then((response) => response.data).catch((error) => {debug('%s', error)diff --git a/app/pages/MainPage/Pricing.tsx b/app/pages/MainPage/Pricing.tsxindex 29c0e33e1..e46d14f75 100644--- a/app/pages/MainPage/Pricing.tsx+++ b/app/pages/MainPage/Pricing.tsx@@ -4,6 +4,7 @@ import { useSelector, useDispatch } from 'react-redux'import { ClientOnly } from 'remix-utils'import { Link } from '@remix-run/react'import { CheckIcon } from '@heroicons/react/24/solid'+import dayjs from 'dayjs'import _map from 'lodash/map'import _isNil from 'lodash/isNil'import _findIndex from 'lodash/findIndex'@@ -20,7 +21,9 @@ import { errorsActions } from 'redux/reducers/errors'import { alertsActions } from 'redux/reducers/alerts'import { authActions } from 'redux/reducers/auth'import sagaActions from 'redux/sagas/actions'-import { authMe } from 'api'+import {+ authMe, previewSubscriptionUpdate, changeSubscriptionPlan,+} from 'api'import routes from 'routesPath'import { IUser } from 'redux/models/IUser'import { AppDispatch, StateType } from 'redux/store'@@ -268,7 +271,9 @@ const PricingItem = ({}interface IPricing {- t: (key: string) => string,+ t: (key: string, options?: {+ [key: string]: string | number,+ }) => string,language: string,authenticated: boolean,}@@ -282,6 +287,10 @@ const Pricing = ({ t, language, authenticated }: IPricing) => {const currencyCode = user?.tierCurrency || metainfo.codeconst [planCodeLoading, setPlanCodeLoading] = useState<string | null>(null)+ const [isNewPlanConfirmationModalOpened, setIsNewPlanConfirmationModalOpened] = useState<boolean>(false)+ const [subUpdatePreview, setSubUpdatePreview] = useState<any>(null) // object - preview itself, null - loading, false - error+ const [newPlanId, setNewPlanId] = useState<number | null>(null)+ const [isSubUpdating, setIsSubUpdating] = useState<boolean>(false)const [downgradeTo, setDowngradeTo] = useState<{planCode: string,name: string,@@ -334,13 +343,34 @@ const Pricing = ({ t, language, authenticated }: IPricing) => {lastEventHandler(lastEvent)}, [lastEvent, dispatch, t])- const onPlanChange = (tier: {+ const loadSubUpdatePreview = async (planId: number) => {+ setIsNewPlanConfirmationModalOpened(true)+ try {+ const preview = await previewSubscriptionUpdate(planId)+ setSubUpdatePreview(preview)+ } catch (reason) {+ console.error('[ERROR] An error occured while loading subscription update pricing preview:', reason)+ dispatch(errorsActions.genericError({+ message: 'An error occured while loading subscription update pricing preview',+ }))+ setSubUpdatePreview(false)+ }+ }++ const onPlanChange = async (tier: {planCode: string,name: string,pid: string,ypid: string,}) => {if (planCodeLoading === null && (user.planCode !== tier.planCode || (user.billingFrequency !== billingFrequency && user.planCode !== 'free' && user.planCode !== 'trial'))) {+ if (user.subID) {+ const planId = Number(billingFrequency === BillingFrequency.monthly ? tier.pid : tier.ypid)+ setNewPlanId(planId)+ await loadSubUpdatePreview(planId)+ return+ }+setPlanCodeLoading(tier.planCode)// @ts-ignore@@ -367,6 +397,46 @@ const Pricing = ({ t, language, authenticated }: IPricing) => {}}+ const closeUpdateModal = (force?: boolean) => {+ if (isSubUpdating && !force) {+ return+ }++ setIsNewPlanConfirmationModalOpened(false)+ setSubUpdatePreview(null)+ setNewPlanId(null)+ setIsSubUpdating(false)+ }++ const updateSubscription = async () => {+ setIsSubUpdating(true)++ try {+ await changeSubscriptionPlan(newPlanId as number)++ try {+ const me = await authMe()++ dispatch(authActions.loginSuccessful(me))+ dispatch(authActions.finishLoading())+ } catch (e) {+ dispatch(authActions.logout())+ dispatch(sagaActions.logout(false, false))+ }++ dispatch(alertsActions.accountUpdated({+ message: t('apiNotifications.subscriptionUpdated'),+ }))+ closeUpdateModal(true)+ } catch (reason) {+ console.error('[ERROR] An error occured while updating subscription:', reason)+ dispatch(errorsActions.genericError({+ message: 'An error occured while updating subscription',+ }))+ closeUpdateModal(true)+ }+ }+const downgradeHandler = (tier: {planCode: string,name: string,@@ -490,6 +560,102 @@ const Pricing = ({ t, language, authenticated }: IPricing) => {)}isOpened={showDowngradeModal}/>+ <Modal+ onClose={closeUpdateModal}+ onSubmit={updateSubscription}+ submitText={t('common.confirm')}+ closeText={t('common.goBack')}+ title={t('billing.confirmNewPlan')}+ submitType='regular'+ type='info'+ isLoading={isSubUpdating}+ message={(+ <>+ {subUpdatePreview === null && (+ <Loader />+ )}+ {subUpdatePreview === false && (+ <p className='whitespace-pre-line'>{t('billing.previewLoadingError')}</p>+ )}+ {subUpdatePreview && (+ <div>+ <h2 className='text-base font-bold'>+ {t('billing.dueNow')}+ </h2>+ <p className='text-sm'>+ {t('billing.dueNowDescription')}+ </p>+ <div className='overflow-hidden shadow ring-1 ring-black ring-opacity-5 md:rounded-lg mt-2'>+ <table className='min-w-full divide-y divide-gray-300 200 dark:divide-gray-500'>+ <thead className='bg-gray-50 dark:bg-slate-800'>+ <tr>+ <th scope='col' className='py-3.5 pl-4 pr-3 text-left text-sm font-semibold text-gray-900 dark:text-gray-50 sm:pl-6'>+ {t('common.amount')}+ </th>+ <th scope='col' className='px-3 py-3.5 text-left text-sm font-semibold text-gray-900 dark:text-gray-50'>+ {t('common.date')}+ </th>+ </tr>+ </thead>+ <tbody className='divide-y divide-gray-200 dark:divide-gray-600 bg-white dark:bg-slate-800'>+ <tr>+ <td className='whitespace-nowrap px-3 py-4 text-sm text-gray-900 dark:text-gray-50 sm:pl-6'>+ {`${subUpdatePreview.immediatePayment.symbol}${subUpdatePreview.immediatePayment.amount}`}+ </td>+ <td className='whitespace-nowrap px-3 py-4 text-sm text-gray-900 dark:text-gray-50'>+ {language === 'en'+ ? dayjs(subUpdatePreview.immediatePayment.date).locale(language).format('MMMM D, YYYY')+ : dayjs(subUpdatePreview.immediatePayment.date).locale(language).format('D MMMM, YYYY')}+ </td>+ </tr>+ </tbody>+ </table>+ </div>+ {subUpdatePreview.immediatePayment.amount < 0 && (+ <p className='mt-2 italic'>+ {t('billing.negativePayment', {+ currency: subUpdatePreview.immediatePayment.symbol,+ dueNowAmount: -subUpdatePreview.immediatePayment.amount,+ dueNowDate: language === 'en' ? dayjs(subUpdatePreview.immediatePayment.date).locale(language).format('MMMM D, YYYY') : dayjs(subUpdatePreview.immediatePayment.date).locale(language).format('D MMMM, YYYY'),+ nextPaymentAmount: subUpdatePreview.nextPayment.amount,+ })}+ </p>+ )}+ <h2 className='text-base font-bold mt-5'>+ {t('billing.nextPayment')}+ </h2>+ <div className='overflow-hidden shadow ring-1 ring-black ring-opacity-5 md:rounded-lg mt-2'>+ <table className='min-w-full divide-y divide-gray-300 200 dark:divide-gray-500'>+ <thead className='bg-gray-50 dark:bg-slate-800'>+ <tr>+ <th scope='col' className='py-3.5 pl-4 pr-3 text-left text-sm font-semibold text-gray-900 dark:text-gray-50 sm:pl-6'>+ {t('common.amount')}+ </th>+ <th scope='col' className='px-3 py-3.5 text-left text-sm font-semibold text-gray-900 dark:text-gray-50'>+ {t('common.date')}+ </th>+ </tr>+ </thead>+ <tbody className='divide-y divide-gray-200 dark:divide-gray-600 bg-white dark:bg-slate-800'>+ <tr>+ <td className='whitespace-nowrap px-3 py-4 text-sm text-gray-900 dark:text-gray-50 sm:pl-6'>+ {`${subUpdatePreview.nextPayment.symbol}${subUpdatePreview.nextPayment.amount}`}+ </td>+ <td className='whitespace-nowrap px-3 py-4 text-sm text-gray-900 dark:text-gray-50'>+ {language === 'en'+ ? dayjs(subUpdatePreview.nextPayment.date).locale(language).format('MMMM D, YYYY')+ : dayjs(subUpdatePreview.nextPayment.date).locale(language).format('D MMMM, YYYY')}+ </td>+ </tr>+ </tbody>+ </table>+ </div>+ </div>+ )}+ </>+ )}+ isOpened={isNewPlanConfirmationModalOpened}+ /></>)}diff --git a/app/pages/UserSettings/UserSettings.tsx b/app/pages/UserSettings/UserSettings.tsxindex 2a417e333..dc69b8fad 100644--- a/app/pages/UserSettings/UserSettings.tsx+++ b/app/pages/UserSettings/UserSettings.tsx@@ -59,7 +59,7 @@ import {exportUserData,generateApiKey,deleteApiKey, // setTheme,- reciveLoginNotification,+ receiveLoginNotification,} from 'api'import ProjectList from './components/ProjectList'import TwoFA from './components/TwoFA'@@ -291,7 +291,7 @@ const UserSettings = ({setSettingUpdating(true)try {- await reciveLoginNotification(checked)+ await receiveLoginNotification(checked)updateUserData({receiveLoginNotifications: checked,})diff --git a/app/ui/Button.tsx b/app/ui/Button.tsxindex 432c52652..db8252090 100644--- a/app/ui/Button.tsx+++ b/app/ui/Button.tsx@@ -60,7 +60,7 @@ const Button = ({}, className)}>{loading && (- <Spin />+ <Spin alwaysLight />)}{text || children}</button>diff --git a/app/ui/Modal.tsx b/app/ui/Modal.tsxindex 9014e3f63..91aa432a5 100644--- a/app/ui/Modal.tsx+++ b/app/ui/Modal.tsx@@ -6,6 +6,7 @@ import {CheckIcon, ExclamationTriangleIcon, InformationCircleIcon, UserGroupIcon,} from '@heroicons/react/24/outline'import Beta from 'ui/Beta'+import Spin from './icons/Spin'interface IModal {className?: string,@@ -21,10 +22,11 @@ interface IModal {size?: 'regular' | 'large',customButtons?: JSX.Element,isBeta?: boolean,+ isLoading?: boolean,}const Modal = ({- className, type, title, message, isOpened, onClose, onSubmit, closeText, submitText, submitType, size, customButtons, isBeta,+ className, type, title, message, isOpened, onClose, onSubmit, closeText, submitText, submitType, size, customButtons, isBeta, isLoading,}: IModal): JSX.Element => (<Transition.Root show={isOpened} as={Fragment}><Dialog@@ -117,6 +119,9 @@ const Modal = ({})}onClick={onSubmit}>+ {isLoading && (+ <Spin alwaysLight />+ )}{submitText}</button>)}@@ -153,6 +158,7 @@ Modal.propTypes = {size: PropTypes.oneOf(['regular', 'large']),customButtons: PropTypes.oneOfType([PropTypes.arrayOf(PropTypes.node), PropTypes.node]),isBeta: PropTypes.bool,+ isLoading: PropTypes.bool,}Modal.defaultProps = {@@ -168,6 +174,7 @@ Modal.defaultProps = {title: null,customButtons: null,isBeta: false,+ isLoading: false,}export default memo(Modal)diff --git a/app/ui/icons/Spin.tsx b/app/ui/icons/Spin.tsxindex 1bcd172ef..cab889949 100644--- a/app/ui/icons/Spin.tsx+++ b/app/ui/icons/Spin.tsx@@ -2,10 +2,21 @@ import React from 'react'import cx from 'clsx'import PropTypes from 'prop-types'-const Spin = ({ className }: {+interface ISpin {className?: string,-}): JSX.Element => (- <svg className={cx('animate-spin -ml-1 mr-2 h-4 w-4 text-slate-900 dark:text-white', className)} xmlns='http://www.w3.org/2000/svg' fill='none' viewBox='0 0 24 24'>+ alwaysLight?: boolean,+}++const Spin = ({ className, alwaysLight }: ISpin): JSX.Element => (+ <svg+ className={cx('animate-spin -ml-1 mr-2 h-4 w-4 text-slate-900 dark:text-white', {+ 'text-slate-900 dark:text-white': !alwaysLight,+ 'text-white': alwaysLight,+ }, className)}+ xmlns='http://www.w3.org/2000/svg'+ fill='none'+ viewBox='0 0 24 24'+ ><circle className='opacity-25' cx='12' cy='12' r='10' stroke='currentColor' strokeWidth='4' /><path className='opacity-75' fill='currentColor' d='M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z' /></svg>@@ -13,10 +24,12 @@ const Spin = ({ className }: {Spin.propTypes = {className: PropTypes.string,+ alwaysLight: PropTypes.bool,}Spin.defaultProps = {className: '',+ alwaysLight: false,}export default Spindiff --git a/public/locales/en.json b/public/locales/en.jsonindex b539da709..25d6c4c0a 100644--- a/public/locales/en.json+++ b/public/locales/en.json@@ -48,6 +48,9 @@"logout": "Logout","save": "Save","continue": "Continue",+ "confirm": "Confirm",+ "amount": "Amount",+ "date": "Date","error": "Error","close": "Close","cancel": "Cancel",@@ -722,7 +725,13 @@"pageviews": "Pageview events: {{quantity}} ({{percentage}}%)","customEvents": "Custom events: {{quantity}} ({{percentage}}%)","captcha": "CAPTCHA events: {{quantity}} ({{percentage}}%)",- "gotoUsage": "Go to plan usage"+ "gotoUsage": "Go to plan usage",+ "confirmNewPlan": "Confirm your new subscription plan",+ "previewLoadingError": "An error occured while loading the pricing preview, please try again later.\nIf the problem persists, please contact us at <mail>{{email}}</mail>.\nYou can still change your plan, but you won't be able to see the pricing preview at the moment, sorry for that.",+ "dueNow": "Due now",+ "dueNowDescription": "You will be charged pro-rated amount for the remaining days of the current billing period.",+ "negativePayment": "Negative 'Amount' means that you will have a credit balance of {{currency}}{{dueNowAmount}}. You will be billed {{currency}}0.00 on {{dueNowDate}}. Once the credit balance is used up, your recurring billing amount will be {{currency}}{{nextPaymentAmount}} every billing cycle of your subscription plan.",+ "nextPayment": "Next payment"},"modals": {"paidFeature": {