feat(api,ui): MFA/TOTP, Inventory, Support, HR-Timeclock, Fiscal, Billing e Design System

Leva grande, pedida como "pelo menos mais 20 etapas, use subagentes":
fecha a pendência de MFA/TOTP da Fase 1 (feito diretamente, autenticação é
sensível demais para delegar) e lança 5 subagentes em paralelo em 2 ondas
(eden-inventory, eden-support, eden-hr-timeclock; depois eden-finance,
eden-fiscal, eden-frontend), cada um em worktree isolado, com integração
seletiva manual (barrel, app.module.ts, migrations renomeadas/aplicadas,
build/typecheck/teste ao vivo antes de cada merge).

## Backend

- MFA/TOTP (`apps/api/src/auth/mfa.service.ts`, `crypto/field-encryption.service.ts`):
  login em duas etapas quando `mfa_enabled=true`, `FieldEncryptionService`
  genérico (AES-256-GCM versionado, ADR-0005) reaproveitado por outros
  segredos reversíveis (ex. credencial de equipamento Control iD).
- Inventory: warehouses, stock_movements (ledger append-only), serialized_assets,
  asset_assignments, stock_reservations — invariante "serial/patrimônio/MAC
  nunca duplicado entre ativos ativos" reforçada por índices únicos parciais
  no banco (Master Prompt §15.3).
- Support/Service Desk: tickets com máquina de estados, SLA com pausa/retomada
  em `waiting_customer`/`waiting_third_party` (funções puras testáveis).
- HR-Timeclock (fundação): dispositivos Control iD (senha cifrada), import de
  AFD com parser + CRC-16/KERMIT, `afd_records` imutável sem exceção nem
  para super_admin (sem válvula de escape, diferente de audit_log).
- Fiscal: NCM/CFOP/municípios/naturezas de operação (eden.md módulo 5, MVP de
  5 das ~19 tabelas), product_fiscal_profiles com invariante de único
  profile ativo por billing_component.
- Billing: subscription→billing_run→invoice idempotente (regenerar em draft
  substitui, nunca duplica) e imutável após consolidar (ADR-0008: nunca
  confunde faturamento/documento fiscal/recebimento).
- FKs cruzadas fechadas: quotes/client_registrations/contracts.

## Frontend — primeira leva

- `packages/ui`: Design System real extraído do tema DreamsERP comprado —
  achado que mudou o escopo: o tema já vem em React+Tailwind (não só
  Angular), tokens visuais reais portados (cores, Geist como fonte real,
  divergindo da doc antiga que citava Nunito/Poppins).
- `apps/core-web`: login real (com suporte a MFA), sessão, shell autenticado
  via `AppShell` — substitui a tela estática "Bootstrap da Fase 1".

## Bugs reais encontrados e corrigidos (todos via teste ao vivo, não leitura)

1. **Segurança**: o token de desafio MFA era aceito como access token normal
   pelo `JwtAuthGuard` (mesma assinatura, nenhuma checagem da claim
   `purpose`) — bypass total do segundo fator. Explorado e fechado ao vivo
   contra o container real; teste de regressão em `test/mfa.spec.ts`.
2. Crase solta dentro de comentário SQL na migration de hr-timeclock quebrava
   o template literal JS (`SyntaxError` ao rodar a migration).
3. CORS ausente por completo na API.
4. `turbo.json` não declarava `VITE_API_BASE_URL` como input de build — o
   Turborepo cacheava o bundle do frontend ignorando mudança na env var.
5. `compose.yaml` usava `${VITE_API_BASE_URL:-/api/v1}`, que colidia com a
   variável de mesmo nome do `.env` local — o default nunca era aplicado.
6. Não existia `.dockerignore` — todo build copiava node_modules/.git/
   worktrees de subagentes (665MB) para dentro do contexto Docker.

