Skip to content
Fiscalzen SEFAZ logo

Fiscalzen SEFAZ

Integrações SEFAZ (NF-e/CT-e/MDF-e) no padrão FiscalZen: DistDFe, Manifestação e eventos — com certificados A1, SOAP, retry/backoff e persistência no produto.

SKILL.md

Full skill instructions

🏗️ Contexto do Projeto (como o FiscalZen é estruturado)

  • Monorepo com pnpm-workspace + Turborepo
  • Código em TypeScript (ESM "type": "module")
  • Backend: Fastify 4 (apps/​api)
  • Jobs: BullMQ (workers + scheduler)
  • Persistência: Drizzle ORM + PostgreSQL
  • Cache/​queues: Redis
  • Logging: Pino
  • Pacote fiscal principal: @fiscalzen/​sefaz-client (NF-e/​CT-e/​MDF-e)
  • Parser fiscal: @fiscalzen/​xml-parser (usado pelo sefaz-client e api)

✅ Regra: alterações de SEFAZ geralmente tocam packages/​ (cliente) e/​ou apps/​api/​ (orquestração + persistência).


🎯 Objetivo (o que esta skill resolve)

Aplicar mudanças relacionadas a SEFAZ mantendo consistência com a codebase:

  • Preferir abstrações internas (@fiscalzen/​sefaz-client) em vez de reimplementar SOAP/​assinatura/​certificado
  • Validar certificado e permissões no backend antes de chamar SEFAZ
  • Respeitar retry/​backoff e throttling
  • Persistir eventos e atualizar documentos do jeito do produto
  • Garantir validação (unit/​integration + homolog)

🧭 Onde mexer (mapa rápido)

Cliente SEFAZ (packages/​sefaz-client)

  • packages/​sefaz-client/​src/​client.ts → política de timeout/​retry/​backoff, https.Agent, dispose(), logging
  • packages/​sefaz-client/​src/​soap-client.ts + src/​soap/​envelope.ts → SOAP + envelope
  • packages/​sefaz-client/​src/​services/​* → implementações por domínio:
    • nfe-distdfe.ts (DistDFe NF-e)
    • cte-distdfe.ts, mdfe-distdfe.ts (DistDFe CT-e/​MDF-e)
    • manifestacao.ts (eventos do destinatário)
    • event-query.ts (consulta eventos)
    • cte-events.ts (eventos CT-e)
  • packages/​sefaz-client/​src/​types.ts → contratos + erros tipados (SefazError, TimeoutError, CertificadoError, etc.)
  • packages/​sefaz-client/​src/​certificate.ts → A1 (PFX), cache/​invalidação, validações
  • packages/​sefaz-client/​src/​signature.ts → digest/​assinatura (helpers)

Produto (apps/​api)

  • apps/​api/​src/​modules/​manifestacao/​service.ts → fluxo real de manifestação + persistência
  • apps/​api/​src/​modules/​certificates/​* → validação de certificados (gate antes de SEFAZ)
  • apps/​api/​src/​modules/​documents/​* → documento + status/​manifestações
  • apps/​api/​src/​jobs/​queues.ts → criação/​agenda de jobs SEFAZ
  • apps/​api/​src/​modules/​nsu/​* + packages/​database/​src/​schema/​nsu-control.ts → controle de NSU/​sync

✅ Regras obrigatórias (gates)

1) Sempre validar certificado antes de chamar SEFAZ (no produto)

Se a chamada vier do apps/​api, não chame SEFAZ sem passar pelo gate:

  • empresa existe
  • company.certificate e company.certificatePassword existem
  • certificado não expirou
  • (se aplicável) tenantId correto (multi-tenant)

2) Não vazar segredo (PFX/​senha)

  • nunca logar senha do certificado
  • nunca logar buffer do PFX
  • ao logar erro, sanitize campos sensíveis

3) TLS estrito

  • não desabilitar validação TLS (rejectUnauthorized)

4) Erros externos padronizados

No apps/​api, problemas da SEFAZ devem virar erro de serviço externo (padrão do projeto), mantendo mensagem útil.


