feat(frontend): Platform > Clientes > Assinaturas/Quotas + achado real no dashboard

GET /billing/subscriptions e POST /billing/plan-versions já existiam desde a fase
Billing (PHASE 22) sem tela nenhuma — Assinaturas agora deixa escolher um tenant, ver
o histórico de versões de preço assinadas, e criar uma nova assinatura reaproveitando
uma versão existente ou versionando um preço novo na mesma ação (preço nunca é
sobrescrito, sempre uma linha nova).

GET /platform/quotas (novo) agrega uso vs. limite do plano em todos os tenants de
uma vez (ramais/agentes/troncos/filas/campanhas/chamadas-mês/armazenamento), com a
tela destacando quem está em 80%+ (amarelo) ou 100%+ (vermelho) do limite.

Achado real ao revisar o dashboard "Visão Geral" antes de escrever a agregação
cross-tenant de Quotas: aiUsageThisMonth/recordingStorageBytes sempre devolviam
zero/vazio, porque a query rodava direto no Prisma sem nenhum app.current_tenant_id
setado — ai_usage_records/recordings têm FORCE RLS, então a policy nega a leitura
silenciosamente (0 linhas, sem erro), não importa quanto uso real existisse. Mesma
classe de bug já corrigida 2x antes nesta sessão; corrigido com o mesmo padrão (loop
withTenantContext por tenant). Confirmado inserindo um AIUsageRecord de teste no
Postgres, vendo o número aparecer, e removendo o teste depois.

Testado ponta a ponta: fluxo completo de criar assinatura via UI pro tenant Beta
Corp (nova versão de preço + assinatura, confirmado na tela e no banco), Quotas
mostrando os números reais dos dois tenants de teste.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01BFaBaBSQGhyXGEgtTYZGV8
This commit is contained in:
2026-08-30 08:32:53 -03:00
parent de0b632fc9
commit b1a409da09
17 changed files with 626 additions and 31 deletions

View File

@@ -0,0 +1,65 @@
"use server";
import { revalidatePath } from "next/cache";
import { requireSession } from "@/lib/session";
import { apiFetch, ApiError } from "@/lib/api";
import type { PlanVersion, TenantSubscription } from "@/lib/billing-types";
function extractErrorMessage(err: unknown): string {
if (err instanceof ApiError) {
try {
const parsed = JSON.parse(err.message);
if (Array.isArray(parsed.message)) return parsed.message.join(" ");
if (typeof parsed.message === "string") return parsed.message;
} catch {
// corpo não era JSON
}
return err.message || "Falha inesperada na API.";
}
return "Falha inesperada. Tente novamente.";
}
export interface CreateSubscriptionInput {
tenantId: string;
planId: string;
billingCycleAnchor: number;
currency: string;
// Ou usa uma versão existente, ou cria uma nova (mutuamente exclusivo — a
// tela só mostra um dos dois blocos de campo por vez).
planVersionId?: string;
newVersion?: { basePrice: number; effectiveFrom: string };
}
export async function createSubscription(input: CreateSubscriptionInput): Promise<{ ok: true } | { ok: false; error: string }> {
const session = await requireSession();
try {
let planVersionId = input.planVersionId;
if (!planVersionId && input.newVersion) {
const planVersion = await apiFetch<PlanVersion>("/billing/plan-versions", session.accessToken, {
method: "POST",
body: JSON.stringify({
planId: input.planId,
basePrice: input.newVersion.basePrice,
currency: input.currency,
effectiveFrom: input.newVersion.effectiveFrom,
}),
});
planVersionId = planVersion.id;
}
if (!planVersionId) return { ok: false, error: "Escolha uma versão de preço ou crie uma nova." };
await apiFetch<TenantSubscription>("/billing/subscriptions", session.accessToken, {
method: "POST",
body: JSON.stringify({
tenantId: input.tenantId,
planVersionId,
billingCycleAnchor: input.billingCycleAnchor,
currency: input.currency,
}),
});
revalidatePath("/platform/clientes/assinaturas");
return { ok: true };
} catch (err) {
return { ok: false, error: extractErrorMessage(err) };
}
}