Decisão do operador incorporada: a API nunca tem domínio público próprio
(só IP interno) — os 3 frontends chamam por caminho relativo `/api/v1`,
proxy externo roteia same-origin; CORS só é relevante para dev local.

Verificado: `pnpm turbo run typecheck build` (28/28), `pnpm --filter
@eden/api test` (30/30, cresceu de 15), todo o lote testado ao vivo via
curl contra os containers reais reconstruídos, incluindo os 6 bugs acima
já fechados e confirmados, e a trilha de auditoria conferida no Postgres.

Claude-Session: https://claude.ai/code/session_01BcWWuKfykGtUweXmHD6cKx

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
This commit is contained in:
2026-09-03 17:25:31 -03:00
parent 18838a9031
commit eff515b70d
105 changed files with 8875 additions and 21 deletions

View File

@@ -0,0 +1,104 @@
import { Body, Controller, Get, Param, Patch, Post, Query, UseGuards } from "@nestjs/common";
import { ApiBearerAuth, ApiTags } from "@nestjs/swagger";
import { BillingService } from "./billing.service.js";
import { CreateBillingSubscriptionDto } from "./dto/create-billing-subscription.dto.js";
import { CreateBillingRunDto } from "./dto/create-billing-run.dto.js";
import { JwtAuthGuard } from "../auth/jwt-auth.guard.js";
import { PermissionGuard } from "../auth/permission.guard.js";
import { RequirePermission } from "../auth/decorators/require-permission.decorator.js";
import { CurrentUser } from "../auth/decorators/current-user.decorator.js";
import type { EdenAuthenticatedUser } from "../auth/jwt-auth.guard.js";
import type {
BillingRunStatus,
BillingSubscriptionStatus,
InvoiceStatus,
} from "@eden/database";
/**
* Billing — Master Prompt §6.10, ADR-0008. Recurring subscription ->
* billing_run -> invoice MVP. Explicitly NOT Finance/AR-AP (títulos,
* boletos, dunning) or Fiscal (documento fiscal) — see ADR-0008. See
* billing.service.ts for the authorization rules (why run
* creation/consolidation requires 'all' scope).
*/
@ApiTags("billing")
@ApiBearerAuth()
@UseGuards(JwtAuthGuard, PermissionGuard)
@Controller("v1/billing")
export class BillingController {
constructor(private readonly billing: BillingService) {}
@Get("subscriptions")
@RequirePermission("billing", "view")
listSubscriptions(
@CurrentUser() user: EdenAuthenticatedUser,
@Query("status") status?: BillingSubscriptionStatus,
) {
return this.billing.listSubscriptions(user, status);
}
@Post("subscriptions")
@RequirePermission("billing", "edit")
createSubscription(
@Body() dto: CreateBillingSubscriptionDto,
@CurrentUser() user: EdenAuthenticatedUser,
) {
return this.billing.createSubscription(dto, user);
}
@Patch("subscriptions/:id/cancel")
@RequirePermission("billing", "edit")
cancelSubscription(@Param("id") id: string, @CurrentUser() user: EdenAuthenticatedUser) {
return this.billing.cancelSubscription(id, user);
}
@Post("runs")
@RequirePermission("billing", "edit")
createRun(@Body() dto: CreateBillingRunDto, @CurrentUser() user: EdenAuthenticatedUser) {
return this.billing.createOrRegenerateRun(dto, user);
}
@Get("runs")
@RequirePermission("billing", "view")
listRuns(
@CurrentUser() user: EdenAuthenticatedUser,
@Query("referenceYear") referenceYear?: string,
@Query("referenceMonth") referenceMonth?: string,
@Query("status") status?: BillingRunStatus,
) {
return this.billing.listRuns(user, {
referenceYear: referenceYear != null ? Number(referenceYear) : undefined,
referenceMonth: referenceMonth != null ? Number(referenceMonth) : undefined,
status,
});
}
@Get("runs/:id")
@RequirePermission("billing", "view")
getRun(@Param("id") id: string, @CurrentUser() user: EdenAuthenticatedUser) {
return this.billing.getRun(id, user);
}
@Post("runs/:id/consolidate")
@RequirePermission("billing", "edit")
consolidateRun(@Param("id") id: string, @CurrentUser() user: EdenAuthenticatedUser) {
return this.billing.consolidateRun(id, user);
}
@Get("invoices")
@RequirePermission("billing", "view")
listInvoices(
@CurrentUser() user: EdenAuthenticatedUser,
@Query("status") status?: InvoiceStatus,
@Query("referenceYear") referenceYear?: string,
@Query("referenceMonth") referenceMonth?: string,
@Query("resellerId") resellerId?: string,
) {
return this.billing.listInvoices(user, {
status,
referenceYear: referenceYear != null ? Number(referenceYear) : undefined,
referenceMonth: referenceMonth != null ? Number(referenceMonth) : undefined,
resellerId,
});
}
}

