A free and open source instant messaging and VoIP chat app built for friends, groups, and communities.
feat(app): block buying in setup or disputes, resume after login
Hampus5b3d32cd7c63
diff --git a/fluxer_app/src/features/premium/components/modals/GiftPlutoniumModal.module.css b/fluxer_app/src/features/premium/components/modals/GiftPlutoniumModal.module.cssindex 18dfb1846..e68f00b31 100644--- a/fluxer_app/src/features/premium/components/modals/GiftPlutoniumModal.module.css+++ b/fluxer_app/src/features/premium/components/modals/GiftPlutoniumModal.module.css@@ -26,16 +26,12 @@white-space: nowrap;}-.badge {- display: inline-flex;- align-items: center;- padding: 0.0625rem 0.5rem;- border-radius: 999px;- background-color: color-mix(in srgb, var(--brand-primary) 18%, transparent);- color: var(--text-link);+.saving {+ color: var(--brand-primary-light);font-size: 0.75rem;font-weight: 700;line-height: 1.125rem;+ white-space: nowrap;}.note {diff --git a/fluxer_app/src/features/premium/components/modals/GiftPlutoniumModal.tsx b/fluxer_app/src/features/premium/components/modals/GiftPlutoniumModal.tsxindex 96d3c26f4..c30c8267d 100644--- a/fluxer_app/src/features/premium/components/modals/GiftPlutoniumModal.tsx+++ b/fluxer_app/src/features/premium/components/modals/GiftPlutoniumModal.tsx@@ -12,14 +12,22 @@ import {} from '@app/features/i18n/utils/CommonMessageDescriptors';import * as PremiumCommands from '@app/features/premium/commands/PremiumCommands';import styles from '@app/features/premium/components/modals/GiftPlutoniumModal.module.css';+import {usePurchaseAccountGate} from '@app/features/premium/hooks/usePurchaseAccountGate';import PremiumState from '@app/features/premium/state/PremiumState';-import {BUY_GIFT_DESCRIPTOR, GIFT_PREMIUM_DESCRIPTOR} from '@app/features/premium/utils/PremiumMessageDescriptors';+import {+ BUY_GIFT_DESCRIPTOR,+ GIFT_PREMIUM_DESCRIPTOR,+ PAYMENT_DISPUTE_OPEN_DESCRIPTOR,+} from '@app/features/premium/utils/PremiumMessageDescriptors';+import {yearlySavingsPercent} from '@app/features/premium/utils/PremiumSavings';import {areGiftPurchasesAvailable, getPremiumProductName} from '@app/features/premium/utils/PremiumUtils';import {Button} from '@app/features/ui/button/Button';import * as ModalCommands from '@app/features/ui/commands/ModalCommands';import {RadioGroup, type RadioOption} from '@app/features/ui/radio_group/RadioGroup';import MobileLayout from '@app/features/ui/state/MobileLayout';import Users from '@app/features/user/state/Users';+import {type PurchaseBlockedReason, PurchaseBlockedReasons} from '@fluxer/constants/src/AccountTierConstants';+import type {MessageDescriptor} from '@lingui/core';import {msg} from '@lingui/core/macro';import {useLingui} from '@lingui/react/macro';import {observer} from 'mobx-react-lite';@@ -36,7 +44,6 @@ const ONE_YEAR_DESCRIPTOR = msg({message: '1 year',comment: 'Gift purchase dialog option for a one-year gift.',});-const GIFT_PLAN_LABEL_DESCRIPTOR = msg({message: 'Gift length',comment: 'Accessible label of the gift length options in the gift purchase dialog.',@@ -50,18 +57,22 @@ const CLAIM_TO_GIFT_DESCRIPTOR = msg({comment: 'Note in the gift purchase dialog for unclaimed accounts.',});const VERIFY_TO_GIFT_DESCRIPTOR = msg({- message: 'Verify your email to buy gifts.',+ message: 'Confirm your email to buy gifts.',comment: 'Note in the gift purchase dialog for accounts without a verified email.',});+const NO_RECEIPT_EMAIL_TO_GIFT_DESCRIPTOR = msg({+ message: "Gifts need an email for receipts, and accounts on this instance don't have one.",+ comment:+ 'Note in the gift purchase dialog on an instance where people sign in with a username and accounts have no email.',+});+const BLOCKED_NOTES: Readonly<Record<PurchaseBlockedReason, MessageDescriptor>> = {+ [PurchaseBlockedReasons.UNCLAIMED]: CLAIM_TO_GIFT_DESCRIPTOR,+ [PurchaseBlockedReasons.EMAIL_UNVERIFIED]: VERIFY_TO_GIFT_DESCRIPTOR,+ [PurchaseBlockedReasons.NO_RECEIPT_EMAIL]: NO_RECEIPT_EMAIL_TO_GIFT_DESCRIPTOR,+};const PRICE_PLACEHOLDER = '...';-function savingsPercent(monthlyMinor: number | null | undefined, yearlyMinor: number | null | undefined) {- if (monthlyMinor == null || yearlyMinor == null || monthlyMinor <= 0) return null;- const percent = Math.round((1 - yearlyMinor / (monthlyMinor * 12)) * 100);- return percent > 0 ? percent : null;-}-export const GiftPlutoniumModal = observer(() => {const {i18n} = useLingui();const currentUser = Users.currentUser;@@ -74,17 +85,16 @@ export const GiftPlutoniumModal = observer(() => {if (!currentUser?.id) return;void PremiumCommands.refreshPremiumState(countryCode ?? undefined);}, [countryCode, currentUser?.id]);- const isClaimed = currentUser?.isClaimed() ?? false;- const isEmailVerified = currentUser?.verified === true;+ const accountGate = usePurchaseAccountGate();const userPurchaseDisabled = premiumState?.effective.premium_purchase_disabled === true;const giftsAvailable = areGiftPurchasesAvailable(priceIds, userPurchaseDisabled);- const blockedNote = !isClaimed- ? i18n._(CLAIM_TO_GIFT_DESCRIPTOR)- : !isEmailVerified- ? i18n._(VERIFY_TO_GIFT_DESCRIPTOR)- : null;+ const accountBlockedNote =+ accountGate.blockedReason !== null ? i18n._(BLOCKED_NOTES[accountGate.blockedReason]) : null;+ const blockedNote =+ accountBlockedNote ??+ (premiumState?.effective.payment_dispute_open === true ? i18n._(PAYMENT_DISPUTE_OPEN_DESCRIPTOR) : null);const pricesLoaded = giftMonthlyPrice !== PRICE_PLACEHOLDER && giftYearlyPrice !== PRICE_PLACEHOLDER;- const percent = savingsPercent(priceIds?.gift_1_month_amount_minor, priceIds?.gift_1_year_amount_minor);+ const percent = yearlySavingsPercent(priceIds?.gift_1_month_amount_minor, priceIds?.gift_1_year_amount_minor);const options = useMemo<ReadonlyArray<RadioOption<GiftPlan>>>(() => [{value: 'gift_1_year', name: i18n._(ONE_YEAR_DESCRIPTOR), desc: giftYearlyPrice},@@ -114,7 +124,7 @@ export const GiftPlutoniumModal = observer(() => {<span className={styles.optionName} data-flx="premium.gift-plutonium-modal.option-name"><span data-flx="premium.gift-plutonium-modal.span">{option.name}</span>{option.value === 'gift_1_year' && percent != null && (- <span className={styles.badge} data-flx="premium.gift-plutonium-modal.badge">+ <span className={styles.saving} data-flx="premium.gift-plutonium-modal.saving">{i18n._(SAVE_PERCENT_DESCRIPTOR, {percent})}</span>)}@@ -140,13 +150,13 @@ export const GiftPlutoniumModal = observer(() => {)}</Modal.ContentLayout></Modal.Content>- <Modal.Footer data-flx="premium.gift-plutonium-modal.modal-footer">- <Button onClick={ModalCommands.pop} variant="secondary" data-flx="premium.gift-plutonium-modal.button.cancel">- {i18n._(CANCEL_DESCRIPTOR)}- </Button>- {giftsAvailable && (+ {giftsAvailable ? (+ <Modal.Footer data-flx="premium.gift-plutonium-modal.modal-footer">+ <Button onClick={ModalCommands.pop} variant="secondary" data-flx="premium.gift-plutonium-modal.button.cancel">+ {i18n._(CANCEL_DESCRIPTOR)}+ </Button><Button- onClick={() => void handleSelectPlan(plan)}+ onClick={() => accountGate.start(() => void handleSelectPlan(plan))}submitting={loadingCheckout}disabled={blockedNote != null || !pricesLoaded}variant="primary"@@ -154,8 +164,10 @@ export const GiftPlutoniumModal = observer(() => {>{i18n._(BUY_GIFT_DESCRIPTOR)}</Button>- )}- </Modal.Footer>+ </Modal.Footer>+ ) : (+ <Modal.DismissFooter data-flx="premium.gift-plutonium-modal.dismiss-footer" />+ )}</Modal.Root>);});diff --git a/fluxer_app/src/features/premium/components/plutonium_page/PlutoniumPage.tsx b/fluxer_app/src/features/premium/components/plutonium_page/PlutoniumPage.tsxindex 25a01a4e8..9cf3d6477 100644--- a/fluxer_app/src/features/premium/components/plutonium_page/PlutoniumPage.tsx+++ b/fluxer_app/src/features/premium/components/plutonium_page/PlutoniumPage.tsx@@ -16,17 +16,21 @@ import {SubscriptionCard} from '@app/features/app/components/dialogs/components/import GeoIP from '@app/features/app/state/GeoIP';import RuntimeConfig from '@app/features/app/state/RuntimeConfig';import Guilds from '@app/features/guild/state/Guilds';+import {getLocaleDirection} from '@app/features/i18n/utils/LocaleDirection';import {marketingUrl} from '@app/features/messaging/utils/MessagingUrlUtils';import * as RouterUtils from '@app/features/navigation/utils/RouterUtils';import * as PlutoniumPageCommands from '@app/features/premium/commands/PlutoniumPageCommands';import * as PremiumCommands from '@app/features/premium/commands/PremiumCommands';+import {OperatorPassPurchasesSection} from '@app/features/premium/components/operator_pass/OperatorPassPurchasesSection';import styles from '@app/features/premium/components/plutonium_page/PlutoniumPage.module.css';+import {PlutoniumPageAtom} from '@app/features/premium/components/plutonium_page/PlutoniumPageAtom';+import {PlutoniumPageButton} from '@app/features/premium/components/plutonium_page/PlutoniumPageButton';import {PlutoniumPageComparison,resolveUploadSizes,} from '@app/features/premium/components/plutonium_page/PlutoniumPageComparison';-import {PlutoniumPageIcon} from '@app/features/premium/components/plutonium_page/PlutoniumPageIcons';-import {CROWN_AVIF, CROWN_WEBP} from '@app/features/premium/components/plutonium_page/PlutoniumPageMedia';+import {PlutoniumPageHeroShapes} from '@app/features/premium/components/plutonium_page/PlutoniumPageHeroShapes';+import {heroArtFor} from '@app/features/premium/components/plutonium_page/PlutoniumPageMedia';import {CLOSING_BODY_DESCRIPTOR,CLOSING_GIFT_BODY_DESCRIPTOR,@@ -48,6 +52,7 @@ import {PAGE_LABEL_DESCRIPTOR,PRICE_OR_DESCRIPTOR,PURCHASE_BLOCKED_CLAIM_DESCRIPTOR,+ PURCHASE_BLOCKED_NO_RECEIPT_EMAIL_DESCRIPTOR,PURCHASE_BLOCKED_VERIFY_DESCRIPTOR,REDEEM_GIFT_CODE_DESCRIPTOR,REDEEM_ONLY_DESCRIPTOR,@@ -58,32 +63,47 @@ import {VISIONARY_THANKS_DESCRIPTOR,YEARLY_PRICE_DESCRIPTOR,} from '@app/features/premium/components/plutonium_page/PlutoniumPageMessages';+import {resolvePurchaseSurface} from '@app/features/premium/components/plutonium_page/PlutoniumPagePurchases';import {PlutoniumPageShowcase} from '@app/features/premium/components/plutonium_page/PlutoniumPageShowcase';+import {usePurchaseAccountGate} from '@app/features/premium/hooks/usePurchaseAccountGate';import PremiumState from '@app/features/premium/state/PremiumState';-import {- areGiftPurchasesAvailable,- arePremiumPurchasesAvailable,- canServiceStripeSubscriptions,- getPremiumProductFullName,- getPremiumProductName,- shouldShowPremiumFeatures,-} from '@app/features/premium/utils/PremiumUtils';+import {forgetPurchaseIntent, type PurchasePlan, peekPurchaseIntent} from '@app/features/premium/state/PurchaseIntent';+import {PAYMENT_DISPUTE_OPEN_DESCRIPTOR} from '@app/features/premium/utils/PremiumMessageDescriptors';+import {yearlySavingsPercent} from '@app/features/premium/utils/PremiumSavings';+import {getPremiumProductFullName, getPremiumProductName} from '@app/features/premium/utils/PremiumUtils';import * as ModalCommands from '@app/features/ui/commands/ModalCommands';import {modal} from '@app/features/ui/commands/ModalCommands';+import * as ToastCommands from '@app/features/ui/commands/ToastCommands';import FocusRing from '@app/features/ui/focus_ring/FocusRing';+import {ArrowLeftIcon} from '@app/features/ui/icons/DirectionalIcons';import MobileLayout from '@app/features/ui/state/MobileLayout';import Users from '@app/features/user/state/Users';import * as LocaleUtils from '@app/features/user/utils/LocaleUtils';+import {type PurchaseBlockedReason, PurchaseBlockedReasons} from '@fluxer/constants/src/AccountTierConstants';import {GuildFeatures} from '@fluxer/constants/src/GuildConstants';import {getFormattedLongDate} from '@fluxer/date_utils/src/DateFormatting';+import type {MessageDescriptor} from '@lingui/core';+import {msg} from '@lingui/core/macro';import {Trans, useLingui} from '@lingui/react/macro';-import {ArrowLeftIcon, GiftIcon, TicketIcon} from '@phosphor-icons/react';+import {GiftIcon, TicketIcon} from '@phosphor-icons/react';import {clsx} from 'clsx';import {observer} from 'mobx-react-lite';import type React from 'react';import {useCallback, useEffect, useMemo, useRef, useState} from 'react';-type CheckoutPlan = 'monthly' | 'yearly' | 'gift_1_month' | 'gift_1_year';+const PLAN_INTENT_UNAVAILABLE_DESCRIPTOR = msg({+ message: "Purchases aren't available for your account right now.",+ comment: 'Toast when someone arrives from a subscribe link but purchases are not available for this account.',+});+const GIFT_INTENT_UNAVAILABLE_DESCRIPTOR = msg({+ message: "Gifts aren't available for your account right now.",+ comment: 'Toast when someone arrives from a gift link but gift purchases are not available for this account.',+});+const PURCHASE_BLOCKED_NOTES: Readonly<Record<PurchaseBlockedReason, MessageDescriptor>> = {+ [PurchaseBlockedReasons.UNCLAIMED]: PURCHASE_BLOCKED_CLAIM_DESCRIPTOR,+ [PurchaseBlockedReasons.EMAIL_UNVERIFIED]: PURCHASE_BLOCKED_VERIFY_DESCRIPTOR,+ [PurchaseBlockedReasons.NO_RECEIPT_EMAIL]: PURCHASE_BLOCKED_NO_RECEIPT_EMAIL_DESCRIPTOR,+};const FOOTNOTE_ID = 'plutonium-page-tag-footnote';const MANAGE_ID = 'plutonium-page-manage';@@ -97,63 +117,6 @@ function splitTemplate(text: string, token: string): [string, string] {return [text.slice(0, index), text.slice(index + token.length)];}-function yearlySavingsPercent(monthlyMinor: number | null | undefined, yearlyMinor: number | null | undefined) {- if (monthlyMinor == null || yearlyMinor == null || monthlyMinor <= 0) return null;- const percent = Math.round((1 - yearlyMinor / (monthlyMinor * 12)) * 100);- return percent > 0 ? percent : null;-}--interface PageButtonProps {- variant: 'primary' | 'secondary';- onClick: () => void;- disabled?: boolean;- loading?: boolean;- directional?: boolean;- badge?: string | null;- children: React.ReactNode;- flx: string;-}--function PageButton({variant, onClick, disabled, loading, directional, badge, children, flx}: PageButtonProps) {- return (- <FocusRing offset={-2} data-flx="premium.plutonium-page.plutonium-page.page-button.focus-ring">- <button- type="button"- className={clsx(styles.button, variant === 'primary' ? styles.buttonPrimary : styles.buttonSecondary)}- onClick={onClick}- disabled={disabled || loading}- aria-busy={loading || undefined}- data-flx={flx}- >- <span data-flx="premium.plutonium-page.plutonium-page.page-button.span">{children}</span>- {badge && (- <span- className={styles.buttonBadge}- data-flx="premium.plutonium-page.plutonium-page.page-button.button-badge"- >- {badge}- </span>- )}- {loading ? (- <span- className={styles.buttonSpinner}- aria-hidden="true"- data-flx="premium.plutonium-page.plutonium-page.page-button.button-spinner"- />- ) : (- directional && (- <PlutoniumPageIcon- name="arrowRight"- className={clsx(styles.buttonIcon, styles.buttonIconDirectional)}- data-flx="premium.plutonium-page.plutonium-page.page-button.button-icon"- />- )- )}- </button>- </FocusRing>- );-}-export const PlutoniumPage = observer(function PlutoniumPage() {const PREMIUM_PRODUCT_NAME = getPremiumProductName();const {i18n} = useLingui();@@ -163,7 +126,7 @@ export const PlutoniumPage = observer(function PlutoniumPage() {const countryCode = GeoIP.countryCode;const isMobile = MobileLayout.enabled;const scrollerRef = useRef<HTMLDivElement | null>(null);- const [pendingPlan, setPendingPlan] = useState<CheckoutPlan | null>(null);+ const [pendingPlan, setPendingPlan] = useState<PurchasePlan | null>(null);const guilds = Guilds.getGuilds();const visionaryGuild = useMemo(() => guilds.find((guild) => guild.features.has(GuildFeatures.VISIONARY)), [guilds]);const subscriptionStatus = useSubscriptionStatus(currentUser, premiumState);@@ -201,34 +164,57 @@ export const PlutoniumPage = observer(function PlutoniumPage() {useEffect(() => {if (!loadingCheckout) setPendingPlan(null);}, [loadingCheckout]);- const isClaimed = currentUser?.isClaimed() ?? false;- const isEmailVerified = currentUser?.verified === true;- const purchaseDisabled = !isClaimed || !isEmailVerified;+ const accountGate = usePurchaseAccountGate();+ const paymentDisputeOpen = premiumState?.effective.payment_dispute_open === true;+ const purchaseDisabled = accountGate.blockedReason !== null || paymentDisputeOpen;const userPurchaseDisabled = premiumState?.effective.premium_purchase_disabled === true;- const purchasesAvailable = arePremiumPurchasesAvailable(userPurchaseDisabled);- const giftPurchasesAvailable = areGiftPurchasesAvailable(priceIds, userPurchaseDisabled);const hasBillingRelationship = subscriptionStatus.hasEverPurchased || premiumState?.billing.subscription != null;- const billingUnavailable =- !shouldShowPremiumFeatures() ||- (!arePremiumPurchasesAvailable() && !(hasBillingRelationship && canServiceStripeSubscriptions()));const isMember = subscriptionStatus.shouldShowPremiumCard;- const canSubscribe = purchasesAvailable && subscriptionStatus.canStartSubscription;+ const {purchasesAvailable, giftPurchasesAvailable, canSubscribe, billingUnavailable, heroMode, showClosing} =+ resolvePurchaseSurface({+ priceIds,+ userPurchaseDisabled,+ isMember,+ canStartSubscription: subscriptionStatus.canStartSubscription,+ hasBillingRelationship,+ });const savingsPercent = yearlySavingsPercent(priceIds?.monthly_amount_minor, priceIds?.yearly_amount_minor);- const savingsBadge = savingsPercent != null ? i18n._(SAVE_PERCENT_DESCRIPTOR, {percent: savingsPercent}) : null;+ const savingsLabel = savingsPercent != null ? i18n._(SAVE_PERCENT_DESCRIPTOR, {percent: savingsPercent}) : null;const uploadSizes = resolveUploadSizes(i18n.locale);- const purchaseBlockedNote = !isClaimed- ? i18n._(PURCHASE_BLOCKED_CLAIM_DESCRIPTOR, {premiumProductName: getPremiumProductName()})- : !isEmailVerified- ? i18n._(PURCHASE_BLOCKED_VERIFY_DESCRIPTOR, {premiumProductName: getPremiumProductName()})- : null;+ const accountBlockedNote =+ accountGate.blockedReason === null+ ? null+ : i18n._(PURCHASE_BLOCKED_NOTES[accountGate.blockedReason], {premiumProductName: getPremiumProductName()});+ const purchaseBlockedNote =+ accountBlockedNote ?? (paymentDisputeOpen ? i18n._(PAYMENT_DISPUTE_OPEN_DESCRIPTOR) : null);const startCheckout = useCallback(- (plan: CheckoutPlan) => {+ (plan: PurchasePlan, onDismiss?: () => void) => {if (purchaseDisabled || loadingCheckout) return;- setPendingPlan(plan);- void handleSelectPlan(plan);+ const checkout = () => {+ setPendingPlan(plan);+ void handleSelectPlan(plan);+ };+ accountGate.start(checkout, onDismiss);},- [handleSelectPlan, loadingCheckout, purchaseDisabled],+ [accountGate, handleSelectPlan, loadingCheckout, purchaseDisabled],);+ const purchaseIntentCheckedRef = useRef(false);+ useEffect(() => {+ if (purchaseIntentCheckedRef.current || priceIds == null || currentUser?.id == null) return;+ purchaseIntentCheckedRef.current = true;+ const intendedPlan = peekPurchaseIntent();+ if (intendedPlan === null) return;+ const gift = intendedPlan === 'gift_1_month' || intendedPlan === 'gift_1_year';+ if (purchaseDisabled || !(gift ? giftPurchasesAvailable : purchasesAvailable)) {+ forgetPurchaseIntent();+ ToastCommands.createToast({+ type: 'info',+ children: i18n._(gift ? GIFT_INTENT_UNAVAILABLE_DESCRIPTOR : PLAN_INTENT_UNAVAILABLE_DESCRIPTOR),+ });+ return;+ }+ startCheckout(intendedPlan, forgetPurchaseIntent);+ }, [priceIds, currentUser?.id, startCheckout, purchaseDisabled, giftPurchasesAvailable, purchasesAvailable, i18n]);const scrollToId = useCallback((id: string, block: ScrollLogicalPosition = 'start') => {const target = scrollerRef.current?.querySelector<HTMLElement>(`#${id}`);target?.scrollIntoView({behavior: 'smooth', block});@@ -292,45 +278,45 @@ export const PlutoniumPage = observer(function PlutoniumPage() {);}, [handleEndPremiumGracePeriod]);if (!currentUser) return null;- const monthlyLabel = i18n._(MONTHLY_PRICE_DESCRIPTOR, {monthlyPrice});- const yearlyLabel = i18n._(YEARLY_PRICE_DESCRIPTOR, {yearlyPrice});const pricesLoaded = monthlyPrice !== PLACEHOLDER_PRICE && yearlyPrice !== PLACEHOLDER_PRICE;+ const [monthlyBefore, monthlyAfter] = splitTemplate(+ i18n._(MONTHLY_PRICE_DESCRIPTOR, {monthlyPrice: '\u0000'}),+ '\u0000',+ );+ const [yearlyBefore, yearlyAfter] = splitTemplate(i18n._(YEARLY_PRICE_DESCRIPTOR, {yearlyPrice: '\u0000'}), '\u0000');+ const priceSavingText = pricesLoaded ? savingsLabel : i18n._(SAVE_PERCENT_DESCRIPTOR, {percent: 0});const subscribeButtons = (flxSuffix: string) => (<>- <PageButton+ <PlutoniumPageButtonvariant="primary"onClick={() => startCheckout('yearly')}disabled={purchaseDisabled}loading={loadingCheckout && pendingPlan === 'yearly'}- badge={savingsBadge}directional- flx={`premium.plutonium-page.${flxSuffix}.subscribe-yearly`}- data-flx="premium.plutonium-page.plutonium-page.subscribe-buttons.page-button.start-checkout"+ data-flx={`premium.plutonium-page.${flxSuffix}.subscribe-yearly`}>{i18n._(SUBSCRIBE_YEARLY_DESCRIPTOR)}- </PageButton>- <PageButton+ </PlutoniumPageButton>+ <PlutoniumPageButtonvariant="secondary"onClick={() => startCheckout('monthly')}disabled={purchaseDisabled}loading={loadingCheckout && pendingPlan === 'monthly'}- flx={`premium.plutonium-page.${flxSuffix}.subscribe-monthly`}- data-flx="premium.plutonium-page.plutonium-page.subscribe-buttons.page-button.start-checkout--2"+ data-flx={`premium.plutonium-page.${flxSuffix}.subscribe-monthly`}>{i18n._(SUBSCRIBE_MONTHLY_DESCRIPTOR)}- </PageButton>+ </PlutoniumPageButton></>);const giftButton = (variant: 'primary' | 'secondary', flxSuffix: string) =>giftPurchasesAvailable ? (- <PageButton+ <PlutoniumPageButtonvariant={variant}onClick={PlutoniumPageCommands.openGiftPlutoniumModal}- flx={`premium.plutonium-page.${flxSuffix}.gift`}- data-flx="premium.plutonium-page.plutonium-page.gift-button.page-button.open-gift-plutonium-modal"+ data-flx={`premium.plutonium-page.${flxSuffix}.gift`}>{i18n._(GIFT_PLUTONIUM_DESCRIPTOR, {premiumProductName: getPremiumProductName()})}- </PageButton>+ </PlutoniumPageButton>) : null;const memberLead = (() => {if (subscriptionStatus.isVisionary) return i18n._(VISIONARY_THANKS_DESCRIPTOR);@@ -349,17 +335,26 @@ export const PlutoniumPage = observer(function PlutoniumPage() {}return i18n._(MEMBER_THANKS_DESCRIPTOR, {premiumProductName: getPremiumProductName()});})();- const closingTitle = !canSubscribe- ? i18n._(CLOSING_MEMBER_TITLE_DESCRIPTOR)- : subscriptionStatus.isGiftSubscription- ? i18n._(CLOSING_GIFT_TITLE_DESCRIPTOR)- : i18n._(CLOSING_TITLE_DESCRIPTOR);- const closingBody = !canSubscribe- ? i18n._(CLOSING_MEMBER_BODY_DESCRIPTOR, {premiumProductName: getPremiumProductName()})- : subscriptionStatus.isGiftSubscription- ? i18n._(CLOSING_GIFT_BODY_DESCRIPTOR)- : i18n._(CLOSING_BODY_DESCRIPTOR);+ let closingTitle: string;+ let closingBody: string;+ if (!canSubscribe) {+ closingTitle = i18n._(CLOSING_MEMBER_TITLE_DESCRIPTOR);+ closingBody = i18n._(CLOSING_MEMBER_BODY_DESCRIPTOR, {premiumProductName: getPremiumProductName()});+ } else if (subscriptionStatus.isGiftSubscription) {+ closingTitle = i18n._(CLOSING_GIFT_TITLE_DESCRIPTOR);+ closingBody = i18n._(CLOSING_GIFT_BODY_DESCRIPTOR);+ } else {+ closingTitle = i18n._(CLOSING_TITLE_DESCRIPTOR);+ closingBody = i18n._(CLOSING_BODY_DESCRIPTOR);+ }+ let comparisonActions: React.ReactNode = null;+ if (canSubscribe) {+ comparisonActions = subscribeButtons('comparison');+ } else if (isMember) {+ comparisonActions = giftButton('primary', 'comparison');+ }const showDonationHint = !RuntimeConfig.isSelfHosted();+ const heroArt = heroArtFor(RuntimeConfig.isSelfHosted());const donationTemplate = i18n._(DONATION_HINT_DESCRIPTOR, {productName: RuntimeConfig.productName,donateLink: '\u0000',@@ -371,6 +366,27 @@ export const PlutoniumPage = observer(function PlutoniumPage() {});const [footnoteBefore, footnoteAfter] = splitTemplate(footnoteTemplate, '\u0000');const visionaryHelpUrl = Routes.helpArticle('visionary');+ const footnote = RuntimeConfig.usesUniqueUsernames ? null : (+ <p id={FOOTNOTE_ID} className={styles.footnote} data-flx="premium.plutonium-page.footnote">+ <span data-flx="premium.plutonium-page.plutonium-page.span--5">{`* ${footnoteBefore}`}</span>+ {visionaryHelpUrl ? (+ <FocusRing offset={-2} data-flx="premium.plutonium-page.plutonium-page.focus-ring--5">+ <a+ className={styles.inlineLink}+ href={visionaryHelpUrl}+ target="_blank"+ rel="noopener noreferrer"+ data-flx="premium.plutonium-page.footnote.visionary-link"+ >+ {i18n._(TAG_FOOTNOTE_LINK_DESCRIPTOR)}+ </a>+ </FocusRing>+ ) : (+ <span data-flx="premium.plutonium-page.footnote.visionary-text">{i18n._(TAG_FOOTNOTE_LINK_DESCRIPTOR)}</span>+ )}+ <span data-flx="premium.plutonium-page.plutonium-page.span--6">{footnoteAfter}</span>+ </p>+ );const secondaryLinks = (<div className={styles.secondaryLinks} data-flx="premium.plutonium-page.hero.secondary-links">{giftPurchasesAvailable && (@@ -418,22 +434,56 @@ export const PlutoniumPage = observer(function PlutoniumPage() {{lead}</p>)}- {pricesLoaded && (- <p className={styles.priceLine} data-flx="premium.plutonium-page.hero.price-line">- <span className={styles.price} data-flx="premium.plutonium-page.plutonium-page.render-purchase-hero.price">- {monthlyLabel}+ <div+ className={clsx(styles.priceRow, !pricesLoaded && styles.priceRowPending)}+ aria-hidden={pricesLoaded ? undefined : true}+ dir={getLocaleDirection(i18n.locale)}+ data-flx="premium.plutonium-page.hero.price-line"+ >+ <span className={styles.priceItem} data-flx="premium.plutonium-page.hero.price-monthly">+ {monthlyBefore && (+ <span className={styles.pricePeriod} data-flx="premium.plutonium-page.hero.price-monthly-before">+ {monthlyBefore}+ </span>+ )}+ <span className={styles.priceAmount} data-flx="premium.plutonium-page.hero.price-monthly-amount">+ {monthlyPrice}</span>- <span- className={styles.priceOr}- data-flx="premium.plutonium-page.plutonium-page.render-purchase-hero.price-or"- >+ {monthlyAfter && (+ <span className={styles.pricePeriod} data-flx="premium.plutonium-page.hero.price-monthly-after">+ {monthlyAfter}+ </span>+ )}+ </span>+ <span className={styles.priceYearly} data-flx="premium.plutonium-page.hero.price-yearly">+ <span className={styles.priceOr} data-flx="premium.plutonium-page.hero.price-or">{i18n._(PRICE_OR_DESCRIPTOR)}</span>- <span className={styles.price} data-flx="premium.plutonium-page.plutonium-page.render-purchase-hero.price--2">- {yearlyLabel}+ <span+ className={clsx(styles.priceItem, styles.priceItemYearly)}+ data-flx="premium.plutonium-page.hero.price-yearly-item"+ >+ {yearlyBefore && (+ <span className={styles.pricePeriod} data-flx="premium.plutonium-page.hero.price-yearly-before">+ {yearlyBefore}+ </span>+ )}+ <span className={styles.priceAmount} data-flx="premium.plutonium-page.hero.price-yearly-amount">+ {yearlyPrice}+ </span>+ {yearlyAfter && (+ <span className={styles.pricePeriod} data-flx="premium.plutonium-page.hero.price-yearly-after">+ {yearlyAfter}+ </span>+ )}+ {priceSavingText && (+ <span className={styles.priceSaving} data-flx="premium.plutonium-page.hero.price-saving">+ {priceSavingText}+ </span>+ )}</span>- </p>- )}+ </span>+ </div><div className={clsx(styles.actions, styles.heroActions)} data-flx="premium.plutonium-page.hero.actions">{subscribeButtons('hero')}</div>@@ -446,44 +496,42 @@ export const PlutoniumPage = observer(function PlutoniumPage() {</>);const renderHeroBody = () => {- if (isMember && canSubscribe) return renderPurchaseHero(memberLead);- if (isMember) {+ if (heroMode === 'member-purchase') return renderPurchaseHero(memberLead);+ if (heroMode === 'member') {return (<><p className={styles.heroLead} data-flx="premium.plutonium-page.hero.lead">{memberLead}</p><div className={clsx(styles.actions, styles.heroActions)} data-flx="premium.plutonium-page.hero.actions">- <PageButton+ <PlutoniumPageButtonvariant="primary"onClick={() => scrollToId(MANAGE_ID)}directional- flx="premium.plutonium-page.hero.manage"- data-flx="premium.plutonium-page.plutonium-page.render-hero-body.page-button.scroll-to-id"+ data-flx="premium.plutonium-page.hero.manage">{i18n._(MANAGE_SUBSCRIPTION_DESCRIPTOR)}- </PageButton>+ </PlutoniumPageButton>{giftButton('secondary', 'hero')}</div></>);}- if (!purchasesAvailable) {+ if (heroMode === 'redeem-only') {return (<><p className={styles.heroLead} data-flx="premium.plutonium-page.hero.lead">{i18n._(REDEEM_ONLY_DESCRIPTOR, {premiumProductName: getPremiumProductName()})}</p><div className={clsx(styles.actions, styles.heroActions)} data-flx="premium.plutonium-page.hero.actions">- <PageButton+ <PlutoniumPageButtonvariant="primary"onClick={PlutoniumPageCommands.openGiftInventorySettings}directional- flx="premium.plutonium-page.hero.redeem"- data-flx="premium.plutonium-page.plutonium-page.render-hero-body.page-button.open-gift-inventory-settings"+ data-flx="premium.plutonium-page.hero.redeem">{i18n._(REDEEM_GIFT_CODE_DESCRIPTOR)}- </PageButton>+ </PlutoniumPageButton></div></>);@@ -498,11 +546,6 @@ export const PlutoniumPage = observer(function PlutoniumPage() {data-flx="premium.plutonium-page.root"><div ref={scrollerRef} className={styles.scroller} data-flx="premium.plutonium-page.scroller">- <div- className={styles.starfield}- aria-hidden="true"- data-flx="premium.plutonium-page.plutonium-page.starfield"- />{isMobile && (<div className={styles.mobileBar} data-flx="premium.plutonium-page.mobile-bar"><FocusRing offset={-2} data-flx="premium.plutonium-page.plutonium-page.focus-ring--3">@@ -523,30 +566,14 @@ export const PlutoniumPage = observer(function PlutoniumPage() {</FocusRing></div>)}- <section className={styles.hero} data-flx="premium.plutonium-page.hero">+ <section className={clsx(styles.hero, styles.onBrand)} data-flx="premium.plutonium-page.hero">+ <PlutoniumPageHeroShapes data-flx="premium.plutonium-page.hero.shapes" /><div className={styles.heroInner} data-flx="premium.plutonium-page.plutonium-page.hero-inner">- {!RuntimeConfig.isSelfHosted() && (- <div className={styles.crownWrap} data-flx="premium.plutonium-page.plutonium-page.crown-wrap">- <picture data-flx="premium.plutonium-page.plutonium-page.picture">- <source- type="image/avif"- srcSet={CROWN_AVIF}- data-flx="premium.plutonium-page.plutonium-page.source.image-avif"- />- <img- draggable={false}- className={styles.crown}- src={CROWN_WEBP}- width={480}- height={395}- alt=""- decoding="sync"- fetchPriority="high"- data-flx="premium.plutonium-page.hero.crown"- />- </picture>- </div>- )}+ <PlutoniumPageAtom+ art={heroArt}+ live={!RuntimeConfig.isSelfHosted()}+ data-flx="premium.plutonium-page.plutonium-page.plutonium-page-atom"+ /><h1 className={styles.displayHeading} data-flx="premium.plutonium-page.hero.title">{getPremiumProductFullName()}</h1>@@ -574,7 +601,7 @@ export const PlutoniumPage = observer(function PlutoniumPage() {{isMember && (<sectionid={MANAGE_ID}- className={clsx(styles.glassPanel, styles.managePanel)}+ className={clsx(styles.board, styles.managePanel)}aria-labelledby={`${MANAGE_ID}-heading`}data-flx="premium.plutonium-page.manage">@@ -595,6 +622,7 @@ export const PlutoniumPage = observer(function PlutoniumPage() {canSubscribe={canSubscribe}storeSubscription={subscriptionStatus.storeSubscription}premiumUntil={subscriptionStatus.actualPremiumUntil}+ renewsAt={subscriptionStatus.renewsAt}billingCycle={subscriptionStatus.billingCycle}monthlyPrice={monthlyPrice}yearlyPrice={yearlyPrice}@@ -645,25 +673,33 @@ export const PlutoniumPage = observer(function PlutoniumPage() {{subscriptionStatus.hasEverPurchased &&!billingUnavailable &&premiumState?.billing.stripe_customer_id != null && (- <>- <PurchaseHistorySection- premiumState={premiumState}- loadingPortal={loadingPortal}- handleOpenCustomerPortal={handleOpenCustomerPortal}- data-flx="premium.plutonium-page.manage.purchase-history"- />- {!RuntimeConfig.isSelfHosted() && (- <SelfServeRefundSection- eligibility={premiumState?.billing.refund_eligibility ?? null}- refreshPremiumState={() => PremiumCommands.refreshPremiumState(countryCode ?? undefined)}- data-flx="premium.plutonium-page.manage.self-serve-refund"- />- )}- </>+ <PurchaseHistorySection+ premiumState={premiumState}+ loadingPortal={loadingPortal}+ handleOpenCustomerPortal={handleOpenCustomerPortal}+ data-flx="premium.plutonium-page.manage.purchase-history"+ />)}+ {subscriptionStatus.hasEverPurchased &&+ !RuntimeConfig.isSelfHosted() &&+ premiumState != null &&+ premiumState.subscription_provider !== 'app_store' && (+ <SelfServeRefundSection+ eligibility={premiumState.billing.refund_eligibility ?? null}+ refreshPremiumState={() => PremiumCommands.refreshPremiumState(countryCode ?? undefined)}+ data-flx="premium.plutonium-page.manage.self-serve-refund"+ />+ )}+ <OperatorPassPurchasesSection data-flx="premium.plutonium-page.manage.operator-pass-purchases" /></div></section>)}+ {!isMember && (+ <OperatorPassPurchasesSection+ className={clsx(styles.board, styles.managePanel)}+ data-flx="premium.plutonium-page.operator-pass-purchases"+ />+ )}<PlutoniumPageShowcaseuploadSize={uploadSizes.premium}freeUploadSize={uploadSizes.free}@@ -675,16 +711,15 @@ export const PlutoniumPage = observer(function PlutoniumPage() {<PlutoniumPageComparisonfootnoteId={FOOTNOTE_ID}onFootnoteClick={handleFootnoteClick}- actions={- canSubscribe ? subscribeButtons('comparison') : isMember ? giftButton('primary', 'comparison') : null- }+ footnote={footnote}+ actions={comparisonActions}data-flx="premium.plutonium-page.plutonium-page.plutonium-page-comparison"/></div>- {(canSubscribe || (isMember && giftPurchasesAvailable)) && (+ {showClosing && (<sectionid={SUBSCRIBE_ID}- className={clsx(styles.glassPanel, styles.glassPanelBrand, styles.closing)}+ className={clsx(styles.board, styles.boardFeature, styles.onBrand, styles.closing)}data-flx="premium.plutonium-page.closing"><div className={styles.closingInner} data-flx="premium.plutonium-page.plutonium-page.closing-inner">@@ -694,38 +729,12 @@ export const PlutoniumPage = observer(function PlutoniumPage() {<p className={styles.closingBody} data-flx="premium.plutonium-page.closing.body">{closingBody}</p>- <div- className={clsx(styles.actions, styles.closingActions)}- data-flx="premium.plutonium-page.closing.actions"- >+ <div className={styles.actions} data-flx="premium.plutonium-page.closing.actions">{canSubscribe ? subscribeButtons('closing') : giftButton('primary', 'closing')}</div></div></section>)}- {!RuntimeConfig.usesUniqueUsernames && (- <p id={FOOTNOTE_ID} className={styles.footnote} data-flx="premium.plutonium-page.footnote">- <span data-flx="premium.plutonium-page.plutonium-page.span--5">{`* ${footnoteBefore}`}</span>- {visionaryHelpUrl ? (- <FocusRing offset={-2} data-flx="premium.plutonium-page.plutonium-page.focus-ring--5">- <a- className={styles.inlineLink}- href={visionaryHelpUrl}- target="_blank"- rel="noopener noreferrer"- data-flx="premium.plutonium-page.footnote.visionary-link"- >- {i18n._(TAG_FOOTNOTE_LINK_DESCRIPTOR)}- </a>- </FocusRing>- ) : (- <span data-flx="premium.plutonium-page.footnote.visionary-text">- {i18n._(TAG_FOOTNOTE_LINK_DESCRIPTOR)}- </span>- )}- <span data-flx="premium.plutonium-page.plutonium-page.span--6">{footnoteAfter}</span>- </p>- )}</div></div></div>diff --git a/fluxer_app/src/features/premium/components/plutonium_page/PlutoniumPageMessages.ts b/fluxer_app/src/features/premium/components/plutonium_page/PlutoniumPageMessages.tsindex 65dd3c8d9..c715cfc69 100644--- a/fluxer_app/src/features/premium/components/plutonium_page/PlutoniumPageMessages.ts+++ b/fluxer_app/src/features/premium/components/plutonium_page/PlutoniumPageMessages.ts@@ -4,15 +4,18 @@ import {msg} from '@lingui/core/macro';export const MONTHLY_PRICE_DESCRIPTOR = msg({message: '{monthlyPrice}/mo',- comment: 'Compact monthly price on the Plutonium page hero. Preserve the monthlyPrice placeholder exactly.',+ comment:+ 'Compact monthly price on the Plutonium page hero. Preserve the monthlyPrice placeholder exactly. The price is shown bold and any text around it in a lighter style, so keep the period words outside the placeholder.',});export const YEARLY_PRICE_DESCRIPTOR = msg({message: '{yearlyPrice}/yr',- comment: 'Compact yearly price on the Plutonium page hero. Preserve the yearlyPrice placeholder exactly.',+ comment:+ 'Compact yearly price on the Plutonium page hero. Preserve the yearlyPrice placeholder exactly. The price is shown bold and any text around it in a lighter style, so keep the period words outside the placeholder.',});export const PRICE_OR_DESCRIPTOR = msg({message: 'or',- comment: 'Compact conjunction between the monthly and yearly price on the Plutonium page hero.',+ comment:+ 'Compact conjunction between the monthly and yearly price on the Plutonium page hero. On narrow screens it starts the second line, right before the yearly price.',});export const DONATION_HINT_DESCRIPTOR = msg({message: "Just want to support {productName}'s open source development? {donateLink}.",@@ -246,10 +249,15 @@ export const PURCHASE_BLOCKED_CLAIM_DESCRIPTOR = msg({'Plutonium page note under disabled buttons for unclaimed accounts. premiumProductName is the paid tier name.',});export const PURCHASE_BLOCKED_VERIFY_DESCRIPTOR = msg({- message: 'Verify your email to buy {premiumProductName}.',+ message: 'Confirm your email to buy {premiumProductName}.',comment:'Plutonium page note under disabled buttons for unverified accounts. premiumProductName is the paid tier name.',});+export const PURCHASE_BLOCKED_NO_RECEIPT_EMAIL_DESCRIPTOR = msg({+ message: "{premiumProductName} needs an email for receipts, and accounts on this instance don't have one.",+ comment:+ 'Plutonium page note under disabled buttons on an instance where people sign in with a username and accounts have no email. premiumProductName is the paid tier name.',+});export const PAGE_LABEL_DESCRIPTOR = msg({message: '{premiumProductName} page',comment: 'Accessible label of the Plutonium page region. premiumProductName is the paid tier name.',diff --git a/fluxer_app/src/features/premium/components/plutonium_page/PlutoniumPagePurchases.ts b/fluxer_app/src/features/premium/components/plutonium_page/PlutoniumPagePurchases.tsnew file mode 100644index 000000000..cadacbe0a--- /dev/null+++ b/fluxer_app/src/features/premium/components/plutonium_page/PlutoniumPagePurchases.ts@@ -0,0 +1,51 @@+// SPDX-License-Identifier: AGPL-3.0-or-later++import type {PriceIds} from '@app/features/premium/commands/PremiumCommands';+import {+ areGiftPurchasesAvailable,+ arePremiumPurchasesAvailable,+ canServiceStripeSubscriptions,+ shouldShowPremiumFeatures,+} from '@app/features/premium/utils/PremiumUtils';++type HeroMode = 'member-purchase' | 'member' | 'redeem-only' | 'purchase';++export interface PurchaseSurfaceInput {+ priceIds: PriceIds | null;+ userPurchaseDisabled: boolean;+ isMember: boolean;+ canStartSubscription: boolean;+ hasBillingRelationship: boolean;+}++export interface PurchaseSurface {+ purchasesAvailable: boolean;+ giftPurchasesAvailable: boolean;+ canSubscribe: boolean;+ billingUnavailable: boolean;+ heroMode: HeroMode;+ showClosing: boolean;+}++export function resolvePurchaseSurface(input: PurchaseSurfaceInput): PurchaseSurface {+ const purchasesAvailable = arePremiumPurchasesAvailable(input.userPurchaseDisabled);+ const giftPurchasesAvailable = areGiftPurchasesAvailable(input.priceIds, input.userPurchaseDisabled);+ const billingUnavailable =+ !shouldShowPremiumFeatures() ||+ (!arePremiumPurchasesAvailable() && !(input.hasBillingRelationship && canServiceStripeSubscriptions()));+ const canSubscribe = purchasesAvailable && input.canStartSubscription;+ let heroMode: HeroMode = 'purchase';+ if (input.isMember) {+ heroMode = canSubscribe ? 'member-purchase' : 'member';+ } else if (!purchasesAvailable) {+ heroMode = 'redeem-only';+ }+ return {+ purchasesAvailable,+ giftPurchasesAvailable,+ canSubscribe,+ billingUnavailable,+ heroMode,+ showClosing: canSubscribe || (input.isMember && giftPurchasesAvailable),+ };+}diff --git a/fluxer_app/src/features/premium/hooks/usePurchaseAccountGate.ts b/fluxer_app/src/features/premium/hooks/usePurchaseAccountGate.tsnew file mode 100644index 000000000..692ac6174--- /dev/null+++ b/fluxer_app/src/features/premium/hooks/usePurchaseAccountGate.ts@@ -0,0 +1,60 @@+// SPDX-License-Identifier: AGPL-3.0-or-later++import RuntimeConfig from '@app/features/app/state/RuntimeConfig';+import type {User} from '@app/features/user/models/User';+import Users from '@app/features/user/state/Users';+import {AccountGateActions, openAccountGateFlow} from '@app/features/user/utils/AccountGatePresentation';+import {+ AccountTiers,+ type AccountVerificationNeed,+ type PurchaseBlockedReason,+ PurchaseBlockedReasons,+} from '@fluxer/constants/src/AccountTierConstants';+import {resolvePurchaseBlockedReason} from '@fluxer/constants/src/AccountTierRules';+import {useLingui} from '@lingui/react/macro';++type PurchaseAccountUser = Pick<User, 'reportsAccountTier' | 'accountTier' | 'verificationNeed' | 'email'>;++type PurchaseAccountState =+ | {readonly kind: 'ready'}+ | {readonly kind: 'claim_inline'; readonly need: AccountVerificationNeed}+ | {readonly kind: 'blocked'; readonly reason: PurchaseBlockedReason};++export function resolvePurchaseAccountState(user: PurchaseAccountUser | null | undefined): PurchaseAccountState {+ const hasEmail = user?.email != null;+ const reason =+ RuntimeConfig.usesUsernameSignIn && !hasEmail+ ? PurchaseBlockedReasons.NO_RECEIPT_EMAIL+ : resolvePurchaseBlockedReason({tier: user?.accountTier ?? AccountTiers.UNCLAIMED, hasEmail});+ if (reason === null) return {kind: 'ready'};+ const need = user?.verificationNeed ?? null;+ if (user?.reportsAccountTier === true && reason !== PurchaseBlockedReasons.NO_RECEIPT_EMAIL && need !== null) {+ return {kind: 'claim_inline', need};+ }+ return {kind: 'blocked', reason};+}++interface PurchaseAccountGate {+ readonly blockedReason: PurchaseBlockedReason | null;+ readonly start: (checkout: () => void, onDismiss?: () => void) => void;+}++export function usePurchaseAccountGate(): PurchaseAccountGate {+ const {i18n} = useLingui();+ const state = resolvePurchaseAccountState(Users.currentUser);+ return {+ blockedReason: state.kind === 'blocked' ? state.reason : null,+ start: (checkout, onDismiss) => {+ switch (state.kind) {+ case 'ready':+ checkout();+ return;+ case 'claim_inline':+ openAccountGateFlow(i18n, {action: AccountGateActions.PURCHASE, need: state.need}, checkout, onDismiss);+ return;+ case 'blocked':+ return;+ }+ },+ };+}diff --git a/fluxer_app/src/features/premium/state/PurchaseIntent.ts b/fluxer_app/src/features/premium/state/PurchaseIntent.tsnew file mode 100644index 000000000..495457b5a--- /dev/null+++ b/fluxer_app/src/features/premium/state/PurchaseIntent.ts@@ -0,0 +1,91 @@+// SPDX-License-Identifier: AGPL-3.0-or-later++import {getProtectedLocalStorage} from '@app/features/platform/state/ProtectedWebStorage';+import {Logger} from '@app/features/platform/utils/AppLogger';+import {MS_PER_HOUR} from '@fluxer/date_utils/src/DateConstants';+import {isObjectLike} from '@fluxer/record_utils/src/RecordGuards';++export type PurchasePlan = 'monthly' | 'yearly' | 'gift_1_month' | 'gift_1_year';++const logger = new Logger('PurchaseIntent');+const PURCHASE_INTENT_KEY = 'fluxer.purchase_intent';++const PRODUCT_PLANS: Readonly<Record<string, PurchasePlan>> = Object.freeze({+ 'plutonium-monthly': 'monthly',+ 'plutonium-yearly': 'yearly',+ 'gift-1-month': 'gift_1_month',+ 'gift-1-year': 'gift_1_year',+});++export function planForCheckoutProduct(product: string): PurchasePlan | null {+ return Object.hasOwn(PRODUCT_PLANS, product) ? PRODUCT_PLANS[product] : null;+}++function parsePurchaseIntent(raw: string | null, now: number): PurchasePlan | null {+ if (raw === null) {+ return null;+ }+ try {+ const value: unknown = JSON.parse(raw);+ if (!isObjectLike(value)) {+ return null;+ }+ if (typeof value.expiresAt !== 'number' || value.expiresAt <= now) {+ return null;+ }+ if (typeof value.plan !== 'string') {+ return null;+ }+ switch (value.plan) {+ case 'monthly':+ case 'yearly':+ case 'gift_1_month':+ case 'gift_1_year':+ return value.plan;+ default:+ return null;+ }+ } catch (error) {+ if (!(error instanceof SyntaxError)) {+ logger.warn('Failed to decode purchase intent', error);+ }+ return null;+ }+}++export function rememberPurchaseIntent(plan: PurchasePlan): void {+ const now = Date.now();+ const intent = {plan, expiresAt: now + MS_PER_HOUR};+ try {+ getProtectedLocalStorage()?.setItem(PURCHASE_INTENT_KEY, JSON.stringify(intent));+ } catch (error) {+ logger.warn('Failed to store purchase intent', error);+ }+}++export function forgetPurchaseIntent(): void {+ try {+ getProtectedLocalStorage()?.removeItem(PURCHASE_INTENT_KEY);+ } catch (error) {+ logger.warn('Failed to remove purchase intent', error);+ }+}++export function peekPurchaseIntent(): PurchasePlan | null {+ const now = Date.now();+ try {+ const raw = getProtectedLocalStorage()?.getItem(PURCHASE_INTENT_KEY) ?? null;+ const plan = parsePurchaseIntent(raw, now);+ if (plan === null && raw !== null) {+ forgetPurchaseIntent();+ }+ return plan;+ } catch (error) {+ logger.warn('Failed to read purchase intent', error);+ return null;+ }+}++export function hasPurchaseIntent(): boolean {+ return peekPurchaseIntent() !== null;+}diff --git a/fluxer_app/src/features/premium/utils/PremiumPurchaseBlock.ts b/fluxer_app/src/features/premium/utils/PremiumPurchaseBlock.tsnew file mode 100644index 000000000..cf3c49f1a--- /dev/null+++ b/fluxer_app/src/features/premium/utils/PremiumPurchaseBlock.ts@@ -0,0 +1,20 @@+// SPDX-License-Identifier: AGPL-3.0-or-later++type PremiumPurchaseBlockedReason = 'lifetime' | 'existing_subscription' | 'purchase_disabled' | 'payment_dispute_open';++export function getPremiumPurchaseBlockedReason(body: unknown): PremiumPurchaseBlockedReason | null {+ if (body == null || typeof body !== 'object' || !('reason' in body)) {+ return null;+ }++ const reason = body.reason;+ switch (reason) {+ case 'lifetime':+ case 'existing_subscription':+ case 'purchase_disabled':+ case 'payment_dispute_open':+ return reason;+ default:+ return null;+ }+}