feat(billing): planes Free/Pro con Suscripciones de Mercado Pago

- Módulo billing: suscripción Pro mensual vía /preapproval con credenciales
  de plataforma por país, webhook firmado y reconciliación por polling.
- PlanGuard en los use-cases que crean grupos/alumnos, cobran con MP o
  activan automatizaciones (402 plan_limit_reached / plan_feature_required /
  plan_read_only), detrás de BILLING_ENFORCEMENT.
- Onboarding: paso Plan obligatorio (POST /onboarding/plan); con Free se
  saltean Cobros y WhatsApp.
- Web: pantalla /billing, aviso de Pro desde el MutationCache.
- Migración billing_subscriptions y docs/billing.md.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Jose Selesan
2026-10-23 15:49:27 -03:00
parent f4d2c26e29
commit f5e77c99f6
93 changed files with 4402 additions and 117 deletions

View File

@@ -0,0 +1,99 @@
import type { BillingChargeList, BillingStatusDto } from '@gruperly/shared'
import type { UseQueryResult } from '@tanstack/react-query'
import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query'
import { useNavigate, useSearch } from '@tanstack/react-router'
import type { ReactNode } from 'react'
import { createContext, useContext, useEffect, useRef, useState } from 'react'
import { useToast } from '../../components/ui'
import { ApiError, cancelSubscription, getBillingCharges } from '../../lib/api'
import { billingStatusQueryKey, useBillingStatus } from './useBillingStatus'
import { useSubscriptionReturnPolling } from './useSubscriptionReturnPolling'
type BillingContextValue = {
statusQuery: UseQueryResult<BillingStatusDto>
chargesQuery: UseQueryResult<BillingChargeList>
chargesPage: number
setChargesPage: (page: number) => void
isSubscribeOpen: boolean
openSubscribe: () => void
closeSubscribe: () => void
cancel: () => void
isCancelling: boolean
}
const BillingContext = createContext<BillingContextValue | null>(null)
export function BillingProvider({ children }: { children: ReactNode }) {
const search = useSearch({ from: '/_authenticated/billing' })
const navigate = useNavigate()
const queryClient = useQueryClient()
const toast = useToast()
const [isSubscribeOpen, setIsSubscribeOpen] = useState(false)
const [chargesPage, setChargesPage] = useState(1)
const polling = useSubscriptionReturnPolling()
const statusQuery = useBillingStatus({ refetchInterval: polling.refetchInterval })
const chargesQuery = useQuery({
queryKey: ['billing', 'charges', chargesPage],
queryFn: () => getBillingCharges(chargesPage),
})
// Vuelta de Mercado Pago (`?sub=return`): se reconsulta hasta que la
// suscripción deje de estar PENDING y se limpia la URL para que recargar no
// repita el aviso.
useEffect(() => {
if (search.sub !== 'return') return
polling.startPolling()
void queryClient.invalidateQueries({ queryKey: billingStatusQueryKey })
void navigate({ to: '/billing', search: {}, replace: true })
}, [search.sub, navigate, queryClient, polling.startPolling])
// Avisar una sola vez cuando la suscripción queda activa tras volver.
const announced = useRef(false)
useEffect(() => {
if (!polling.isPolling || announced.current) return
if (statusQuery.data?.status === 'AUTHORIZED') {
announced.current = true
toast.success('¡Listo! Ya tenés Gruperly Pro.')
void queryClient.invalidateQueries({ queryKey: ['billing', 'charges'] })
}
// `toast` cambia en cada aviso: el efecto depende solo del estado.
}, [polling.isPolling, statusQuery.data?.status, queryClient])
const cancelMutation = useMutation({
mutationFn: cancelSubscription,
onSuccess: () => {
toast.success('Cancelaste tu suscripción. Seguís con Pro hasta el fin del período pago.')
void queryClient.invalidateQueries({ queryKey: billingStatusQueryKey })
},
onError: (error: Error) => {
toast.error(error instanceof ApiError ? error.message : 'No pudimos cancelar la suscripción.')
},
})
return (
<BillingContext.Provider
value={{
statusQuery,
chargesQuery,
chargesPage,
setChargesPage,
isSubscribeOpen,
openSubscribe: () => setIsSubscribeOpen(true),
closeSubscribe: () => setIsSubscribeOpen(false),
cancel: () => cancelMutation.mutate(),
isCancelling: cancelMutation.isPending,
}}
>
{children}
</BillingContext.Provider>
)
}
export function useBilling() {
const context = useContext(BillingContext)
if (!context) {
throw new Error('useBilling debe usarse dentro de <BillingProvider>')
}
return context
}

View File

@@ -0,0 +1,80 @@
import { PLAN_LIMITS } from '@gruperly/shared'
import { Link } from '@tanstack/react-router'
import { ChevronLeft, Sparkles } from 'lucide-react'
import { useState } from 'react'
import { Button } from '../../components/ui'
import { formatPrice } from '../../lib/format'
import { useBilling } from './BillingProvider'
import { CancelSubscriptionModal } from './CancelSubscriptionModal'
import { ChargesList } from './ChargesList'
import { PlanOptionCard } from './PlanOptionCard'
import { PlanSummaryCard } from './PlanSummaryCard'
import { SubscribeModal } from './SubscribeModal'
export function BillingView() {
const { statusQuery, openSubscribe, cancel, isCancelling } = useBilling()
const [isConfirmingCancel, setIsConfirmingCancel] = useState(false)
const status = statusQuery.data
const subscribed = status?.status === 'AUTHORIZED' || status?.status === 'PAUSED'
const pending = status?.status === 'PENDING'
const proPrice = status ? `${formatPrice(status.priceAmount, status.currency)} / mes` : undefined
return (
<section className="space-y-6">
<div>
<Link
to="/settings"
className="mb-2 hidden items-center gap-1 text-sm text-foreground/60 hover:text-primary lg:inline-flex"
>
<ChevronLeft className="size-4" />
Ajustes
</Link>
<h1 className="text-2xl font-bold text-primary">Tu plan</h1>
<p className="mt-1 text-sm text-foreground/60">Elegí cómo usar Gruperly.</p>
</div>
<PlanSummaryCard />
{status ? (
<div className="grid gap-4 sm:grid-cols-2">
<PlanOptionCard plan="FREE" limits={PLAN_LIMITS.FREE} current={status.plan === 'FREE'} />
<PlanOptionCard
plan="PRO"
limits={PLAN_LIMITS.PRO}
price={proPrice}
current={status.plan === 'PRO'}
highlighted={status.plan === 'FREE'}
>
{subscribed ? (
<Button variant="outline" className="w-full" onClick={() => setIsConfirmingCancel(true)}>
Cancelar suscripción
</Button>
) : status.availableInCountry ? (
<Button variant="primary" className="w-full" onClick={openSubscribe}>
<Sparkles className="size-4" />
{pending ? 'Reintentar el pago' : 'Pasar a Pro'}
</Button>
) : (
<p className="text-xs text-foreground/50">Todavía no está disponible en tu país.</p>
)}
</PlanOptionCard>
</div>
) : null}
<ChargesList />
<SubscribeModal />
<CancelSubscriptionModal
isOpen={isConfirmingCancel}
isPending={isCancelling}
paidThrough={status?.paidThrough ?? null}
onClose={() => setIsConfirmingCancel(false)}
onConfirm={() => {
setIsConfirmingCancel(false)
cancel()
}}
/>
</section>
)
}

View File