View File

@@ -0,0 +1,248 @@
"use client";
import { useState, useTransition } from "react";
import { useRouter } from "next/navigation";
import { Plus, X } from "lucide-react";
import { Panel, PanelHeader } from "@/components/ui/panel";
import { Button } from "@/components/ui/button";
import { Input, Select, FieldLabel } from "@/components/ui/input";
import { Pill } from "@/components/ui/pill";
import { EmptyState, TBody, TD, TH, THead, TR, Table } from "@/components/ui/table";
import { formatCurrency, formatDate } from "@/lib/format";
import type { Tenant } from "@/lib/platform-types";
import { TENANT_SUBSCRIPTION_STATUS_LABELS, type PlanVersion, type TenantSubscription } from "@/lib/billing-types";
import { createSubscription } from "./actions";
const STATUS_TONE: Record<string, "accent" | "neutral"> = {
ACTIVE: "accent",
TRIALING: "neutral",
PAST_DUE: "neutral",
CANCELED: "neutral",
};
export function AssinaturasView({
tenants,
selectedTenant,
subscriptions,
planVersions,
}: {
tenants: Tenant[];
selectedTenant: Tenant | null;
subscriptions: TenantSubscription[];
planVersions: PlanVersion[];
}) {
const router = useRouter();
const [showForm, setShowForm] = useState(false);
return (
<div className="space-y-5">
<div className="flex flex-wrap items-start justify-between gap-3">
<div>
<h1 className="text-lg font-semibold text-foreground">Assinaturas</h1>
<p className="mt-1 max-w-2xl text-sm text-muted-foreground">
Qual versão de preço (agente.md secao 126-127) um tenant assinou, e em que dia do mês fecha o ciclo de
billing dele. Histórico, nunca sobrescrito trocar de preço cria uma linha nova.
</p>
</div>
{selectedTenant && (
<Button type="button" onClick={() => setShowForm((s) => !s)}>
{showForm ? <X className="h-4 w-4" aria-hidden /> : <Plus className="h-4 w-4" aria-hidden />}
{showForm ? "Cancelar" : "Nova assinatura"}
</Button>
)}
</div>
<Panel className="p-5">
<FieldLabel htmlFor="as-tenant">Tenant</FieldLabel>
<Select
id="as-tenant"
value={selectedTenant?.id ?? ""}
onChange={(e) => router.push(e.target.value ? `/platform/clientes/assinaturas?tenantId=${e.target.value}` : "/platform/clientes/assinaturas")}
className="max-w-sm"
>
<option value="">Escolha um tenant</option>
{tenants.map((t) => (
<option key={t.id} value={t.id}>
{t.legalName}
</option>
))}
</Select>
</Panel>
{!selectedTenant ? (
<Panel>
<EmptyState title="Escolha um tenant" description="Selecione um tenant acima pra ver as assinaturas dele." />
</Panel>
) : (
<>
{showForm && (
<NewSubscriptionForm
tenantId={selectedTenant.id}
planId={selectedTenant.planId}
planName={selectedTenant.plan.name}
planVersions={planVersions}
onDone={() => setShowForm(false)}
/>
)}
<Panel>
<PanelHeader title="Histórico de assinaturas" description={`Plano atual do tenant: ${selectedTenant.plan.name}`} />
{subscriptions.length === 0 ? (
<EmptyState title="Nenhuma assinatura ainda" description="Crie a primeira assinatura pra este tenant." />
) : (
<Table>
<THead>
<TR>
<TH>Versão</TH>
<TH>Preço base</TH>
<TH>Vigente desde</TH>
<TH>Início da assinatura</TH>
<TH>Ciclo (dia)</TH>
<TH>Status</TH>
</TR>
</THead>
<TBody>
{subscriptions.map((s) => (
<TR key={s.id}>
<TD className="font-mono text-muted-foreground">v{s.planVersion.version}</TD>
<TD className="font-mono text-foreground">{formatCurrency(s.planVersion.basePrice, s.currency)}</TD>
<TD className="text-muted-foreground">{formatDate(s.planVersion.effectiveFrom)}</TD>
<TD className="text-muted-foreground">{formatDate(s.startedAt)}</TD>
<TD className="font-mono tabular-nums text-muted-foreground">{s.billingCycleAnchor}</TD>
<TD>
<Pill tone={STATUS_TONE[s.status]}>{TENANT_SUBSCRIPTION_STATUS_LABELS[s.status] ?? s.status}</Pill>
</TD>
</TR>
))}
</TBody>
</Table>
)}
</Panel>
</>
)}
</div>
);
}
function NewSubscriptionForm({
tenantId,
planId,
planName,
planVersions,
onDone,
}: {
tenantId: string;
planId: string;
planName: string;
planVersions: PlanVersion[];
onDone: () => void;
}) {
const router = useRouter();
const [mode, setMode] = useState<"existing" | "new">(planVersions.length > 0 ? "existing" : "new");
const [planVersionId, setPlanVersionId] = useState(planVersions[0]?.id ?? "");
const [basePrice, setBasePrice] = useState("");
const [effectiveFrom, setEffectiveFrom] = useState(new Date().toISOString().slice(0, 10));
const [billingCycleAnchor, setBillingCycleAnchor] = useState("1");
const [currency, setCurrency] = useState("BRL");
const [error, setError] = useState<string | null>(null);
const [pending, startTransition] = useTransition();
function onSubmit(e: React.FormEvent) {
e.preventDefault();
setError(null);
const anchor = Number(billingCycleAnchor);
if (!Number.isInteger(anchor) || anchor < 1 || anchor > 28) {
setError("Dia do ciclo precisa ser um número entre 1 e 28.");
return;
}
if (mode === "new" && (!basePrice || Number(basePrice) < 0)) {
setError("Informe o preço base da nova versão.");
return;
}
startTransition(async () => {
const result = await createSubscription({
tenantId,
planId,
billingCycleAnchor: anchor,
currency,
...(mode === "existing" ? { planVersionId } : { newVersion: { basePrice: Number(basePrice), effectiveFrom } }),
});
if (!result.ok) {
setError(result.error);
return;
}
onDone();
router.refresh();
});
}
return (
<Panel className="p-5">
<form onSubmit={onSubmit} noValidate className="space-y-4">
<p className="text-sm text-muted-foreground">
Plano deste tenant: <span className="font-medium text-foreground">{planName}</span> a versão de preço
precisa pertencer a este plano.
</p>
<div className="flex gap-2">
<Button type="button" size="sm" variant={mode === "existing" ? "default" : "outline"} onClick={() => setMode("existing")} disabled={planVersions.length === 0}>
Usar versão existente
</Button>
<Button type="button" size="sm" variant={mode === "new" ? "default" : "outline"} onClick={() => setMode("new")}>
Criar nova versão de preço
</Button>
</div>
{mode === "existing" ? (
planVersions.length === 0 ? (
<p className="text-sm text-muted-foreground">Nenhuma versão de preço existe ainda pra este plano crie uma nova.</p>
) : (
<div>
<FieldLabel htmlFor="as-version">Versão</FieldLabel>
<Select id="as-version" value={planVersionId} onChange={(e) => setPlanVersionId(e.target.value)} disabled={pending} className="max-w-sm">
{planVersions.map((v) => (
<option key={v.id} value={v.id}>
v{v.version} {formatCurrency(v.basePrice, v.currency)} (desde {formatDate(v.effectiveFrom)})
</option>
))}
</Select>
</div>
)
) : (
<div className="grid grid-cols-1 gap-4 sm:grid-cols-2">
<div>
<FieldLabel htmlFor="as-price">Preço base</FieldLabel>
<Input id="as-price" type="number" min="0" step="0.01" value={basePrice} onChange={(e) => setBasePrice(e.target.value)} disabled={pending} />
</div>
<div>
<FieldLabel htmlFor="as-from">Vigente a partir de</FieldLabel>
<Input id="as-from" type="date" value={effectiveFrom} onChange={(e) => setEffectiveFrom(e.target.value)} disabled={pending} />
</div>
</div>
)}
<div className="grid grid-cols-1 gap-4 sm:grid-cols-2">
<div>
<FieldLabel htmlFor="as-anchor">Dia do ciclo de billing (1-28)</FieldLabel>
<Input id="as-anchor" type="number" min="1" max="28" value={billingCycleAnchor} onChange={(e) => setBillingCycleAnchor(e.target.value)} disabled={pending} />
</div>
<div>
<FieldLabel htmlFor="as-currency">Moeda</FieldLabel>
<Input id="as-currency" value={currency} onChange={(e) => setCurrency(e.target.value.toUpperCase())} maxLength={3} disabled={pending} className="font-mono" />
</div>
</div>
{error && (
<p role="alert" className="rounded-md border border-destructive/30 bg-destructive/10 px-3 py-2 text-sm text-destructive">
{error}
</p>
)}
<div className="flex justify-end">
<Button type="submit" disabled={pending}>
{pending ? "Criando…" : "Criar assinatura"}
</Button>
</div>
</form>
</Panel>
);
}

