Files
gruperly/apps/web/src/features/admin/PlanLimitsCard.tsx
Jose Selesan aac142d324 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>
2026-11-11 07:50:14 -03:00

132 lines
5.1 KiB
TypeScript

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>
)
}