@@ -0,0 +1,45 @@
import { Loader2 } from 'lucide-react'
import { Button, Modal } from '../../components/ui'
import { formatBillingDate } from './copy'
type CancelSubscriptionModalProps = {
isOpen: boolean
isPending: boolean
paidThrough: string | null
onClose: () => void
onConfirm: () => void
}
/** Cancelar se confirma: deja de debitarse, pero el período pago se mantiene. */
export function CancelSubscriptionModal({
isOpen,
isPending,
paidThrough,
onClose,
onConfirm,
}: CancelSubscriptionModalProps) {
const until = formatBillingDate(paidThrough)
return (
<Modal
isOpen={isOpen}
onClose={onClose}
title="Cancelar Pro"
description={
until
? `No te vamos a cobrar más. Seguís con Pro hasta el ${until}; después tu cuenta pasa a Free.`
: 'No te vamos a cobrar más y tu cuenta pasa a Free.'
}
maxWidth="sm"
>
<div className="flex justify-end gap-3">
<Button variant="outline" onClick={onClose}>
Volver
</Button>
<Button variant="primary" disabled={isPending} onClick={onConfirm}>
{isPending ? <Loader2 className="size-4 animate-spin" /> : null}
Cancelar suscripción
</Button>
</div>
</Modal>
)
}

View File

@@ -0,0 +1,63 @@
import { Button } from '../../components/ui'
import { formatPrice } from '../../lib/format'
import { useBilling } from './BillingProvider'
import { formatBillingDate } from './copy'
const CHARGE_STATUS_LABELS: Record<string, string> = {
approved: 'Pagado',
rejected: 'Rechazado',
pending: 'Pendiente',
in_process: 'En proceso',
cancelled: 'Cancelado',
refunded: 'Devuelto',
}
/** Historial de cobros de la suscripción a Pro. */
export function ChargesList() {
const { chargesQuery, chargesPage, setChargesPage } = useBilling()
const charges = chargesQuery.data?.data ?? []
const totalPages = chargesQuery.data?.pagination.totalPages ?? 0
if (charges.length === 0) return null
return (
<section className="space-y-2">
<h2 className="text-sm font-semibold text-primary">Historial de pagos</h2>
<ul className="divide-y divide-border rounded-xl border border-border bg-surface">
{charges.map((charge) => (
<li key={charge.id} className="flex items-center justify-between gap-3 px-4 py-3">
<div className="min-w-0">
<p className="text-sm text-primary">{formatPrice(charge.amount, charge.currency)}</p>
<p className="text-xs text-foreground/50">
{formatBillingDate(charge.paidAt ?? charge.createdAt)}
</p>
</div>
<span className="text-xs text-foreground/60">
{CHARGE_STATUS_LABELS[charge.status] ?? charge.status}
</span>
</li>
))}
</ul>
{totalPages > 1 ? (
<div className="flex justify-end gap-2">
<Button
variant="ghost"
size="sm"
disabled={chargesPage <= 1}
onClick={() => setChargesPage(chargesPage - 1)}
>
Anteriores
</Button>
<Button
variant="ghost"
size="sm"
disabled={chargesPage >= totalPages}
onClick={() => setChargesPage(chargesPage + 1)}
>
Siguientes
</Button>
</div>
) : null}
</section>
)
}

View File

@@ -0,0 +1,43 @@
import { Link, useLocation } from '@tanstack/react-router'
import { TriangleAlert } from 'lucide-react'
import { useAuth } from '../../context/AuthProvider'
import { cn } from '../../lib/utils'
import { planNoticeMessage } from './copy'
import { useBillingStatus } from './useBillingStatus'
/**
* Aviso global del plan: cuenta en solo lectura o Pro en período de gracia.
* Como `MpReauthNotice`, va dentro de <main> y solo con sesión iniciada. En la
* pantalla del plan no se muestra porque ahí está la acción, con más contexto.
*/
export function PlanNotice() {
const { user } = useAuth()
const statusQuery = useBillingStatus({ enabled: !!user })
const pathname = useLocation({ select: (location) => location.pathname })
if (!user || pathname === '/billing' || !statusQuery.data) return null
const notice = planNoticeMessage(statusQuery.data)
if (!notice) return null
const danger = notice.tone === 'danger'
return (
<div
className={cn(
'mb-4 flex items-start gap-3 rounded-xl border px-4 py-3',
danger ? 'border-danger/30 bg-danger-soft' : 'border-warning/30 bg-warning-soft',
)}
>
<TriangleAlert className={cn('mt-0.5 size-4 shrink-0', danger ? 'text-danger' : 'text-warning')} />
<p className={cn('min-w-0 flex-1 text-xs', danger ? 'text-danger' : 'text-warning')}>{notice.text}</p>
<Link
to="/billing"
className={cn(
'shrink-0 self-center text-sm font-medium underline',
danger ? 'text-danger' : 'text-warning',
)}
>
Ver plan
</Link>
</div>
)
}

View File

@@ -0,0 +1,50 @@
import type { Plan, PlanLimits } from '@gruperly/shared'
import { Check } from 'lucide-react'
import type { ReactNode } from 'react'
import { Badge } from '../../components/ui'
import { cn } from '../../lib/utils'
import { PLAN_NAMES, planFeatureList } from './copy'
type PlanOptionCardProps = {
plan: Plan
limits: PlanLimits
/** Precio ya formateado ("$15.000 / mes"); Free no lleva. */
price?: string
current?: boolean
highlighted?: boolean
/** La acción de la tarjeta (elegir, suscribirse); queda abajo de todo. */
children?: ReactNode
}
/** Una tarjeta de plan, igual en la pantalla del plan y en el onboarding. */
export function PlanOptionCard({ plan, limits, price, current, highlighted, children }: PlanOptionCardProps) {
return (
<div
className={cn(
'flex flex-col rounded-xl border bg-surface p-4',
highlighted ? 'border-accent ring-2 ring-accent/20' : 'border-border',
)}
>
<div className="flex items-center justify-between gap-3">
<p className="text-base font-semibold text-primary">{PLAN_NAMES[plan]}</p>
{current ? <Badge variant="info">Tu plan</Badge> : null}
</div>
<p className="mt-1 text-sm text-foreground/60">{price ?? 'Gratis'}</p>
<ul className="mt-3 flex-1 space-y-1.5">
{planFeatureList(limits).map((feature) => (
<li key={feature.label} className="flex items-start gap-2 text-sm">
<Check
className={cn('mt-0.5 size-4 shrink-0', feature.included ? 'text-success' : 'text-foreground/20')}
/>
<span className={feature.included ? 'text-primary' : 'text-foreground/40 line-through'}>
{feature.label}
</span>
</li>
))}
</ul>
{children ? <div className="mt-4">{children}</div> : null}
</div>
)
}

View File

@@ -0,0 +1,31 @@
import { Link } from '@tanstack/react-router'
import { ChevronRight, Sparkles } from 'lucide-react'
import { Badge } from '../../components/ui'
import { PLAN_NAMES, planBadgeVariant } from './copy'
import { useBillingStatus } from './useBillingStatus'
/** Entrada a la pantalla del plan desde Ajustes. */
export function PlanSettingsCard() {
const statusQuery = useBillingStatus()
const status = statusQuery.data
return (
<div className="divide-y divide-border rounded-xl border border-border bg-surface">
<Link to="/billing" className="flex items-center gap-3 px-4 py-3 hover:bg-primary-soft">
<span className="rounded-lg bg-accent-soft p-2">
<Sparkles className="size-4 text-accent-fg" />
</span>
<div className="min-w-0 flex-1">
<p className="text-sm font-medium text-primary">Plan</p>
<p className="text-xs text-foreground/50">Tu plan de Gruperly y tus pagos</p>
</div>
{status ? (
<Badge variant={planBadgeVariant(status)}>
{status.readOnly ? 'Solo lectura' : PLAN_NAMES[status.plan]}
</Badge>
) : null}
<ChevronRight className="size-4 text-foreground/40" />
</Link>
</div>
)
}

View File