View File

@@ -0,0 +1,31 @@
import { requireSession } from "@/lib/session";
import { apiFetch } from "@/lib/api";
import type { Tenant } from "@/lib/platform-types";
import type { PlanVersion, TenantSubscription } from "@/lib/billing-types";
import { AssinaturasView } from "./assinaturas-view";
export default async function AssinaturasPage({ searchParams }: { searchParams: Promise<{ tenantId?: string }> }) {
const { tenantId } = await searchParams;
const session = await requireSession();
const tenants = await apiFetch<Tenant[]>("/tenants", session.accessToken);
const selectedTenant = tenantId ? (tenants.find((t) => t.id === tenantId) ?? null) : null;
const [subscriptions, planVersions] = tenantId
? await Promise.all([
apiFetch<TenantSubscription[]>(`/billing/subscriptions/by-tenant/${tenantId}`, session.accessToken),
selectedTenant
? apiFetch<PlanVersion[]>(`/billing/plan-versions/by-plan/${selectedTenant.planId}`, session.accessToken)
: Promise.resolve([]),
])
: [[], []];
return (
<AssinaturasView
tenants={tenants}
selectedTenant={selectedTenant}
subscriptions={subscriptions}
planVersions={planVersions}
/>
);
}

View File

@@ -0,0 +1,10 @@
import { requireSession } from "@/lib/session";
import { apiFetch } from "@/lib/api";
import type { TenantQuotas } from "@/lib/platform-types";
import { QuotasView } from "./quotas-view";
export default async function QuotasPage() {
const session = await requireSession();
const quotas = await apiFetch<TenantQuotas[]>("/platform/quotas", session.accessToken);
return <QuotasView quotas={quotas} />;
}

