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 ? (

View File

@@ -86,5 +86,49 @@
"PENDING": "Connecting",
"DISCONNECTED": "Disconnected",
"NONE": "Not connected"
},
"plans": {
"title": "Plans",
"subtitle": "Free and Pro limits, and the Pro price in each country.",
"loading": "Loading plans",
"loadError": "We couldn't load the plans.",
"saveError": "We couldn't save the change.",
"edit": "Edit",
"save": "Save",
"cancel": "Cancel",
"limits": {
"title": "Limits",
"hint": "They apply right away to every account on the plan. An account left above them becomes read only.",
"maxGroups": "Groups",
"maxAttendees": "Active students",
"unlimited": "No limit",
"unlimitedFor": "{{label}} with no limit",
"mpCharges": "Mercado Pago charges",
"whatsappAutomations": "Automatic WhatsApp messages",
"impact_one": "{{count}} account already exceeds these limits and will become read only when you save.",
"impact_other": "{{count}} accounts already exceed these limits and will become read only when you save.",
"saved": "Limits saved."
},
"prices": {
"title": "Pro price",
"hint": "New subscriptions take the price right away. Existing ones keep theirs unless you choose to apply it.",
"live_one": "{{count}} active subscription",
"live_other": "{{count}} active subscriptions",
"atOtherPrice_one": "{{count}} at another price",
"atOtherPrice_other": "{{count}} at another price",
"updatedAt": "changed on {{date}}",
"pending_one": "{{count}} change in progress",
"pending_other": "{{count}} changes in progress",
"failed_one": "{{count}} change failed",
"failed_other": "{{count}} changes failed",
"editFor": "Edit the price for {{country}}",
"amount": "Monthly price ({{currency}})",
"applyToExisting": "Apply to existing subscriptions",
"applyHint_one": "{{count}} subscription moves to the new price from its next charge. We'll email them.",
"applyHint_other": "{{count}} subscriptions move to the new price from their next charge. We'll email them.",
"saved": "Price saved.",
"savedQueued_one": "Price saved. {{count}} subscription moves to the new price from its next charge.",
"savedQueued_other": "Price saved. {{count}} subscriptions move to the new price from their next charge."
}
}
}

View File

@@ -88,6 +88,7 @@
"paidThrough": "Paid through {{date}}.",
"notEnforced": "For now, every feature is enabled for every account.",
"groups": "Groups",
"students": "Active students"
"students": "Active students",
"nextPrice": "New price from your next charge: {{amount}} a month."
}
}

View File

@@ -60,5 +60,8 @@
},
"attendance": {
"empty": "Send at least one attendance record"
},
"billing": {
"priceInvalid": "Enter a price greater than zero"
}
}

View File

