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>
269 lines
9.4 KiB
TypeScript
269 lines
9.4 KiB
TypeScript
import { BadRequestException, ConflictException, Injectable, NotFoundException } from "@nestjs/common";
|
|
import {
|
|
auditRepo,
|
|
inventoryRepo,
|
|
productsRepo,
|
|
type SerializedAsset,
|
|
type StockMovement,
|
|
type StockReservation,
|
|
} from "@eden/database";
|
|
import type { CreateAssetDto } from "./dto/create-asset.dto.js";
|
|
import type { ReserveAssetDto } from "./dto/reserve-asset.dto.js";
|
|
import type { InstallAssetDto } from "./dto/install-asset.dto.js";
|
|
import type { ReturnAssetDto } from "./dto/return-asset.dto.js";
|
|
import type { CreateReservationDto } from "./dto/create-reservation.dto.js";
|
|
import type { EdenAuthenticatedUser } from "../auth/jwt-auth.guard.js";
|
|
|
|
const {
|
|
AssetNotFoundError,
|
|
InvalidAssetTransitionError,
|
|
NoOpenAssignmentError,
|
|
ReservationNotFoundError,
|
|
InvalidReservationTransitionError,
|
|
} = inventoryRepo;
|
|
|
|
@Injectable()
|
|
export class InventoryService {
|
|
// ---------------------------------------------------------------------
|
|
// serialized_assets
|
|
// ---------------------------------------------------------------------
|
|
|
|
listAssets(status?: string, warehouseId?: string, productId?: string): Promise<SerializedAsset[]> {
|
|
return inventoryRepo.listSerializedAssets({
|
|
status: status as SerializedAsset["status"] | undefined,
|
|
warehouseId,
|
|
productId,
|
|
});
|
|
}
|
|
|
|
async getAsset(id: string): Promise<SerializedAsset> {
|
|
const asset = await inventoryRepo.getSerializedAssetById(id);
|
|
if (!asset) throw new NotFoundException("Ativo não encontrado");
|
|
return asset;
|
|
}
|
|
|
|
async createAsset(dto: CreateAssetDto, user: EdenAuthenticatedUser): Promise<SerializedAsset> {
|
|
if (!dto.serial && !dto.patrimonyTag) {
|
|
throw new BadRequestException("Informe ao menos serial ou patrimonyTag");
|
|
}
|
|
|
|
const product = await productsRepo.getProductById(dto.productId);
|
|
if (!product) throw new BadRequestException(`Produto ${dto.productId} não encontrado`);
|
|
|
|
const warehouse = await inventoryRepo.getWarehouseById(dto.warehouseId);
|
|
if (!warehouse) throw new BadRequestException(`Armazém ${dto.warehouseId} não encontrado`);
|
|
|
|
let result: Awaited<ReturnType<typeof inventoryRepo.createAssetWithPurchaseMovement>>;
|
|
try {
|
|
result = await inventoryRepo.createAssetWithPurchaseMovement({
|
|
productId: dto.productId,
|
|
warehouseId: dto.warehouseId,
|
|
serial: dto.serial ?? null,
|
|
patrimonyTag: dto.patrimonyTag ?? null,
|
|
macAddress: dto.macAddress ?? null,
|
|
warrantyExpiresAt: dto.warrantyExpiresAt ?? null,
|
|
notes: dto.notes ?? null,
|
|
createdBy: user.id,
|
|
});
|
|
} catch (err) {
|
|
// 23505 = unique_violation — the DB-enforced "serial/patrimony/MAC
|
|
// never active twice" invariant (see migration).
|
|
if (isUniqueViolation(err)) {
|
|
throw new ConflictException(
|
|
"Serial, patrimônio ou MAC já está em uso por outro ativo ativo",
|
|
);
|
|
}
|
|
throw err;
|
|
}
|
|
|
|
await auditRepo.appendAuditEvent({
|
|
actorType: "user",
|
|
actorId: user.id,
|
|
action: "inventory.asset_created",
|
|
resourceType: "serialized_asset",
|
|
resourceId: result.asset.id,
|
|
metadata: { productId: dto.productId, warehouseId: dto.warehouseId, serial: dto.serial ?? null },
|
|
});
|
|
|
|
return result.asset;
|
|
}
|
|
|
|
async reserveAsset(id: string, dto: ReserveAssetDto, user: EdenAuthenticatedUser): Promise<SerializedAsset> {
|
|
try {
|
|
const result = await inventoryRepo.reserveAsset(id, {
|
|
referenceType: dto.referenceType ?? null,
|
|
referenceId: dto.referenceId ?? null,
|
|
notes: dto.notes ?? null,
|
|
createdBy: user.id,
|
|
});
|
|
|
|
await auditRepo.appendAuditEvent({
|
|
actorType: "user",
|
|
actorId: user.id,
|
|
action: "inventory.asset_reserved",
|
|
resourceType: "serialized_asset",
|
|
resourceId: id,
|
|
metadata: { reservationId: result.reservation.id },
|
|
});
|
|
|
|
return result.asset;
|
|
} catch (err) {
|
|
if (err instanceof AssetNotFoundError) throw new NotFoundException("Ativo não encontrado");
|
|
if (err instanceof InvalidAssetTransitionError) {
|
|
throw new ConflictException(
|
|
`Ativo com status '${err.fromStatus}' não pode ser reservado (esperado: in_stock)`,
|
|
);
|
|
}
|
|
throw err;
|
|
}
|
|
}
|
|
|
|
async installAsset(id: string, dto: InstallAssetDto, user: EdenAuthenticatedUser): Promise<SerializedAsset> {
|
|
try {
|
|
const result = await inventoryRepo.installAsset(id, {
|
|
contractId: dto.contractId,
|
|
assignmentType: dto.assignmentType,
|
|
notes: dto.notes ?? null,
|
|
createdBy: user.id,
|
|
});
|
|
|
|
await auditRepo.appendAuditEvent({
|
|
actorType: "user",
|
|
actorId: user.id,
|
|
action: "inventory.asset_installed",
|
|
resourceType: "serialized_asset",
|
|
resourceId: id,
|
|
metadata: { contractId: dto.contractId, assignmentType: dto.assignmentType },
|
|
});
|
|
|
|
return result.asset;
|
|
} catch (err) {
|
|
if (err instanceof AssetNotFoundError) throw new NotFoundException("Ativo não encontrado");
|
|
if (err instanceof InvalidAssetTransitionError) {
|
|
throw new ConflictException(
|
|
`Ativo com status '${err.fromStatus}' não pode ser instalado/comodato (esperado: in_stock ou reserved)`,
|
|
);
|
|
}
|
|
throw err;
|
|
}
|
|
}
|
|
|
|
async returnAsset(id: string, dto: ReturnAssetDto, user: EdenAuthenticatedUser): Promise<SerializedAsset> {
|
|
const warehouse = await inventoryRepo.getWarehouseById(dto.warehouseId);
|
|
if (!warehouse) throw new BadRequestException(`Armazém ${dto.warehouseId} não encontrado`);
|
|
|
|
try {
|
|
const result = await inventoryRepo.returnAsset(id, {
|
|
warehouseId: dto.warehouseId,
|
|
notes: dto.notes ?? null,
|
|
createdBy: user.id,
|
|
});
|
|
|
|
await auditRepo.appendAuditEvent({
|
|
actorType: "user",
|
|
actorId: user.id,
|
|
action: "inventory.asset_returned",
|
|
resourceType: "serialized_asset",
|
|
resourceId: id,
|
|
metadata: { warehouseId: dto.warehouseId },
|
|
});
|
|
|
|
return result.asset;
|
|
} catch (err) {
|
|
if (err instanceof AssetNotFoundError) throw new NotFoundException("Ativo não encontrado");
|
|
if (err instanceof InvalidAssetTransitionError) {
|
|
throw new ConflictException(
|
|
`Ativo com status '${err.fromStatus}' não pode ser devolvido (esperado: installed ou comodato)`,
|
|
);
|
|
}
|
|
if (err instanceof NoOpenAssignmentError) {
|
|
throw new ConflictException("Ativo não tem vínculo aberto para encerrar");
|
|
}
|
|
throw err;
|
|
}
|
|
}
|
|
|
|
// ---------------------------------------------------------------------
|
|
// stock_movements
|
|
// ---------------------------------------------------------------------
|
|
|
|
listMovements(
|
|
warehouseId?: string,
|
|
productId?: string,
|
|
referenceType?: string,
|
|
referenceId?: string,
|
|
): Promise<StockMovement[]> {
|
|
return inventoryRepo.listStockMovements({ warehouseId, productId, referenceType, referenceId });
|
|
}
|
|
|
|
// ---------------------------------------------------------------------
|
|
// stock_reservations
|
|
// ---------------------------------------------------------------------
|
|
|
|
listReservations(status?: string, warehouseId?: string, productId?: string): Promise<StockReservation[]> {
|
|
return inventoryRepo.listStockReservations({
|
|
status: status as StockReservation["status"] | undefined,
|
|
warehouseId,
|
|
productId,
|
|
});
|
|
}
|
|
|
|
async createReservation(dto: CreateReservationDto, user: EdenAuthenticatedUser): Promise<StockReservation> {
|
|
const product = await productsRepo.getProductById(dto.productId);
|
|
if (!product) throw new BadRequestException(`Produto ${dto.productId} não encontrado`);
|
|
|
|
const warehouse = await inventoryRepo.getWarehouseById(dto.warehouseId);
|
|
if (!warehouse) throw new BadRequestException(`Armazém ${dto.warehouseId} não encontrado`);
|
|
|
|
const result = await inventoryRepo.createGenericReservation({
|
|
warehouseId: dto.warehouseId,
|
|
productId: dto.productId,
|
|
quantity: dto.quantity,
|
|
referenceType: dto.referenceType ?? null,
|
|
referenceId: dto.referenceId ?? null,
|
|
notes: dto.notes ?? null,
|
|
createdBy: user.id,
|
|
});
|
|
|
|
await auditRepo.appendAuditEvent({
|
|
actorType: "user",
|
|
actorId: user.id,
|
|
action: "inventory.reservation_created",
|
|
resourceType: "stock_reservation",
|
|
resourceId: result.reservation.id,
|
|
metadata: { productId: dto.productId, warehouseId: dto.warehouseId, quantity: dto.quantity },
|
|
});
|
|
|
|
return result.reservation;
|
|
}
|
|
|
|
async releaseReservation(id: string, user: EdenAuthenticatedUser): Promise<StockReservation> {
|
|
try {
|
|
const result = await inventoryRepo.releaseReservation(id, user.id);
|
|
|
|
await auditRepo.appendAuditEvent({
|
|
actorType: "user",
|
|
actorId: user.id,
|
|
action: "inventory.reservation_released",
|
|
resourceType: "stock_reservation",
|
|
resourceId: id,
|
|
metadata: {},
|
|
});
|
|
|
|
return result.reservation;
|
|
} catch (err) {
|
|
if (err instanceof ReservationNotFoundError) throw new NotFoundException("Reserva não encontrada");
|
|
if (err instanceof InvalidReservationTransitionError) {
|
|
throw new ConflictException(
|
|
`Reserva com status '${err.fromStatus}' não pode ser liberada (esperado: active)`,
|
|
);
|
|
}
|
|
throw err;
|
|
}
|
|
}
|
|
}
|
|
|
|
function isUniqueViolation(err: unknown): boolean {
|
|
return typeof err === "object" && err !== null && (err as { code?: string }).code === "23505";
|
|
}
|