View File

@@ -0,0 +1,65 @@
import { cn } from "@/lib/utils";
import { Panel, PanelHeader } from "@/components/ui/panel";
import { Pill } from "@/components/ui/pill";
import { EmptyState } from "@/components/ui/table";
import { formatPercent } from "@/lib/format";
import { TENANT_STATUS_LABELS, type TenantQuotas } from "@/lib/platform-types";
function ratioColor(ratio: number | null): string {
if (ratio == null) return "text-muted-foreground";
if (ratio >= 1) return "text-status-red";
if (ratio >= 0.8) return "text-status-yellow";
return "text-foreground";
}
export function QuotasView({ quotas }: { quotas: TenantQuotas[] }) {
const nearLimit = quotas.filter((q) => q.items.some((i) => i.ratio != null && i.ratio >= 0.8));
return (
<div className="space-y-5">
<div>
<h1 className="text-lg font-semibold text-foreground">Quotas</h1>
<p className="mt-1 max-w-2xl text-sm text-muted-foreground">
Uso vs. limite do plano em todos os tenants (agente.md secao 169) sem limite no plano ({"—"}) nunca
conta como "estourado". Amarelo a partir de 80% do limite, vermelho a partir de 100%.
</p>
</div>
{nearLimit.length > 0 && (
<Panel className="border-status-yellow/40 bg-status-yellow/5 p-4">
<p className="text-sm text-foreground">
<span className="font-medium">{nearLimit.length} tenant(s)</span> com pelo menos um item em 80% ou mais do
limite: {nearLimit.map((t) => t.legalName).join(", ")}
</p>
</Panel>
)}
{quotas.length === 0 ? (
<Panel>
<EmptyState title="Nenhum tenant" description="Nenhum tenant cadastrado ainda." />
</Panel>
) : (
quotas.map((tenant) => (
<Panel key={tenant.tenantId} className="p-5">
<div className="flex flex-wrap items-center justify-between gap-2">
<PanelHeader title={tenant.legalName} description={`Plano ${tenant.planName}`} />
<Pill tone={tenant.status === "ACTIVE" ? "accent" : "neutral"}>{TENANT_STATUS_LABELS[tenant.status] ?? tenant.status}</Pill>
</div>
<div className="mt-4 grid grid-cols-2 gap-x-6 gap-y-3 sm:grid-cols-4">
{tenant.items.map((item) => (
<div key={item.key}>
<span className="block text-xs font-medium uppercase tracking-wide text-muted-foreground">{item.label}</span>
<span className={cn("mt-1 block font-mono text-sm tabular-nums", ratioColor(item.ratio))}>
{item.used}
{item.max != null && <span className="text-muted-foreground"> / {item.max}</span>}
{item.ratio != null && <span className="ml-1.5 text-xs">({formatPercent(item.ratio)})</span>}
</span>
</div>
))}
</div>
</Panel>
))
)}
</div>
);
}

