Ir al contenido

BillingAndPlan

Lo que paga la organización, cuánto ha usado, cómo paga y cada factura. Cambiar de plan muestra todos los planes lado a lado; un pago fallido se dice arriba, con qué hacer.

import { PlanCard, PricingTable, UsageBar } from '@sypnia/ui/react'

En esta página
  1. En un computador
  2. En un celular
  3. Cuando un pago falla
  4. Skeleton
  5. Cuándo usarlo
  6. Para todos
  7. Props

En un computador

Pulsa «Cambiar de plan» para ver los planes lado a lado y pasar a otro.

Facturación

Aquí Northwind paga por sus proyectos.

Pro

Tu plan

29 US$mes

Para un producto en producción.

Cómo pagas

Tarjeta
Visa terminada en 4242Vence 08/2028
Las facturas van a
billing@northwind.io
Próximo cobro
29,00 US$ · 1 dic 2026

Uso de este mes

Vuelve a empezar el 1 de diciembre
Solicitudes a la API1,6 M de 2 M
82 % usado: pronto estará lleno.
Almacenamiento8,2 GB de 10 GB
82 % usado: pronto estará lleno.
Puestos5 de 8

Facturas

FechaNúmeroValorEstado
1 nov 2026INV-2026-01129,00 US$PagadaDescargar PDF
1 oct 2026INV-2026-01029,00 US$PagadaDescargar PDF
1 sept 2026INV-2026-00941,50 US$PagadaDescargar PDF
1 ago 2026INV-2026-00829,00 US$PagadaDescargar PDF
Código
import { useState } from 'react';
import {
  Alert, Badge, Button, Columns, Currency, DescriptionList, Dialog, DownloadButton, InlineCode, Page, PageHeader, Panel,
  PlanCard, PricingTable, SkeletonOf, SkeletonWords, Stack, Table, Text, Toaster, UsageBar, toast, useSypnia,
} from '@sypnia/ui/react';

