feat(platform): Billing > Fechamentos e Relatórios
GET /billing/periods e /billing/statements só serviam o próprio tenant do JWT — sem uso pra um platform admin escolhendo um tenant arbitrário. Adicionado GET .../by-tenant/:tenantId nos dois (mesmo padrão já usado em Subscriptions), e GET /billing/statements/:id ganhou um ?tenantId= opcional só aceito de quem tem role de plataforma. Frontend: /platform/billing/fechamentos (fecha/reabre período por tenant, seletor via querystring pra não duplicar rota) e /relatorios (statements por tenant, detalhe com itens por categoria). Bug real achado testando o fluxo: fechar um período de 01/08 a 31/08 mostrava "31 de jul." a "30 de ago." — meia-noite UTC de uma data-only vira o dia anterior no timezone local do servidor. Corrigido com formatDateUTC novo, usado só em fronteiras de calendário (não em timestamps de verdade, que continuam com formatDate local). Testado ponta a ponta contra a API real: período fechado, statement gerado (R$ 0,00 honesto — Acme sem assinatura/price book ainda), detalhe correto. Smoke test nas 19 telas do tenant + 8 telas platform, todas 200. Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01BFaBaBSQGhyXGEgtTYZGV8
This commit is contained in:
47
TODO.md
47
TODO.md
@@ -1287,6 +1287,53 @@ Saúde (agente.md secao 148, 150-151, 168, 187)
|
|||||||
platform-wide (ver GLOBAL, agregar uso/custo entre tenants) não foi
|
platform-wide (ver GLOBAL, agregar uso/custo entre tenants) não foi
|
||||||
construída ainda
|
construída ainda
|
||||||
|
|
||||||
|
## PHASE 35 — Platform: Billing > Fechamentos e Relatórios (agente.md
|
||||||
|
secao 134-139, 168)
|
||||||
|
- [x] **Lacuna de backend fechada primeiro**: `GET /billing/periods` e
|
||||||
|
`GET /billing/statements` só serviam o próprio tenant do JWT — sem
|
||||||
|
uso pra um platform admin escolhendo um tenant arbitrário (a mesma
|
||||||
|
exceção já resolvida em Subscriptions na PHASE 22, só não tinha
|
||||||
|
sido replicada aqui ainda). Adicionado `GET /billing/periods/by-
|
||||||
|
tenant/:tenantId` e `GET /billing/statements/by-tenant/:tenantId`
|
||||||
|
(mesmo padrão), e `GET /billing/statements/:id` ganhou um
|
||||||
|
`?tenantId=` opcional só aceito de quem tem role de plataforma
|
||||||
|
(nunca confiado sem essa checagem, secao 31).
|
||||||
|
- [x] Frontend: `/platform/billing/fechamentos` (seletor de tenant via
|
||||||
|
`?tenantId=` na própria URL — sem isso, 4 itens de menu
|
||||||
|
apontariam pro mesmo lugar; um seletor dentro da página resolve sem
|
||||||
|
duplicar rota) — lista períodos, fecha um novo (intervalo de
|
||||||
|
datas), reabre um fechado com motivo obrigatório.
|
||||||
|
`/platform/billing/relatorios` — lista statements por tenant,
|
||||||
|
detalhe com itens por categoria + subtotal/ajustes/total. Nunca
|
||||||
|
chamado de "nota fiscal" na UI (PRODUCT.md).
|
||||||
|
- [x] **Bug real, achado testando o fluxo completo**: fechar um período
|
||||||
|
de 01/08 a 31/08 mostrava "31 de jul." a "30 de ago." na tela —
|
||||||
|
meia-noite UTC de uma data-only vira o dia anterior quando
|
||||||
|
formatada no timezone local do servidor (America/Sao_Paulo,
|
||||||
|
UTC-3). `formatDate` (local) está certo pra timestamps de verdade
|
||||||
|
(criado em, gerado em), mas errado pra fronteiras de calendário.
|
||||||
|
Corrigido com `formatDateUTC` novo em `lib/format.ts`, usado só
|
||||||
|
onde o valor é uma fronteira de período, não um instante.
|
||||||
|
- Achado incidental durante a investigação (não um bug de produto):
|
||||||
|
um 404 na tela de detalhe do statement era eu mesmo esquecendo de
|
||||||
|
reiniciar `apps/api` depois de editar o `get()` do controller —
|
||||||
|
confirmado isolando com um cliente Prisma direto (achou a linha
|
||||||
|
sem problema) antes de suspeitar da camada HTTP.
|
||||||
|
- [x] Testado ponta a ponta contra a API real: fechado um período de
|
||||||
|
agosto/2026 pro tenant Acme (sem assinatura/price book atribuído
|
||||||
|
ainda, então R$ 0,00 — honesto, não um erro), aparece em
|
||||||
|
Fechamentos com as datas certas, gera um statement visível em
|
||||||
|
Relatórios, detalhe mostra 0 itens/subtotal/total corretos. Smoke
|
||||||
|
test de regressão nas 19 telas do tenant + 8 telas platform, todas
|
||||||
|
200.
|
||||||
|
- [ ] "Billing > Consumo" continua "em breve" — distinção de escopo com
|
||||||
|
"Relatórios" nunca ficou 100% clara na especificação (secao 138 vs
|
||||||
|
135); vai depender de decidir se é uma view de uso corrente
|
||||||
|
(período aberto) ou se sobrepõe com o dashboard de plataforma
|
||||||
|
- [ ] Sem exclusão de statement nem edição manual de item — statements
|
||||||
|
são gerados, nunca editados à mão (consistente com "fechamento
|
||||||
|
imutável", secao 137)
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
## Riscos conhecidos
|
## Riscos conhecidos
|
||||||
|
|||||||
@@ -54,4 +54,19 @@ export class BillingPeriodsController {
|
|||||||
tx.billingPeriod.findMany({ where: { tenantId }, orderBy: { periodStart: "desc" } }),
|
tx.billingPeriod.findMany({ where: { tenantId }, orderBy: { periodStart: "desc" } }),
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/** Platform admin olhando um tenant arbitrário (secao 168, "Billing >
|
||||||
|
* Fechamentos") — `GET /billing/periods` acima só serve o próprio
|
||||||
|
* tenant do JWT, que um platform admin não tem. */
|
||||||
|
@RequirePermission("billing.manage")
|
||||||
|
@Get("by-tenant/:tenantId")
|
||||||
|
async listByTenant(@CurrentUser() user: AccessTokenClaims, @Param("tenantId") tenantId: string) {
|
||||||
|
if (!(await isPlatformUser(user.sub))) {
|
||||||
|
throw new ForbiddenException("So' um usuario com role de plataforma pode ver fechamentos de outro tenant");
|
||||||
|
}
|
||||||
|
const prisma = getPrismaClient();
|
||||||
|
return withTenantContext(prisma, tenantId, (tx) =>
|
||||||
|
tx.billingPeriod.findMany({ where: { tenantId }, orderBy: { periodStart: "desc" } }),
|
||||||
|
);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,6 +1,6 @@
|
|||||||
import { Controller, Get, NotFoundException, Param, UseGuards } from "@nestjs/common";
|
import { Controller, ForbiddenException, Get, NotFoundException, Param, Query, UseGuards } from "@nestjs/common";
|
||||||
import { getPrismaClient, withTenantContext } from "@b2bcall/database";
|
import { getPrismaClient, withTenantContext } from "@b2bcall/database";
|
||||||
import 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";
|
||||||
import { RequirePermission } from "../common/decorators/require-permission.decorator";
|
import { RequirePermission } from "../common/decorators/require-permission.decorator";
|
||||||
@@ -29,10 +29,39 @@ export class BillingStatementsController {
|
|||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/** Platform admin olhando um tenant arbitrário (secao 168, "Billing >
|
||||||
|
* Relatórios") — `GET /billing/statements` acima só serve o próprio
|
||||||
|
* tenant do JWT, que um platform admin não tem. */
|
||||||
|
@RequirePermission("billing.manage")
|
||||||
|
@Get("by-tenant/:tenantId")
|
||||||
|
async listByTenant(@CurrentUser() user: AccessTokenClaims, @Param("tenantId") tenantId: string) {
|
||||||
|
if (!(await isPlatformUser(user.sub))) {
|
||||||
|
throw new ForbiddenException("So' um usuario com role de plataforma pode ver relatorios de outro tenant");
|
||||||
|
}
|
||||||
|
const prisma = getPrismaClient();
|
||||||
|
return withTenantContext(prisma, tenantId, (tx) =>
|
||||||
|
tx.billingStatement.findMany({
|
||||||
|
where: { tenantId },
|
||||||
|
include: { billingPeriod: true },
|
||||||
|
orderBy: { generatedAt: "desc" },
|
||||||
|
}),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
/** `tenantId` na query só é aceito de quem tem role de plataforma (secao
|
||||||
|
* 31: nunca confiar em tenant vindo do client sem checar) — um tenant
|
||||||
|
* admin comum sempre olha só o próprio, do JWT, mesmo que tente mandar
|
||||||
|
* outro. */
|
||||||
@RequirePermission("billing.view")
|
@RequirePermission("billing.view")
|
||||||
@Get(":id")
|
@Get(":id")
|
||||||
async get(@CurrentUser() user: AccessTokenClaims, @Param("id") id: string) {
|
async get(@CurrentUser() user: AccessTokenClaims, @Param("id") id: string, @Query("tenantId") queryTenantId?: string) {
|
||||||
const tenantId = user.tenantId!;
|
let tenantId = user.tenantId!;
|
||||||
|
if (queryTenantId && queryTenantId !== tenantId) {
|
||||||
|
if (!(await isPlatformUser(user.sub))) {
|
||||||
|
throw new ForbiddenException("So' um usuario com role de plataforma pode ver statement de outro tenant");
|
||||||
|
}
|
||||||
|
tenantId = queryTenantId;
|
||||||
|
}
|
||||||
const prisma = getPrismaClient();
|
const prisma = getPrismaClient();
|
||||||
const statement = await withTenantContext(prisma, tenantId, (tx) =>
|
const statement = await withTenantContext(prisma, tenantId, (tx) =>
|
||||||
tx.billingStatement.findFirst({
|
tx.billingStatement.findFirst({
|
||||||
|
|||||||
Binary file not shown.
|
After Width: | Height: | Size: 75 KiB |
Binary file not shown.
|
After Width: | Height: | Size: 85 KiB |
Binary file not shown.
|
After Width: | Height: | Size: 79 KiB |
Binary file not shown.
|
After Width: | Height: | Size: 86 KiB |
Binary file not shown.
|
After Width: | Height: | Size: 78 KiB |
@@ -0,0 +1,51 @@
|
|||||||
|
"use server";
|
||||||
|
|
||||||
|
import { revalidatePath } from "next/cache";
|
||||||
|
import { requireSession } from "@/lib/session";
|
||||||
|
import { apiFetch, ApiError } from "@/lib/api";
|
||||||
|
import type { BillingPeriod } from "@/lib/billing-types";
|
||||||
|
|
||||||
|
function extractErrorMessage(err: unknown): string {
|
||||||
|
if (err instanceof ApiError) {
|
||||||
|
try {
|
||||||
|
const parsed = JSON.parse(err.message);
|
||||||
|
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 async function closePeriod(
|
||||||
|
tenantId: string,
|
||||||
|
periodStart: string,
|
||||||
|
periodEnd: string,
|
||||||
|
): Promise<{ ok: true; period: BillingPeriod } | { ok: false; error: string }> {
|
||||||
|
const session = await requireSession();
|
||||||
|
try {
|
||||||
|
const period = await apiFetch<BillingPeriod>("/billing/periods/close", session.accessToken, {
|
||||||
|
method: "POST",
|
||||||
|
body: JSON.stringify({ tenantId, periodStart, periodEnd }),
|
||||||
|
});
|
||||||
|
revalidatePath("/platform/billing/fechamentos");
|
||||||
|
return { ok: true, period };
|
||||||
|
} catch (err) {
|
||||||
|
return { ok: false, error: extractErrorMessage(err) };
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function reopenPeriod(periodId: string, tenantId: string, reason: string): Promise<{ ok: true } | { ok: false; error: string }> {
|
||||||
|
const session = await requireSession();
|
||||||
|
try {
|
||||||
|
await apiFetch<void>(`/billing/periods/${periodId}/reopen`, session.accessToken, {
|
||||||
|
method: "POST",
|
||||||
|
body: JSON.stringify({ tenantId, reason }),
|
||||||
|
});
|
||||||
|
revalidatePath("/platform/billing/fechamentos");
|
||||||
|
return { ok: true };
|
||||||
|
} catch (err) {
|
||||||
|
return { ok: false, error: extractErrorMessage(err) };
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,223 @@
|
|||||||
|
"use client";
|
||||||
|
|
||||||
|
import { useState, useTransition } from "react";
|
||||||
|
import { useRouter } from "next/navigation";
|
||||||
|
import { Lock, LockOpen, 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 { formatDate, formatDateUTC } from "@/lib/format";
|
||||||
|
import { BILLING_PERIOD_STATUS_LABELS, type BillingPeriod } from "@/lib/billing-types";
|
||||||
|
import type { Tenant } from "@/lib/platform-types";
|
||||||
|
import { closePeriod, reopenPeriod } from "./actions";
|
||||||
|
|
||||||
|
const STATUS_TONE: Record<string, "accent" | "neutral"> = {
|
||||||
|
OPEN: "neutral",
|
||||||
|
CALCULATING: "neutral",
|
||||||
|
READY: "neutral",
|
||||||
|
CLOSED: "accent",
|
||||||
|
REOPENED: "neutral",
|
||||||
|
};
|
||||||
|
|
||||||
|
export function FechamentosView({
|
||||||
|
tenants,
|
||||||
|
selectedTenantId,
|
||||||
|
periods,
|
||||||
|
}: {
|
||||||
|
tenants: Tenant[];
|
||||||
|
selectedTenantId: string | null;
|
||||||
|
periods: BillingPeriod[];
|
||||||
|
}) {
|
||||||
|
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">Fechamentos</h1>
|
||||||
|
<p className="mt-1 max-w-2xl text-sm text-muted-foreground">
|
||||||
|
Fechamento de período por tenant (agente.md secao 134-137) — fechar é imutável, só reabrir explícito
|
||||||
|
(com motivo) permite recalcular.
|
||||||
|
</p>
|
||||||
|
</div>
|
||||||
|
{selectedTenantId && (
|
||||||
|
<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" : "Fechar período"}
|
||||||
|
</Button>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<Panel className="p-5">
|
||||||
|
<FieldLabel htmlFor="fc-tenant">Tenant</FieldLabel>
|
||||||
|
<Select
|
||||||
|
id="fc-tenant"
|
||||||
|
value={selectedTenantId ?? ""}
|
||||||
|
onChange={(e) => router.push(e.target.value ? `/platform/billing/fechamentos?tenantId=${e.target.value}` : "/platform/billing/fechamentos")}
|
||||||
|
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>
|
||||||
|
|
||||||
|
{!selectedTenantId ? (
|
||||||
|
<Panel>
|
||||||
|
<EmptyState title="Escolha um tenant" description="Selecione um tenant acima pra ver os períodos de billing dele." />
|
||||||
|
</Panel>
|
||||||
|
) : (
|
||||||
|
<>
|
||||||
|
{showForm && <NewPeriodForm tenantId={selectedTenantId} onDone={() => setShowForm(false)} />}
|
||||||
|
|
||||||
|
<Panel>
|
||||||
|
<PanelHeader title="Períodos" description={`${periods.length} período(s) deste tenant`} />
|
||||||
|
{periods.length === 0 ? (
|
||||||
|
<EmptyState title="Nenhum período fechado ainda" description="Feche o primeiro período pra este tenant." />
|
||||||
|
) : (
|
||||||
|
<Table>
|
||||||
|
<THead>
|
||||||
|
<TR>
|
||||||
|
<TH>Início</TH>
|
||||||
|
<TH>Fim</TH>
|
||||||
|
<TH>Status</TH>
|
||||||
|
<TH>Fechado em</TH>
|
||||||
|
<TH>
|
||||||
|
<span className="sr-only">Ações</span>
|
||||||
|
</TH>
|
||||||
|
</TR>
|
||||||
|
</THead>
|
||||||
|
<TBody>
|
||||||
|
{periods.map((p) => (
|
||||||
|
<PeriodRow key={p.id} period={p} tenantId={selectedTenantId} />
|
||||||
|
))}
|
||||||
|
</TBody>
|
||||||
|
</Table>
|
||||||
|
)}
|
||||||
|
</Panel>
|
||||||
|
</>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
function NewPeriodForm({ tenantId, onDone }: { tenantId: string; onDone: () => void }) {
|
||||||
|
const router = useRouter();
|
||||||
|
const [periodStart, setPeriodStart] = useState("");
|
||||||
|
const [periodEnd, setPeriodEnd] = useState("");
|
||||||
|
const [error, setError] = useState<string | null>(null);
|
||||||
|
const [pending, startTransition] = useTransition();
|
||||||
|
|
||||||
|
function onSubmit(e: React.FormEvent) {
|
||||||
|
e.preventDefault();
|
||||||
|
setError(null);
|
||||||
|
if (!periodStart || !periodEnd) {
|
||||||
|
setError("Informe início e fim do período.");
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
startTransition(async () => {
|
||||||
|
const result = await closePeriod(tenantId, new Date(periodStart).toISOString(), new Date(periodEnd).toISOString());
|
||||||
|
if (!result.ok) {
|
||||||
|
setError(result.error);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
onDone();
|
||||||
|
router.refresh();
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
return (
|
||||||
|
<Panel className="p-5">
|
||||||
|
<form onSubmit={onSubmit} noValidate className="space-y-4">
|
||||||
|
<div className="grid grid-cols-1 gap-4 sm:grid-cols-2">
|
||||||
|
<div>
|
||||||
|
<FieldLabel htmlFor="fc-start">Início do período</FieldLabel>
|
||||||
|
<Input id="fc-start" type="date" value={periodStart} onChange={(e) => setPeriodStart(e.target.value)} disabled={pending} />
|
||||||
|
</div>
|
||||||
|
<div>
|
||||||
|
<FieldLabel htmlFor="fc-end">Fim do período</FieldLabel>
|
||||||
|
<Input id="fc-end" type="date" value={periodEnd} onChange={(e) => setPeriodEnd(e.target.value)} disabled={pending} />
|
||||||
|
</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 ? "Fechando…" : "Fechar período"}
|
||||||
|
</Button>
|
||||||
|
</div>
|
||||||
|
</form>
|
||||||
|
</Panel>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
function PeriodRow({ period, tenantId }: { period: BillingPeriod; tenantId: string }) {
|
||||||
|
const router = useRouter();
|
||||||
|
const [reopening, setReopening] = useState(false);
|
||||||
|
const [reason, setReason] = useState("");
|
||||||
|
const [error, setError] = useState<string | null>(null);
|
||||||
|
const [pending, startTransition] = useTransition();
|
||||||
|
|
||||||
|
function onReopen() {
|
||||||
|
if (!reopening) {
|
||||||
|
setReopening(true);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
if (reason.trim().length < 3) {
|
||||||
|
setError("Motivo precisa de pelo menos 3 caracteres.");
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
setError(null);
|
||||||
|
startTransition(async () => {
|
||||||
|
const result = await reopenPeriod(period.id, tenantId, reason.trim());
|
||||||
|
if (!result.ok) {
|
||||||
|
setError(result.error);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
setReopening(false);
|
||||||
|
router.refresh();
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
const canReopen = period.status === "CLOSED" || period.status === "REOPENED";
|
||||||
|
|
||||||
|
return (
|
||||||
|
<TR>
|
||||||
|
<TD className="text-muted-foreground">{formatDateUTC(period.periodStart)}</TD>
|
||||||
|
<TD className="text-muted-foreground">{formatDateUTC(period.periodEnd)}</TD>
|
||||||
|
<TD>
|
||||||
|
<Pill tone={STATUS_TONE[period.status]}>{BILLING_PERIOD_STATUS_LABELS[period.status]}</Pill>
|
||||||
|
</TD>
|
||||||
|
<TD className="text-muted-foreground">{period.closedAt ? formatDate(period.closedAt) : "—"}</TD>
|
||||||
|
<TD>
|
||||||
|
{canReopen && (
|
||||||
|
<div className="flex items-center justify-end gap-2">
|
||||||
|
{error && <span className="text-xs text-destructive">{error}</span>}
|
||||||
|
{reopening && (
|
||||||
|
<Input
|
||||||
|
value={reason}
|
||||||
|
onChange={(e) => setReason(e.target.value)}
|
||||||
|
placeholder="Motivo da reabertura"
|
||||||
|
className="h-8 w-48"
|
||||||
|
disabled={pending}
|
||||||
|
/>
|
||||||
|
)}
|
||||||
|
<Button type="button" variant="outline" size="sm" onClick={onReopen} disabled={pending}>
|
||||||
|
{reopening ? <Lock className="h-3.5 w-3.5" aria-hidden /> : <LockOpen className="h-3.5 w-3.5" aria-hidden />}
|
||||||
|
{reopening ? (pending ? "Reabrindo…" : "Confirmar") : "Reabrir"}
|
||||||
|
</Button>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
</TD>
|
||||||
|
</TR>
|
||||||
|
);
|
||||||
|
}
|
||||||
17
apps/frontend/src/app/platform/billing/fechamentos/page.tsx
Normal file
17
apps/frontend/src/app/platform/billing/fechamentos/page.tsx
Normal file
@@ -0,0 +1,17 @@
|
|||||||
|
import { requireSession } from "@/lib/session";
|
||||||
|
import { apiFetch } from "@/lib/api";
|
||||||
|
import type { Tenant } from "@/lib/platform-types";
|
||||||
|
import type { BillingPeriod } from "@/lib/billing-types";
|
||||||
|
import { FechamentosView } from "./fechamentos-view";
|
||||||
|
|
||||||
|
export default async function FechamentosPage({ searchParams }: { searchParams: Promise<{ tenantId?: string }> }) {
|
||||||
|
const { tenantId } = await searchParams;
|
||||||
|
const session = await requireSession();
|
||||||
|
|
||||||
|
const tenants = await apiFetch<Tenant[]>("/tenants", session.accessToken);
|
||||||
|
const periods = tenantId
|
||||||
|
? await apiFetch<BillingPeriod[]>(`/billing/periods/by-tenant/${tenantId}`, session.accessToken)
|
||||||
|
: [];
|
||||||
|
|
||||||
|
return <FechamentosView tenants={tenants} selectedTenantId={tenantId ?? null} periods={periods} />;
|
||||||
|
}
|
||||||
@@ -0,0 +1,26 @@
|
|||||||
|
import { notFound } from "next/navigation";
|
||||||
|
import { requireSession } from "@/lib/session";
|
||||||
|
import { apiFetch, ApiError } from "@/lib/api";
|
||||||
|
import type { BillingStatement } from "@/lib/billing-types";
|
||||||
|
import { StatementDetailView } from "./statement-detail-view";
|
||||||
|
|
||||||
|
export default async function StatementDetailPage({
|
||||||
|
params,
|
||||||
|
searchParams,
|
||||||
|
}: {
|
||||||
|
params: Promise<{ id: string }>;
|
||||||
|
searchParams: Promise<{ tenantId?: string }>;
|
||||||
|
}) {
|
||||||
|
const { id } = await params;
|
||||||
|
const { tenantId } = await searchParams;
|
||||||
|
const session = await requireSession();
|
||||||
|
|
||||||
|
try {
|
||||||
|
const query = tenantId ? `?tenantId=${tenantId}` : "";
|
||||||
|
const statement = await apiFetch<BillingStatement>(`/billing/statements/${id}${query}`, session.accessToken);
|
||||||
|
return <StatementDetailView statement={statement} />;
|
||||||
|
} catch (err) {
|
||||||
|
if (err instanceof ApiError && err.status === 404) notFound();
|
||||||
|
throw err;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,70 @@
|
|||||||
|
import { Receipt } from "lucide-react";
|
||||||
|
import { Panel, PanelHeader } from "@/components/ui/panel";
|
||||||
|
import { Pill } from "@/components/ui/pill";
|
||||||
|
import { TBody, TD, TH, THead, TR, Table } from "@/components/ui/table";
|
||||||
|
import { formatDate, formatDateUTC, formatCurrency } from "@/lib/format";
|
||||||
|
import { BILLING_PERIOD_STATUS_LABELS, BILLING_STATEMENT_CATEGORY_LABELS, type BillingStatement } from "@/lib/billing-types";
|
||||||
|
|
||||||
|
export function StatementDetailView({ statement }: { statement: BillingStatement }) {
|
||||||
|
return (
|
||||||
|
<div className="max-w-3xl space-y-5">
|
||||||
|
<div>
|
||||||
|
<h1 className="flex items-center gap-2 text-lg font-semibold text-foreground">
|
||||||
|
<Receipt className="h-5 w-5 text-muted-foreground" aria-hidden />
|
||||||
|
Statement — {formatDateUTC(statement.billingPeriod.periodStart)} a {formatDateUTC(statement.billingPeriod.periodEnd)}
|
||||||
|
</h1>
|
||||||
|
<p className="mt-1 text-sm text-muted-foreground">
|
||||||
|
Gerado em {formatDate(statement.generatedAt)} — período{" "}
|
||||||
|
<Pill>{BILLING_PERIOD_STATUS_LABELS[statement.billingPeriod.status]}</Pill>
|
||||||
|
</p>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<Panel>
|
||||||
|
<PanelHeader title="Itens" description={`${statement.items?.length ?? 0} item(ns)`} />
|
||||||
|
<Table>
|
||||||
|
<THead>
|
||||||
|
<TR>
|
||||||
|
<TH>Categoria</TH>
|
||||||
|
<TH>Descrição</TH>
|
||||||
|
<TH>Quantidade</TH>
|
||||||
|
<TH>Preço unitário</TH>
|
||||||
|
<TH>Valor</TH>
|
||||||
|
</TR>
|
||||||
|
</THead>
|
||||||
|
<TBody>
|
||||||
|
{(statement.items ?? []).map((item) => (
|
||||||
|
<TR key={item.id}>
|
||||||
|
<TD>
|
||||||
|
<Pill>{BILLING_STATEMENT_CATEGORY_LABELS[item.category] ?? item.category}</Pill>
|
||||||
|
</TD>
|
||||||
|
<TD className="text-muted-foreground">{item.description}</TD>
|
||||||
|
<TD className="font-mono tabular-nums text-muted-foreground">{item.quantity ?? "—"}</TD>
|
||||||
|
<TD className="font-mono tabular-nums text-muted-foreground">
|
||||||
|
{item.unitPrice != null ? formatCurrency(item.unitPrice, statement.currency) : "—"}
|
||||||
|
</TD>
|
||||||
|
<TD className="font-mono tabular-nums text-foreground">{formatCurrency(item.amount, statement.currency)}</TD>
|
||||||
|
</TR>
|
||||||
|
))}
|
||||||
|
</TBody>
|
||||||
|
</Table>
|
||||||
|
</Panel>
|
||||||
|
|
||||||
|
<Panel className="p-5">
|
||||||
|
<dl className="space-y-2 text-sm">
|
||||||
|
<div className="flex items-center justify-between">
|
||||||
|
<dt className="text-muted-foreground">Subtotal</dt>
|
||||||
|
<dd className="font-mono tabular-nums text-foreground">{formatCurrency(statement.subtotal, statement.currency)}</dd>
|
||||||
|
</div>
|
||||||
|
<div className="flex items-center justify-between">
|
||||||
|
<dt className="text-muted-foreground">Ajustes</dt>
|
||||||
|
<dd className="font-mono tabular-nums text-foreground">{formatCurrency(statement.adjustments, statement.currency)}</dd>
|
||||||
|
</div>
|
||||||
|
<div className="flex items-center justify-between border-t border-border pt-2 text-base font-semibold">
|
||||||
|
<dt className="text-foreground">Total</dt>
|
||||||
|
<dd className="font-mono tabular-nums text-foreground">{formatCurrency(statement.total, statement.currency)}</dd>
|
||||||
|
</div>
|
||||||
|
</dl>
|
||||||
|
</Panel>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
17
apps/frontend/src/app/platform/billing/relatorios/page.tsx
Normal file
17
apps/frontend/src/app/platform/billing/relatorios/page.tsx
Normal file
@@ -0,0 +1,17 @@
|
|||||||
|
import { requireSession } from "@/lib/session";
|
||||||
|
import { apiFetch } from "@/lib/api";
|
||||||
|
import type { Tenant } from "@/lib/platform-types";
|
||||||
|
import type { BillingStatement } from "@/lib/billing-types";
|
||||||
|
import { RelatoriosBillingView } from "./relatorios-view";
|
||||||
|
|
||||||
|
export default async function BillingRelatoriosPage({ searchParams }: { searchParams: Promise<{ tenantId?: string }> }) {
|
||||||
|
const { tenantId } = await searchParams;
|
||||||
|
const session = await requireSession();
|
||||||
|
|
||||||
|
const tenants = await apiFetch<Tenant[]>("/tenants", session.accessToken);
|
||||||
|
const statements = tenantId
|
||||||
|
? await apiFetch<BillingStatement[]>(`/billing/statements/by-tenant/${tenantId}`, session.accessToken)
|
||||||
|
: [];
|
||||||
|
|
||||||
|
return <RelatoriosBillingView tenants={tenants} selectedTenantId={tenantId ?? null} statements={statements} />;
|
||||||
|
}
|
||||||
@@ -0,0 +1,97 @@
|
|||||||
|
"use client";
|
||||||
|
|
||||||
|
import Link from "next/link";
|
||||||
|
import { useRouter } from "next/navigation";
|
||||||
|
import { Receipt } from "lucide-react";
|
||||||
|
import { Panel, PanelHeader } from "@/components/ui/panel";
|
||||||
|
import { 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 { formatDate, formatDateUTC, formatCurrency } from "@/lib/format";
|
||||||
|
import { BILLING_PERIOD_STATUS_LABELS, type BillingStatement } from "@/lib/billing-types";
|
||||||
|
import type { Tenant } from "@/lib/platform-types";
|
||||||
|
|
||||||
|
export function RelatoriosBillingView({
|
||||||
|
tenants,
|
||||||
|
selectedTenantId,
|
||||||
|
statements,
|
||||||
|
}: {
|
||||||
|
tenants: Tenant[];
|
||||||
|
selectedTenantId: string | null;
|
||||||
|
statements: BillingStatement[];
|
||||||
|
}) {
|
||||||
|
const router = useRouter();
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div className="space-y-5">
|
||||||
|
<div>
|
||||||
|
<h1 className="text-lg font-semibold text-foreground">Relatórios de billing</h1>
|
||||||
|
<p className="mt-1 max-w-2xl text-sm text-muted-foreground">
|
||||||
|
Statements gerados por período fechado (agente.md secao 135-136) — nunca chamado de "nota
|
||||||
|
fiscal", é um relatório de consumo interno.
|
||||||
|
</p>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<Panel className="p-5">
|
||||||
|
<FieldLabel htmlFor="rb-tenant">Tenant</FieldLabel>
|
||||||
|
<Select
|
||||||
|
id="rb-tenant"
|
||||||
|
value={selectedTenantId ?? ""}
|
||||||
|
onChange={(e) => router.push(e.target.value ? `/platform/billing/relatorios?tenantId=${e.target.value}` : "/platform/billing/relatorios")}
|
||||||
|
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>
|
||||||
|
|
||||||
|
{!selectedTenantId ? (
|
||||||
|
<Panel>
|
||||||
|
<EmptyState title="Escolha um tenant" description="Selecione um tenant acima pra ver os statements dele." />
|
||||||
|
</Panel>
|
||||||
|
) : (
|
||||||
|
<Panel>
|
||||||
|
<PanelHeader title="Statements" description={`${statements.length} statement(s) deste tenant`} />
|
||||||
|
{statements.length === 0 ? (
|
||||||
|
<EmptyState title="Nenhum statement ainda" description="Feche um período em Fechamentos pra gerar o primeiro." />
|
||||||
|
) : (
|
||||||
|
<Table>
|
||||||
|
<THead>
|
||||||
|
<TR>
|
||||||
|
<TH>Período</TH>
|
||||||
|
<TH>Status do período</TH>
|
||||||
|
<TH>Total</TH>
|
||||||
|
<TH>Gerado em</TH>
|
||||||
|
</TR>
|
||||||
|
</THead>
|
||||||
|
<TBody>
|
||||||
|
{statements.map((s) => (
|
||||||
|
<TR key={s.id}>
|
||||||
|
<TD>
|
||||||
|
<Link
|
||||||
|
href={`/platform/billing/relatorios/${s.id}?tenantId=${selectedTenantId}`}
|
||||||
|
className="flex items-center gap-2 font-medium text-foreground underline-offset-4 hover:text-primary hover:underline focus-visible:underline"
|
||||||
|
>
|
||||||
|
<Receipt className="h-3.5 w-3.5 text-muted-foreground" aria-hidden />
|
||||||
|
{formatDateUTC(s.billingPeriod.periodStart)} — {formatDateUTC(s.billingPeriod.periodEnd)}
|
||||||
|
</Link>
|
||||||
|
</TD>
|
||||||
|
<TD>
|
||||||
|
<Pill>{BILLING_PERIOD_STATUS_LABELS[s.billingPeriod.status]}</Pill>
|
||||||
|
</TD>
|
||||||
|
<TD className="font-mono tabular-nums text-foreground">{formatCurrency(s.total, s.currency)}</TD>
|
||||||
|
<TD className="text-muted-foreground">{formatDate(s.generatedAt)}</TD>
|
||||||
|
</TR>
|
||||||
|
))}
|
||||||
|
</TBody>
|
||||||
|
</Table>
|
||||||
|
)}
|
||||||
|
</Panel>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -44,8 +44,16 @@ export const PLATFORM_NAV: NavSection[] = [
|
|||||||
href: "/platform/billing/tarifas",
|
href: "/platform/billing/tarifas",
|
||||||
description: "Price books e rate decks — catálogos globais de preço",
|
description: "Price books e rate decks — catálogos globais de preço",
|
||||||
},
|
},
|
||||||
{ label: "Fechamentos" },
|
{
|
||||||
{ label: "Relatórios" },
|
label: "Fechamentos",
|
||||||
|
href: "/platform/billing/fechamentos",
|
||||||
|
description: "Fechar/reabrir período de billing por tenant",
|
||||||
|
},
|
||||||
|
{
|
||||||
|
label: "Relatórios",
|
||||||
|
href: "/platform/billing/relatorios",
|
||||||
|
description: "Statements gerados por tenant",
|
||||||
|
},
|
||||||
],
|
],
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
|
|||||||
@@ -37,3 +37,58 @@ export interface RateDeck {
|
|||||||
updatedAt: string;
|
updatedAt: string;
|
||||||
entries: RateDeckEntry[];
|
entries: RateDeckEntry[];
|
||||||
}
|
}
|
||||||
|
|
||||||
|
export interface BillingPeriod {
|
||||||
|
id: string;
|
||||||
|
tenantId: string;
|
||||||
|
periodStart: string;
|
||||||
|
periodEnd: string;
|
||||||
|
status: "OPEN" | "CALCULATING" | "READY" | "CLOSED" | "REOPENED";
|
||||||
|
closedAt: string | null;
|
||||||
|
reopenedAt: string | null;
|
||||||
|
createdAt: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
export const BILLING_PERIOD_STATUS_LABELS: Record<string, string> = {
|
||||||
|
OPEN: "Aberto",
|
||||||
|
CALCULATING: "Calculando",
|
||||||
|
READY: "Pronto",
|
||||||
|
CLOSED: "Fechado",
|
||||||
|
REOPENED: "Reaberto",
|
||||||
|
};
|
||||||
|
|
||||||
|
export const BILLING_STATEMENT_CATEGORY_LABELS: Record<string, string> = {
|
||||||
|
PLAN_BASE: "Assinatura base",
|
||||||
|
EXTENSIONS: "Ramais",
|
||||||
|
AGENTS: "Agentes",
|
||||||
|
TRUNKS: "Troncos",
|
||||||
|
CALLS: "Chamadas",
|
||||||
|
MINUTES: "Minutos",
|
||||||
|
AI_TRANSCRIPTION: "IA — transcrição",
|
||||||
|
AI_ANALYSIS: "IA — análise",
|
||||||
|
AI_TOKENS: "IA — tokens",
|
||||||
|
STORAGE: "Armazenamento",
|
||||||
|
ADJUSTMENT: "Ajuste",
|
||||||
|
};
|
||||||
|
|
||||||
|
export interface BillingStatementItem {
|
||||||
|
id: string;
|
||||||
|
category: string;
|
||||||
|
description: string;
|
||||||
|
quantity: number | null;
|
||||||
|
unitPrice: number | null;
|
||||||
|
amount: number;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface BillingStatement {
|
||||||
|
id: string;
|
||||||
|
tenantId: string;
|
||||||
|
billingPeriodId: string;
|
||||||
|
currency: string;
|
||||||
|
subtotal: number;
|
||||||
|
adjustments: number;
|
||||||
|
total: number;
|
||||||
|
generatedAt: string;
|
||||||
|
billingPeriod: BillingPeriod;
|
||||||
|
items?: BillingStatementItem[];
|
||||||
|
}
|
||||||
|
|||||||
@@ -37,6 +37,15 @@ export function formatDate(iso: string): string {
|
|||||||
return new Intl.DateTimeFormat("pt-BR", { day: "2-digit", month: "short", year: "numeric" }).format(new Date(iso));
|
return new Intl.DateTimeFormat("pt-BR", { day: "2-digit", month: "short", year: "numeric" }).format(new Date(iso));
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/** Como `formatDate`, mas em UTC — pra fronteiras de calendário (início/fim
|
||||||
|
* de período de billing, por exemplo) que nunca deveriam deslizar um dia
|
||||||
|
* pra trás por causa do timezone local do servidor renderizando a página.
|
||||||
|
* Achado real: fechar um período de 01/08 a 31/08 mostrava "31 de jul." a
|
||||||
|
* "30 de ago." porque meia-noite UTC vira o dia anterior em UTC-3. */
|
||||||
|
export function formatDateUTC(iso: string): string {
|
||||||
|
return new Intl.DateTimeFormat("pt-BR", { day: "2-digit", month: "short", year: "numeric", timeZone: "UTC" }).format(new Date(iso));
|
||||||
|
}
|
||||||
|
|
||||||
export function formatDateTime(iso: string): string {
|
export function formatDateTime(iso: string): string {
|
||||||
return new Intl.DateTimeFormat("pt-BR", {
|
return new Intl.DateTimeFormat("pt-BR", {
|
||||||
day: "2-digit",
|
day: "2-digit",
|
||||||
|
|||||||
Reference in New Issue
Block a user