@@ -0,0 +1,89 @@
import { Loader2 } from 'lucide-react'
import { Badge } from '../../components/ui'
import { formatPrice } from '../../lib/format'
import { useBilling } from './BillingProvider'
import {
formatBillingDate,
formatUsage,
PLAN_NAMES,
planBadgeVariant,
planNoticeMessage,
subscriptionStatusLabel,
} from './copy'
/** El plan actual: estado de la suscripción, próximo cobro y uso contra los límites. */
export function PlanSummaryCard() {
const { statusQuery } = useBilling()
const status = statusQuery.data
if (!status) {
return (
<div className="flex items-center gap-3 rounded-xl border border-border bg-surface px-4 py-3">
<Loader2 className="size-4 animate-spin text-foreground/40" />
<p className="text-sm text-foreground/50">Consultando tu plan…</p>
</div>
)
}
const notice = planNoticeMessage(status)
const nextPayment = formatBillingDate(status.nextPaymentDate)
const paidThrough = formatBillingDate(status.paidThrough)
return (
<div className="divide-y divide-border rounded-xl border border-border bg-surface">
<div className="px-4 py-3">
<div className="flex items-center justify-between gap-3">
<p className="text-sm font-medium text-primary">Plan {PLAN_NAMES[status.plan]}</p>
<Badge variant={planBadgeVariant(status)}>
{status.readOnly ? 'Solo lectura' : subscriptionStatusLabel(status.status)}
</Badge>
</div>
{status.status === 'AUTHORIZED' && nextPayment ? (
<p className="mt-0.5 text-xs text-foreground/50">
Próximo cobro: {formatPrice(status.priceAmount, status.currency)} el {nextPayment}
</p>
) : null}
{status.status === 'PENDING' ? (
<p className="mt-0.5 text-xs text-foreground/50">
Estamos esperando que Mercado Pago confirme tu suscripción.
</p>
) : null}
{status.status === 'CANCELLED' && status.plan === 'PRO' && paidThrough ? (
<p className="mt-0.5 text-xs text-foreground/50">Pagado hasta el {paidThrough}.</p>
) : null}
{!status.enforced ? (
<p className="mt-0.5 text-xs text-foreground/50">
Por ahora todas las funciones están habilitadas para todas las cuentas.
</p>
) : null}
</div>
{notice ? (
<p
className={
notice.tone === 'danger'
? 'bg-danger-soft px-4 py-3 text-xs text-danger'
: 'bg-warning-soft px-4 py-3 text-xs text-warning'
}
>
{notice.text}
</p>
) : null}
<dl className="grid grid-cols-2 gap-3 px-4 py-3">
<div>
<dt className="text-xs text-foreground/50">Grupos</dt>
<dd className="text-sm font-medium text-primary">
{formatUsage(status.usage.groups, status.limits.maxGroups)}
</dd>
</div>
<div>
<dt className="text-xs text-foreground/50">Alumnos activos</dt>
<dd className="text-sm font-medium text-primary">
{formatUsage(status.usage.attendees, status.limits.maxAttendees)}
</dd>
</div>
</dl>
</div>
)
}

View File

@@ -0,0 +1,40 @@
import { useNavigate } from '@tanstack/react-router'
import { Sparkles } from 'lucide-react'
import { Button, Modal } from '../../components/ui'
import { dismissPlanPrompt, usePlanPrompt } from './plan-prompt'
/**
* Aviso de "esto es de Pro". Lo dispara cualquier 402 de plan (ver el
* MutationCache de main.tsx) o un botón que ya sabe que el plan no alcanza.
* El motivo es el `detail` del backend, que ya explica qué límite se alcanzó.
*/
export function PlanUpgradePrompt() {
const detail = usePlanPrompt()
const navigate = useNavigate()
return (
<Modal
isOpen={detail !== null}
onClose={dismissPlanPrompt}
title="Disponible en Pro"
description={detail ?? undefined}
maxWidth="sm"
>
<div className="flex justify-end gap-3">
<Button variant="outline" onClick={dismissPlanPrompt}>
Ahora no
</Button>
<Button
variant="primary"
onClick={() => {
dismissPlanPrompt()
void navigate({ to: '/billing' })
}}
>
<Sparkles className="size-4" />
Ver planes
</Button>
</div>
</Modal>
)
}

View File

@@ -0,0 +1,67 @@
import { Loader2 } from 'lucide-react'
import { type FormEvent, useState } from 'react'
import { Button, Input, Label } from '../../components/ui'
type SubscribeFormProps = {
defaultEmail: string
isPending: boolean
error: string | null
submitLabel?: string
onSubmit: (payerEmail: string) => void
onCancel?: () => void
}
/**
* El email de la cuenta de Mercado Pago que paga. Mercado Pago exige que el
* profesor inicie sesión con ese mismo email, por eso se pide en vez de asumir
* el de Gruperly (que viene precargado).
*/
export function SubscribeForm({
defaultEmail,
isPending,
error,
submitLabel = 'Ir a Mercado Pago',
onSubmit,
onCancel,
}: SubscribeFormProps) {
const [email, setEmail] = useState(defaultEmail)
const handleSubmit = (event: FormEvent) => {
event.preventDefault()
onSubmit(email.trim())
}
return (
<form className="space-y-4" onSubmit={handleSubmit}>
<div className="space-y-1.5">
<Label htmlFor="payer-email">Email de tu cuenta de Mercado Pago</Label>
<Input
id="payer-email"
type="email"
required
autoFocus
autoComplete="email"
value={email}
onChange={(event) => setEmail(event.target.value)}
/>
<p className="text-xs text-foreground/50">
Tenés que entrar a Mercado Pago con este mismo email para autorizar el débito mensual.
</p>
</div>
{error ? <p className="rounded-xl bg-danger-soft px-4 py-3 text-sm text-danger">{error}</p> : null}
<div className="flex justify-end gap-3">
{onCancel ? (
<Button type="button" variant="outline" onClick={onCancel}>
Cancelar
</Button>
) : null}
<Button type="submit" variant="primary" disabled={isPending || !email.trim()}>
{isPending ? <Loader2 className="size-4 animate-spin" /> : null}
{isPending ? 'Abriendo…' : submitLabel}
</Button>
</div>
</form>
)
}

View File

@@ -0,0 +1,32 @@
import { Modal } from '../../components/ui'
import { useAuth } from '../../context/AuthProvider'
import { useBilling } from './BillingProvider'
import { SubscribeForm } from './SubscribeForm'
import { useStartSubscription } from './useStartSubscription'
export function SubscribeModal() {
const { user } = useAuth()
const { isSubscribeOpen, closeSubscribe, statusQuery } = useBilling()
const subscription = useStartSubscription()
return (
<Modal
isOpen={isSubscribeOpen}
onClose={closeSubscribe}
title="Pasate a Pro"
description="Te llevamos a Mercado Pago para autorizar el débito mensual. Podés cancelarlo cuando quieras."
maxWidth="sm"
>
{/* Se monta solo con el modal abierto, así el autoFocus del email funciona cada vez. */}
{isSubscribeOpen ? (
<SubscribeForm
defaultEmail={statusQuery.data?.payerEmail ?? user?.email ?? ''}
isPending={subscription.isStarting}
error={subscription.error}
onSubmit={(email) => void subscription.start(email, 'billing')}
onCancel={closeSubscribe}
/>
) : null}
</Modal>
)
}

View File

