feat(billing): proveedores intercambiables (Mercado Pago en AR, Stripe en el resto)
- Puerto BillingProvider con adaptadores de Mercado Pago (/preapproval) y Stripe (Checkout en modo suscripción, fetch plano). El país elige proveedor solo para suscripciones nuevas; sync, cancel y webhook usan row.provider. - Migración add_billing_providers (provider, checkout_ref, ids genéricos). - fix: /authorized_payments/search respondía 400 "Invalid value for limit"; se pagina por offset sin limit. - fix: si falla la consulta de cobros, la sync guarda igual el estado de la suscripción (ya no queda PENDING tras autorizar) y reintenta los cobros. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
@@ -5,7 +5,7 @@ import { ArrowLeft, Loader2 } from 'lucide-react'
|
||||
import type { ReactNode } from 'react'
|
||||
import { Badge, Button } from '../../components/ui'
|
||||
import { formatPrice } from '../../lib/format'
|
||||
import { formatBillingDate, formatUsage, subscriptionStatusLabel } from '../billing'
|
||||
import { BILLING_PROVIDER_NAMES, formatBillingDate, formatUsage, subscriptionStatusLabel } from '../billing'
|
||||
import { useAdminAccountDetail } from './AdminAccountDetailProvider'
|
||||
import {
|
||||
countryLabel,
|
||||
@@ -85,6 +85,7 @@ function AccountDetail({ account }: { account: AdminAccountDetail }) {
|
||||
</Field>
|
||||
{subscription ? (
|
||||
<>
|
||||
<Field label="Cobra">{BILLING_PROVIDER_NAMES[subscription.provider]}</Field>
|
||||
<Field label="Precio">{formatPrice(subscription.amount, subscription.currency)} / mes</Field>
|
||||
<Field label="Pagado hasta">{formatBillingDate(subscription.paidThrough) ?? '—'}</Field>
|
||||
<Field label="Próximo cobro">{formatBillingDate(subscription.nextPaymentDate) ?? '—'}</Field>
|
||||
|
||||
@@ -3,6 +3,7 @@ import { Badge } from '../../components/ui'
|
||||
import { formatPrice } from '../../lib/format'
|
||||
import { useBilling } from './BillingProvider'
|
||||
import {
|
||||
BILLING_PROVIDER_NAMES,
|
||||
formatBillingDate,
|
||||
formatUsage,
|
||||
PLAN_NAMES,
|
||||
@@ -45,7 +46,7 @@ export function PlanSummaryCard() {
|
||||
) : null}
|
||||
{status.status === 'PENDING' ? (
|
||||
<p className="mt-0.5 text-xs text-foreground/50">
|
||||
Estamos esperando que Mercado Pago confirme tu suscripción.
|
||||
Estamos esperando que {BILLING_PROVIDER_NAMES[status.provider]} confirme tu suscripción.
|
||||
</p>
|
||||
) : null}
|
||||
{status.status === 'CANCELLED' && status.plan === 'PRO' && paidThrough ? (
|
||||
|
||||
@@ -1,53 +1,62 @@
|
||||
import type { BillingProviderId } from '@gruperly/shared'
|
||||
import { Loader2 } from 'lucide-react'
|
||||
import { type FormEvent, useState } from 'react'
|
||||
import { Button, Input, Label } from '../../components/ui'
|
||||
import { BILLING_PROVIDER_NAMES } from './copy'
|
||||
|
||||
type SubscribeFormProps = {
|
||||
provider: BillingProviderId
|
||||
defaultEmail: string
|
||||
isPending: boolean
|
||||
error: string | null
|
||||
submitLabel?: string
|
||||
onSubmit: (payerEmail: string) => void
|
||||
/** `undefined` cuando el proveedor no necesita el email (Stripe lo pide en su checkout). */
|
||||
onSubmit: (payerEmail: string | undefined) => 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).
|
||||
* Antes de ir a pagar Pro. Con Mercado Pago pide el email de la cuenta que
|
||||
* paga: Mercado Pago exige que el profesor inicie sesión con ese mismo email,
|
||||
* por eso no se asume el de Gruperly (que viene precargado). Con Stripe no hay
|
||||
* nada que completar: el email y la tarjeta se cargan en su checkout.
|
||||
*/
|
||||
export function SubscribeForm({
|
||||
provider,
|
||||
defaultEmail,
|
||||
isPending,
|
||||
error,
|
||||
submitLabel = 'Ir a Mercado Pago',
|
||||
submitLabel = `Ir a ${BILLING_PROVIDER_NAMES[provider]}`,
|
||||
onSubmit,
|
||||
onCancel,
|
||||
}: SubscribeFormProps) {
|
||||
const [email, setEmail] = useState(defaultEmail)
|
||||
const asksEmail = provider === 'MERCADO_PAGO'
|
||||
|
||||
const handleSubmit = (event: FormEvent) => {
|
||||
event.preventDefault()
|
||||
onSubmit(email.trim())
|
||||
onSubmit(asksEmail ? email.trim() : undefined)
|
||||
}
|
||||
|
||||
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>
|
||||
{asksEmail ? (
|
||||
<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>
|
||||
) : null}
|
||||
|
||||
{error ? <p className="rounded-xl bg-danger-soft px-4 py-3 text-sm text-danger">{error}</p> : null}
|
||||
|
||||
@@ -57,7 +66,7 @@ export function SubscribeForm({
|
||||
Cancelar
|
||||
</Button>
|
||||
) : null}
|
||||
<Button type="submit" variant="primary" disabled={isPending || !email.trim()}>
|
||||
<Button type="submit" variant="primary" disabled={isPending || (asksEmail && !email.trim())}>
|
||||
{isPending ? <Loader2 className="size-4 animate-spin" /> : null}
|
||||
{isPending ? 'Abriendo…' : submitLabel}
|
||||
</Button>
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
import { Modal } from '../../components/ui'
|
||||
import { useAuth } from '../../context/AuthProvider'
|
||||
import { useBilling } from './BillingProvider'
|
||||
import { subscribeDescription } from './copy'
|
||||
import { SubscribeForm } from './SubscribeForm'
|
||||
import { useStartSubscription } from './useStartSubscription'
|
||||
|
||||
@@ -8,18 +9,20 @@ export function SubscribeModal() {
|
||||
const { user } = useAuth()
|
||||
const { isSubscribeOpen, closeSubscribe, statusQuery } = useBilling()
|
||||
const subscription = useStartSubscription()
|
||||
const provider = statusQuery.data?.provider ?? 'MERCADO_PAGO'
|
||||
|
||||
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."
|
||||
description={subscribeDescription(provider)}
|
||||
maxWidth="sm"
|
||||
>
|
||||
{/* Se monta solo con el modal abierto, así el autoFocus del email funciona cada vez. */}
|
||||
{isSubscribeOpen ? (
|
||||
<SubscribeForm
|
||||
provider={provider}
|
||||
defaultEmail={statusQuery.data?.payerEmail ?? user?.email ?? ''}
|
||||
isPending={subscription.isStarting}
|
||||
error={subscription.error}
|
||||
|
||||
@@ -1,4 +1,11 @@
|
||||
import type { BillingStatusDto, Plan, PlanFeature, PlanLimits, SubscriptionStatus } from '@gruperly/shared'
|
||||
import type {
|
||||
BillingProviderId,
|
||||
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
|
||||
@@ -8,7 +15,21 @@ import type { BadgeVariant } from '../../components/ui'
|
||||
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.'
|
||||
'No pudimos abrir la página de pago. Revisá tu conexión e intentá de nuevo.'
|
||||
|
||||
/* Quién cobra Pro: Mercado Pago en Argentina, Stripe en el resto. Es solo la
|
||||
suscripción a Gruperly; los cobros a alumnos siguen siendo con Mercado Pago. */
|
||||
export const BILLING_PROVIDER_NAMES: Record<BillingProviderId, string> = {
|
||||
MERCADO_PAGO: 'Mercado Pago',
|
||||
STRIPE: 'Stripe',
|
||||
}
|
||||
|
||||
/** Qué pasa al tocar "Pasar a Pro", según quién cobra. */
|
||||
export function subscribeDescription(provider: BillingProviderId): string {
|
||||
return provider === 'STRIPE'
|
||||
? 'Te llevamos a Stripe para cargar tu tarjeta. El cobro es mensual y podés cancelarlo cuando quieras.'
|
||||
: 'Te llevamos a Mercado Pago para autorizar el débito mensual. Podés cancelarlo cuando quieras.'
|
||||
}
|
||||
|
||||
/** Lo que incluye cada plan, como lista para las tarjetas de comparación. */
|
||||
export function planFeatureList(limits: PlanLimits): { label: string; included: boolean }[] {
|
||||
@@ -113,7 +134,7 @@ export function planNoticeMessage(status: BillingStatusDto): { tone: 'danger' |
|
||||
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}.`,
|
||||
: `No pudimos cobrar tu suscripción a Pro. Revisá tu medio de pago en ${BILLING_PROVIDER_NAMES[status.provider]} antes del ${graceUntil}.`,
|
||||
}
|
||||
}
|
||||
return null
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
export {
|
||||
BILLING_PROVIDER_NAMES,
|
||||
formatBillingDate,
|
||||
formatUsage,
|
||||
hasPlanFeature,
|
||||
@@ -7,6 +8,7 @@ export {
|
||||
PLAN_NAMES,
|
||||
planFeatureList,
|
||||
planNoticeMessage,
|
||||
subscribeDescription,
|
||||
subscriptionStatusLabel,
|
||||
} from './copy'
|
||||
export { dismissPlanPrompt, showPlanPrompt, usePlanPrompt } from './plan-prompt'
|
||||
|
||||
@@ -5,14 +5,14 @@ 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`.
|
||||
* resuelve con `fetch`: el navegador navega al checkout del proveedor (Mercado
|
||||
* Pago o Stripe) para que el profesor autorice el cobro, y vuelve 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') => {
|
||||
const start = async (payerEmail: string | undefined, returnTo: BillingReturnTo = 'billing') => {
|
||||
setError(null)
|
||||
setIsStarting(true)
|
||||
try {
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import type { SelectPlanInput } from '@gruperly/shared'
|
||||
import { COUNTRY_CURRENCY, PLAN_LIMITS, PRO_PRICE_BY_COUNTRY } from '@gruperly/shared'
|
||||
import { billingProviderForCountry, 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'
|
||||
@@ -8,6 +8,7 @@ import { useAuth } from '../../context/AuthProvider'
|
||||
import { ApiError, selectPlan } from '../../lib/api'
|
||||
import { formatPrice } from '../../lib/format'
|
||||
import {
|
||||
BILLING_PROVIDER_NAMES,
|
||||
PlanOptionCard,
|
||||
SubscribeForm,
|
||||
useBillingStatus,
|
||||
@@ -19,15 +20,16 @@ const SELECT_PLAN_ERROR_MESSAGE = 'No pudimos guardar tu plan. Revisá tu conexi
|
||||
|
||||
/**
|
||||
* 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.
|
||||
* (sin Cobros ni WhatsApp, que son de Pro). Pro lleva al checkout del
|
||||
* proveedor del país (Mercado Pago en Argentina, Stripe en el resto) y vuelve
|
||||
* acá con `?sub=return`; mientras el proveedor confirma se puede seguir igual.
|
||||
*/
|
||||
export function PlanStep() {
|
||||
const { user } = useAuth()
|
||||
const queryClient = useQueryClient()
|
||||
const { country, selectedPlan, setSelectedPlan, returnedFromSubscription, goTo, goBack, statusQuery } =
|
||||
useOnboarding()
|
||||
// Con Mercado Pago, el paso intermedio de pedir el email; con Stripe, el de confirmar.
|
||||
const [isEnteringEmail, setIsEnteringEmail] = useState(false)
|
||||
const [error, setError] = useState<string | null>(null)
|
||||
const [proUnavailable, setProUnavailable] = useState(false)
|
||||
@@ -42,6 +44,8 @@ export function PlanStep() {
|
||||
if (returnedFromSubscription) polling.startPolling()
|
||||
}, [returnedFromSubscription, polling.startPolling])
|
||||
|
||||
const provider = billingProviderForCountry(country)
|
||||
const providerName = BILLING_PROVIDER_NAMES[provider]
|
||||
const subscriptionStatus = billingQuery.data?.status ?? statusQuery.data?.subscriptionStatus ?? null
|
||||
|
||||
const mutation = useMutation({
|
||||
@@ -71,7 +75,7 @@ export function PlanStep() {
|
||||
setError(null)
|
||||
mutation.mutate({ plan: 'FREE', country })
|
||||
}
|
||||
const choosePro = (payerEmail: string) => {
|
||||
const choosePro = (payerEmail: string | undefined) => {
|
||||
setError(null)
|
||||
mutation.mutate({ plan: 'PRO', country, payerEmail })
|
||||
}
|
||||
@@ -109,8 +113,8 @@ export function PlanStep() {
|
||||
</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.'}
|
||||
? `${providerName} puede tardar unos minutos en confirmarlo. Podés seguir mientras tanto: te avisamos cuando quede activa.`
|
||||
: `No terminaste de autorizar el pago en ${providerName}. Podés reintentarlo o seguir con Free.`}
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
@@ -156,6 +160,7 @@ export function PlanStep() {
|
||||
<p className="text-xs text-foreground/50">Todavía no está disponible en tu país.</p>
|
||||
) : isEnteringEmail ? (
|
||||
<SubscribeForm
|
||||
provider={provider}
|
||||
defaultEmail={user?.email ?? ''}
|
||||
isPending={isLeavingToMp}
|
||||
error={null}
|
||||
|
||||
Reference in New Issue
Block a user