diff --git a/TODO.md b/TODO.md index 0f465e8..d6d330d 100644 --- a/TODO.md +++ b/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 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 diff --git a/apps/api/src/billing/billing-periods.controller.ts b/apps/api/src/billing/billing-periods.controller.ts index 34c212b..53749a4 100644 --- a/apps/api/src/billing/billing-periods.controller.ts +++ b/apps/api/src/billing/billing-periods.controller.ts @@ -54,4 +54,19 @@ export class BillingPeriodsController { 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" } }), + ); + } } diff --git a/apps/api/src/billing/billing-statements.controller.ts b/apps/api/src/billing/billing-statements.controller.ts index da2a683..04dcd56 100644 --- a/apps/api/src/billing/billing-statements.controller.ts +++ b/apps/api/src/billing/billing-statements.controller.ts @@ -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 type { AccessTokenClaims } from "@b2bcall/auth"; +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"; @@ -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") @Get(":id") - async get(@CurrentUser() user: AccessTokenClaims, @Param("id") id: string) { - const tenantId = user.tenantId!; + async get(@CurrentUser() user: AccessTokenClaims, @Param("id") id: string, @Query("tenantId") queryTenantId?: string) { + 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 statement = await withTenantContext(prisma, tenantId, (tx) => tx.billingStatement.findFirst({ diff --git a/apps/frontend/.impeccable/review/platform-fechamentos-empty-desktop.png b/apps/frontend/.impeccable/review/platform-fechamentos-empty-desktop.png new file mode 100644 index 0000000..a8f7a08 Binary files /dev/null and b/apps/frontend/.impeccable/review/platform-fechamentos-empty-desktop.png differ diff --git a/apps/frontend/.impeccable/review/platform-fechamentos-fixed-dates-desktop.png b/apps/frontend/.impeccable/review/platform-fechamentos-fixed-dates-desktop.png new file mode 100644 index 0000000..49fe67b Binary files /dev/null and b/apps/frontend/.impeccable/review/platform-fechamentos-fixed-dates-desktop.png differ diff --git a/apps/frontend/.impeccable/review/platform-fechamentos-tenant-desktop.png b/apps/frontend/.impeccable/review/platform-fechamentos-tenant-desktop.png new file mode 100644 index 0000000..7ae5695 Binary files /dev/null and b/apps/frontend/.impeccable/review/platform-fechamentos-tenant-desktop.png differ diff --git a/apps/frontend/.impeccable/review/platform-relatorios-list-desktop.png b/apps/frontend/.impeccable/review/platform-relatorios-list-desktop.png new file mode 100644 index 0000000..cfcfbf9 Binary files /dev/null and b/apps/frontend/.impeccable/review/platform-relatorios-list-desktop.png differ diff --git a/apps/frontend/.impeccable/review/platform-statement-detail-desktop.png b/apps/frontend/.impeccable/review/platform-statement-detail-desktop.png new file mode 100644 index 0000000..9567b2f Binary files /dev/null and b/apps/frontend/.impeccable/review/platform-statement-detail-desktop.png differ diff --git a/apps/frontend/src/app/platform/billing/fechamentos/actions.ts b/apps/frontend/src/app/platform/billing/fechamentos/actions.ts new file mode 100644 index 0000000..a6e4874 --- /dev/null +++ b/apps/frontend/src/app/platform/billing/fechamentos/actions.ts @@ -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("/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(`/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) }; + } +} diff --git a/apps/frontend/src/app/platform/billing/fechamentos/fechamentos-view.tsx b/apps/frontend/src/app/platform/billing/fechamentos/fechamentos-view.tsx new file mode 100644 index 0000000..7cb647e --- /dev/null +++ b/apps/frontend/src/app/platform/billing/fechamentos/fechamentos-view.tsx @@ -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 = { + 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 ( +
+
+
+

Fechamentos

+

+ Fechamento de período por tenant (agente.md secao 134-137) — fechar é imutável, só reabrir explícito + (com motivo) permite recalcular. +

+
+ {selectedTenantId && ( + + )} +
+ + + Tenant + + + + {!selectedTenantId ? ( + + + + ) : ( + <> + {showForm && setShowForm(false)} />} + + + + {periods.length === 0 ? ( + + ) : ( + + + + + + + + + + + + {periods.map((p) => ( + + ))} + +
InícioFimStatusFechado em + Ações +
+ )} +
+ + )} +
+ ); +} + +function NewPeriodForm({ tenantId, onDone }: { tenantId: string; onDone: () => void }) { + const router = useRouter(); + const [periodStart, setPeriodStart] = useState(""); + const [periodEnd, setPeriodEnd] = useState(""); + const [error, setError] = useState(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 ( + +
+
+
+ Início do período + setPeriodStart(e.target.value)} disabled={pending} /> +
+
+ Fim do período + setPeriodEnd(e.target.value)} disabled={pending} /> +
+
+ {error && ( +

+ {error} +

+ )} +
+ +
+
+
+ ); +} + +function PeriodRow({ period, tenantId }: { period: BillingPeriod; tenantId: string }) { + const router = useRouter(); + const [reopening, setReopening] = useState(false); + const [reason, setReason] = useState(""); + const [error, setError] = useState(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 ( + + {formatDateUTC(period.periodStart)} + {formatDateUTC(period.periodEnd)} + + {BILLING_PERIOD_STATUS_LABELS[period.status]} + + {period.closedAt ? formatDate(period.closedAt) : "—"} + + {canReopen && ( +
+ {error && {error}} + {reopening && ( + setReason(e.target.value)} + placeholder="Motivo da reabertura" + className="h-8 w-48" + disabled={pending} + /> + )} + +
+ )} + + + ); +} diff --git a/apps/frontend/src/app/platform/billing/fechamentos/page.tsx b/apps/frontend/src/app/platform/billing/fechamentos/page.tsx new file mode 100644 index 0000000..b0be609 --- /dev/null +++ b/apps/frontend/src/app/platform/billing/fechamentos/page.tsx @@ -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("/tenants", session.accessToken); + const periods = tenantId + ? await apiFetch(`/billing/periods/by-tenant/${tenantId}`, session.accessToken) + : []; + + return ; +} diff --git a/apps/frontend/src/app/platform/billing/relatorios/[id]/page.tsx b/apps/frontend/src/app/platform/billing/relatorios/[id]/page.tsx new file mode 100644 index 0000000..b3b906a --- /dev/null +++ b/apps/frontend/src/app/platform/billing/relatorios/[id]/page.tsx @@ -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(`/billing/statements/${id}${query}`, session.accessToken); + return ; + } catch (err) { + if (err instanceof ApiError && err.status === 404) notFound(); + throw err; + } +} diff --git a/apps/frontend/src/app/platform/billing/relatorios/[id]/statement-detail-view.tsx b/apps/frontend/src/app/platform/billing/relatorios/[id]/statement-detail-view.tsx new file mode 100644 index 0000000..02aa8d1 --- /dev/null +++ b/apps/frontend/src/app/platform/billing/relatorios/[id]/statement-detail-view.tsx @@ -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 ( +
+
+

+ + Statement — {formatDateUTC(statement.billingPeriod.periodStart)} a {formatDateUTC(statement.billingPeriod.periodEnd)} +

+

+ Gerado em {formatDate(statement.generatedAt)} — período{" "} + {BILLING_PERIOD_STATUS_LABELS[statement.billingPeriod.status]} +

+
+ + + + + + + + + + + + + + + {(statement.items ?? []).map((item) => ( + + + + + + + + ))} + +
CategoriaDescriçãoQuantidadePreço unitárioValor
+ {BILLING_STATEMENT_CATEGORY_LABELS[item.category] ?? item.category} + {item.description}{item.quantity ?? "—"} + {item.unitPrice != null ? formatCurrency(item.unitPrice, statement.currency) : "—"} + {formatCurrency(item.amount, statement.currency)}
+
+ + +
+
+
Subtotal
+
{formatCurrency(statement.subtotal, statement.currency)}
+
+
+
Ajustes
+
{formatCurrency(statement.adjustments, statement.currency)}
+
+
+
Total
+
{formatCurrency(statement.total, statement.currency)}
+
+
+
+
+ ); +} diff --git a/apps/frontend/src/app/platform/billing/relatorios/page.tsx b/apps/frontend/src/app/platform/billing/relatorios/page.tsx new file mode 100644 index 0000000..f206de4 --- /dev/null +++ b/apps/frontend/src/app/platform/billing/relatorios/page.tsx @@ -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("/tenants", session.accessToken); + const statements = tenantId + ? await apiFetch(`/billing/statements/by-tenant/${tenantId}`, session.accessToken) + : []; + + return ; +} diff --git a/apps/frontend/src/app/platform/billing/relatorios/relatorios-view.tsx b/apps/frontend/src/app/platform/billing/relatorios/relatorios-view.tsx new file mode 100644 index 0000000..7074f10 --- /dev/null +++ b/apps/frontend/src/app/platform/billing/relatorios/relatorios-view.tsx @@ -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 ( +
+
+

Relatórios de billing

+

+ Statements gerados por período fechado (agente.md secao 135-136) — nunca chamado de "nota + fiscal", é um relatório de consumo interno. +

+
+ + + Tenant + + + + {!selectedTenantId ? ( + + + + ) : ( + + + {statements.length === 0 ? ( + + ) : ( + + + + + + + + + + + {statements.map((s) => ( + + + + + + + ))} + +
PeríodoStatus do períodoTotalGerado em
+ + + {formatDateUTC(s.billingPeriod.periodStart)} — {formatDateUTC(s.billingPeriod.periodEnd)} + + + {BILLING_PERIOD_STATUS_LABELS[s.billingPeriod.status]} + {formatCurrency(s.total, s.currency)}{formatDate(s.generatedAt)}
+ )} +
+ )} +
+ ); +} diff --git a/apps/frontend/src/components/platform-shell/nav-data.ts b/apps/frontend/src/components/platform-shell/nav-data.ts index e765138..7e8bade 100644 --- a/apps/frontend/src/components/platform-shell/nav-data.ts +++ b/apps/frontend/src/components/platform-shell/nav-data.ts @@ -44,8 +44,16 @@ export const PLATFORM_NAV: NavSection[] = [ href: "/platform/billing/tarifas", 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", + }, ], }, { diff --git a/apps/frontend/src/lib/billing-types.ts b/apps/frontend/src/lib/billing-types.ts index 93a9271..8eeb2ec 100644 --- a/apps/frontend/src/lib/billing-types.ts +++ b/apps/frontend/src/lib/billing-types.ts @@ -37,3 +37,58 @@ export interface RateDeck { updatedAt: string; 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 = { + OPEN: "Aberto", + CALCULATING: "Calculando", + READY: "Pronto", + CLOSED: "Fechado", + REOPENED: "Reaberto", +}; + +export const BILLING_STATEMENT_CATEGORY_LABELS: Record = { + 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[]; +} diff --git a/apps/frontend/src/lib/format.ts b/apps/frontend/src/lib/format.ts index f4cd69a..c8db677 100644 --- a/apps/frontend/src/lib/format.ts +++ b/apps/frontend/src/lib/format.ts @@ -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)); } +/** 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 { return new Intl.DateTimeFormat("pt-BR", { day: "2-digit",