// What the organization pays for, what it has used of it, how it pays, and every invoice. Changing the plan shows every
// plan side by side and says what the change costs today. A failed payment is said at the top, with what to do.
const en = {
  title: 'Billing', lead: 'Northwind pays for its projects here.', plan: 'Your plan', change: 'Change plan', usage: 'Use this month',
  resets: 'Starts again on December 1', requests: 'API requests', storage: 'Storage', seats: 'Seats', addSeats: 'Add seats',
  method: 'How you pay', card: 'Card', cardV: 'Visa ending in 4242', expires: 'Expires', billTo: 'Invoices go to', updateCard: 'Update card', nextCharge: 'Next charge',
  invoices: 'Invoices', date: 'Date', number: 'Number', amount: 'Amount', status: 'Status', paid: 'Paid', due: 'Not paid', download: 'Download PDF',
  compare: 'Choose a plan', current: 'Your plan', choose: (n: string) => `Move to ${n}`, moved: (n: string) => `You are on ${n} now. The difference is on your next invoice.`,
  failTitle: 'The payment of November did not go through', failBody: 'The bank declined the card ending in 4242. Update the card before December 1 to keep your projects running.',
  emptyInvoices: 'No invoices yet. The first one comes on December 1.',
  blurbs: { hobby: 'To try it.', pro: 'For a product in production.', team: 'For several teams.' },
  rows: { projects: 'Projects', requests: 'API requests a month', storage: 'Storage', backups: 'Backups kept', sso: 'Single sign-on' },
  vals: { unlimited: 'Unlimited', d7: '7 days', d30: '30 days', y1: '1 year' }, month: 'month', free: 'Free',
};
const es: typeof en = {
  title: 'Facturación', lead: 'Aquí Northwind paga por sus proyectos.', plan: 'Tu plan', change: 'Cambiar de plan', usage: 'Uso de este mes',
  resets: 'Vuelve a empezar el 1 de diciembre', requests: 'Solicitudes a la API', storage: 'Almacenamiento', seats: 'Puestos', addSeats: 'Agregar puestos',
  method: 'Cómo pagas', card: 'Tarjeta', cardV: 'Visa terminada en 4242', expires: 'Vence', billTo: 'Las facturas van a', updateCard: 'Cambiar tarjeta', nextCharge: 'Próximo cobro',
  invoices: 'Facturas', date: 'Fecha', number: 'Número', amount: 'Valor', status: 'Estado', paid: 'Pagada', due: 'Sin pagar', download: 'Descargar PDF',
  compare: 'Elige un plan', current: 'Tu plan', choose: (n: string) => `Pasar a ${n}`, moved: (n: string) => `Ya estás en ${n}. La diferencia va en tu próxima factura.`,
  failTitle: 'El pago de noviembre no pasó', failBody: 'El banco rechazó la tarjeta terminada en 4242. Cámbiala antes del 1 de diciembre para que tus proyectos sigan funcionando.',
  emptyInvoices: 'Aún no hay facturas. La primera llega el 1 de diciembre.',
  blurbs: { hobby: 'Para probarlo.', pro: 'Para un producto en producción.', team: 'Para varios equipos.' },
  rows: { projects: 'Proyectos', requests: 'Solicitudes a la API al mes', storage: 'Almacenamiento', backups: 'Copias guardadas', sso: 'Inicio de sesión único' },
  vals: { unlimited: 'Ilimitados', d7: '7 días', d30: '30 días', y1: '1 año' }, month: 'mes', free: 'Gratis',
};
const invoices = [
  { id: 'INV-2026-011', at: Date.UTC(2026, 10, 1, 12), amount: 29, paid: false },
  { id: 'INV-2026-010', at: Date.UTC(2026, 9, 1, 12), amount: 29, paid: true },
  { id: 'INV-2026-009', at: Date.UTC(2026, 8, 1, 12), amount: 41.5, paid: true },
  { id: 'INV-2026-008', at: Date.UTC(2026, 7, 1, 12), amount: 29, paid: true },
];
const GB = 1024 ** 3;