🔁 Retry/​Backoff e Throttling (padrão FiscalZen)

Ponto único de política: packages/​sefaz-client/​src/​client.ts

✅ Regra: se você precisar mudar retry/​backoff/​timeout, faça no client (não espalhe retry pelos services).

Throttling (ex.: cStat 656)

Recomendação de implementação consistente:

  • tratar como erro recuperável
  • aplicar retry com backoff exponencial + jitter
  • evitar tempestade: preferir job/​queue para processar em série por empresa/​UF

📦 DistDFe (Golden Path) — como fazer no FiscalZen

Cenários típicos

  • Consulta por último NSU (sync contínuo)
  • Consulta por NSU específico
  • Consulta por chave (pontual)

Padrão de implementação

  1. Validar parâmetros (CNPJ, chave, nsu/​ultNSU)
  2. Montar request XML conforme tipo de consulta
  3. Enviar via SoapClient / SefazClient (abstração interna)
  4. Parsear retorno (cStat/​xMotivo/​ultNSU/​maxNSU)
  5. Extrair docZip e:
    • decodificar
    • detectar schema
    • derivar tipo/​chave usando @fiscalzen/​xml-parser
  6. Retornar DistDFeResponse consistente
  7. Se estiver no produto (apps/​api): persistir e atualizar controle de NSU

Regras de robustez

  • nsu e ultNSU sempre como string com 15 dígitos (padStart(15,'0'))
  • docZip inválido não deve derrubar o lote inteiro (registrar erro e seguir)
  • ao tratar throttling, preferir política central no client

🧾 Manifestação do Destinatário (Golden Path) — padrão do produto

Passo a passo (apps/​api)

  1. obter empresa com certificado (gate)
  2. buscar documento por chave com tenantId
  3. montar CertificadoA1 no formato do @fiscalzen/​sefaz-client
  4. usar env.SEFAZ_AMBIENTE
  5. chamar o client do pacote
  6. se sucesso=false: lançar ExternalServiceError('SEFAZ', xMotivo)
  7. persistir em documentEvents + atualizar documents.manifestacao

Regras específicas

  • eventos devem ser idempotentes na camada do produto (não duplicar o mesmo evento sem necessidade)
  • manter rastreabilidade (documentId/​chave/​tipoEvento/​protocolo/​dataRegistro)

🧪 Validação (Fase V) — mínimo obrigatório

Unit / pacote (sefaz-client)

  • validar validateParams (CNPJ/​chave)
  • validar montagem de request por ultNSU/​nsu/​chave
  • validar parsing de resposta (cStat e campos)
  • validar docZip: sucesso e falha isolada

Integration / produto (apps/​api)

  • empresa sem certificado → erro de validação
  • certificado expirado → erro de validação
  • documento inexistente → NotFound
  • retorno sucesso=false da SEFAZ → ExternalServiceError
  • persistência: criou event + atualizou documento

Homologação

  • testar ao menos:
    • DistDFe por ultNSU
    • Manifestação (um evento)
    • cenário de throttling (se possível reproduzir)

🧰 Prompt templates (como invocar a skill)

Manifestação (produto)

“Aplique a skill fiscalzen-sefaz para ajustar o fluxo de manifestação em apps/​api.
Preserve o gate de certificado + multi-tenant e mapeie falhas SEFAZ para erro externo padrão. Atualize persistência em documentEvents e documents.manifestacao.”

DistDFe (pacote)

“Aplique a skill fiscalzen-sefaz para modificar packages/​sefaz-client/​src/​services/​nfe-distdfe.ts.
Preserve validações, padStart(15) e parsing docZip com @fiscalzen/​xml-parser. Se tratar 656, preferir política central no client.”


More skills from diegosouzapw

accessibility logo
diegosouzapw/awesome-omni-skill

accessibility

Accessibility guidelines for VS Code features — covers accessibility help dialogs, accessible views, verbosity settings, accessibility signals, ARIA alerts/status announcements, keyboard navigation, and ARIA labels/roles. Applies to both new interactive UI surfaces and updates to existing feature...

