feat(billing): configurable plans from the backoffice and MP payment notifications

Plans:
- Plan limits and Pro prices per country live in the database
  (plan_configs, plan_prices, seeded with the previous constants) and are
  read through PlanCatalog (30 s cache, defaults as fallback).
- /admin/plans edits limits (with the count of accounts that would become
  read-only) and prices, optionally pushing the new price to live
  subscriptions from their next charge (MP preapproval amount, Stripe item
  without proration) via the ApplyPriceChanges job, with an email and a
  notice on /billing.
- GET /billing/plans feeds the onboarding and the billing screen.

Mercado Pago:
- The Pro checkout returns through GET /billing/return on API_PUBLIC_URL,
  since MP refuses a back_url on localhost.
- The OAuth callback bounces from the tunnel to BETTER_AUTH_URL to find the
  session, requires the session to own the state, and redirects instead of
  answering JSON on unexpected errors.
- Checkout Pro links skip auto_return off public HTTPS and carry a
  notification_url to POST /payments/webhooks/mp/:paymentId, which confirms
  the payment with the owner's token (same rule as the polling job, which
  stays as fallback). The search now prefers the approved attempt.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Jose Selesan
2026-11-11 07:50:14 -03:00
parent abb18f1815
commit aac142d324
90 changed files with 2642 additions and 104 deletions

View File