@@ -86,5 +86,49 @@
"PENDING": "Conectando",
"DISCONNECTED": "Desconectado",
"NONE": "Sin conectar"
},
"plans": {
"title": "Planes",
"subtitle": "Límites de Free y Pro, y precio de Pro en cada país.",
"loading": "Cargando planes",
"loadError": "No pudimos cargar los planes.",
"saveError": "No pudimos guardar el cambio.",
"edit": "Editar",
"save": "Guardar",
"cancel": "Cancelar",
"limits": {
"title": "Límites",
"hint": "Se aplican al instante a todas las cuentas del plan. Una cuenta que quede por encima pasa a solo lectura.",
"maxGroups": "Grupos",
"maxAttendees": "Alumnos activos",
"unlimited": "Sin límite",
"unlimitedFor": "{{label}} sin límite",
"mpCharges": "Cobros con Mercado Pago",
"whatsappAutomations": "Mensajes automáticos por WhatsApp",
"impact_one": "{{count}} cuenta ya supera estos límites y quedará en solo lectura al guardar.",
"impact_other": "{{count}} cuentas ya superan estos límites y quedarán en solo lectura al guardar.",
"saved": "Límites guardados."
},
"prices": {
"title": "Precio de Pro",
"hint": "Las suscripciones nuevas toman el precio al instante. Las existentes conservan el suyo, salvo que elijas aplicarlo.",
"live_one": "{{count}} suscripción activa",
"live_other": "{{count}} suscripciones activas",
"atOtherPrice_one": "{{count}} con otro precio",
"atOtherPrice_other": "{{count}} con otro precio",
"updatedAt": "cambiado el {{date}}",
"pending_one": "{{count}} cambio en curso",
"pending_other": "{{count}} cambios en curso",
"failed_one": "{{count}} cambio falló",
"failed_other": "{{count}} cambios fallaron",
"editFor": "Editar el precio de {{country}}",
"amount": "Precio mensual ({{currency}})",
"applyToExisting": "Aplicar a las suscripciones existentes",
"applyHint_one": "{{count}} suscripción pasa al precio nuevo desde su próximo cobro. Le avisamos por correo.",
"applyHint_other": "{{count}} suscripciones pasan al precio nuevo desde su próximo cobro. Les avisamos por correo.",
"saved": "Precio guardado.",
"savedQueued_one": "Precio guardado. {{count}} suscripción pasa al precio nuevo desde su próximo cobro.",
"savedQueued_other": "Precio guardado. {{count}} suscripciones pasan al precio nuevo desde su próximo cobro."
}
}
}

View File

@@ -88,6 +88,7 @@
"paidThrough": "Pagado hasta el {{date}}.",
"notEnforced": "Por ahora todas las funciones están habilitadas para todas las cuentas.",
"groups": "Grupos",
"students": "Alumnos activos"
"students": "Alumnos activos",
"nextPrice": "Nuevo precio desde tu próximo cobro: {{amount}} al mes."
}
}

View File

@@ -60,5 +60,8 @@
},
"attendance": {
"empty": "Envía al menos un registro de asistencia"
},
"billing": {
"priceInvalid": "Ingresa un precio mayor a cero"
}
}

View File

@@ -86,5 +86,49 @@
"PENDING": "Conectando",
"DISCONNECTED": "Desconectado",
"NONE": "Sin conectar"
},
"plans": {
"title": "Planes",
"subtitle": "Límites de Free y Pro, y precio de Pro en cada país.",
"loading": "Cargando planes",
"loadError": "No pudimos cargar los planes.",
"saveError": "No pudimos guardar el cambio.",
"edit": "Editar",
"save": "Guardar",
"cancel": "Cancelar",
"limits": {
"title": "Límites",
"hint": "Rigen al instante para todas las cuentas del plan. Una cuenta que quede por encima pasa a solo lectura.",
"maxGroups": "Grupos",
"maxAttendees": "Alumnos activos",
"unlimited": "Sin límite",
"unlimitedFor": "{{label}} sin límite",
"mpCharges": "Cobros con Mercado Pago",
"whatsappAutomations": "Mensajes automáticos por WhatsApp",
"impact_one": "{{count}} cuenta ya supera estos límites y va a quedar en solo lectura al guardar.",
"impact_other": "{{count}} cuentas ya superan estos límites y van a quedar en solo lectura al guardar.",
"saved": "Límites guardados."
},
"prices": {
"title": "Precio de Pro",
"hint": "Las suscripciones nuevas toman el precio al instante. Las existentes conservan el suyo, salvo que elijas aplicarlo.",
"live_one": "{{count}} suscripción activa",
"live_other": "{{count}} suscripciones activas",
"atOtherPrice_one": "{{count}} con otro precio",
"atOtherPrice_other": "{{count}} con otro precio",
"updatedAt": "cambiado el {{date}}",
"pending_one": "{{count}} cambio en curso",
"pending_other": "{{count}} cambios en curso",
"failed_one": "{{count}} cambio falló",
"failed_other": "{{count}} cambios fallaron",
"editFor": "Editar el precio de {{country}}",
"amount": "Precio mensual ({{currency}})",
"applyToExisting": "Aplicar a las suscripciones existentes",
"applyHint_one": "{{count}} suscripción pasa al precio nuevo desde su próximo cobro. Le avisamos por mail.",
"applyHint_other": "{{count}} suscripciones pasan al precio nuevo desde su próximo cobro. Les avisamos por mail.",
"saved": "Precio guardado.",
"savedQueued_one": "Precio guardado. {{count}} suscripción pasa al precio nuevo desde su próximo cobro.",
"savedQueued_other": "Precio guardado. {{count}} suscripciones pasan al precio nuevo desde su próximo cobro."
}
}
}