View File

@@ -0,0 +1,12 @@
import { Module } from "@nestjs/common";
import { AuthModule } from "../auth/auth.module.js";
import { BillingController } from "./billing.controller.js";
import { BillingService } from "./billing.service.js";
@Module({
imports: [AuthModule],
controllers: [BillingController],
providers: [BillingService],
exports: [BillingService],
})
export class BillingModule {}

View File

@@ -0,0 +1,262 @@
import {
ConflictException,
ForbiddenException,
Injectable,
NotFoundException,
} from "@nestjs/common";
import {
auditRepo,
billingRepo,
type BillingRun,
type BillingRunWithInvoices,
type BillingSubscription,
type Invoice,
} from "@eden/database";
import type { EdenAuthenticatedUser } from "../auth/jwt-auth.guard.js";
import { maxGrantedScope } from "../auth/permissions.js";
import type { CreateBillingSubscriptionDto } from "./dto/create-billing-subscription.dto.js";
import type { CreateBillingRunDto } from "./dto/create-billing-run.dto.js";
const {
BillingSubscriptionNotFoundError,
BillingRunNotFoundError,
BillingRunConsolidatedError,
BillingPeriodAlreadyConsolidatedError,
} = billingRepo;
const RESOURCE = "billing";
/**
* Billing (Master Prompt §6.10, ADR-0008) — recurring subscription ->
* billing_run -> invoice flow. Strictly distinct from Finance/AR-AP
* (títulos/boletos/cobrança) and Fiscal (documento fiscal) — neither is
* touched here.
*
* Authorization: creating/regenerating and consolidating a billing_run
* always requires 'all' scope for 'billing'/'edit' — a run spans every
* reseller with a matching billing_day, so only central back-office
* operators (not a single reseller) can trigger a billing close. Reading
* and per-subscription/invoice mutations respect the actor's scope
* ('all' vs 'reseller'), same pattern as contracts.service.ts.
*/
@Injectable()
export class BillingService {
// -------------------------------------------------------------------
// billing_subscriptions
// -------------------------------------------------------------------
async listSubscriptions(
user: EdenAuthenticatedUser,
status?: BillingSubscription["status"],
): Promise<BillingSubscription[]> {
const scope = maxGrantedScope(user.permissions, RESOURCE, "view");
if (!scope) throw new ForbiddenException(`Sem permissão para 'view' em '${RESOURCE}'`);
if (scope === "all") return billingRepo.listBillingSubscriptions({ scope: "all", status });
return billingRepo.listBillingSubscriptions({
scope: "reseller",
resellerId: user.resellerId,
status,
});
}
async createSubscription(
dto: CreateBillingSubscriptionDto,
user: EdenAuthenticatedUser,
): Promise<BillingSubscription> {
const scope = maxGrantedScope(user.permissions, RESOURCE, "edit");
if (!scope) throw new ForbiddenException(`Sem permissão para 'edit' em '${RESOURCE}'`);
// Never trust a client-supplied resellerId to place a subscription
// under an arbitrary reseller (CLAUDE.md: no authz decision trusts a
// client-supplied reseller_id). A 'reseller'-scoped actor always gets
// their own session-resolved reseller; only 'all' scope may target an
// explicit resellerId from the body.
let resellerId: string | null;
if (scope === "all") {
resellerId = dto.resellerId ?? null;
} else {
resellerId = user.resellerId;
if (!resellerId) {
throw new ForbiddenException("Usuário não está vinculado a nenhuma revenda");
}
}
const subscription = await billingRepo.createBillingSubscription({
contractId: dto.contractId,
resellerId,
monthlyValue: dto.monthlyValue,
billingDay: dto.billingDay,
createdBy: user.id,
});
await auditRepo.appendAuditEvent({
actorType: "user",
actorId: user.id,
action: "billing_subscription.created",
resourceType: "billing_subscription",
resourceId: subscription.id,
metadata: { contractId: dto.contractId, billingDay: dto.billingDay },
});
return subscription;
}
async cancelSubscription(id: string, user: EdenAuthenticatedUser): Promise<BillingSubscription> {
const scope = maxGrantedScope(user.permissions, RESOURCE, "edit");
if (!scope) throw new ForbiddenException(`Sem permissão para 'edit' em '${RESOURCE}'`);
const existing = await billingRepo.getBillingSubscriptionById(id);
if (!existing) throw new NotFoundException("Subscription não encontrada");
if (scope !== "all" && existing.reseller_id !== user.resellerId) {
throw new NotFoundException("Subscription não encontrada");
}
const cancelled = await billingRepo.cancelBillingSubscription(id, user.id);
await auditRepo.appendAuditEvent({
actorType: "user",
actorId: user.id,
action: "billing_subscription.cancelled",
resourceType: "billing_subscription",
resourceId: id,
metadata: {},
});
return cancelled;
}
// -------------------------------------------------------------------
// billing_runs / invoices
// -------------------------------------------------------------------
/**
* Creates a new draft run, or — if a draft already exists for the same
* (referenceYear, referenceMonth, billingDay) — regenerates its
* invoices in place (idempotent: never duplicates). 409s if a run for
* that exact period is already consolidated (controlled re-billing is
* deferred, see PENDING_billing.cjs header).
*/
async createOrRegenerateRun(
dto: CreateBillingRunDto,
user: EdenAuthenticatedUser,
): Promise<BillingRunWithInvoices> {
this.requireAllScope(user, "edit");
try {
const run = await billingRepo.generateOrRegenerateBillingRun({
referenceYear: dto.referenceYear,
referenceMonth: dto.referenceMonth,
billingDay: dto.billingDay,
triggeredBy: user.id,
});
await auditRepo.appendAuditEvent({
actorType: "user",
actorId: user.id,
action: "billing_run.generated",
resourceType: "billing_run",
resourceId: run.id,
metadata: {
referenceYear: dto.referenceYear,
referenceMonth: dto.referenceMonth,
billingDay: dto.billingDay,
invoiceCount: run.invoices.length,
totalAmount: run.totalAmount,
},
});
return run;
} catch (err) {
if (err instanceof BillingPeriodAlreadyConsolidatedError) {
throw new ConflictException(err.message);
}
throw err;
}
}
async listRuns(
user: EdenAuthenticatedUser,
filter: { referenceYear?: number; referenceMonth?: number; status?: BillingRun["status"] },
): Promise<BillingRun[]> {
const scope = maxGrantedScope(user.permissions, RESOURCE, "view");
if (!scope) throw new ForbiddenException(`Sem permissão para 'view' em '${RESOURCE}'`);
return billingRepo.listBillingRuns(filter);
}
async getRun(id: string, user: EdenAuthenticatedUser): Promise<BillingRunWithInvoices> {
const scope = maxGrantedScope(user.permissions, RESOURCE, "view");
if (!scope) throw new ForbiddenException(`Sem permissão para 'view' em '${RESOURCE}'`);
const run = await billingRepo.getBillingRunById(id);
if (!run) throw new NotFoundException("Billing run não encontrado");
if (scope !== "all") {
// Reseller-scoped actors only ever see their own reseller's slice
// of a run's invoices — never another reseller's amounts.
run.invoices = run.invoices.filter((inv: Invoice) => inv.reseller_id === user.resellerId);
}
return run;
}
async consolidateRun(id: string, user: EdenAuthenticatedUser): Promise<BillingRunWithInvoices> {
this.requireAllScope(user, "edit");
try {
const run = await billingRepo.consolidateBillingRun(id, user.id);
await auditRepo.appendAuditEvent({
actorType: "user",
actorId: user.id,
action: "billing_run.consolidated",
resourceType: "billing_run",
resourceId: id,
metadata: { invoiceCount: run.invoices.length, totalAmount: run.totalAmount },
});
return run;
} catch (err) {
if (err instanceof BillingRunNotFoundError) throw new NotFoundException("Billing run não encontrado");
if (err instanceof BillingRunConsolidatedError) {
throw new ConflictException("Billing run já está consolidado");
}
throw err;
}
}
async listInvoices(
user: EdenAuthenticatedUser,
filter: {
status?: Invoice["status"];
referenceYear?: number;
referenceMonth?: number;
/** Only honored when the actor holds 'all' scope — see below. */
resellerId?: string;
},
): Promise<Invoice[]> {
const scope = maxGrantedScope(user.permissions, RESOURCE, "view");
if (!scope) throw new ForbiddenException(`Sem permissão para 'view' em '${RESOURCE}'`);
const { resellerId: requestedResellerId, ...rest } = filter;
if (scope === "all") {
// A client-supplied resellerId is only ever honored once the
// actor's own server-resolved scope already grants full ('all')
// visibility — it narrows an already-unrestricted view, it never
// grants access beyond what the session allows.
return billingRepo.listInvoices(
requestedResellerId
? { scope: "reseller", resellerId: requestedResellerId, ...rest }
: { scope: "all", ...rest },
);
}
return billingRepo.listInvoices({ scope: "reseller", resellerId: user.resellerId, ...rest });
}
private requireAllScope(user: EdenAuthenticatedUser, action: "view" | "edit"): void {
const scope = maxGrantedScope(user.permissions, RESOURCE, action);
if (scope !== "all") {
throw new ForbiddenException(
`Fechamento de billing exige escopo 'all' para '${RESOURCE}:${action}'`,
);
}
}
}

