# Bloco: Painel

O painel de um SaaS de assinaturas com um número herói: o MRR grande com a receita por plano logo abaixo, o que pede ação ao lado, os números de apoio numa faixa sem moldura e as últimas assinaturas numa tabela.

Uma tela inteira, montada só com peças do @rivocode/ui e as regras da skill. Copie o arquivo, troque os dados de exemplo pelos da sua consulta e mantenha os quatro finais: dados, carregando, erro e vazio. Ele importa só de `@rivocode/ui`, `@rivocode/ui/chart`, `lucide-react` e `react`.

Peças: [PageHeader](https://ds.rivocode.com.br/componentes/page-header.md), [Heading](https://ds.rivocode.com.br/componentes/heading.md), [ChartContainer](https://ds.rivocode.com.br/componentes/chart-container.md), [DataTable](https://ds.rivocode.com.br/componentes/data-table.md), [Link](https://ds.rivocode.com.br/componentes/link.md).

Padrões de UX que ele aplica: [Espera](https://ds.rivocode.com.br/padroes/espera.md).

Ao vivo, no desktop e no celular: https://ds.rivocode.com.br/blocos#painel

## Código

```tsx
import {
  Badge,
  Button,
  DataTable,
  Heading,
  Link,
  PageHeader,
  QueryBoundary,
  Skeleton,
  type Column,
} from '@rivocode/ui'
import {
  Area,
  AreaChart,
  CartesianGrid,
  ChartAreaGradient,
  ChartContainer,
  ChartLegend,
  ChartLegendContent,
  ChartTooltip,
  ChartTooltipContent,
  ChartXAxis,
  ChartYAxis,
  areaGradient,
  currencyShort,
  type ChartConfig,
} from '@rivocode/ui/chart'
import { ArrowUpRight, Download, UserPlus } from 'lucide-react'
import { useCallback, useEffect, useRef, useState } from 'react'

type Subscription = {
  id: string
  customer: string
  plan: 'Essencial' | 'Pro' | 'Empresa'
  mrr: number
  status: 'active' | 'trial' | 'cancelled'
}

const STATUS: Record<Subscription['status'], { label: string; tone: 'success' | 'info' | 'danger' }> = {
  active: { label: 'Ativa', tone: 'success' },
  trial: { label: 'Em teste', tone: 'info' },
  cancelled: { label: 'Cancelada', tone: 'danger' },
}

const MONTHS = [
  { month: 'mar', essential: 18_200, pro: 31_400, business: 22_000 },
  { month: 'abr', essential: 19_100, pro: 33_900, business: 22_000 },
  { month: 'mai', essential: 19_800, pro: 35_200, business: 26_500 },
  { month: 'jun', essential: 20_600, pro: 38_700, business: 26_500 },
  { month: 'jul', essential: 21_300, pro: 41_200, business: 31_000 },
  { month: 'ago', essential: 22_400, pro: 44_800, business: 31_000 },
]

const RECENT: Subscription[] = [
  { id: 'AS-1287', customer: 'Estúdio Lume', plan: 'Pro', mrr: 349, status: 'trial' },
  { id: 'AS-1286', customer: 'Padaria Aurora', plan: 'Essencial', mrr: 129, status: 'active' },
  { id: 'AS-1285', customer: 'Oficina Norte', plan: 'Empresa', mrr: 1_490, status: 'active' },
  { id: 'AS-1284', customer: 'Escola Mar Azul', plan: 'Pro', mrr: 349, status: 'cancelled' },
  { id: 'AS-1283', customer: 'Academia Ponta Verde', plan: 'Essencial', mrr: 129, status: 'active' },
]

/** O que precisa de alguem hoje. Cada linha leva para onde a acao acontece. */
const PENDING = [
  {
    id: 'declined',
    href: '/cobrancas?situacao=recusada',
    title: '3 cartões recusados na renovação',
    reason: `${currencyShort(1_247)} de MRR esperando nova tentativa até sexta.`,
  },
  {
    id: 'downgrade',
    href: '/assinantes/oficina-norte',
    title: 'Oficina Norte pediu para sair do Empresa',
    reason: `Vai para o Pro em 1º de setembro, ${currencyShort(1_141)} a menos por mês.`,
  },
  {
    id: 'trials',
    href: '/assinantes?situacao=teste',
    title: '9 testes terminam esta semana',
    reason: 'Nenhum cadastrou cartão ainda.',
  },
]

/** Os numeros de apoio: sem moldura, numa faixa so, porque nenhum deles e o assunto. */
const SECONDARY = [
  { id: 'active', label: 'Assinantes ativos', value: '642', note: '25 a mais que julho' },
  { id: 'trial', label: 'Em teste', value: '58', note: '6 a mais que julho' },
  { id: 'cancelled', label: 'Cancelamentos', value: '17', note: '3 a mais que julho', worse: true },
  { id: 'ticket', label: 'Tíquete médio', value: currencyShort(153), note: 'igual a julho' },
]

const BY_PLAN: ChartConfig = {
  essential: { label: 'Essencial' },
  pro: { label: 'Pro' },
  business: { label: 'Empresa' },
}

const COLUMNS: Column<Subscription>[] = [
  { key: 'customer', header: 'Assinante' },
  { key: 'plan', header: 'Plano', hideOnMobile: true },
  {
    key: 'mrr',
    header: 'MRR',
    align: 'right',
    cell: (subscription) => <span className="tabular-nums">{currencyShort(subscription.mrr)}</span>,
  },
  {
    key: 'status',
    header: 'Situação',
    hideOnMobile: true,
    cell: (subscription) => (
      <Badge tone={STATUS[subscription.status].tone} size="sm">
        {STATUS[subscription.status].label}
      </Badge>
    ),
  },
]

type Overview = { months: typeof MONTHS; recent: Subscription[] }

/** A consulta de mentira: troque pelo `useQuery` do seu app, com os mesmos quatro campos. */
function useOverview() {
  const [data, setData] = useState<Overview | undefined>(undefined)
  const [isFetching, setFetching] = useState(true)
  const timer = useRef<ReturnType<typeof setTimeout>>(undefined)

  const refetch = useCallback(() => {
    setFetching(true)
    clearTimeout(timer.current)
    timer.current = setTimeout(() => {
      setData((current) => current ?? { months: MONTHS, recent: RECENT })
      setFetching(false)
    }, 700)
  }, [])

  useEffect(() => {
    refetch()
    return () => clearTimeout(timer.current)
  }, [refetch])

  return { data, isLoading: data === undefined, isError: false, isFetching, refetch }
}

/** O CSV dos meses do grafico, baixado pelo navegador. */
function downloadCsv(months: typeof MONTHS) {
  const lines = [
    'Mês;Essencial;Pro;Empresa',
    ...months.map((row) => `${row.month};${row.essential};${row.pro};${row.business}`),
  ]
  const url = URL.createObjectURL(new Blob([lines.join('\n')], { type: 'text/csv;charset=utf-8' }))
  const link = document.createElement('a')
  link.href = url
  link.download = 'receita-por-plano.csv'
  link.click()
  URL.revokeObjectURL(url)
}

/** O esqueleto tem a forma da tela: o numero grande, a lista ao lado, a faixa e o grafico. */
function OverviewSkeleton() {
  return (
    <div className="space-y-10">
      <div className="grid gap-10 lg:grid-cols-[minmax(0,2fr)_minmax(0,1fr)] lg:gap-x-12">
        <div className="space-y-3">
          <Skeleton className="h-4 w-48" />
          <Skeleton className="h-14 w-56" />
          <Skeleton className="h-4 w-72 max-w-full" />
          <Skeleton className="mt-6 h-48 w-full sm:h-64" />
        </div>
        <div className="space-y-3">
          <Skeleton className="h-5 w-32" />
          <Skeleton className="h-12 w-full" />
          <Skeleton className="h-12 w-full" />
          <Skeleton className="h-12 w-full" />
        </div>
      </div>
      <Skeleton className="h-20 w-full" />
    </div>
  )
}

export default function DashboardPage() {
  const overview = useOverview()

  return (
    <div className="w-full space-y-8 bg-bg p-4 sm:p-6">
      <PageHeader
        title="Assinaturas de agosto"
        description="Atualizado às 14h20 de 24/08, com as cobranças da madrugada."
        actions={
          <Button
            variant="secondary"
            disabled={!overview.data}
            onClick={() => overview.data && downloadCsv(overview.data.months)}
          >
            <Download size={16} aria-hidden="true" />
            Exportar planilha
          </Button>
        }
      />

      <QueryBoundary
        data={overview.data}
        isLoading={overview.isLoading}
        isError={overview.isError}
        isFetching={overview.isFetching}
        onRetry={overview.refetch}
        isEmpty={overview.data?.recent.length === 0}
        errorTitle="Não foi possível carregar o painel"
        errorMessage="Os números voltam assim que a conexão voltar. Nenhuma assinatura foi afetada."
        empty={{
          icon: <UserPlus aria-hidden="true" />,
          title: 'Nenhum assinante ainda',
          description: 'O painel começa a contar a partir da primeira assinatura.',
          action: <Button render={<a href="/convites/novo" />}>Convidar o primeiro cliente</Button>,
        }}
        skeleton={<OverviewSkeleton />}
      >
        {({ months, recent }) => (
          <div className="space-y-10">
            <div className="grid gap-10 lg:grid-cols-[minmax(0,2fr)_minmax(0,1fr)] lg:gap-x-12 lg:gap-y-6">
              <section aria-labelledby="painel-mrr" className="min-w-0">
                <h2 id="painel-mrr" className="text-sm text-fg-muted">
                  Receita recorrente do mês (MRR)
                </h2>
                <p className="mt-2 font-display font-rc-display text-display leading-tight tracking-display tabular-nums text-fg">
                  {currencyShort(98_200)}
                </p>
                <p className="mt-3 text-sm text-fg-muted">
                  <span className="font-rc-medium text-success-text">
                    <ArrowUpRight size={14} aria-hidden="true" className="mr-1 inline align-[-2px]" />
                    6% acima de julho
                  </span>
                  , {currencyShort(5_600)} a mais, puxado pelo plano Pro.
                </p>
              </section>

              <section
                aria-labelledby="painel-pendencias"
                className="min-w-0 lg:col-start-2 lg:row-span-2 lg:row-start-1"
              >
                <Heading level={2} size="md" id="painel-pendencias">
                  Pede ação hoje
                </Heading>
                <ul className="mt-2 divide-y divide-border">
                  {PENDING.map((item) => (
                    <li key={item.id} className="py-3">
                      <Link href={item.href} tone="neutral" className="text-sm font-rc-medium">
                        {item.title}
                      </Link>
                      <p className="mt-0.5 text-sm text-fg-muted">{item.reason}</p>
                    </li>
                  ))}
                </ul>
              </section>

              <section aria-labelledby="painel-planos" className="min-w-0 lg:col-start-1 lg:row-start-2">
                <h2 id="painel-planos" className="sr-only">
                  MRR por plano, de março a agosto
                </h2>
                <ChartContainer config={BY_PLAN} className="h-48 sm:h-64">
                  <AreaChart data={months} margin={{ left: 0, right: 8, top: 8 }}>
                    <ChartAreaGradient id="painel-planos" series={['essential', 'pro', 'business']} />
                    <CartesianGrid vertical={false} />
                    <ChartXAxis dataKey="month" />
                    <ChartYAxis format="compact" />
                    <ChartTooltip content={<ChartTooltipContent config={BY_PLAN} />} />
                    <ChartLegend content={<ChartLegendContent config={BY_PLAN} />} />
                    <Area
                      dataKey="essential"
                      stroke="var(--color-essential)"
                      fill={areaGradient('painel-planos', 'essential')}
                      strokeWidth={2}
                    />
                    <Area
                      dataKey="pro"
                      stroke="var(--color-pro)"
                      fill={areaGradient('painel-planos', 'pro')}
                      strokeWidth={2}
                    />
                    <Area
                      dataKey="business"
                      stroke="var(--color-business)"
                      fill={areaGradient('painel-planos', 'business')}
                      strokeWidth={2}
                    />
                  </AreaChart>
                </ChartContainer>
              </section>
            </div>

            <dl className="grid grid-cols-2 gap-y-5 border-y border-border py-4 sm:grid-cols-4 sm:divide-x sm:divide-border">
              {SECONDARY.map((metric) => (
                <div key={metric.id} className="min-w-0 pr-4 sm:px-6 sm:first:pl-0">
                  <dt className="text-sm text-fg-muted">{metric.label}</dt>
                  <dd className="mt-1 font-display font-rc-display text-xl tabular-nums text-fg">
                    {metric.value}
                  </dd>
                  <dd className={`mt-0.5 text-xs ${metric.worse ? 'text-danger-text' : 'text-fg-subtle'}`}>
                    {metric.note}
                  </dd>
                </div>
              ))}
            </dl>

            <section aria-labelledby="painel-recentes" className="space-y-3">
              <div className="flex flex-wrap items-baseline gap-3">
                <Heading level={2} size="md" id="painel-recentes">
                  Últimas assinaturas
                </Heading>
                <Link href="/assinantes" className="ml-auto text-sm">
                  Ver todos os assinantes
                </Link>
              </div>
              <DataTable
                data={recent}
                columns={COLUMNS}
                rowKey={(subscription) => subscription.id}
                caption="As cinco assinaturas mais recentes"
                empty={{
                  title: 'Nenhuma assinatura neste mês',
                  description: 'Quando alguém assinar ou cancelar, aparece aqui.',
                }}
              />
            </section>
          </div>
        )}
      </QueryBoundary>
    </div>
  )
}
```