View File

@@ -30,8 +30,16 @@ export const PLATFORM_NAV: NavSection[] = [
href: "/platform/clientes/planos",
description: "Catálogo de limites e recursos por plano",
},
{ label: "Assinaturas" },
{ label: "Quotas" },
{
label: "Assinaturas",
href: "/platform/clientes/assinaturas",
description: "Versão de preço assinada e ciclo de billing por tenant",
},
{
label: "Quotas",
href: "/platform/clientes/quotas",
description: "Uso vs. limite do plano — todos os tenants, quem está perto do limite",
},
],
},
{

View File

@@ -92,3 +92,33 @@ export interface BillingStatement {
billingPeriod: BillingPeriod;
items?: BillingStatementItem[];
}
export interface PlanVersion {
id: string;
planId: string;
version: number;
basePrice: number;
currency: string;
effectiveFrom: string;
effectiveUntil: string | null;
createdAt: string;
}
export const TENANT_SUBSCRIPTION_STATUS_LABELS: Record<string, string> = {
TRIALING: "Em trial",
ACTIVE: "Ativa",
PAST_DUE: "Inadimplente",
CANCELED: "Cancelada",
};
export interface TenantSubscription {
id: string;
tenantId: string;
planVersionId: string;
status: string;
startedAt: string;
endsAt: string | null;
billingCycleAnchor: number;
currency: string;
planVersion: PlanVersion;
}

View File

@@ -83,6 +83,22 @@ export interface PlatformHealth {
checkedAt: string;
}
export interface QuotaItem {
key: string;
label: string;
used: number;
max: number | null;
ratio: number | null;
}
export interface TenantQuotas {
tenantId: string;
legalName: string;
planName: string;
status: string;
items: QuotaItem[];
}
export const PLAN_LIMIT_FIELDS: { key: keyof Plan; label: string }[] = [
{ key: "maxExtensions", label: "Ramais" },
{ key: "maxAgents", label: "Agentes" },