View File

@@ -0,0 +1,18 @@
import { IsInt, Max, Min } from "class-validator";
export class CreateBillingRunDto {
@IsInt()
@Min(2000)
@Max(2100)
referenceYear!: number;
@IsInt()
@Min(1)
@Max(12)
referenceMonth!: number;
@IsInt()
@Min(1)
@Max(28)
billingDay!: number;
}

View File

@@ -0,0 +1,30 @@
import { IsInt, IsNumber, IsOptional, IsUUID, Max, Min } from "class-validator";
/**
* `monthlyValue` is accepted directly in the body (never recalculated
* from a contract) — this worktree/leva has no guaranteed access to the
* real `contracts` module to look the value up server-side, so the
* caller (typically a Contracts-side workflow) supplies the snapshot
* explicitly. `resellerId` is only actually trusted from the client when
* the caller holds 'all' scope; for 'reseller' scope it is always
* overridden server-side with the actor's own reseller (see
* billing.service.ts#create) — no authorization decision ever trusts a
* client-supplied resellerId (CLAUDE.md).
*/
export class CreateBillingSubscriptionDto {
@IsUUID()
contractId!: string;
@IsOptional()
@IsUUID()
resellerId?: string;
@IsNumber()
@Min(0)
monthlyValue!: number;
@IsInt()
@Min(1)
@Max(28)
billingDay!: number;
}