View File

@@ -88,6 +88,7 @@
"paidThrough": "Pagado hasta el {{date}}.",
"notEnforced": "Por ahora todas las funciones están habilitadas para todas las cuentas.",
"groups": "Grupos",
"students": "Alumnos activos"
"students": "Alumnos activos",
"nextPrice": "Nuevo precio desde tu próximo cobro: {{amount}} por mes."
}
}

View File

@@ -60,5 +60,8 @@
},
"attendance": {
"empty": "Mandá al menos un registro de asistencia"
},
"billing": {
"priceInvalid": "Ingresá un precio mayor a cero"
}
}

View File

@@ -86,5 +86,49 @@
"PENDING": "Conectando",
"DISCONNECTED": "Desconectado",
"NONE": "Não conectado"
},
"plans": {
"title": "Planos",
"subtitle": "Limites do Free e do Pro, e preço do Pro em cada país.",
"loading": "Carregando planos",
"loadError": "Não conseguimos carregar os planos.",
"saveError": "Não conseguimos salvar a alteração.",
"edit": "Editar",
"save": "Salvar",
"cancel": "Cancelar",
"limits": {
"title": "Limites",
"hint": "Valem na hora para todas as contas do plano. Uma conta que ficar acima passa a somente leitura.",
"maxGroups": "Grupos",
"maxAttendees": "Alunos ativos",
"unlimited": "Sem limite",
"unlimitedFor": "{{label}} sem limite",
"mpCharges": "Cobranças com Mercado Pago",
"whatsappAutomations": "Mensagens automáticas por WhatsApp",
"impact_one": "{{count}} conta já passa desses limites e vai ficar em somente leitura ao salvar.",
"impact_other": "{{count}} contas já passam desses limites e vão ficar em somente leitura ao salvar.",
"saved": "Limites salvos."
},
"prices": {
"title": "Preço do Pro",
"hint": "As assinaturas novas usam o preço na hora. As existentes mantêm o delas, a menos que você escolha aplicá-lo.",
"live_one": "{{count}} assinatura ativa",
"live_other": "{{count}} assinaturas ativas",
"atOtherPrice_one": "{{count}} com outro preço",
"atOtherPrice_other": "{{count}} com outro preço",
"updatedAt": "alterado em {{date}}",
"pending_one": "{{count}} alteração em andamento",
"pending_other": "{{count}} alterações em andamento",
"failed_one": "{{count}} alteração falhou",
"failed_other": "{{count}} alterações falharam",
"editFor": "Editar o preço de {{country}}",
"amount": "Preço mensal ({{currency}})",
"applyToExisting": "Aplicar às assinaturas existentes",
"applyHint_one": "{{count}} assinatura passa ao preço novo a partir da próxima cobrança. Avisamos por e-mail.",
"applyHint_other": "{{count}} assinaturas passam ao preço novo a partir da próxima cobrança. Avisamos por e-mail.",
"saved": "Preço salvo.",
"savedQueued_one": "Preço salvo. {{count}} assinatura passa ao preço novo a partir da próxima cobrança.",
"savedQueued_other": "Preço salvo. {{count}} assinaturas passam ao preço novo a partir da próxima cobrança."
}
}
}

View File