export default function BillingAndPlan({ state = 'ready' }: { state?: 'ready' | 'loading' | 'failed' }) {
  const { locale, format } = useSypnia();
  const c = locale.startsWith('es') ? es : en;
  const [plan, setPlan] = useState('pro');
  const [open, setOpen] = useState(false);
  // Loading: the real page. The plan, the card, the usage and the invoices are drawn with the last known values (here
  // the same ones), each as a skeleton as long as its words; titles, names and the buttons that need no data stay.
  const loading = state === 'loading';
  const names: Record<string, string> = { hobby: 'Hobby', pro: 'Pro', team: 'Team' };
  const prices: Record<string, number> = { hobby: 0, pro: 29, team: 99 };
  const plans = (['hobby', 'pro', 'team'] as const).map((id) => ({
    id, name: names[id], price: prices[id], currency: 'USD', period: c.month, free: c.free, blurb: c.blurbs[id], lit: id === 'team' && plan !== 'team', current: id === plan,
    action: id === plan ? <Badge tone="light">{c.current}</Badge>
      : <Button size="sm" variant={id === 'team' ? 'primary' : 'secondary'} onClick={() => { setPlan(id); setOpen(false); toast(c.moved(names[id]), { tone: 'ok' }); }}>{c.choose(names[id])}</Button>,
  }));
  const failed = state === 'failed';
  return (
    <Page>
      <PageHeader title={c.title} lead={c.lead} />
      {failed && <Alert tone="fail" title={c.failTitle} actions={<Button size="sm" variant="primary" icon="credit-card">{c.updateCard}</Button>}>{c.failBody}</Alert>}
      <Columns cols={2} stack>
        <PlanCard loading={loading} name={names[plan]} price={prices[plan]} currency="USD" period={c.month} free={c.free} blurb={c.blurbs[plan as 'pro']} current
          action={<Button icon="upgrade" onClick={() => setOpen(true)}>{c.change}</Button>} />
        <Panel title={c.method} actions={<Button size="sm" icon="credit-card">{c.updateCard}</Button>}>
          <DescriptionList columns={1} loading={loading} items={[
            { term: c.card, description: c.cardV, hint: `${c.expires} 08/2028` },
            { term: c.billTo, description: 'billing@northwind.io' },
            { term: c.nextCharge, description: <span><Currency value={prices[plan]} currency="USD" /> · {format.date(new Date(Date.UTC(2026, 11, 1, 12)))}</span> },
          ]} />
        </Panel>
      </Columns>
      <Panel title={c.usage} actions={<Text as="span" size="xs" tone="muted">{c.resets}</Text>}>
        <Stack gap={5}>
          <UsageBar loading={loading} label={c.requests} used={1_640_000} limit={2_000_000} format={(v) => format.number(v, { notation: 'compact' })} />
          <UsageBar loading={loading} label={c.storage} used={8.2 * GB} limit={10 * GB} format={(v) => format.bytes(v)} />
          <UsageBar loading={loading} label={c.seats} used={5} limit={8} action={<Button size="sm" variant="quiet">{c.addSeats}</Button>} />
        </Stack>
      </Panel>
      <Panel title={c.invoices} flush>
        <Table label={c.invoices} rows={loading ? undefined : invoices} loading={loading} loadingRows={invoices.length} rowKey={(i) => i.id} empty={c.emptyInvoices} columns={[
          { id: 'date', header: c.date, cell: (i) => format.date(new Date(i.at)), skeleton: (n) => <SkeletonWords>{format.date(new Date(invoices[n].at))}</SkeletonWords> },
          { id: 'number', header: c.number, cell: (i) => <InlineCode>{i.id}</InlineCode>, skeleton: (n) => <SkeletonOf><InlineCode>{invoices[n].id}</InlineCode></SkeletonOf> },
          { id: 'amount', header: c.amount, numeric: true, cell: (i) => <Currency value={i.amount} currency="USD" />, skeleton: (n) => <SkeletonWords><Currency value={invoices[n].amount} currency="USD" /></SkeletonWords> },
          { id: 'status', header: c.status, cell: (i) => (i.paid || !failed ? <Badge tone="ok" dot>{c.paid}</Badge> : <Badge tone="fail" dot>{c.due}</Badge>), skeleton: <SkeletonOf><Badge dot>{c.paid}</Badge></SkeletonOf> },
          { id: 'pdf', header: '', actions: true, skeleton: (n) => <SkeletonOf><DownloadButton size="sm" variant="quiet" href="#" filename={`${invoices[n].id}.pdf`}>{c.download}</DownloadButton></SkeletonOf>, cell: (i) => <DownloadButton size="sm" variant="quiet" href={`#${i.id}.pdf`} filename={`${i.id}.pdf`}>{c.download}</DownloadButton> },
        ]} />
      </Panel>
      <Dialog open={open} onClose={() => setOpen(false)} title={c.compare} size="xl">
        <PricingTable caption={c.compare} plans={plans} rows={[
          { id: 'projects', label: c.rows.projects, values: { hobby: '1', pro: '10', team: c.vals.unlimited } },
          { id: 'requests', label: c.rows.requests, values: { hobby: '50K', pro: '2M', team: '10M' } },
          { id: 'storage', label: c.rows.storage, values: { hobby: '1 GB', pro: '10 GB', team: '100 GB' } },
          { id: 'backups', label: c.rows.backups, values: { hobby: c.vals.d7, pro: c.vals.d30, team: c.vals.y1 } },
          { id: 'sso', label: c.rows.sso, values: { hobby: false, pro: false, team: true } },
        ]} />
      </Dialog>
      <Toaster />
    </Page>
  );
}

En un celular