62 1
View
mermaid-diagrams logo
diegosouzapw/awesome-omni-skill

mermaid-diagrams

Mermaid diagram creation for flowcharts, sequences, ERDs, and more. Generate diagrams from text in markdown files. Use for documentation, architecture diagrams, and visual representations. Triggers on mermaid, flowchart, sequence diagram, ERD, entity relationship, gantt chart, pie chart, class di...

62 1
View
tauri2-react-rust logo
diegosouzapw/awesome-omni-skill

tauri2-react-rust

Guides development of cross-platform desktop apps with Tauri 2, TypeScript, React, and Rust. Use when building Tauri apps, implementing IPC, designing Rust backend or TypeScript/React frontend, when researching or cloning a website (open site, snapshot elements), when verifying local dev or built...

62 1
View
fp-ts-errors logo
diegosouzapw/awesome-omni-skill

fp-ts-errors

Handle errors as values using fp-ts Either and TaskEither for cleaner, more predictable TypeScript code. Use when implementing error handling patterns with fp-ts.

62 0
View
ring:pre-dev-research logo
diegosouzapw/awesome-omni-skill

ring:pre-dev-research

Gate 0 research phase for pre-dev workflow. Dispatches 3 parallel research agents to gather codebase patterns, external best practices, and framework documentation BEFORE creating PRD/TRD. Outputs research.md with file:line references.

62 0
View
create-assistant logo
diegosouzapw/awesome-omni-skill

create-assistant

Create and configure Vapi voice AI assistants with models, voices, transcribers, tools, hooks, and advanced settings. Use when building voice agents, phone bots, customer support assistants, or any conversational AI that handles phone or web calls.

62 0
View
codex-headless logo
diegosouzapw/awesome-omni-skill

codex-headless

Delegiere Aufgaben an OpenAI Codex CLI im Headless-Mode. Nutzt ChatGPT Subscription (KEIN API Key). Nur Workspace-Zugriff, KEIN System-Zugriff. Auto-Accept mit --full-auto. Web-Recherche mit --search.

62 0
View
social-media-scheduler logo
diegosouzapw/awesome-omni-skill

social-media-scheduler

Generate a full week of social media content for any topic. Outputs platform-optimized posts for Twitter/X, LinkedIn, and Instagram with hashtags and posting times.

62 0
View
Data Privacy Compliance logo
diegosouzapw/awesome-omni-skill

Data Privacy Compliance

Data privacy and regulatory compliance specialist for GDPR, CCPA, HIPAA, and international data protection laws. Use when implementing privacy controls, conducting data protection impact assessments, ensuring regulatory compliance, or managing data subject rights. Expert in consent management, da...

62 0
View
triple-review logo
diegosouzapw/awesome-omni-skill

triple-review

Reviews a task using the TRIPLE protocol, as the review agent.

62 0
View
Tech Stack & Architecture Decision logo
diegosouzapw/awesome-omni-skill

Tech Stack & Architecture Decision

Define and document the technology stack and architecture decisions for a project. Use when the user needs to choose a tech stack, make architecture decisions, define infrastructure choices, or document technology selections. Triggers on requests like "define the tech stack", "choose technologies...

62 0
View

Popular AI tools

Kaiber logo
Video

Kaiber

Generate, edit, and beat-sync AI video with leading models in one workspace.

Paid
View
Vimcal logo
Productivity

Vimcal

The world's fastest calendar for remote work

Free
View

Transform Your Design with AI Designer by ImgCreator.ai

Freemium
View
Akool AI logo
Content & writing

Akool AI

Revolutionizing Video Production with AI-Powered Creativity

Paid
View

Extend an image past the frame and let AI fill the new aspect ratio.

Freemium
View
StarByFace logo
Security

StarByFace

Discover your celebrity doppelgänger with StarByFace!

Free
View
C

ChainClarity explains 700+ crypto whitepapers in plain English, with layered summaries, comparisons, research tools, alerts, and a $4.99 Pro plan.

Freemium
View
Opus Clip logo
Coding & apps

Opus Clip

Opus.ai: Revolutionize Your Web Experience

Free
View