@@ -88,6 +88,7 @@
"paidThrough": "Pago até {{date}}.",
"notEnforced": "Por enquanto todos os recursos estão liberados para todas as contas.",
"groups": "Grupos",
"students": "Alunos ativos"
"students": "Alunos ativos",
"nextPrice": "Novo preço a partir da próxima cobrança: {{amount}} por mês."
}
}

View File

@@ -60,5 +60,8 @@
},
"attendance": {
"empty": "Envie pelo menos um registro de presença"
},
"billing": {
"priceInvalid": "Informe um preço maior que zero"
}
}

View File

@@ -1,4 +1,13 @@
import type {
AdminPlansDto,
PlanCatalogDto,
PlanLimits,
PlanLimitsImpactDto,
UpdatePlanLimitsInput,
UpdatePlanPriceInput,
UpdatePlanPriceResultDto,
Plan,
CountryCode,
AbsenceDetails,
AdminAccountDetail,
AdminAccountList,
@@ -189,6 +198,9 @@ export const cancelSubscription = () =>
export const getBillingCharges = (page = 1) =>
apiFetch<BillingChargeList>(`/api/v1/billing/charges?page=${page}&pageSize=10`)
/* Límites de cada plan y precio de Pro por país, tal como los configuró el backoffice. */
export const getPlanCatalog = () => apiFetch<PlanCatalogDto>('/api/v1/billing/plans')
// --- WhatsApp (recordatorios y reenganche automáticos) ---
export const startWhatsappConnection = (returnTo: WhatsappReturnTo) =>
@@ -457,6 +469,27 @@ export const getAdminAccounts = (params: AdminAccountQueryInput) => {
export const getAdminAccount = (accountId: string) =>
apiFetch<AdminAccountDetail>(`/api/v1/admin/accounts/${encodeURIComponent(accountId)}`)
export const getAdminPlans = () => apiFetch<AdminPlansDto>('/api/v1/admin/plans')
export const getPlanLimitsImpact = (plan: Plan, limits: Pick<PlanLimits, 'maxGroups' | 'maxAttendees'>) => {
const query = new URLSearchParams()
if (limits.maxGroups !== null) query.set('maxGroups', String(limits.maxGroups))
if (limits.maxAttendees !== null) query.set('maxAttendees', String(limits.maxAttendees))
return apiFetch<PlanLimitsImpactDto>(`/api/v1/admin/plans/${plan}/impact?${query.toString()}`)
}
export const updatePlanLimits = (plan: Plan, payload: UpdatePlanLimitsInput) =>
apiFetch<PlanLimits>(`/api/v1/admin/plans/${plan}/limits`, {
method: 'PUT',
body: JSON.stringify(payload),
})
export const updatePlanPrice = (country: CountryCode, payload: UpdatePlanPriceInput) =>
apiFetch<UpdatePlanPriceResultDto>(`/api/v1/admin/plans/prices/${country}`, {
method: 'PUT',
body: JSON.stringify(payload),
})
// — App del alumno (sesión propia, nunca la del profe) —
const STUDENT_API = '/api/v1/student-portal'

View File

@@ -26,6 +26,7 @@ import { Route as AuthenticatedSecurityRouteImport } from './routes/_authenticat
import { Route as AuthenticatedSettingsRouteImport } from './routes/_authenticated/settings'
import { Route as AccessIndexRouteImport } from './routes/access.index'
import { Route as AdminIndexRouteImport } from './routes/admin/index'
import { Route as AdminPlansRouteImport } from './routes/admin/plans'
import { Route as ITokenRouteImport } from './routes/i.$token'
import { Route as JoinTokenRouteImport } from './routes/join.$token'
import { Route as ReportAbsenceTokenRouteImport } from './routes/report-absence.$token'
@@ -130,6 +131,11 @@ const AdminIndexRoute = AdminIndexRouteImport.update({
path: '/',
getParentRoute: () => AdminRoute,
} as any)
const AdminPlansRoute = AdminPlansRouteImport.update({
id: '/plans',
path: '/plans',
getParentRoute: () => AdminRoute,
} as any)
const ITokenRoute = ITokenRouteImport.update({
id: '/i/$token',
path: '/i/$token',
@@ -254,6 +260,7 @@ export interface FileRoutesByFullPath {
'/profile': typeof AuthenticatedProfileRoute
'/security': typeof AuthenticatedSecurityRoute
'/settings': typeof AuthenticatedSettingsRoute
'/admin/plans': typeof AdminPlansRoute
'/i/$token': typeof ITokenRoute
'/join/$token': typeof JoinTokenRoute
'/report-absence/$token': typeof ReportAbsenceTokenRoute
@@ -290,6 +297,7 @@ export interface FileRoutesByTo {
'/profile': typeof AuthenticatedProfileRoute
'/security': typeof AuthenticatedSecurityRoute
'/settings': typeof AuthenticatedSettingsRoute
'/admin/plans': typeof AdminPlansRoute
'/i/$token': typeof ITokenRoute
'/join/$token': typeof JoinTokenRoute
'/report-absence/$token': typeof ReportAbsenceTokenRoute
@@ -329,6 +337,7 @@ export interface FileRoutesById {
'/_authenticated/profile': typeof AuthenticatedProfileRoute
'/_authenticated/security': typeof AuthenticatedSecurityRoute
'/_authenticated/settings': typeof AuthenticatedSettingsRoute
'/admin/plans': typeof AdminPlansRoute
'/i/$token': typeof ITokenRoute
'/join/$token': typeof JoinTokenRoute
'/report-absence/$token': typeof ReportAbsenceTokenRoute
@@ -369,6 +378,7 @@ export interface FileRouteTypes {
| '/profile'
| '/security'
| '/settings'
| '/admin/plans'
| '/i/$token'
| '/join/$token'
| '/report-absence/$token'
@@ -405,6 +415,7 @@ export interface FileRouteTypes {
| '/profile'
| '/security'
| '/settings'
| '/admin/plans'
| '/i/$token'
| '/join/$token'
| '/report-absence/$token'
@@ -443,6 +454,7 @@ export interface FileRouteTypes {
| '/_authenticated/profile'
| '/_authenticated/security'
| '/_authenticated/settings'
| '/admin/plans'
| '/i/$token'
| '/join/$token'
| '/report-absence/$token'
@@ -606,6 +618,13 @@ declare module '@tanstack/react-router' {
preLoaderRoute: typeof AdminIndexRouteImport
parentRoute: typeof AdminRoute
}
'/admin/plans': {
id: '/admin/plans'
path: '/plans'
fullPath: '/admin/plans'
preLoaderRoute: typeof AdminPlansRouteImport
parentRoute: typeof AdminRoute
}
'/i/$token': {
id: '/i/$token'
path: '/i/$token'
@@ -815,11 +834,13 @@ const StudentRouteWithChildren =
StudentRoute._addFileChildren(StudentRouteChildren)
interface AdminRouteChildren {
AdminPlansRoute: typeof AdminPlansRoute
AdminIndexRoute: typeof AdminIndexRoute
AdminAccountsAccountIdRoute: typeof AdminAccountsAccountIdRoute
}
const AdminRouteChildren: AdminRouteChildren = {
AdminPlansRoute: AdminPlansRoute,
AdminIndexRoute: AdminIndexRoute,
AdminAccountsAccountIdRoute: AdminAccountsAccountIdRoute,
}

View File

@@ -0,0 +1,11 @@
import { createFileRoute } from '@tanstack/react-router'
import { AdminPlansProvider } from '../../features/admin/AdminPlansProvider'
import { AdminPlansView } from '../../features/admin/AdminPlansView'
export const Route = createFileRoute('/admin/plans')({
component: () => (
<AdminPlansProvider>
<AdminPlansView />
</AdminPlansProvider>
),
})