En un celular el plan y la tarjeta se apilan, y las facturas se vuelven tarjetas.

Cuando un pago falla

El mensaje va arriba, dice hasta cuándo arreglarlo y trae el botón.

Facturación

Aquí Northwind paga por sus proyectos.

Pro

Tu plan

29 US$mes

Para un producto en producción.

Cómo pagas

Tarjeta
Visa terminada en 4242Vence 08/2028
Las facturas van a
billing@northwind.io
Próximo cobro
29,00 US$ · 1 dic 2026

Uso de este mes

Vuelve a empezar el 1 de diciembre
Solicitudes a la API1,6 M de 2 M
82 % usado: pronto estará lleno.
Almacenamiento8,2 GB de 10 GB
82 % usado: pronto estará lleno.
Puestos5 de 8

Facturas

FechaNúmeroValorEstado
1 nov 2026INV-2026-01129,00 US$Sin pagarDescargar PDF
1 oct 2026INV-2026-01029,00 US$PagadaDescargar PDF
1 sept 2026INV-2026-00941,50 US$PagadaDescargar PDF
1 ago 2026INV-2026-00829,00 US$PagadaDescargar PDF

Skeleton

La página real: el plan, la tarjeta, el uso y las facturas con los últimos valores conocidos, como skeletons tan largos como sus palabras.

Facturación

Aquí Northwind paga por sus proyectos.

Cómo pagas

Tarjeta
Las facturas van a
Próximo cobro

Uso de este mes

Vuelve a empezar el 1 de diciembre
Solicitudes a la API
Almacenamiento
Puestos

Facturas

FechaNúmeroValorEstado

Cuándo usarlo

Úsalo cuando

  • La página de facturación de una organización.
  • Barras de uso con su límite y cuándo vuelven a empezar, para que nadie se sorprenda con un límite.

No lo uses cuando

  • Ocultar el precio del plan actual o del próximo cobro.
  • Enterrar un pago fallido entre las facturas: va arriba, con el botón que lo arregla.

Para todos

  • Cada barra de uso es un medidor con su valor en palabras: «8,2 GB de 10 GB».
  • Cada factura tiene su propio botón de descarga, nombrado con la factura.
  • La tabla de planes es una tabla en pantallas anchas y una tarjeta por plan en celulares.

Props

PlanCardTipoPor defecto
nameobligatorio ReactNode
priceobligatorio

The price as written, or a number with `currency`. 0 is «Free» when `free` is given.

ReactNode
action

The button: «Start with Pro».

ReactNode
blurb

One line: who the plan is for.

ReactNode
currency

ISO code, when `price` is a number.

string
current

The person's own plan: says so instead of offering it.

boolean
features FeatureItem[]
free

Words for a price of 0: «Free».

string
lit

The plan most people should take: lit, with «Recommended».

boolean
loading

The plan is on its way (the person's own, read from the server): the card keeps its shape, and the name, price, period, blurb, features and button are skeletons as long as the ones given (the last known, or typical ones).

boolean
period

What the price is for, as the page writes it: «per month», «per user per month», «al mes».

string
PricingTableTipoPor defecto
captionobligatorio string
plansobligatorio PricingPlan[]
rowsobligatorio CompareRow[]
UsageBarTipoPor defecto
labelobligatorio ReactNode
limitobligatorio number
usedobligatorio number
action

The next step, shown from 80 %: usually a LinkButton to the plans.

ReactNode
format

How amounts are written: bytes, rows, requests. Defaults to a number.

((v: number) => string)
loading

The amount is on its way: the label stays, the amount and the bar are skeletons. Pass the last known `used` and `limit`, so the amount's bar is as long as its words will be.

boolean
resetsAt

When the count starts again, for monthly limits.

string | number | Date
  1. En un computador
  2. En un celular
  3. Cuando un pago falla
  4. Skeleton
  5. Cuándo usarlo
  6. Para todos
  7. Props

    Busca páginas, secciones y términos