@@ -0,0 +1,120 @@
import type { BillingStatusDto, Plan, PlanFeature, PlanLimits, SubscriptionStatus } from '@gruperly/shared'
import type { BadgeVariant } from '../../components/ui'
/* Copy del plan de Gruperly en un solo lugar: Ajustes, la pantalla del plan, el
paso del onboarding y los avisos tienen que decir lo mismo. Funciones puras,
cubiertas con tests sin renderizar. */
export const PLAN_NAMES: Record<Plan, string> = { FREE: 'Free', PRO: 'Pro' }
export const SUBSCRIBE_ERROR_MESSAGE =
'No pudimos abrir Mercado Pago. Revisá tu conexión e intentá de nuevo.'
/** Lo que incluye cada plan, como lista para las tarjetas de comparación. */
export function planFeatureList(limits: PlanLimits): { label: string; included: boolean }[] {
return [
{
label:
limits.maxGroups === null
? 'Grupos ilimitados'
: `${limits.maxGroups} ${limits.maxGroups === 1 ? 'grupo' : 'grupos'}`,
included: true,
},
{
label:
limits.maxAttendees === null
? 'Alumnos ilimitados'
: `Hasta ${limits.maxAttendees} alumnos activos`,
included: true,
},
{ label: 'Cobros con Mercado Pago', included: limits.mpCharges },
{ label: 'Mensajes automáticos por WhatsApp', included: limits.whatsappAutomations },
]
}
export const PLAN_FEATURE_REQUIRED_MESSAGES: Record<PlanFeature, string> = {
mpCharges: 'Cobrar con Mercado Pago está disponible en el plan Pro.',
whatsappAutomations: 'Los mensajes automáticos de WhatsApp están disponibles en el plan Pro.',
}
/**
* Si el plan del profesor incluye la función. Sin datos todavía, o con los
* límites apagados en el servidor, se deja pasar: el backend decide igual.
*/
export function hasPlanFeature(status: BillingStatusDto | undefined, feature: PlanFeature): boolean {
return !status || !status.enforced || status.limits[feature]
}
export function subscriptionStatusLabel(status: SubscriptionStatus | null): string {
switch (status) {
case 'AUTHORIZED':
return 'Activa'
case 'PENDING':
return 'Pendiente de pago'
case 'PAUSED':
return 'Pausada'
case 'CANCELLED':
return 'Cancelada'
default:
return 'Sin suscripción'
}
}
export function planBadgeVariant(status: BillingStatusDto): BadgeVariant {
if (status.readOnly) return 'danger'
if (status.graceUntil) return 'warning'
return status.plan === 'PRO' ? 'success' : 'neutral'
}
export function formatBillingDate(iso: string | null): string | null {
if (!iso) return null
const date = new Date(iso)
if (Number.isNaN(date.getTime())) return null
return new Intl.DateTimeFormat('es', { day: 'numeric', month: 'short', year: 'numeric' }).format(
date,
)
}
/** "3 de 15": el uso contra el límite, o solo el uso cuando no hay límite. */
export function formatUsage(used: number, limit: number | null): string {
return limit === null ? `${used}` : `${used} de ${limit}`
}
const PLAN_PROBLEM_CODES = ['plan_limit_reached', 'plan_feature_required', 'plan_read_only']
type PlanProblemError = { status: number; problem: { code?: string; detail?: string } | null }
/**
* Un 402 del backend porque el plan no alcanza: se ofrece pasar a Pro. Mira la
* forma de `ApiError` en vez de importarlo, así el copy no arrastra el cliente.
*/
export function isPlanProblem(error: unknown): error is PlanProblemError {
if (typeof error !== 'object' || error === null) return false
const candidate = error as Partial<PlanProblemError>
return candidate.status === 402 && PLAN_PROBLEM_CODES.includes(candidate.problem?.code ?? '')
}
/**
* Qué decir arriba de la app cuando el plan limita. `null` si no hay nada que
* avisar. El período de gracia se avisa aunque la cuenta siga funcionando: si
* no paga, en unos días puede quedar en solo lectura.
*/
export function planNoticeMessage(status: BillingStatusDto): { tone: 'danger' | 'warning'; text: string } | null {
if (status.readOnly) {
return {
tone: 'danger',
text: 'Tu cuenta está en solo lectura: superás los límites del plan Free. Pasate a Pro o reducí tus alumnos para volver a editar.',
}
}
const graceUntil = formatBillingDate(status.graceUntil)
if (graceUntil) {
return {
tone: 'warning',
text:
status.status === 'CANCELLED'
? `Cancelaste Pro: lo seguís teniendo hasta el ${graceUntil}.`
: `No pudimos cobrar tu suscripción a Pro. Revisá tu medio de pago en Mercado Pago antes del ${graceUntil}.`,
}
}
return null
}

View File

@@ -0,0 +1,18 @@
export {
formatBillingDate,
hasPlanFeature,
isPlanProblem,
PLAN_FEATURE_REQUIRED_MESSAGES,
PLAN_NAMES,
planFeatureList,
planNoticeMessage,
subscriptionStatusLabel,
} from './copy'
export { dismissPlanPrompt, showPlanPrompt, usePlanPrompt } from './plan-prompt'
export { PlanNotice } from './PlanNotice'
export { PlanOptionCard } from './PlanOptionCard'
export { PlanSettingsCard } from './PlanSettingsCard'
export { PlanUpgradePrompt } from './PlanUpgradePrompt'
export { SubscribeForm } from './SubscribeForm'
export { billingStatusQueryKey, useBillingStatus } from './useBillingStatus'
export { useSubscriptionReturnPolling } from './useSubscriptionReturnPolling'

View File

@@ -0,0 +1,34 @@
import { useSyncExternalStore } from 'react'
/* El aviso de "pasate a Pro" se dispara desde cualquier mutación (el
MutationCache de main.tsx) y se muestra en un solo lugar (RootLayout). Este
store mínimo los conecta sin un provider más en el árbol. */
let current: string | null = null
const listeners = new Set<() => void>()
function emit() {
for (const listener of listeners) listener()
}
/** Muestra el aviso con el motivo que mandó el backend (o uno propio). */
export function showPlanPrompt(detail: string) {
current = detail
emit()
}
export function dismissPlanPrompt() {
current = null
emit()
}
export function usePlanPrompt(): string | null {
return useSyncExternalStore(
(listener) => {
listeners.add(listener)
return () => listeners.delete(listener)
},
() => current,
() => null,
)
}

View File

@@ -0,0 +1,22 @@
import type { BillingStatusDto } from '@gruperly/shared'
import { useQuery } from '@tanstack/react-query'
import { getBillingStatus } from '../../lib/api'
/** La misma clave en toda la app: Ajustes, /billing, el onboarding y los avisos. */
export const billingStatusQueryKey = ['billing', 'status'] as const
type UseBillingStatusOptions = {
/** `RootLayout` se renderiza sin sesión, así que la consulta se puede apagar. */
enabled?: boolean
/** Al volver de Mercado Pago: cada cuánto reconsultar, según el último estado. */
refetchInterval?: (data: BillingStatusDto | undefined) => number | false
}
export function useBillingStatus({ enabled = true, refetchInterval }: UseBillingStatusOptions = {}) {
return useQuery({
queryKey: billingStatusQueryKey,
queryFn: getBillingStatus,
enabled,
refetchInterval: refetchInterval ? (query) => refetchInterval(query.state.data) : false,
})
}

View File

@@ -0,0 +1,28 @@
import type { BillingReturnTo } from '@gruperly/shared'
import { useState } from 'react'
import { ApiError, subscribeToPro } from '../../lib/api'
import { SUBSCRIBE_ERROR_MESSAGE } from './copy'
/**
* Empieza la suscripción a Pro. Como la vinculación de Mercado Pago, no se
* resuelve con `fetch`: el navegador navega a Mercado Pago para que el profesor
* autorice el débito, y Mercado Pago lo devuelve con `?sub=return`.
*/
export function useStartSubscription() {
const [error, setError] = useState<string | null>(null)
const [isStarting, setIsStarting] = useState(false)
const start = async (payerEmail: string, returnTo: BillingReturnTo = 'billing') => {
setError(null)
setIsStarting(true)
try {
const { checkoutUrl } = await subscribeToPro({ payerEmail, returnTo })
window.location.assign(checkoutUrl)
} catch (caught) {
setError(caught instanceof ApiError && caught.problem?.detail ? caught.problem.detail : SUBSCRIBE_ERROR_MESSAGE)
setIsStarting(false)
}
}
return { start, isStarting, error }
}

View File

