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:
35
TODO.md
35
TODO.md
@@ -1556,6 +1556,41 @@ Usuários (agente.md secao 169)
|
|||||||
Acme (2 dias-tronco já ledgerados, resto zerado — nenhuma chamada
|
Acme (2 dias-tronco já ledgerados, resto zerado — nenhuma chamada
|
||||||
rodou ainda neste tenant), tela renderizando os mesmos números
|
rodou ainda neste tenant), tela renderizando os mesmos números
|
||||||
|
|
||||||
|
## PHASE 43 — Platform > Clientes > Assinaturas/Quotas (agente.md secao
|
||||||
|
126-127, 169) + achado real no dashboard de plataforma
|
||||||
|
- [x] achado real (não relacionado às telas novas, achado revisando
|
||||||
|
`PlatformOverviewController` antes de escrever a versão platform-wide
|
||||||
|
de `/reports/consumo`): `aiUsageThisMonth` e `recordingStorageBytes`
|
||||||
|
no dashboard "Visão Geral" SEMPRE devolviam zero/vazio, não importa
|
||||||
|
quanto uso real existisse — `ai_usage_records`/`recordings` têm
|
||||||
|
FORCE RLS (secao 32) e o código rodava `prisma.aIUsageRecord.groupBy`/
|
||||||
|
`prisma.recording.aggregate` direto, sem nenhum `app.current_tenant_id`
|
||||||
|
setado, então a policy nega tudo silenciosamente (0 linhas, sem
|
||||||
|
erro). Mesma classe de bug já corrigida 2x antes nesta sessão
|
||||||
|
(`TenantsController.list`, `UsersController.remove`). Corrigido com
|
||||||
|
o mesmo padrão (loop `withTenantContext` por tenant, soma no
|
||||||
|
código) — confirmado inserindo um `AIUsageRecord` de teste direto no
|
||||||
|
Postgres, vendo o número aparecer no endpoint, e removendo o teste
|
||||||
|
depois
|
||||||
|
- [x] `GET /billing/subscriptions` e `POST /billing/plan-versions` já
|
||||||
|
existiam desde a fase Billing (PHASE 22) sem nenhuma tela — só
|
||||||
|
faltava o frontend. Tela `/platform/clientes/assinaturas`: escolher
|
||||||
|
tenant, ver histórico de assinaturas (versão/preço/vigência/ciclo/
|
||||||
|
status), criar uma nova assinatura reaproveitando uma versão de
|
||||||
|
preço existente OU criando uma nova na mesma ação (dois preços
|
||||||
|
nunca sobrescritos, sempre uma versão nova)
|
||||||
|
- [x] `GET /platform/quotas` (novo) — uso vs. limite do plano em TODOS os
|
||||||
|
tenants (ramais/agentes/troncos/filas/campanhas/chamadas-mês/
|
||||||
|
armazenamento), pra achar quem está perto de estourar sem abrir
|
||||||
|
tenant por tenant. Tela `/platform/clientes/quotas` destaca em
|
||||||
|
amarelo (>=80%) e vermelho (>=100%), nunca conta "sem limite" como
|
||||||
|
estourado
|
||||||
|
- [x] Testado ponta a ponta: fluxo completo de criar assinatura via UI
|
||||||
|
pro tenant Beta Corp (nova versão de preço R$499,90 + assinatura
|
||||||
|
com ciclo dia 15, confirmado na tela e no banco), Quotas mostrando
|
||||||
|
os números reais e corretos dos dois tenants de teste (Acme com
|
||||||
|
50% de troncos usados, Beta Corp com zero)
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
## Riscos conhecidos
|
## Riscos conhecidos
|
||||||
|
|||||||
@@ -1,5 +1,5 @@
|
|||||||
import { Controller, ForbiddenException, Get, UseGuards } from "@nestjs/common";
|
import { Controller, ForbiddenException, Get, UseGuards } from "@nestjs/common";
|
||||||
import { getPrismaClient } from "@b2bcall/database";
|
import { getPrismaClient, withTenantContext } from "@b2bcall/database";
|
||||||
import { isPlatformUser, type AccessTokenClaims } from "@b2bcall/auth";
|
import { isPlatformUser, type AccessTokenClaims } from "@b2bcall/auth";
|
||||||
import { JwtAuthGuard } from "../common/guards/jwt-auth.guard";
|
import { JwtAuthGuard } from "../common/guards/jwt-auth.guard";
|
||||||
import { PermissionGuard } from "../common/guards/permission.guard";
|
import { PermissionGuard } from "../common/guards/permission.guard";
|
||||||
@@ -28,32 +28,46 @@ export class PlatformOverviewController {
|
|||||||
todayStart.setUTCHours(0, 0, 0, 0);
|
todayStart.setUTCHours(0, 0, 0, 0);
|
||||||
const monthStart = new Date(Date.UTC(new Date().getUTCFullYear(), new Date().getUTCMonth(), 1));
|
const monthStart = new Date(Date.UTC(new Date().getUTCFullYear(), new Date().getUTCMonth(), 1));
|
||||||
|
|
||||||
const [
|
const [tenantsActive, tenantsTotal, extensionsTotal, agentsTotal, callsCurrent, callsToday, cpsCapacity] =
|
||||||
tenantsActive,
|
await Promise.all([
|
||||||
tenantsTotal,
|
prisma.tenant.count({ where: { status: "ACTIVE", deletedAt: null } }),
|
||||||
extensionsTotal,
|
prisma.tenant.count({ where: { deletedAt: null } }),
|
||||||
agentsTotal,
|
prisma.extension.count({ where: { deletedAt: null } }),
|
||||||
callsCurrent,
|
prisma.agent.count({ where: { deletedAt: null } }),
|
||||||
callsToday,
|
prisma.call.count({ where: { endAt: null } }),
|
||||||
cpsCapacity,
|
prisma.call.count({ where: { createdAt: { gte: todayStart } } }),
|
||||||
aiUsageThisMonth,
|
prisma.plan.aggregate({ _sum: { maxCps: true } }),
|
||||||
recordingBytesAgg,
|
]);
|
||||||
] = await Promise.all([
|
|
||||||
prisma.tenant.count({ where: { status: "ACTIVE", deletedAt: null } }),
|
// `ai_usage_records`/`recordings` têm FORCE RLS (secao 32) — as duas
|
||||||
prisma.tenant.count({ where: { deletedAt: null } }),
|
// agregações acima (achado real, corrigido aqui) rodavam direto no
|
||||||
prisma.extension.count({ where: { deletedAt: null } }),
|
// Prisma sem `app.current_tenant_id` nenhum setado, então SEMPRE
|
||||||
prisma.agent.count({ where: { deletedAt: null } }),
|
// devolviam 0 linhas (zero silencioso, sem erro nenhum), nunca o
|
||||||
prisma.call.count({ where: { endAt: null } }),
|
// número real, não importa quanto uso existisse nos tenants. Mesma
|
||||||
prisma.call.count({ where: { createdAt: { gte: todayStart } } }),
|
// classe de bug já corrigida em `TenantsController.list` — só um
|
||||||
prisma.plan.aggregate({ _sum: { maxCps: true } }),
|
// loop `withTenantContext` por tenant enxerga as linhas de verdade.
|
||||||
prisma.aIUsageRecord.groupBy({
|
const activeTenantIds = await prisma.tenant.findMany({ where: { deletedAt: null }, select: { id: true } });
|
||||||
by: ["type"],
|
const [aiUsagePerTenant, recordingBytesPerTenant] = await Promise.all([
|
||||||
where: { occurredAt: { gte: monthStart } },
|
Promise.all(
|
||||||
_sum: { quantity: true },
|
activeTenantIds.map((t) =>
|
||||||
}),
|
withTenantContext(prisma, t.id, (tx) =>
|
||||||
prisma.recording.aggregate({ _sum: { sizeBytes: true } }),
|
tx.aIUsageRecord.groupBy({ by: ["type"], where: { tenantId: t.id, occurredAt: { gte: monthStart } }, _sum: { quantity: true } }),
|
||||||
|
),
|
||||||
|
),
|
||||||
|
),
|
||||||
|
Promise.all(
|
||||||
|
activeTenantIds.map((t) =>
|
||||||
|
withTenantContext(prisma, t.id, (tx) => tx.recording.aggregate({ where: { tenantId: t.id }, _sum: { sizeBytes: true } })),
|
||||||
|
),
|
||||||
|
),
|
||||||
]);
|
]);
|
||||||
|
|
||||||
|
const aiUsageThisMonth: Record<string, number> = {};
|
||||||
|
for (const rows of aiUsagePerTenant) {
|
||||||
|
for (const row of rows) aiUsageThisMonth[row.type] = (aiUsageThisMonth[row.type] ?? 0) + (row._sum.quantity ?? 0);
|
||||||
|
}
|
||||||
|
const recordingStorageBytes = recordingBytesPerTenant.reduce((sum, agg) => sum + Number(agg._sum.sizeBytes ?? 0n), 0);
|
||||||
|
|
||||||
return {
|
return {
|
||||||
tenantsActive,
|
tenantsActive,
|
||||||
tenantsTotal,
|
tenantsTotal,
|
||||||
@@ -70,10 +84,8 @@ export class PlatformOverviewController {
|
|||||||
// token bucket do Redis do predictive-dialer, apps/api nao le de
|
// token bucket do Redis do predictive-dialer, apps/api nao le de
|
||||||
// la ainda).
|
// la ainda).
|
||||||
cpsCapacityConfigured: cpsCapacity._sum.maxCps ?? null,
|
cpsCapacityConfigured: cpsCapacity._sum.maxCps ?? null,
|
||||||
aiUsageThisMonth: Object.fromEntries(
|
aiUsageThisMonth,
|
||||||
aiUsageThisMonth.map((row) => [row.type, row._sum.quantity ?? 0]),
|
recordingStorageBytes,
|
||||||
),
|
|
||||||
recordingStorageBytes: Number(recordingBytesAgg._sum.sizeBytes ?? 0n),
|
|
||||||
// Precisa de BillingPeriod/BillingStatement fechados de verdade
|
// Precisa de BillingPeriod/BillingStatement fechados de verdade
|
||||||
// (fase Billing, em construcao) — nenhum periodo foi fechado ainda
|
// (fase Billing, em construcao) — nenhum periodo foi fechado ainda
|
||||||
// nesta lab, entao nao ha numero real pra mostrar. null e' honesto,
|
// nesta lab, entao nao ha numero real pra mostrar. null e' honesto,
|
||||||
|
|||||||
73
apps/api/src/platform/platform-quotas.controller.ts
Normal file
73
apps/api/src/platform/platform-quotas.controller.ts
Normal file
@@ -0,0 +1,73 @@
|
|||||||
|
import { Controller, ForbiddenException, Get, UseGuards } from "@nestjs/common";
|
||||||
|
import { getPrismaClient, withTenantContext } from "@b2bcall/database";
|
||||||
|
import { isPlatformUser, type AccessTokenClaims } from "@b2bcall/auth";
|
||||||
|
import { JwtAuthGuard } from "../common/guards/jwt-auth.guard";
|
||||||
|
import { PermissionGuard } from "../common/guards/permission.guard";
|
||||||
|
import { RequirePermission } from "../common/decorators/require-permission.decorator";
|
||||||
|
import { CurrentUser } from "../common/decorators/current-user.decorator";
|
||||||
|
|
||||||
|
/**
|
||||||
|
* "Clientes > Quotas" (agente.md secao 169) — uso vs. limite do plano em
|
||||||
|
* TODOS os tenants, pra platform admin achar quem está perto de estourar
|
||||||
|
* sem precisar abrir um por um. Mesmo cálculo de `/reports/consumo`
|
||||||
|
* (tenant), só que looping por tenant (RLS, secao 32) em vez de um só.
|
||||||
|
*/
|
||||||
|
@UseGuards(JwtAuthGuard, PermissionGuard)
|
||||||
|
@Controller("platform/quotas")
|
||||||
|
export class PlatformQuotasController {
|
||||||
|
@RequirePermission("tenants.view")
|
||||||
|
@Get()
|
||||||
|
async list(@CurrentUser() user: AccessTokenClaims): Promise<Record<string, unknown>[]> {
|
||||||
|
if (!(await isPlatformUser(user.sub))) {
|
||||||
|
throw new ForbiddenException("So' um usuario com role de plataforma pode ver quotas de todos os tenants");
|
||||||
|
}
|
||||||
|
const prisma = getPrismaClient();
|
||||||
|
const now = new Date();
|
||||||
|
const monthStart = new Date(Date.UTC(now.getUTCFullYear(), now.getUTCMonth(), 1));
|
||||||
|
|
||||||
|
const tenants = await prisma.tenant.findMany({
|
||||||
|
where: { deletedAt: null },
|
||||||
|
include: { plan: true },
|
||||||
|
orderBy: { legalName: "asc" },
|
||||||
|
});
|
||||||
|
|
||||||
|
return Promise.all(
|
||||||
|
tenants.map(async (tenant) => {
|
||||||
|
const [callCountAgg, recordingAgg, extensionCount, agentCount, trunkCount, queueCount, campaignCount] =
|
||||||
|
await withTenantContext(prisma, tenant.id, (tx) =>
|
||||||
|
Promise.all([
|
||||||
|
tx.usageEvent.aggregate({ where: { tenantId: tenant.id, meter: "CALL_COUNT", occurredAt: { gte: monthStart } }, _sum: { quantity: true } }),
|
||||||
|
tx.recording.aggregate({ where: { tenantId: tenant.id }, _sum: { sizeBytes: true } }),
|
||||||
|
tx.extension.count({ where: { tenantId: tenant.id, deletedAt: null } }),
|
||||||
|
tx.agent.count({ where: { tenantId: tenant.id, deletedAt: null } }),
|
||||||
|
tx.trunk.count({ where: { tenantId: tenant.id, deletedAt: null } }),
|
||||||
|
tx.queue.count({ where: { tenantId: tenant.id, deletedAt: null } }),
|
||||||
|
tx.campaign.count({ where: { tenantId: tenant.id, deletedAt: null } }),
|
||||||
|
]),
|
||||||
|
);
|
||||||
|
|
||||||
|
const callCount = callCountAgg._sum.quantity ?? 0;
|
||||||
|
const recordingBytes = Number(recordingAgg._sum.sizeBytes ?? 0n);
|
||||||
|
const recordingGb = recordingBytes / 1024 ** 3;
|
||||||
|
|
||||||
|
const ratio = (used: number, max: number | null) => (max ? used / max : null);
|
||||||
|
|
||||||
|
return {
|
||||||
|
tenantId: tenant.id,
|
||||||
|
legalName: tenant.legalName,
|
||||||
|
planName: tenant.plan.name,
|
||||||
|
status: tenant.status,
|
||||||
|
items: [
|
||||||
|
{ key: "extensions", label: "Ramais", used: extensionCount, max: tenant.plan.maxExtensions, ratio: ratio(extensionCount, tenant.plan.maxExtensions) },
|
||||||
|
{ key: "agents", label: "Agentes", used: agentCount, max: tenant.plan.maxAgents, ratio: ratio(agentCount, tenant.plan.maxAgents) },
|
||||||
|
{ key: "trunks", label: "Troncos", used: trunkCount, max: tenant.plan.maxTrunks, ratio: ratio(trunkCount, tenant.plan.maxTrunks) },
|
||||||
|
{ key: "queues", label: "Filas", used: queueCount, max: tenant.plan.maxQueues, ratio: ratio(queueCount, tenant.plan.maxQueues) },
|
||||||
|
{ key: "campaigns", label: "Campanhas", used: campaignCount, max: tenant.plan.maxCampaigns, ratio: ratio(campaignCount, tenant.plan.maxCampaigns) },
|
||||||
|
{ key: "monthlyCalls", label: "Chamadas/mês", used: callCount, max: tenant.plan.maxMonthlyCalls, ratio: ratio(callCount, tenant.plan.maxMonthlyCalls) },
|
||||||
|
{ key: "recordingGb", label: "Armazenamento (GB)", used: Number(recordingGb.toFixed(3)), max: tenant.plan.maxRecordingStorageGb, ratio: ratio(recordingGb, tenant.plan.maxRecordingStorageGb) },
|
||||||
|
],
|
||||||
|
};
|
||||||
|
}),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -4,6 +4,7 @@ import { PlatformUsersController } from "./platform-users.controller";
|
|||||||
import { PlatformAuditController } from "./platform-audit.controller";
|
import { PlatformAuditController } from "./platform-audit.controller";
|
||||||
import { PlatformHealthController } from "./platform-health.controller";
|
import { PlatformHealthController } from "./platform-health.controller";
|
||||||
import { PlatformRolesController } from "./platform-roles.controller";
|
import { PlatformRolesController } from "./platform-roles.controller";
|
||||||
|
import { PlatformQuotasController } from "./platform-quotas.controller";
|
||||||
|
|
||||||
@Module({
|
@Module({
|
||||||
controllers: [
|
controllers: [
|
||||||
@@ -12,6 +13,7 @@ import { PlatformRolesController } from "./platform-roles.controller";
|
|||||||
PlatformAuditController,
|
PlatformAuditController,
|
||||||
PlatformHealthController,
|
PlatformHealthController,
|
||||||
PlatformRolesController,
|
PlatformRolesController,
|
||||||
|
PlatformQuotasController,
|
||||||
],
|
],
|
||||||
})
|
})
|
||||||
export class PlatformModule {}
|
export class PlatformModule {}
|
||||||
|
|||||||
BIN
apps/frontend/.impeccable/review/assinaturas-created-desktop.png
Normal file
BIN
apps/frontend/.impeccable/review/assinaturas-created-desktop.png
Normal file
Binary file not shown.
|
After Width: | Height: | Size: 96 KiB |
BIN
apps/frontend/.impeccable/review/assinaturas-empty-desktop.png
Normal file
BIN
apps/frontend/.impeccable/review/assinaturas-empty-desktop.png
Normal file
Binary file not shown.
|
After Width: | Height: | Size: 78 KiB |
BIN
apps/frontend/.impeccable/review/assinaturas-form-desktop.png
Normal file
BIN
apps/frontend/.impeccable/review/assinaturas-form-desktop.png
Normal file
Binary file not shown.
|
After Width: | Height: | Size: 107 KiB |
Binary file not shown.
|
After Width: | Height: | Size: 84 KiB |
BIN
apps/frontend/.impeccable/review/quotas-desktop.png
Normal file
BIN
apps/frontend/.impeccable/review/quotas-desktop.png
Normal file
Binary file not shown.
|
After Width: | Height: | Size: 101 KiB |
@@ -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) };
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -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>
|
||||||
|
);
|
||||||
|
}
|
||||||
31
apps/frontend/src/app/platform/clientes/assinaturas/page.tsx
Normal file
31
apps/frontend/src/app/platform/clientes/assinaturas/page.tsx
Normal 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}
|
||||||
|
/>
|
||||||
|
);
|
||||||
|
}
|
||||||
10
apps/frontend/src/app/platform/clientes/quotas/page.tsx
Normal file
10
apps/frontend/src/app/platform/clientes/quotas/page.tsx
Normal 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} />;
|
||||||
|
}
|
||||||
@@ -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>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -30,8 +30,16 @@ export const PLATFORM_NAV: NavSection[] = [
|
|||||||
href: "/platform/clientes/planos",
|
href: "/platform/clientes/planos",
|
||||||
description: "Catálogo de limites e recursos por plano",
|
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",
|
||||||
|
},
|
||||||
],
|
],
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
|
|||||||
@@ -92,3 +92,33 @@ export interface BillingStatement {
|
|||||||
billingPeriod: BillingPeriod;
|
billingPeriod: BillingPeriod;
|
||||||
items?: BillingStatementItem[];
|
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;
|
||||||
|
}
|
||||||
|
|||||||
@@ -83,6 +83,22 @@ export interface PlatformHealth {
|
|||||||
checkedAt: string;
|
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 }[] = [
|
export const PLAN_LIMIT_FIELDS: { key: keyof Plan; label: string }[] = [
|
||||||
{ key: "maxExtensions", label: "Ramais" },
|
{ key: "maxExtensions", label: "Ramais" },
|
||||||
{ key: "maxAgents", label: "Agentes" },
|
{ key: "maxAgents", label: "Agentes" },
|
||||||
|
|||||||
Reference in New Issue
Block a user