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:
21
apps/api/src/fiscal/dto/create-cfop.dto.ts
Normal file
21
apps/api/src/fiscal/dto/create-cfop.dto.ts
Normal file
@@ -0,0 +1,21 @@
|
||||
import { IsBoolean, IsDateString, IsObject, IsOptional, IsString } from "class-validator";
|
||||
|
||||
/**
|
||||
* direction/scope are free-text, no CHECK/enum — exactly as the legacy
|
||||
* (eden.md §4): the CFOP code's 1st digit encodes direction+scope in
|
||||
* practice, but neither this DTO nor the schema derives it automatically.
|
||||
*/
|
||||
export class CreateCfopDto {
|
||||
@IsString() code!: string;
|
||||
@IsString() description!: string;
|
||||
|
||||
@IsOptional() @IsString() direction?: string;
|
||||
@IsOptional() @IsString() scope?: string;
|
||||
@IsOptional() @IsDateString() validFrom?: string;
|
||||
@IsOptional() @IsDateString() validUntil?: string;
|
||||
@IsOptional() @IsBoolean() active?: boolean;
|
||||
@IsOptional() @IsString() source?: string;
|
||||
@IsOptional() @IsString() sourceVersion?: string;
|
||||
@IsOptional() @IsDateString() sourceUpdatedAt?: string;
|
||||
@IsOptional() @IsObject() metadata?: Record<string, unknown>;
|
||||
}
|
||||
12
apps/api/src/fiscal/dto/create-municipality.dto.ts
Normal file
12
apps/api/src/fiscal/dto/create-municipality.dto.ts
Normal file
@@ -0,0 +1,12 @@
|
||||
import { IsBoolean, IsOptional, IsString, Length } from "class-validator";
|
||||
|
||||
/** fiscal_municipality has NO valid_from/valid_until/metadata — eden.md §2.3 ("não faz sentido um município expirar"). */
|
||||
export class CreateMunicipalityDto {
|
||||
@IsString() code!: string;
|
||||
@IsString() name!: string;
|
||||
@IsString() @Length(2, 2) state!: string;
|
||||
|
||||
@IsOptional() @IsBoolean() active?: boolean;
|
||||
@IsOptional() @IsString() source?: string;
|
||||
@IsOptional() @IsString() sourceVersion?: string;
|
||||
}
|
||||
14
apps/api/src/fiscal/dto/create-ncm.dto.ts
Normal file
14
apps/api/src/fiscal/dto/create-ncm.dto.ts
Normal file
@@ -0,0 +1,14 @@
|
||||
import { IsBoolean, IsDateString, IsObject, IsOptional, IsString } from "class-validator";
|
||||
|
||||
export class CreateNcmDto {
|
||||
@IsString() code!: string;
|
||||
@IsString() description!: string;
|
||||
|
||||
@IsOptional() @IsDateString() validFrom?: string;
|
||||
@IsOptional() @IsDateString() validUntil?: string;
|
||||
@IsOptional() @IsBoolean() active?: boolean;
|
||||
@IsOptional() @IsString() source?: string;
|
||||
@IsOptional() @IsString() sourceVersion?: string;
|
||||
@IsOptional() @IsDateString() sourceUpdatedAt?: string;
|
||||
@IsOptional() @IsObject() metadata?: Record<string, unknown>;
|
||||
}
|
||||
23
apps/api/src/fiscal/dto/create-product-fiscal-profile.dto.ts
Normal file
23
apps/api/src/fiscal/dto/create-product-fiscal-profile.dto.ts
Normal file
@@ -0,0 +1,23 @@
|
||||
import { IsDateString, IsIn, IsOptional, IsUUID } from "class-validator";
|
||||
|
||||
/**
|
||||
* Creates a new ACTIVE profile for a (productId, billingComponent) pair.
|
||||
* If one is already active, the service inactivates it and creates this
|
||||
* one in the same transaction (eden.md §2.5's central invariant) — never a
|
||||
* destructive update of the old profile.
|
||||
*/
|
||||
export class CreateProductFiscalProfileDto {
|
||||
@IsIn(["RECURRING", "IMPLEMENTATION"])
|
||||
billingComponent!: "RECURRING" | "IMPLEMENTATION";
|
||||
|
||||
@IsOptional()
|
||||
@IsIn(["NFCOM", "NFSE", "NFE", "NONE"])
|
||||
documentType?: "NFCOM" | "NFSE" | "NFE" | "NONE";
|
||||
|
||||
@IsOptional() @IsUUID() ncmId?: string;
|
||||
@IsOptional() @IsUUID() cfopId?: string;
|
||||
@IsOptional() @IsUUID() municipalityId?: string;
|
||||
@IsOptional() @IsUUID() operationNatureId?: string;
|
||||
@IsOptional() @IsDateString() validFrom?: string;
|
||||
@IsOptional() @IsDateString() validUntil?: string;
|
||||
}
|
||||
15
apps/api/src/fiscal/dto/update-cfop.dto.ts
Normal file
15
apps/api/src/fiscal/dto/update-cfop.dto.ts
Normal file
@@ -0,0 +1,15 @@
|
||||
import { IsBoolean, IsDateString, IsObject, IsOptional, IsString } from "class-validator";
|
||||
|
||||
export class UpdateCfopDto {
|
||||
@IsOptional() @IsString() code?: string;
|
||||
@IsOptional() @IsString() description?: string;
|
||||
@IsOptional() @IsString() direction?: string;
|
||||
@IsOptional() @IsString() scope?: string;
|
||||
@IsOptional() @IsDateString() validFrom?: string;
|
||||
@IsOptional() @IsDateString() validUntil?: string;
|
||||
@IsOptional() @IsBoolean() active?: boolean;
|
||||
@IsOptional() @IsString() source?: string;
|
||||
@IsOptional() @IsString() sourceVersion?: string;
|
||||
@IsOptional() @IsDateString() sourceUpdatedAt?: string;
|
||||
@IsOptional() @IsObject() metadata?: Record<string, unknown>;
|
||||
}
|
||||
10
apps/api/src/fiscal/dto/update-municipality.dto.ts
Normal file
10
apps/api/src/fiscal/dto/update-municipality.dto.ts
Normal file
@@ -0,0 +1,10 @@
|
||||
import { IsBoolean, IsOptional, IsString, Length } from "class-validator";
|
||||
|
||||
export class UpdateMunicipalityDto {
|
||||
@IsOptional() @IsString() code?: string;
|
||||
@IsOptional() @IsString() name?: string;
|
||||
@IsOptional() @IsString() @Length(2, 2) state?: string;
|
||||
@IsOptional() @IsBoolean() active?: boolean;
|
||||
@IsOptional() @IsString() source?: string;
|
||||
@IsOptional() @IsString() sourceVersion?: string;
|
||||
}
|
||||
14
apps/api/src/fiscal/dto/update-ncm.dto.ts
Normal file
14
apps/api/src/fiscal/dto/update-ncm.dto.ts
Normal file
@@ -0,0 +1,14 @@
|
||||
import { IsBoolean, IsDateString, IsObject, IsOptional, IsString } from "class-validator";
|
||||
|
||||
/** All fields optional — PATCH is a partial update, including flipping `active` alone. */
|
||||
export class UpdateNcmDto {
|
||||
@IsOptional() @IsString() code?: string;
|
||||
@IsOptional() @IsString() description?: string;
|
||||
@IsOptional() @IsDateString() validFrom?: string;
|
||||
@IsOptional() @IsDateString() validUntil?: string;
|
||||
@IsOptional() @IsBoolean() active?: boolean;
|
||||
@IsOptional() @IsString() source?: string;
|
||||
@IsOptional() @IsString() sourceVersion?: string;
|
||||
@IsOptional() @IsDateString() sourceUpdatedAt?: string;
|
||||
@IsOptional() @IsObject() metadata?: Record<string, unknown>;
|
||||
}
|
||||
142
apps/api/src/fiscal/fiscal.controller.ts
Normal file
142
apps/api/src/fiscal/fiscal.controller.ts
Normal file
@@ -0,0 +1,142 @@
|
||||
import { Body, Controller, Get, Param, Patch, Post, Query, UseGuards } from "@nestjs/common";
|
||||
import { ApiBearerAuth, ApiTags } from "@nestjs/swagger";
|
||||
import { FiscalService } from "./fiscal.service.js";
|
||||
import { CreateNcmDto } from "./dto/create-ncm.dto.js";
|
||||
import { UpdateNcmDto } from "./dto/update-ncm.dto.js";
|
||||
import { CreateCfopDto } from "./dto/create-cfop.dto.js";
|
||||
import { UpdateCfopDto } from "./dto/update-cfop.dto.js";
|
||||
import { CreateMunicipalityDto } from "./dto/create-municipality.dto.js";
|
||||
import { UpdateMunicipalityDto } from "./dto/update-municipality.dto.js";
|
||||
import { CreateProductFiscalProfileDto } from "./dto/create-product-fiscal-profile.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";
|
||||
|
||||
/**
|
||||
* Fiscal catalogs + product fiscal profiles (eden.md módulo 5). Uses the
|
||||
* same `fiscal` permission feature as the legacy, with `view`/`edit`
|
||||
* levels (eden.md §8). No bulk/mass operations in this MVP — writes always
|
||||
* touch a single catalog row, never a whole table.
|
||||
*/
|
||||
@ApiTags("fiscal")
|
||||
@ApiBearerAuth()
|
||||
@UseGuards(JwtAuthGuard, PermissionGuard)
|
||||
@Controller("v1/fiscal")
|
||||
export class FiscalController {
|
||||
constructor(private readonly fiscal: FiscalService) {}
|
||||
|
||||
// -- fiscal_ncm ---------------------------------------------------------
|
||||
|
||||
@Get("ncm")
|
||||
@RequirePermission("fiscal", "view")
|
||||
listNcm(@Query("q") q?: string, @Query("active") active?: string) {
|
||||
return this.fiscal.listNcm(q, parseActive(active));
|
||||
}
|
||||
|
||||
@Get("ncm/:id")
|
||||
@RequirePermission("fiscal", "view")
|
||||
getNcm(@Param("id") id: string) {
|
||||
return this.fiscal.getNcm(id);
|
||||
}
|
||||
|
||||
@Post("ncm")
|
||||
@RequirePermission("fiscal", "edit")
|
||||
createNcm(@Body() dto: CreateNcmDto, @CurrentUser() user: EdenAuthenticatedUser) {
|
||||
return this.fiscal.createNcm(dto, user);
|
||||
}
|
||||
|
||||
@Patch("ncm/:id")
|
||||
@RequirePermission("fiscal", "edit")
|
||||
updateNcm(@Param("id") id: string, @Body() dto: UpdateNcmDto, @CurrentUser() user: EdenAuthenticatedUser) {
|
||||
return this.fiscal.updateNcm(id, dto, user);
|
||||
}
|
||||
|
||||
// -- fiscal_cfop ----------------------------------------------------------
|
||||
|
||||
@Get("cfop")
|
||||
@RequirePermission("fiscal", "view")
|
||||
listCfop(@Query("q") q?: string, @Query("active") active?: string) {
|
||||
return this.fiscal.listCfop(q, parseActive(active));
|
||||
}
|
||||
|
||||
@Get("cfop/:id")
|
||||
@RequirePermission("fiscal", "view")
|
||||
getCfop(@Param("id") id: string) {
|
||||
return this.fiscal.getCfop(id);
|
||||
}
|
||||
|
||||
@Post("cfop")
|
||||
@RequirePermission("fiscal", "edit")
|
||||
createCfop(@Body() dto: CreateCfopDto, @CurrentUser() user: EdenAuthenticatedUser) {
|
||||
return this.fiscal.createCfop(dto, user);
|
||||
}
|
||||
|
||||
@Patch("cfop/:id")
|
||||
@RequirePermission("fiscal", "edit")
|
||||
updateCfop(@Param("id") id: string, @Body() dto: UpdateCfopDto, @CurrentUser() user: EdenAuthenticatedUser) {
|
||||
return this.fiscal.updateCfop(id, dto, user);
|
||||
}
|
||||
|
||||
// -- fiscal_municipality --------------------------------------------------
|
||||
|
||||
@Get("municipalities")
|
||||
@RequirePermission("fiscal", "view")
|
||||
listMunicipalities(@Query("q") q?: string, @Query("active") active?: string) {
|
||||
return this.fiscal.listMunicipalities(q, parseActive(active));
|
||||
}
|
||||
|
||||
@Get("municipalities/:id")
|
||||
@RequirePermission("fiscal", "view")
|
||||
getMunicipality(@Param("id") id: string) {
|
||||
return this.fiscal.getMunicipality(id);
|
||||
}
|
||||
|
||||
@Post("municipalities")
|
||||
@RequirePermission("fiscal", "edit")
|
||||
createMunicipality(@Body() dto: CreateMunicipalityDto, @CurrentUser() user: EdenAuthenticatedUser) {
|
||||
return this.fiscal.createMunicipality(dto, user);
|
||||
}
|
||||
|
||||
@Patch("municipalities/:id")
|
||||
@RequirePermission("fiscal", "edit")
|
||||
updateMunicipality(
|
||||
@Param("id") id: string,
|
||||
@Body() dto: UpdateMunicipalityDto,
|
||||
@CurrentUser() user: EdenAuthenticatedUser,
|
||||
) {
|
||||
return this.fiscal.updateMunicipality(id, dto, user);
|
||||
}
|
||||
|
||||
// -- fiscal_operation_nature — read-only in this MVP -----------------------
|
||||
|
||||
@Get("operation-natures")
|
||||
@RequirePermission("fiscal", "view")
|
||||
listOperationNatures() {
|
||||
return this.fiscal.listOperationNatures();
|
||||
}
|
||||
|
||||
// -- product_fiscal_profiles ----------------------------------------------
|
||||
|
||||
@Get("products/:productId/profiles")
|
||||
@RequirePermission("fiscal", "view")
|
||||
listProfiles(@Param("productId") productId: string) {
|
||||
return this.fiscal.listProfiles(productId);
|
||||
}
|
||||
|
||||
@Post("products/:productId/profiles")
|
||||
@RequirePermission("fiscal", "edit")
|
||||
createProfile(
|
||||
@Param("productId") productId: string,
|
||||
@Body() dto: CreateProductFiscalProfileDto,
|
||||
@CurrentUser() user: EdenAuthenticatedUser,
|
||||
) {
|
||||
return this.fiscal.createProfile(productId, dto, user);
|
||||
}
|
||||
}
|
||||
|
||||
function parseActive(value?: string): boolean | undefined {
|
||||
if (value === undefined) return undefined;
|
||||
return value === "true";
|
||||
}
|
||||
12
apps/api/src/fiscal/fiscal.module.ts
Normal file
12
apps/api/src/fiscal/fiscal.module.ts
Normal file
@@ -0,0 +1,12 @@
|
||||
import { Module } from "@nestjs/common";
|
||||
import { AuthModule } from "../auth/auth.module.js";
|
||||
import { FiscalController } from "./fiscal.controller.js";
|
||||
import { FiscalService } from "./fiscal.service.js";
|
||||
|
||||
@Module({
|
||||
imports: [AuthModule],
|
||||
controllers: [FiscalController],
|
||||
providers: [FiscalService],
|
||||
exports: [FiscalService],
|
||||
})
|
||||
export class FiscalModule {}
|
||||
219
apps/api/src/fiscal/fiscal.service.ts
Normal file
219
apps/api/src/fiscal/fiscal.service.ts
Normal file
@@ -0,0 +1,219 @@
|
||||
import { Injectable, NotFoundException } from "@nestjs/common";
|
||||
import {
|
||||
auditRepo,
|
||||
fiscalRepo,
|
||||
productsRepo,
|
||||
type FiscalCfop,
|
||||
type FiscalMunicipality,
|
||||
type FiscalNcm,
|
||||
type FiscalOperationNature,
|
||||
type ProductFiscalProfile,
|
||||
} from "@eden/database";
|
||||
import type { EdenAuthenticatedUser } from "../auth/jwt-auth.guard.js";
|
||||
import type { CreateNcmDto } from "./dto/create-ncm.dto.js";
|
||||
import type { UpdateNcmDto } from "./dto/update-ncm.dto.js";
|
||||
import type { CreateCfopDto } from "./dto/create-cfop.dto.js";
|
||||
import type { UpdateCfopDto } from "./dto/update-cfop.dto.js";
|
||||
import type { CreateMunicipalityDto } from "./dto/create-municipality.dto.js";
|
||||
import type { UpdateMunicipalityDto } from "./dto/update-municipality.dto.js";
|
||||
import type { CreateProductFiscalProfileDto } from "./dto/create-product-fiscal-profile.dto.js";
|
||||
|
||||
/**
|
||||
* Fiscal catalogs (eden.md módulo 5) — see PENDING_fiscal.cjs migration
|
||||
* header for the MVP scope. Read (`fiscal:view`) is open to any
|
||||
* authenticated user holding that grant; write (`fiscal:edit`) creates or
|
||||
* PATCHes a single catalog row — no bulk/mass operations in this MVP.
|
||||
*/
|
||||
@Injectable()
|
||||
export class FiscalService {
|
||||
// ---------------------------------------------------------------------
|
||||
// fiscal_ncm
|
||||
// ---------------------------------------------------------------------
|
||||
|
||||
async listNcm(q?: string, active?: boolean): Promise<FiscalNcm[]> {
|
||||
return fiscalRepo.listNcm({ q, active });
|
||||
}
|
||||
|
||||
async getNcm(id: string): Promise<FiscalNcm> {
|
||||
const row = await fiscalRepo.getNcmById(id);
|
||||
if (!row) throw new NotFoundException("NCM não encontrado");
|
||||
return row;
|
||||
}
|
||||
|
||||
async createNcm(dto: CreateNcmDto, user: EdenAuthenticatedUser): Promise<FiscalNcm> {
|
||||
const row = await fiscalRepo.createNcm(dto);
|
||||
await auditRepo.appendAuditEvent({
|
||||
actorType: "user",
|
||||
actorId: user.id,
|
||||
action: "fiscal.ncm.created",
|
||||
resourceType: "fiscal_ncm",
|
||||
resourceId: row.id,
|
||||
metadata: { code: row.code },
|
||||
});
|
||||
return row;
|
||||
}
|
||||
|
||||
async updateNcm(id: string, dto: UpdateNcmDto, user: EdenAuthenticatedUser): Promise<FiscalNcm> {
|
||||
const row = await fiscalRepo.updateNcm(id, dto);
|
||||
if (!row) throw new NotFoundException("NCM não encontrado");
|
||||
await auditRepo.appendAuditEvent({
|
||||
actorType: "user",
|
||||
actorId: user.id,
|
||||
action: "fiscal.ncm.updated",
|
||||
resourceType: "fiscal_ncm",
|
||||
resourceId: row.id,
|
||||
metadata: { ...dto },
|
||||
});
|
||||
return row;
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------
|
||||
// fiscal_cfop
|
||||
// ---------------------------------------------------------------------
|
||||
|
||||
async listCfop(q?: string, active?: boolean): Promise<FiscalCfop[]> {
|
||||
return fiscalRepo.listCfop({ q, active });
|
||||
}
|
||||
|
||||
async getCfop(id: string): Promise<FiscalCfop> {
|
||||
const row = await fiscalRepo.getCfopById(id);
|
||||
if (!row) throw new NotFoundException("CFOP não encontrado");
|
||||
return row;
|
||||
}
|
||||
|
||||
async createCfop(dto: CreateCfopDto, user: EdenAuthenticatedUser): Promise<FiscalCfop> {
|
||||
const row = await fiscalRepo.createCfop(dto);
|
||||
await auditRepo.appendAuditEvent({
|
||||
actorType: "user",
|
||||
actorId: user.id,
|
||||
action: "fiscal.cfop.created",
|
||||
resourceType: "fiscal_cfop",
|
||||
resourceId: row.id,
|
||||
metadata: { code: row.code },
|
||||
});
|
||||
return row;
|
||||
}
|
||||
|
||||
async updateCfop(id: string, dto: UpdateCfopDto, user: EdenAuthenticatedUser): Promise<FiscalCfop> {
|
||||
const row = await fiscalRepo.updateCfop(id, dto);
|
||||
if (!row) throw new NotFoundException("CFOP não encontrado");
|
||||
await auditRepo.appendAuditEvent({
|
||||
actorType: "user",
|
||||
actorId: user.id,
|
||||
action: "fiscal.cfop.updated",
|
||||
resourceType: "fiscal_cfop",
|
||||
resourceId: row.id,
|
||||
metadata: { ...dto },
|
||||
});
|
||||
return row;
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------
|
||||
// fiscal_municipality
|
||||
// ---------------------------------------------------------------------
|
||||
|
||||
async listMunicipalities(q?: string, active?: boolean): Promise<FiscalMunicipality[]> {
|
||||
return fiscalRepo.listMunicipalities({ q, active });
|
||||
}
|
||||
|
||||
async getMunicipality(id: string): Promise<FiscalMunicipality> {
|
||||
const row = await fiscalRepo.getMunicipalityById(id);
|
||||
if (!row) throw new NotFoundException("Município não encontrado");
|
||||
return row;
|
||||
}
|
||||
|
||||
async createMunicipality(
|
||||
dto: CreateMunicipalityDto,
|
||||
user: EdenAuthenticatedUser,
|
||||
): Promise<FiscalMunicipality> {
|
||||
const row = await fiscalRepo.createMunicipality(dto);
|
||||
await auditRepo.appendAuditEvent({
|
||||
actorType: "user",
|
||||
actorId: user.id,
|
||||
action: "fiscal.municipality.created",
|
||||
resourceType: "fiscal_municipality",
|
||||
resourceId: row.id,
|
||||
metadata: { code: row.code },
|
||||
});
|
||||
return row;
|
||||
}
|
||||
|
||||
async updateMunicipality(
|
||||
id: string,
|
||||
dto: UpdateMunicipalityDto,
|
||||
user: EdenAuthenticatedUser,
|
||||
): Promise<FiscalMunicipality> {
|
||||
const row = await fiscalRepo.updateMunicipality(id, dto);
|
||||
if (!row) throw new NotFoundException("Município não encontrado");
|
||||
await auditRepo.appendAuditEvent({
|
||||
actorType: "user",
|
||||
actorId: user.id,
|
||||
action: "fiscal.municipality.updated",
|
||||
resourceType: "fiscal_municipality",
|
||||
resourceId: row.id,
|
||||
metadata: { ...dto },
|
||||
});
|
||||
return row;
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------
|
||||
// fiscal_operation_nature — read-only in this MVP (fixed business enum,
|
||||
// seeded by the migration)
|
||||
// ---------------------------------------------------------------------
|
||||
|
||||
async listOperationNatures(): Promise<FiscalOperationNature[]> {
|
||||
return fiscalRepo.listOperationNatures();
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------
|
||||
// product_fiscal_profiles
|
||||
// ---------------------------------------------------------------------
|
||||
|
||||
async listProfiles(productId: string): Promise<ProductFiscalProfile[]> {
|
||||
await this.assertProductExists(productId);
|
||||
return fiscalRepo.listProductFiscalProfiles(productId);
|
||||
}
|
||||
|
||||
/**
|
||||
* Creates a new ACTIVE profile for (productId, billingComponent). If one
|
||||
* is already active, the repository layer inactivates it and creates the
|
||||
* new one in a single transaction — never a destructive update of the
|
||||
* old profile (eden.md §2.5).
|
||||
*/
|
||||
async createProfile(
|
||||
productId: string,
|
||||
dto: CreateProductFiscalProfileDto,
|
||||
user: EdenAuthenticatedUser,
|
||||
): Promise<ProductFiscalProfile> {
|
||||
await this.assertProductExists(productId);
|
||||
|
||||
const created = await fiscalRepo.createActiveProductFiscalProfile({
|
||||
productId,
|
||||
billingComponent: dto.billingComponent,
|
||||
documentType: dto.documentType,
|
||||
ncmId: dto.ncmId ?? null,
|
||||
cfopId: dto.cfopId ?? null,
|
||||
municipalityId: dto.municipalityId ?? null,
|
||||
operationNatureId: dto.operationNatureId ?? null,
|
||||
validFrom: dto.validFrom ?? null,
|
||||
validUntil: dto.validUntil ?? null,
|
||||
createdBy: user.id,
|
||||
});
|
||||
|
||||
await auditRepo.appendAuditEvent({
|
||||
actorType: "user",
|
||||
actorId: user.id,
|
||||
action: "fiscal.product_profile.created",
|
||||
resourceType: "product_fiscal_profile",
|
||||
resourceId: created.id,
|
||||
metadata: { productId, billingComponent: dto.billingComponent, documentType: created.document_type },
|
||||
});
|
||||
|
||||
return created;
|
||||
}
|
||||
|
||||
private async assertProductExists(productId: string): Promise<void> {
|
||||
const product = await productsRepo.getProductById(productId);
|
||||
if (!product) throw new NotFoundException("Produto não encontrado");
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user