@@ -0,0 +1,24 @@
import type { BillingStatusDto } from '@gruperly/shared'
import { useCallback, useState } from 'react'
const POLL_EVERY_MS = 5_000
const POLL_FOR_MS = 60_000
/**
* Al volver de Mercado Pago la suscripción suele seguir PENDING unos segundos:
* el webhook todavía no llegó (en local, nunca llega). El backend la reconsulta
* a Mercado Pago en cada status, así que alcanza con reconsultar un rato.
*/
export function useSubscriptionReturnPolling() {
const [pollUntil, setPollUntil] = useState<number | null>(null)
const startPolling = useCallback(() => setPollUntil(Date.now() + POLL_FOR_MS), [])
const refetchInterval = useCallback(
(data: BillingStatusDto | undefined) =>
pollUntil !== null && Date.now() < pollUntil && data?.status === 'PENDING' ? POLL_EVERY_MS : false,
[pollUntil],
)
return { isPolling: pollUntil !== null, startPolling, refetchInterval }
}

View File

@@ -1,7 +1,8 @@
import type { GroupAutomationsDto } from '@gruperly/shared'
import { Link } from '@tanstack/react-router'
import { MessageCircle } from 'lucide-react'
import { Switch } from '../../../components/ui'
import { Badge, Switch } from '../../../components/ui'
import { hasPlanFeature, useBillingStatus } from '../../billing'
import { automationBlockedReason, useWhatsappStatus, WEEKLY_SEND_LABEL } from '../../whatsapp'
import { useGroupDetail } from './GroupDetailProvider'
@@ -35,7 +36,9 @@ const AUTOMATIONS: readonly Automation[] = [
export function GroupAutomationsCard() {
const { group, updateAutomations, isUpdatingAutomations, isGroupOwner } = useGroupDetail()
const whatsappQuery = useWhatsappStatus({ enabled: isGroupOwner })
const billingQuery = useBillingStatus({ enabled: isGroupOwner })
if (!group || !isGroupOwner) return null
const includedInPlan = hasPlanFeature(billingQuery.data, 'whatsappAutomations')
return (
<section className="rounded-xl border border-border bg-surface">
@@ -44,8 +47,22 @@ export function GroupAutomationsCard() {
<MessageCircle className="size-4 text-success" />
</span>
<div className="min-w-0 flex-1">
<h2 className="text-sm font-semibold text-primary">Mensajes automáticos por WhatsApp</h2>
<p className="text-xs text-foreground/50">{WEEKLY_SEND_LABEL}</p>
<div className="flex items-center gap-2">
<h2 className="text-sm font-semibold text-primary">Mensajes automáticos por WhatsApp</h2>
{includedInPlan ? null : <Badge variant="info">Pro</Badge>}
</div>
<p className="text-xs text-foreground/50">
{WEEKLY_SEND_LABEL}
{includedInPlan ? null : (
<>
{' '}
Disponible en el plan Pro.{' '}
<Link to="/billing" className="font-medium text-accent-fg underline">
Ver planes
</Link>
</>
)}
</p>
</div>
</header>
@@ -75,7 +92,9 @@ export function GroupAutomationsCard() {
</div>
<Switch
checked={checked}
disabled={isUpdatingAutomations || (!checked && blocked !== null)}
disabled={
isUpdatingAutomations || (!checked && (blocked !== null || !includedInPlan))
}
aria-label={automation.title}
aria-describedby={hintId}
onCheckedChange={(next) => updateAutomations({ [automation.key]: next })}

View File

@@ -2,6 +2,12 @@ import { useNavigate } from '@tanstack/react-router'
import { Loader2 } from 'lucide-react'
import { useState } from 'react'
import { Button } from '../../../components/ui'
import {
hasPlanFeature,
PLAN_FEATURE_REQUIRED_MESSAGES,
showPlanPrompt,
useBillingStatus,
} from '../../billing'
import { ChargeMembersModal } from './ChargeMembersModal'
import { GroupAutomationsCard } from './GroupAutomationsCard'
import { GroupHeader } from './GroupHeader'
@@ -23,16 +29,27 @@ export function GroupDetailView() {
firstWaitlistEntry,
waitlistTotal,
isSubmittingRemoval,
isGroupOwner,
} = useGroupDetail()
const navigate = useNavigate()
const [isChargeModalOpen, setIsChargeModalOpen] = useState(false)
// El plan que cuenta es el del dueño: para un ADMIN no sabemos el suyo y
// decide el backend (un 402 abre el mismo aviso).
const billingQuery = useBillingStatus({ enabled: isGroupOwner })
const handleCharge = () => {
if (isGroupOwner && !hasPlanFeature(billingQuery.data, 'mpCharges')) {
showPlanPrompt(PLAN_FEATURE_REQUIRED_MESSAGES.mpCharges)
return
}
setIsChargeModalOpen(true)
}
return (
<section className="animate-fade-in space-y-5 sm:space-y-6">
{/* The large title always renders, even while loading: it is what gives
the immersive bar its height and stops the layout from jumping when
the data arrives. */}
<GroupHeader onCharge={() => setIsChargeModalOpen(true)} />
<GroupHeader onCharge={handleCharge} />
{groupQueryPending ? (
<div className="flex items-center justify-center py-20">

View File

@@ -1,12 +1,14 @@
import type { OnboardingGroupDto } from '@gruperly/shared'
import { useQueryClient } from '@tanstack/react-query'
import { useNavigate } from '@tanstack/react-router'
import { ArrowRight, CheckCircle2, CreditCard, MessageCircle } from 'lucide-react'
import { ArrowRight, CheckCircle2, CreditCard, MessageCircle, Sparkles } from 'lucide-react'
import { Badge, Button } from '../../components/ui'
import { useAuth } from '../../context/AuthProvider'
import { PLAN_NAMES } from '../billing'
import { MP_PROVIDER_NAME, useMpStatus } from '../mp'
import { useWhatsappStatus } from '../whatsapp'
import { BILLING_LABELS, formatPrice, formatSchedule } from './constants'
import { useOnboarding } from './OnboardingProvider'
type ConfirmationStepProps = {
group: OnboardingGroupDto
@@ -20,6 +22,7 @@ export function ConfirmationStep({ group }: ConfirmationStepProps) {
const isMpConnected = statusQuery.data?.status === 'active'
const whatsappQuery = useWhatsappStatus()
const isWhatsappConnected = whatsappQuery.data?.status === 'active'
const { selectedPlan } = useOnboarding()
const goToDashboard = () => {
// Revalidates the cache (onboarding state, session, groups) before redirecting.
@@ -70,41 +73,58 @@ export function ConfirmationStep({ group }: ConfirmationStepProps) {
</dl>
</div>
<div className="flex items-center gap-2 rounded-xl bg-primary-soft px-4 py-3">
<CreditCard className="size-4 shrink-0 text-accent" />
<p className="text-xs text-primary">
{isMpConnected ? (
<>
Vas a cobrar con <span className="font-semibold">{MP_PROVIDER_NAME}</span>. Los
pagos entran directo en tu cuenta.
</>
) : (
<>
Cuando quieras cobrar, vinculá <span className="font-semibold">
{MP_PROVIDER_NAME}
</span>{' '}
desde Ajustes. Tu grupo ya quedó creado.
</>
)}
</p>
</div>
{selectedPlan ? (
<div className="flex items-center gap-2 rounded-xl bg-primary-soft px-4 py-3">
<Sparkles className="size-4 shrink-0 text-accent" />
<p className="text-xs text-primary">
Estás en el plan <span className="font-semibold">{PLAN_NAMES[selectedPlan]}</span>.
{selectedPlan === 'FREE'
? ' Cuando quieras cobrar con Mercado Pago o automatizar WhatsApp, pasate a Pro desde Ajustes.'
: ''}
</p>
</div>
) : null}
<div className="flex items-center gap-2 rounded-xl bg-primary-soft px-4 py-3">
<MessageCircle className="size-4 shrink-0 text-accent" />
<p className="text-xs text-primary">
{isWhatsappConnected ? (
<>
Tu WhatsApp está vinculado. Activá los recordatorios de pago y el reenganche desde la
ficha del grupo.
</>
) : (
<>
Para enviar recordatorios automáticos, vinculá{' '}
<span className="font-semibold">WhatsApp</span> desde Ajustes.
</>
)}
</p>
</div>
{/* Con Free no se cobra ni se automatiza: esos avisos son solo de Pro. */}
{selectedPlan === 'FREE' ? null : (
<>
<div className="flex items-center gap-2 rounded-xl bg-primary-soft px-4 py-3">
<CreditCard className="size-4 shrink-0 text-accent" />
<p className="text-xs text-primary">
{isMpConnected ? (
<>
Vas a cobrar con <span className="font-semibold">{MP_PROVIDER_NAME}</span>. Los
pagos entran directo en tu cuenta.
</>
) : (
<>
Cuando quieras cobrar, vinculá <span className="font-semibold">
{MP_PROVIDER_NAME}
</span>{' '}
desde Ajustes. Tu grupo ya quedó creado.
</>
)}
</p>
</div>
<div className="flex items-center gap-2 rounded-xl bg-primary-soft px-4 py-3">
<MessageCircle className="size-4 shrink-0 text-accent" />
<p className="text-xs text-primary">
{isWhatsappConnected ? (
<>
Tu WhatsApp está vinculado. Activá los recordatorios de pago y el reenganche desde la
ficha del grupo.
</>
) : (
<>
Para enviar recordatorios automáticos, vinculá{' '}
<span className="font-semibold">WhatsApp</span> desde Ajustes.
</>
)}
</p>
</div>
</>
)}
<Button variant="primary" className="w-full" onClick={goToDashboard}>
Ir a mi Panel

View File

@@ -1,9 +1,9 @@
import type { CountryCode } from '@gruperly/shared'
import { COUNTRY_CURRENCY, COUNTRY_LABELS, DEFAULT_COUNTRY } from '@gruperly/shared'
import { COUNTRY_CURRENCY, COUNTRY_LABELS } from '@gruperly/shared'
import { ArrowLeft, ArrowRight } from 'lucide-react'
import { useState } from 'react'
import { Button } from '../../components/ui'
import { cn } from '../../lib/utils'
import { useOnboarding } from './OnboardingProvider'
export const COUNTRY_OPTIONS: readonly CountryCode[] = [
'AR',
@@ -24,11 +24,12 @@ type CountryStepProps = {
* Paso "País" del onboarding.
*
* El país del profesor define la moneda con la que se generan los links de
* cobro, así que se pregunta al empezar. Por default Argentina (la moneda por
* default es ARS); se cambia después desde Ajustes.
* cobro y el precio de Pro, así que se pregunta al empezar. Por default
* Argentina (la moneda por default es ARS). Vive en el provider: el paso Plan y
* el del primer grupo lo usan, y se guarda junto con el plan.
*/
export function CountryStep({ onNext, onBack }: CountryStepProps) {
const [country, setCountry] = useState<CountryCode>(DEFAULT_COUNTRY)
const { country, setCountry } = useOnboarding()
return (
<section className="space-y-5">

View File

@@ -1,4 +1,4 @@
import type { CountryCode, OnboardingGroupDto, OnboardingStatusDto } from '@gruperly/shared'
import type { CountryCode, OnboardingGroupDto, OnboardingStatusDto, Plan } from '@gruperly/shared'
import { DEFAULT_COUNTRY } from '@gruperly/shared'
import type { UseQueryResult } from '@tanstack/react-query'
import { useQuery, useQueryClient } from '@tanstack/react-query'
@@ -7,26 +7,31 @@ import type { ReactNode } from 'react'
import { createContext, useContext, useEffect, useMemo, useState } from 'react'
import { useAuth } from '../../context/AuthProvider'
import { getOnboardingStatus } from '../../lib/api'
import { billingStatusQueryKey } from '../billing'
import type { MpCallbackFeedback } from '../mp'
import { mpStatusQueryKey, readMpCallbackFeedback } from '../mp'
import type { WhatsappCallbackFeedback } from '../whatsapp'
import { readWhatsappCallbackFeedback, whatsappStatusQueryKey } from '../whatsapp'
const WELCOME_STEP = 0
const PAYMENT_STEP = 2
const WHATSAPP_STEP = 3
const FIRST_GROUP_STEP = 4
import { type OnboardingStepId, resumeStep, visibleSteps } from './steps'
type OnboardingContextValue = {
step: number
setStep: (step: number) => void
/** El país del profesor; define la moneda de los links de cobro. */
step: OnboardingStepId
steps: OnboardingStepId[]
goTo: (step: OnboardingStepId) => void
goNext: () => void
goBack: () => void
/** El país del profesor; define la moneda de los links de cobro y el precio de Pro. */
country: CountryCode
setCountry: (country: CountryCode) => void
/** El plan elegido en el paso "Plan"; decide qué pasos siguen. */
selectedPlan: Plan | null
setSelectedPlan: (plan: Plan) => void
/** Lo que volvió de Mercado Pago en `?mp=`, ya traducido a feedback. */
mpFeedback: MpCallbackFeedback | null
/** Lo que volvió de una vinculación de WhatsApp por redirect en `?wa=`. */
waFeedback: WhatsappCallbackFeedback | null
/** Volvió de autorizar (o abandonar) la suscripción a Pro (`?sub=return`). */
returnedFromSubscription: boolean
createdGroup: OnboardingGroupDto | null
setCreatedGroup: (group: OnboardingGroupDto) => void
statusQuery: UseQueryResult<OnboardingStatusDto>
@@ -39,10 +44,12 @@ export function OnboardingProvider({ children }: { children: ReactNode }) {
const navigate = useNavigate()
const queryClient = useQueryClient()
const search = useSearch({ from: '/onboarding' })
const [step, setStep] = useState(WELCOME_STEP)
const [step, setStep] = useState<OnboardingStepId>('welcome')
const [country, setCountry] = useState<CountryCode>(DEFAULT_COUNTRY)
const [selectedPlan, setSelectedPlan] = useState<Plan | null>(null)
const [mpFeedback, setMpFeedback] = useState<MpCallbackFeedback | null>(null)
const [waFeedback, setWaFeedback] = useState<WhatsappCallbackFeedback | null>(null)
const [returnedFromSubscription, setReturnedFromSubscription] = useState(false)
const [createdGroup, setCreatedGroup] = useState<OnboardingGroupDto | null>(null)
const statusQuery = useQuery({
@@ -51,6 +58,16 @@ export function OnboardingProvider({ children }: { children: ReactNode }) {
enabled: !!user,
})
const steps = useMemo(() => visibleSteps(selectedPlan), [selectedPlan])
const goNext = () => {
const next = steps[steps.indexOf(step) + 1]
if (next) setStep(next)
}
const goBack = () => {
const previous = steps[steps.indexOf(step) - 1]
if (previous) setStep(previous)
}
const callbackFeedback = useMemo(
() => readMpCallbackFeedback(search.mp, search.reason),
[search.mp, search.reason],
@@ -67,7 +84,7 @@ export function OnboardingProvider({ children }: { children: ReactNode }) {
// Vuelve al paso de Cobros, que es de donde salió el flujo. Setearlo siempre
// (y no solo desde el primer paso) evita que un `?mp=` que llega con el
// proveedor recién montado salte al resumen sin mostrar la confirmación.
setStep(PAYMENT_STEP)
setStep('payment')
// Se limpian los parámetros de la URL: si no, recargar la página volvería a
// mostrar el aviso de la vinculación vieja.
@@ -87,32 +104,51 @@ export function OnboardingProvider({ children }: { children: ReactNode }) {
setWaFeedback(whatsappCallbackFeedback)
void queryClient.invalidateQueries({ queryKey: whatsappStatusQueryKey })
void queryClient.invalidateQueries({ queryKey: ['onboarding', 'status'] })
setStep(WHATSAPP_STEP)
setStep('whatsapp')
void navigate({ to: '/onboarding', search: {}, replace: true })
}, [whatsappCallbackFeedback, navigate, queryClient])
// Vuelta de Mercado Pago tras la suscripción a Pro: el paso Plan muestra si
// quedó activa o se sigue procesando (y deja seguir igual).
useEffect(() => {
if (search.sub !== 'return') return
setReturnedFromSubscription(true)
setSelectedPlan('PRO')
void queryClient.invalidateQueries({ queryKey: billingStatusQueryKey })
void queryClient.invalidateQueries({ queryKey: ['onboarding', 'status'] })
setStep('plan')
void navigate({ to: '/onboarding', search: {}, replace: true })
}, [search.sub, navigate, queryClient])
useEffect(() => {
const status = statusQuery.data
if (!status) return
// Si dejó el onboarding después de vincular los cobros, se retoma en
// WhatsApp (o en el grupo, si también lo vinculó). Con la cuenta ya activa
// el paso de Cobros muestra "Cambiar de cuenta", así que solo se salta
// desde la bienvenida.
if (status.step === 'PAYMENT_CONNECTED') {
const resumeAt = status.whatsappConnected ? FIRST_GROUP_STEP : WHATSAPP_STEP
setStep((current) => (current === WELCOME_STEP ? resumeAt : current))
}
// El estado local se pierde con cada redirect (Mercado Pago, WhatsApp): el
// país y el plan elegidos se recuperan del servidor.
if (status.country) setCountry(status.country)
if (status.selectedPlan) setSelectedPlan((current) => current ?? status.selectedPlan)
// Retomar donde quedó, solo si recién arranca (desde la bienvenida).
const resumeAt = resumeStep(status)
if (resumeAt) setStep((current) => (current === 'welcome' ? resumeAt : current))
}, [statusQuery.data])
return (
<OnboardingContext.Provider
value={{
step,
setStep,
steps,
goTo: setStep,
goNext,
goBack,
country,
setCountry,
selectedPlan,
setSelectedPlan,
mpFeedback,
waFeedback,
returnedFromSubscription,
createdGroup,
setCreatedGroup,
statusQuery,
@@ -129,4 +165,4 @@ export function useOnboarding() {
throw new Error('useOnboarding debe usarse dentro de <OnboardingProvider>')
}
return context
}
}

View File

@@ -9,24 +9,27 @@ import { CountryStep } from './CountryStep'
import { FirstGroupStep } from './FirstGroupStep'
import { useOnboarding } from './OnboardingProvider'
import { PaymentStep } from './PaymentStep'
import { PlanStep } from './PlanStep'
import { STEP_LABELS } from './steps'
import { Stepper } from './Stepper'
import { WelcomeStep } from './WelcomeStep'
import { WhatsappStep } from './WhatsappStep'
const STEPS = [
{ label: 'Bienvenida' },
{ label: 'País' },
{ label: 'Cobros' },
{ label: 'WhatsApp' },
{ label: 'Tu grupo' },
{ label: 'Listo' },
]
export function OnboardingView() {
const { user, isPending: authPending } = useAuth()
const navigate = useNavigate()
const { step, setStep, mpFeedback, waFeedback, createdGroup, setCreatedGroup, statusQuery } =
useOnboarding()
const {
step,
steps,
goTo,
goNext,
goBack,
mpFeedback,
waFeedback,
createdGroup,
setCreatedGroup,
statusQuery,
} = useOnboarding()
useEffect(() => {
if (statusQuery.data?.completed) {
@@ -81,29 +84,33 @@ export function OnboardingView() {
<Logo className="h-6" />
</header>
<Stepper steps={STEPS} current={step} />
{/* Con Free no se muestran Cobros ni WhatsApp: el stepper refleja solo
los pasos que se van a recorrer. */}
<Stepper
steps={steps.map((id) => ({ label: STEP_LABELS[id] }))}
current={steps.indexOf(step)}
/>
<div key={step} className="mt-8 animate-step-enter">
{step === 0 ? <WelcomeStep name={firstName} onNext={() => setStep(1)} /> : null}
{step === 1 ? (
<CountryStep onNext={() => setStep(2)} onBack={() => setStep(0)} />
{step === 'welcome' ? <WelcomeStep name={firstName} onNext={goNext} /> : null}
{step === 'country' ? <CountryStep onNext={goNext} onBack={goBack} /> : null}
{step === 'plan' ? <PlanStep /> : null}
{step === 'payment' ? (
<PaymentStep feedback={mpFeedback} onNext={goNext} onBack={goBack} />
) : null}
{step === 2 ? (
<PaymentStep feedback={mpFeedback} onNext={() => setStep(3)} onBack={() => setStep(1)} />
{step === 'whatsapp' ? (
<WhatsappStep feedback={waFeedback} onNext={goNext} onBack={goBack} />
) : null}
{step === 3 ? (
<WhatsappStep feedback={waFeedback} onNext={() => setStep(4)} onBack={() => setStep(2)} />
) : null}
{step === 4 ? (
{step === 'group' ? (
<FirstGroupStep
onBack={() => setStep(3)}
onBack={goBack}
onCompleted={(group) => {
setCreatedGroup(group)
setStep(5)
goTo('done')
}}
/>
) : null}
{step === 5 && createdGroup ? <ConfirmationStep group={createdGroup} /> : null}
{step === 'done' && createdGroup ? <ConfirmationStep group={createdGroup} /> : null}
</div>
</main>
)

View File

@@ -0,0 +1,199 @@
import type { SelectPlanInput } from '@gruperly/shared'
import { COUNTRY_CURRENCY, PLAN_LIMITS, 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'
import { Button } from '../../components/ui'
import { useAuth } from '../../context/AuthProvider'
import { ApiError, selectPlan } from '../../lib/api'
import { formatPrice } from '../../lib/format'
import {
PlanOptionCard,
SubscribeForm,
useBillingStatus,
useSubscriptionReturnPolling,
} from '../billing'
import { useOnboarding } from './OnboardingProvider'
const SELECT_PLAN_ERROR_MESSAGE = 'No pudimos guardar tu plan. Revisá tu conexión e intentá de nuevo.'
/**
* Paso "Plan" del onboarding (obligatorio). Free sigue directo al primer grupo
* (sin Cobros ni WhatsApp, que son de Pro). Pro lleva a Mercado Pago a
* autorizar el débito y vuelve acá con `?sub=return`; mientras Mercado Pago
* confirma se puede seguir igual.
*/
export function PlanStep() {
const { user } = useAuth()
const queryClient = useQueryClient()
const { country, selectedPlan, setSelectedPlan, returnedFromSubscription, goTo, goBack, statusQuery } =
useOnboarding()
const [isEnteringEmail, setIsEnteringEmail] = useState(false)
const [error, setError] = useState<string | null>(null)
const [proUnavailable, setProUnavailable] = useState(false)
const polling = useSubscriptionReturnPolling()
const choseProBefore = selectedPlan === 'PRO' && statusQuery.data?.subscriptionStatus != null
const billingQuery = useBillingStatus({
enabled: returnedFromSubscription || choseProBefore,
refetchInterval: polling.refetchInterval,
})
useEffect(() => {
if (returnedFromSubscription) polling.startPolling()
}, [returnedFromSubscription, polling.startPolling])
const subscriptionStatus = billingQuery.data?.status ?? statusQuery.data?.subscriptionStatus ?? null
const mutation = useMutation({
mutationFn: (input: SelectPlanInput) => selectPlan(input),
onSuccess: (result) => {
void queryClient.invalidateQueries({ queryKey: ['onboarding', 'status'] })
if (result.checkoutUrl) {
window.location.assign(result.checkoutUrl)
return
}
setSelectedPlan(result.plan)
// `goTo` y no `goNext`: el plan recién elegido cambia la lista de pasos.
goTo(result.plan === 'FREE' ? 'group' : 'payment')
},
onError: (caught: Error) => {
if (caught instanceof ApiError && caught.problem?.code === 'billing_not_available') {
setProUnavailable(true)
setIsEnteringEmail(false)
}
setError(caught instanceof ApiError && caught.problem?.detail ? caught.problem.detail : SELECT_PLAN_ERROR_MESSAGE)
},
})
// Pending de `selectPlan` con Pro incluye el redirect: el botón queda cargando.
const isLeavingToMp = mutation.isPending || (mutation.isSuccess && !!mutation.data?.checkoutUrl)
const chooseFree = () => {
setError(null)
mutation.mutate({ plan: 'FREE', country })
}
const choosePro = (payerEmail: string) => {
setError(null)
mutation.mutate({ plan: 'PRO', country, payerEmail })
}
const proPrice = `${formatPrice(PRO_PRICE_BY_COUNTRY[country], COUNTRY_CURRENCY[country])} / mes`
if (subscriptionStatus === 'AUTHORIZED') {
return (
<StepShell>
<p className="flex items-start gap-2 rounded-xl bg-success-soft px-4 py-3 text-sm text-success">
<CheckCircle2 className="mt-0.5 size-4 shrink-0" />
¡Listo! Tu suscripción a Pro quedó activa.
</p>
<Button variant="primary" className="w-full" onClick={() => goTo('payment')}>
Continuar
<ArrowRight className="size-4" />
</Button>
</StepShell>
)
}
if (subscriptionStatus === 'PENDING' && (returnedFromSubscription || choseProBefore) && !isEnteringEmail) {
const stillChecking = returnedFromSubscription && billingQuery.isFetching
return (
<StepShell>
<div className="flex items-start gap-3 rounded-xl border border-border bg-surface px-4 py-3">
{stillChecking ? (
<Loader2 className="mt-0.5 size-4 shrink-0 animate-spin text-accent" />
) : (
<Clock className="mt-0.5 size-4 shrink-0 text-warning" />
)}
<div className="min-w-0 flex-1">
<p className="text-sm font-medium text-primary">
{returnedFromSubscription ? 'Procesando tu pago…' : 'Tu suscripción a Pro quedó pendiente'}
</p>
<p className="text-xs text-foreground/50">
{returnedFromSubscription
? 'Mercado Pago puede tardar unos minutos en confirmarlo. Podés seguir mientras tanto: te avisamos cuando quede activa.'
: 'No terminaste de autorizar el débito en Mercado Pago. Podés reintentarlo o seguir con Free.'}
</p>
</div>
</div>
{error ? <p className="rounded-xl bg-danger-soft px-4 py-3 text-sm text-danger">{error}</p> : null}
<div className="flex flex-col gap-3 sm:flex-row">
{returnedFromSubscription ? (
<Button variant="primary" className="flex-1" onClick={() => goTo('payment')}>
Continuar
<ArrowRight className="size-4" />
</Button>
) : (
<>
<Button variant="primary" className="flex-1" onClick={() => setIsEnteringEmail(true)}>
<Sparkles className="size-4" />
Reintentar el pago
</Button>
<Button variant="outline" className="flex-1" disabled={mutation.isPending} onClick={chooseFree}>
Seguir con Free
</Button>
</>
)}
</div>
</StepShell>
)
}
return (
<StepShell>
<div className="grid gap-3">
<PlanOptionCard plan="FREE" limits={PLAN_LIMITS.FREE}>
<Button variant="outline" className="w-full" disabled={isLeavingToMp} onClick={chooseFree}>
{mutation.isPending && mutation.variables?.plan === 'FREE' ? (
<Loader2 className="size-4 animate-spin" />
) : null}
Empezar gratis
</Button>
</PlanOptionCard>
<PlanOptionCard plan="PRO" limits={PLAN_LIMITS.PRO} price={proPrice} highlighted>
{proUnavailable ? (
<p className="text-xs text-foreground/50">Todavía no está disponible en tu país.</p>
) : isEnteringEmail ? (
<SubscribeForm
defaultEmail={user?.email ?? ''}
isPending={isLeavingToMp}
error={null}
onSubmit={choosePro}
onCancel={() => setIsEnteringEmail(false)}
/>
) : (
<Button variant="primary" className="w-full" onClick={() => setIsEnteringEmail(true)}>
<Sparkles className="size-4" />
Elegir Pro
</Button>
)}
</PlanOptionCard>
</div>
{error ? <p className="rounded-xl bg-danger-soft px-4 py-3 text-sm text-danger">{error}</p> : null}
<div className="flex items-center gap-3">
<Button variant="outline" onClick={goBack} className="hidden lg:inline-flex">
<ArrowLeft className="size-4" />
Volver
</Button>
</div>
</StepShell>
)
}
/** Encabezado común a los tres estados del paso. */
function StepShell({ children }: { children: ReactNode }) {
return (
<section className="space-y-5">
<header className="space-y-1">
<h2 className="text-2xl font-bold text-primary">Elegí tu plan</h2>
<p className="text-sm text-foreground/60">
Empezá gratis o pasate a Pro para cobrar con Mercado Pago y automatizar WhatsApp.
</p>
</header>
{children}
</section>
)
}

View File

@@ -0,0 +1,55 @@
import type { OnboardingStatusDto, Plan } from '@gruperly/shared'
/* Los pasos del onboarding y cómo se retoma, como funciones puras: el provider
las usa y los tests las cubren sin montar nada. */
export type OnboardingStepId =
| 'welcome'
| 'country'
| 'plan'
| 'payment'
| 'whatsapp'
| 'group'
| 'done'
export const STEP_LABELS: Record<OnboardingStepId, string> = {
welcome: 'Bienvenida',
country: 'País',
plan: 'Plan',
payment: 'Cobros',
whatsapp: 'WhatsApp',
group: 'Tu grupo',
done: 'Listo',
}
const ALL_STEPS: readonly OnboardingStepId[] = [
'welcome',
'country',
'plan',
'payment',
'whatsapp',
'group',
'done',
]
/** Pasos que solo sirven con Pro: con Free no se puede cobrar ni automatizar. */
const PRO_ONLY_STEPS: readonly OnboardingStepId[] = ['payment', 'whatsapp']
/** Los pasos que se recorren con el plan elegido (sin elegir, se muestran todos). */
export function visibleSteps(plan: Plan | null): OnboardingStepId[] {
return plan === 'FREE' ? ALL_STEPS.filter((id) => !PRO_ONLY_STEPS.includes(id)) : [...ALL_STEPS]
}
/**
* Dónde retomar un onboarding interrumpido. Sin plan elegido arranca de cero
* (el país se guarda junto con el plan). Con Free va directo al grupo. Con Pro,
* una suscripción abandonada vuelve a Plan (para reintentar o pasar a Free) y si
* no, se sigue como antes: Cobros, WhatsApp o el grupo según lo ya vinculado.
*/
export function resumeStep(status: OnboardingStatusDto): OnboardingStepId | null {
if (!status.planSelected) return null
if (status.selectedPlan === 'FREE') return 'group'
if (status.subscriptionStatus === 'PENDING') return 'plan'
if (status.step === 'PAYMENT_CONNECTED') return status.whatsappConnected ? 'group' : 'whatsapp'
return 'payment'
}

View File

@@ -2,6 +2,7 @@ import { Link } from '@tanstack/react-router'
import { Fingerprint } from 'lucide-react'
import { Button } from '../../components/ui'
import { signOut } from '../../lib/auth-client'
import { PlanSettingsCard } from '../billing'
import { MpStatusCard } from '../mp'
import { WhatsappStatusCard } from '../whatsapp'
import { AppearanceCard } from './AppearanceCard'
@@ -36,6 +37,8 @@ export function SettingsView() {
</Link>
</div>
<PlanSettingsCard />
<MpStatusCard />
<WhatsappStatusCard />