@@ -1,5 +1,4 @@
import type { AdminAccountDetail } from '@gruperly/shared'
import { PLAN_LIMITS } from '@gruperly/shared'
import { Link } from '@tanstack/react-router'
import { ArrowLeft, Loader2 } from 'lucide-react'
import type { ReactNode } from 'react'
@@ -60,7 +59,7 @@ export function AdminAccountDetailView() {
function AccountDetail({ account }: { account: AdminAccountDetail }) {
const subscription = account.subscription
const limits = PLAN_LIMITS[account.plan ?? 'FREE']
const limits = account.limits
const { t } = useTranslation(['admin', 'common', 'billing'])
return (

View File

@@ -4,6 +4,9 @@ import { ArrowLeft } from 'lucide-react'
import { ThemeToggle } from '../../components/layout/ThemeToggle'
import { useTranslation } from 'react-i18next'
const navLinkClass = 'rounded-xl px-2.5 py-1.5 font-medium text-foreground/60 transition-colors hover:bg-primary-soft hover:text-primary'
const activeNavLinkClass = 'bg-primary-soft text-primary'
/* Layout propio del backoffice: sin la navegación del profesor y pensado para
escritorio, aunque en móvil se lee igual (columna única). */
export function AdminLayout({ children }: { children: ReactNode }) {
@@ -12,9 +15,25 @@ export function AdminLayout({ children }: { children: ReactNode }) {
<div className="min-h-dvh bg-background">
<header className="sticky top-0 z-30 border-b border-border bg-surface/90 backdrop-blur">
<div className="mx-auto flex h-14 max-w-6xl items-center justify-between gap-3 px-4 lg:px-8">
<Link to="/admin" className="text-base font-bold text-primary">
Gruperly <span className="font-medium text-foreground/50">· {t('brand')}</span>
</Link>
<div className="flex min-w-0 items-center gap-4">
<Link to="/admin" className="shrink-0 text-base font-bold text-primary">
Gruperly <span className="hidden font-medium text-foreground/50 sm:inline">· {t('brand')}</span>
</Link>
<nav className="flex items-center gap-1 text-sm">
{/* exact: /admin no queda activo dentro de /admin/plans */}
<Link
to="/admin"
activeOptions={{ exact: true }}
className={navLinkClass}
activeProps={{ className: activeNavLinkClass }}
>
{t('accounts')}
</Link>
<Link to="/admin/plans" className={navLinkClass} activeProps={{ className: activeNavLinkClass }}>
{t('plans.title')}
</Link>
</nav>
</div>
<div className="flex items-center gap-2">
<ThemeToggle />
<Link

View File

@@ -0,0 +1,95 @@
import type { AdminPlansDto, CountryCode, Plan, UpdatePlanLimitsInput, UpdatePlanPriceInput } from '@gruperly/shared'
import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query'
import type { ReactNode } from 'react'
import { createContext, useContext } from 'react'
import { useToast } from '../../components/ui'
import { getAdminPlans, updatePlanLimits, updatePlanPrice } from '../../lib/api'
import { errorMessage as apiErrorMessage } from '../../i18n'
import { i18n } from '../../i18n/instance'
const adminPlansQueryKey = ['admin', 'plans'] as const
type AdminPlansContextValue = {
plans: AdminPlansDto | null
isPending: boolean
isError: boolean
errorMessage: string | null
retry: () => void
saveLimits: (plan: Plan, input: UpdatePlanLimitsInput) => Promise<boolean>
isSavingLimits: boolean
savePrice: (country: CountryCode, input: UpdatePlanPriceInput) => Promise<boolean>
isSavingPrice: boolean
}
const AdminPlansContext = createContext<AdminPlansContextValue | null>(null)
export function AdminPlansProvider({ children }: { children: ReactNode }) {
const queryClient = useQueryClient()
const toast = useToast()
const plansQuery = useQuery({ queryKey: adminPlansQueryKey, queryFn: getAdminPlans })
// Lo que ve el profe (catálogo y su estado) también cambia.
const refresh = () => {
void queryClient.invalidateQueries({ queryKey: adminPlansQueryKey })
void queryClient.invalidateQueries({ queryKey: ['billing'] })
void queryClient.invalidateQueries({ queryKey: ['admin', 'accounts'] })
}
const limitsMutation = useMutation({
mutationFn: ({ plan, input }: { plan: Plan; input: UpdatePlanLimitsInput }) => updatePlanLimits(plan, input),
onSuccess: () => {
toast.success(i18n.t('admin:plans.limits.saved'))
refresh()
},
onError: (error) => toast.error(apiErrorMessage(error, i18n.t('admin:plans.saveError'))),
})
const priceMutation = useMutation({
mutationFn: ({ country, input }: { country: CountryCode; input: UpdatePlanPriceInput }) =>
updatePlanPrice(country, input),
onSuccess: (result) => {
toast.success(
result.queued > 0
? i18n.t('admin:plans.prices.savedQueued', { count: result.queued })
: i18n.t('admin:plans.prices.saved'),
)
refresh()
},
onError: (error) => toast.error(apiErrorMessage(error, i18n.t('admin:plans.saveError'))),
})
const run = async (mutation: () => Promise<unknown>) => {
try {
await mutation()
return true
} catch {
return false
}
}
return (
<AdminPlansContext.Provider
value={{
plans: plansQuery.data ?? null,
isPending: plansQuery.isPending,
isError: plansQuery.isError,
errorMessage: plansQuery.isError
? apiErrorMessage(plansQuery.error, i18n.t('admin:plans.loadError'))
: null,
retry: () => void plansQuery.refetch(),
saveLimits: (plan, input) => run(() => limitsMutation.mutateAsync({ plan, input })),
isSavingLimits: limitsMutation.isPending,
savePrice: (country, input) => run(() => priceMutation.mutateAsync({ country, input })),
isSavingPrice: priceMutation.isPending,
}}
>
{children}
</AdminPlansContext.Provider>
)
}
export function useAdminPlans(): AdminPlansContextValue {
const context = useContext(AdminPlansContext)
if (!context) throw new Error('useAdminPlans must be used inside AdminPlansProvider')
return context
}

View File

@@ -0,0 +1,61 @@
import { Loader2 } from 'lucide-react'
import { Button } from '../../components/ui'
import { useAdminPlans } from './AdminPlansProvider'
import { PlanLimitsCard } from './PlanLimitsCard'
import { PlanPriceRow } from './PlanPriceRow'
import { useTranslation } from 'react-i18next'
export function AdminPlansView() {
const { plans, isPending, isError, errorMessage, retry } = useAdminPlans()
const { t } = useTranslation(['admin', 'common'])
return (
<section>
<h1 className="text-2xl font-bold text-primary">{t('plans.title')}</h1>
<p className="mt-1 text-sm text-foreground/60">{t('plans.subtitle')}</p>
{isPending ? (
<div className="mt-8 flex items-center justify-center py-16" role="status">
<Loader2 className="size-6 animate-spin text-secondary/50" aria-hidden="true" />
<span className="sr-only">{t('plans.loading')}</span>
</div>
) : null}
{isError ? (
<div className="mt-8 space-y-3 rounded-xl bg-danger-soft px-4 py-3 text-sm text-danger">
<p>{errorMessage}</p>
<Button variant="outline" size="sm" onClick={retry}>
{t('common:actions.retry')}
</Button>
</div>
) : null}
{plans ? (
<div className="mt-6 space-y-8">
<div>
<h2 className="text-sm font-semibold uppercase tracking-wide text-foreground/50">
{t('plans.limits.title')}
</h2>
<p className="mt-1 text-xs text-foreground/50">{t('plans.limits.hint')}</p>
<div className="mt-3 grid gap-4 sm:grid-cols-2">
<PlanLimitsCard plan="FREE" limits={plans.limits.FREE} />
<PlanLimitsCard plan="PRO" limits={plans.limits.PRO} />
</div>
</div>
<div>
<h2 className="text-sm font-semibold uppercase tracking-wide text-foreground/50">
{t('plans.prices.title')}
</h2>
<p className="mt-1 text-xs text-foreground/50">{t('plans.prices.hint')}</p>
<ul className="mt-3 divide-y divide-border rounded-xl border border-border bg-surface">
{plans.prices.map((price) => (
<PlanPriceRow key={price.country} price={price} />
))}
</ul>
</div>
</div>
) : null}
</section>
)
}

View File

@@ -0,0 +1,52 @@
import { Input, Switch } from '../../components/ui'
import { useTranslation } from 'react-i18next'
type LimitInputProps = {
id: string
label: string
/** `null` es sin límite. */
value: number | null
onChange: (value: number | null) => void
autoFocus?: boolean
}
/* Un límite numérico con su interruptor de "Sin límite". Al apagar el
interruptor se vuelve al último número escrito. */
export function LimitInput({ id, label, value, onChange, autoFocus }: LimitInputProps) {
const { t } = useTranslation('admin')
const unlimited = value === null
return (
<div>
<label htmlFor={id} className="mb-1.5 block text-sm font-medium text-primary">
{label}
</label>
<div className="flex items-center gap-3">
<Input
id={id}
type="number"
inputMode="numeric"
min={0}
step={1}
autoFocus={autoFocus}
disabled={unlimited}
value={unlimited ? '' : value}
placeholder={unlimited ? t('plans.limits.unlimited') : undefined}
onChange={(event) => {
const parsed = Number.parseInt(event.target.value, 10)
onChange(Number.isNaN(parsed) ? 0 : Math.max(0, parsed))
}}
className="max-w-32"
/>
<span className="flex items-center gap-2 text-sm text-foreground/70">
<Switch
checked={unlimited}
onCheckedChange={(checked) => onChange(checked ? null : 0)}
aria-label={t('plans.limits.unlimitedFor', { label })}
/>
{t('plans.limits.unlimited')}
</span>
</div>
</div>
)
}

View File

@@ -0,0 +1,131 @@
import type { Plan, PlanLimits } from '@gruperly/shared'
import { useQuery } from '@tanstack/react-query'
import { AlertTriangle, Loader2, Pencil } from 'lucide-react'
import { useEffect, useState } from 'react'
import { Button, Switch } from '../../components/ui'
import { getPlanLimitsImpact } from '../../lib/api'
import { PLAN_NAMES, planFeatureList } from '../billing'
import { useAdminPlans } from './AdminPlansProvider'
import { LimitInput } from './LimitInput'
import { useTranslation } from 'react-i18next'
const IMPACT_DEBOUNCE_MS = 400
/* Límites de un plan: se ven como la lista de beneficios y se editan en el
lugar. Rigen al instante, así que antes de guardar se muestra cuántas
cuentas quedarían en solo lectura. */
export function PlanLimitsCard({ plan, limits }: { plan: Plan; limits: PlanLimits }) {
const { t } = useTranslation(['admin', 'billing'])
const { saveLimits, isSavingLimits } = useAdminPlans()
const [draft, setDraft] = useState<PlanLimits | null>(null)
return (
<div className="rounded-xl border border-border bg-surface p-4">
<div className="flex items-center justify-between gap-3">
<h3 className="text-base font-semibold text-primary">{PLAN_NAMES[plan]}</h3>
{draft ? null : (
<Button variant="outline" size="sm" onClick={() => setDraft(limits)}>
<Pencil className="size-3.5" aria-hidden="true" />
{t('plans.edit')}
</Button>
)}
</div>
{draft ? (
<form
className="mt-4 space-y-4"
onSubmit={async (event) => {
event.preventDefault()
if (await saveLimits(plan, draft)) setDraft(null)
}}
>
<LimitInput
id={`${plan}-max-groups`}
label={t('plans.limits.maxGroups')}
value={draft.maxGroups}
onChange={(maxGroups) => setDraft({ ...draft, maxGroups })}
autoFocus
/>
<LimitInput
id={`${plan}-max-attendees`}
label={t('plans.limits.maxAttendees')}
value={draft.maxAttendees}
onChange={(maxAttendees) => setDraft({ ...draft, maxAttendees })}
/>
<FeatureSwitch
label={t('plans.limits.mpCharges')}
checked={draft.mpCharges}
onChange={(mpCharges) => setDraft({ ...draft, mpCharges })}
/>
<FeatureSwitch
label={t('plans.limits.whatsappAutomations')}
checked={draft.whatsappAutomations}
onChange={(whatsappAutomations) => setDraft({ ...draft, whatsappAutomations })}
/>
<LimitsImpact plan={plan} draft={draft} current={limits} />
<div className="flex justify-end gap-2">
<Button variant="ghost" onClick={() => setDraft(null)} disabled={isSavingLimits}>
{t('plans.cancel')}
</Button>
<Button variant="primary" type="submit" disabled={isSavingLimits}>
{isSavingLimits ? <Loader2 className="size-4 animate-spin" aria-hidden="true" /> : null}
{t('plans.save')}
</Button>
</div>
</form>
) : (
<ul className="mt-3 space-y-1.5 text-sm">
{planFeatureList(limits).map((feature) => (
<li key={feature.label} className={feature.included ? 'text-primary' : 'text-foreground/40 line-through'}>
{feature.label}
</li>
))}
</ul>
)}
</div>
)
}
function FeatureSwitch({ label, checked, onChange }: { label: string; checked: boolean; onChange: (value: boolean) => void }) {
return (
<div className="flex items-center justify-between gap-3 text-sm text-primary">
<span>{label}</span>
<Switch checked={checked} onCheckedChange={onChange} aria-label={label} />
</div>
)
}
function LimitsImpact({ plan, draft, current }: { plan: Plan; draft: PlanLimits; current: PlanLimits }) {
const { t } = useTranslation('admin')
const [debounced, setDebounced] = useState({ maxGroups: draft.maxGroups, maxAttendees: draft.maxAttendees })
useEffect(() => {
const timeout = setTimeout(
() => setDebounced({ maxGroups: draft.maxGroups, maxAttendees: draft.maxAttendees }),
IMPACT_DEBOUNCE_MS,
)
return () => clearTimeout(timeout)
}, [draft.maxGroups, draft.maxAttendees])
// Solo importa si algún límite baja respecto del actual.
const tighter =
(debounced.maxGroups !== null && (current.maxGroups === null || debounced.maxGroups < current.maxGroups))
|| (debounced.maxAttendees !== null && (current.maxAttendees === null || debounced.maxAttendees < current.maxAttendees))
const impactQuery = useQuery({
queryKey: ['admin', 'plans', 'impact', plan, debounced],
queryFn: () => getPlanLimitsImpact(plan, debounced),
enabled: tighter,
})
if (!tighter || !impactQuery.data || impactQuery.data.affectedAccounts === 0) return null
return (
<p className="flex items-start gap-2 rounded-xl bg-warning-soft px-3 py-2 text-xs text-warning">
<AlertTriangle className="mt-0.5 size-3.5 shrink-0" aria-hidden="true" />
{t('plans.limits.impact', { count: impactQuery.data.affectedAccounts })}
</p>
)
}

View File

@@ -0,0 +1,118 @@
import type { AdminPlanPrice } from '@gruperly/shared'
import { Loader2, Pencil } from 'lucide-react'
import { useState } from 'react'
import { Badge, Button, Input, Switch } from '../../components/ui'
import { formatPrice } from '../../lib/format'
import { BILLING_PROVIDER_NAMES, formatBillingDate } from '../billing'
import { useAdminPlans } from './AdminPlansProvider'
import { countryLabel } from './copy'
import { useTranslation } from 'react-i18next'
/* Precio de Pro en un país. Al editarlo se puede pasar también a las
suscripciones vivas: el proveedor lo cobra desde el próximo débito y al
profe le llega un mail. */
export function PlanPriceRow({ price }: { price: AdminPlanPrice }) {
const { t } = useTranslation(['admin', 'billing'])
const { savePrice, isSavingPrice } = useAdminPlans()
const [amount, setAmount] = useState<string | null>(null)
const [applyToExisting, setApplyToExisting] = useState(true)
const parsed = Number(amount?.replace(',', '.'))
const valid = amount !== null && Number.isFinite(parsed) && parsed > 0
const updatedAt = formatBillingDate(price.updatedAt)
return (
<li className="px-4 py-3">
<div className="flex flex-wrap items-center justify-between gap-3">
<div className="min-w-0">
<p className="text-sm font-medium text-primary">
{countryLabel(price.country)}{' '}
<span className="font-normal text-foreground/50">· {BILLING_PROVIDER_NAMES[price.provider]}</span>
</p>
<p className="mt-0.5 text-xs text-foreground/50">
{t('plans.prices.live', { count: price.liveSubscriptions })}
{price.atOtherPrice > 0 ? ` · ${t('plans.prices.atOtherPrice', { count: price.atOtherPrice })}` : ''}
{updatedAt ? ` · ${t('plans.prices.updatedAt', { date: updatedAt })}` : ''}
</p>
{price.pendingChanges > 0 || price.failedChanges > 0 ? (
<div className="mt-1 flex flex-wrap gap-1.5">
{price.pendingChanges > 0 ? (
<Badge variant="info">{t('plans.prices.pending', { count: price.pendingChanges })}</Badge>
) : null}
{price.failedChanges > 0 ? (
<Badge variant="danger">{t('plans.prices.failed', { count: price.failedChanges })}</Badge>
) : null}
</div>
) : null}
</div>
<div className="flex items-center gap-3">
<span className="text-sm font-semibold text-primary">
{t('detail.perMonth', { price: formatPrice(price.amount, price.currency) })}
</span>
{amount === null ? (
<Button
variant="outline"
size="sm"
onClick={() => {
setAmount(String(price.amount))
setApplyToExisting(true)
}}
aria-label={t('plans.prices.editFor', { country: countryLabel(price.country) })}
>
<Pencil className="size-3.5" aria-hidden="true" />
{t('plans.edit')}
</Button>
) : null}
</div>
</div>
{amount !== null ? (
<form
className="mt-3 space-y-3 rounded-xl bg-background p-3"
onSubmit={async (event) => {
event.preventDefault()
if (!valid) return
if (await savePrice(price.country, { amount: parsed, applyToExisting })) setAmount(null)
}}
>
<label className="block">
<span className="mb-1.5 block text-sm font-medium text-primary">
{t('plans.prices.amount', { currency: price.currency })}
</span>
<Input
type="text"
inputMode="decimal"
autoFocus
value={amount}
invalid={amount !== '' && !valid}
onChange={(event) => setAmount(event.target.value)}
className="max-w-40"
/>
</label>
<div className="flex items-start justify-between gap-3">
<div className="text-sm">
<p className="text-primary">{t('plans.prices.applyToExisting')}</p>
<p className="mt-0.5 text-xs text-foreground/50">
{t('plans.prices.applyHint', { count: price.liveSubscriptions })}
</p>
</div>
<Switch
checked={applyToExisting}
onCheckedChange={setApplyToExisting}
aria-label={t('plans.prices.applyToExisting')}
/>
</div>
<div className="flex justify-end gap-2">
<Button variant="ghost" onClick={() => setAmount(null)} disabled={isSavingPrice}>
{t('plans.cancel')}
</Button>
<Button variant="primary" type="submit" disabled={!valid || isSavingPrice}>
{isSavingPrice ? <Loader2 className="size-4 animate-spin" aria-hidden="true" /> : null}
{t('plans.save')}
</Button>
</div>
</form>
) : null}
</li>
)
}

View File

@@ -1,4 +1,3 @@
import { PLAN_LIMITS } from '@gruperly/shared'
import { Link } from '@tanstack/react-router'
import { ChevronLeft, Sparkles } from 'lucide-react'
import { useState } from 'react'
@@ -10,6 +9,7 @@ import { ChargesList } from './ChargesList'
import { PlanOptionCard } from './PlanOptionCard'
import { PlanSummaryCard } from './PlanSummaryCard'
import { SubscribeModal } from './SubscribeModal'
import { usePlanCatalog } from './usePlanCatalog'
import { useTranslation } from 'react-i18next'
export function BillingView() {
@@ -17,6 +17,7 @@ export function BillingView() {
const [isConfirmingCancel, setIsConfirmingCancel] = useState(false)
const { t } = useTranslation(['billing', 'common'])
const status = statusQuery.data
const { catalog } = usePlanCatalog()
const subscribed = status?.status === 'AUTHORIZED' || status?.status === 'PAUSED'
const pending = status?.status === 'PENDING'
@@ -42,10 +43,10 @@ export function BillingView() {
{status ? (
<div className="grid gap-4 sm:grid-cols-2">
<PlanOptionCard plan="FREE" limits={PLAN_LIMITS.FREE} current={status.plan === 'FREE'} />
<PlanOptionCard plan="FREE" limits={catalog.limits.FREE} current={status.plan === 'FREE'} />
<PlanOptionCard
plan="PRO"
limits={PLAN_LIMITS.PRO}
limits={catalog.limits.PRO}
price={proPrice}
current={status.plan === 'PRO'}
highlighted={status.plan === 'FREE'}

View File

@@ -43,7 +43,12 @@ export function PlanSummaryCard() {
</div>
{status.status === 'AUTHORIZED' && nextPayment ? (
<p className="mt-0.5 text-xs text-foreground/50">
{t('summary.next', { amount: formatPrice(status.priceAmount, status.currency), date: nextPayment })}
{t('summary.next', { amount: formatPrice(status.nextPriceAmount ?? status.priceAmount, status.currency), date: nextPayment })}
</p>
) : null}
{status.nextPriceAmount !== null && status.status !== 'CANCELLED' ? (
<p className="mt-1 rounded-lg bg-warning-soft px-2 py-1 text-xs text-warning">
{t('summary.nextPrice', { amount: formatPrice(status.nextPriceAmount, status.currency) })}
</p>
) : null}
{status.status === 'PENDING' ? (

View File

@@ -18,4 +18,5 @@ export { PlanSettingsCard } from './PlanSettingsCard'
export { PlanUpgradePrompt } from './PlanUpgradePrompt'
export { SubscribeForm } from './SubscribeForm'
export { billingStatusQueryKey, useBillingStatus } from './useBillingStatus'
export { planCatalogQueryKey, usePlanCatalog } from './usePlanCatalog'
export { useSubscriptionReturnPolling } from './useSubscriptionReturnPolling'

View File

@@ -0,0 +1,23 @@
import { PLAN_LIMITS, PRO_PRICE_BY_COUNTRY, type CountryCode, type PlanCatalogDto, COUNTRY_CURRENCY } from '@gruperly/shared'
import { useQuery } from '@tanstack/react-query'
import { getPlanCatalog } from '../../lib/api'
export const planCatalogQueryKey = ['billing', 'plans'] as const
/* Límites y precios los edita el backoffice. Mientras llega la respuesta (o si
falla) se muestran los valores por defecto de shared, que son los mismos con
los que se sembró la base. */
const FALLBACK: PlanCatalogDto = {
limits: PLAN_LIMITS,
proPrices: Object.fromEntries(
(Object.keys(PRO_PRICE_BY_COUNTRY) as CountryCode[]).map((country) => [
country,
{ amount: PRO_PRICE_BY_COUNTRY[country], currency: COUNTRY_CURRENCY[country] },
]),
) as PlanCatalogDto['proPrices'],
}
export function usePlanCatalog() {
const query = useQuery({ queryKey: planCatalogQueryKey, queryFn: getPlanCatalog, staleTime: 60_000 })
return { ...query, catalog: query.data ?? FALLBACK }
}

View File

@@ -1,5 +1,5 @@
import type { SelectPlanInput } from '@gruperly/shared'
import { billingProviderForCountry, COUNTRY_CURRENCY, PLAN_LIMITS, PRO_PRICE_BY_COUNTRY } from '@gruperly/shared'
import { billingProviderForCountry, COUNTRY_CURRENCY, PRO_PRICE_BY_COUNTRY } from '@gruperly/shared'
import { useMutation, useQueryClient } from '@tanstack/react-query'
import { ArrowLeft, ArrowRight, CheckCircle2, Clock, Loader2, Sparkles } from 'lucide-react'
import { type ReactNode, useEffect, useState } from 'react'
@@ -12,6 +12,7 @@ import {
PlanOptionCard,
SubscribeForm,
useBillingStatus,
usePlanCatalog,
useSubscriptionReturnPolling,
} from '../billing'
import { useOnboarding } from './OnboardingProvider'
@@ -37,6 +38,7 @@ export function PlanStep() {
const [proUnavailable, setProUnavailable] = useState(false)
const polling = useSubscriptionReturnPolling()
const { catalog } = usePlanCatalog()
const choseProBefore = selectedPlan === 'PRO' && statusQuery.data?.subscriptionStatus != null
const billingQuery = useBillingStatus({
enabled: returnedFromSubscription || choseProBefore,
@@ -93,8 +95,12 @@ export function PlanStep() {
}
}
const countryPrice = catalog.proPrices[country] ?? {
amount: PRO_PRICE_BY_COUNTRY[country],
currency: COUNTRY_CURRENCY[country],
}
const proPrice = t('billing:view.perMonth', {
price: formatPrice(PRO_PRICE_BY_COUNTRY[country], COUNTRY_CURRENCY[country]),
price: formatPrice(countryPrice.amount, countryPrice.currency),
})
if (subscriptionStatus === 'AUTHORIZED') {
@@ -161,7 +167,7 @@ export function PlanStep() {
return (
<StepShell>
<div className="grid gap-3">
<PlanOptionCard plan="FREE" limits={PLAN_LIMITS.FREE}>
<PlanOptionCard plan="FREE" limits={catalog.limits.FREE}>
<Button variant="outline" size="lg" className="w-full" disabled={isLeavingToMp} onClick={chooseFree}>
{mutation.isPending && mutation.variables?.plan === 'FREE' ? (
<Loader2 className="size-4 animate-spin" />
@@ -170,7 +176,7 @@ export function PlanStep() {
</Button>
</PlanOptionCard>
<PlanOptionCard plan="PRO" limits={PLAN_LIMITS.PRO} price={proPrice} highlighted>
<PlanOptionCard plan="PRO" limits={catalog.limits.PRO} price={proPrice} highlighted>
{proUnavailable ? (
<p className="text-xs text-foreground/50">{t('billing:view.unavailable')}</p>
) : isEnteringEmail ? (