### Setup Manual - Instalar Dependências Source: https://github.com/nfe/client-nodejs/blob/master/examples/README.md Instale as dependências do projeto. ```bash npm install ``` -------------------------------- ### NfeClient Quick Start Source: https://github.com/nfe/client-nodejs/blob/master/skills/nfeio-sdk/SKILL.md A quick start example showing how to instantiate the NfeClient with essential configuration options like apiKey, environment, and timeout. ```typescript import { NfeClient } from 'nfe-io'; const nfe = new NfeClient({ apiKey: 'your-api-key', // Required for most resources environment: 'production', // 'production' | 'development' timeout: 30000, // Request timeout in ms (default: 30000) retryConfig: { // Optional retry configuration maxRetries: 3, // Default: 3 baseDelay: 1000, // Default: 1000ms maxDelay: 30000, // Default: 30000ms backoffMultiplier: 2, // Default: 2 }, }); ``` -------------------------------- ### Service Invoices README Examples Source: https://github.com/nfe/client-nodejs/blob/master/openspec/changes/implement-service-invoices/tasks.md Examples for Service Invoices quick start section in README. ```javascript import { ServiceInvoices } from "@/core/resources/service-invoices"; // Recommended: createAndWait() for automatic polling const invoice = await serviceInvoices.createAndWait(companyId, { // ... invoice data }); // Manual creation with sync/async detection const response = await serviceInvoices.create(companyId, { // ... invoice data }); if (response.status === 201) { console.log("Invoice created synchronously:", response.data); } else if (response.status === 202) { console.log("Invoice creation accepted, polling for status..."); const status = await serviceInvoices.getStatus(companyId, response.data.id); console.log("Invoice status:", status); } // List invoices with pagination and filters const invoices = await serviceInvoices.list(companyId, { page: 1, pageSize: 20, startDate: "2026-01-01", endDate: "2026-01-18" }); // Retrieve a single invoice const invoiceDetails = await serviceInvoices.retrieve(companyId, "invoice-id-123"); // Get invoice status const statusDetails = await serviceInvoices.getStatus(companyId, "invoice-id-123"); // Cancel an invoice await serviceInvoices.cancel(companyId, "invoice-id-123"); // Send email to multiple recipients await serviceInvoices.sendEmail(companyId, "invoice-id-123", { to: ["client1@example.com", "client2@example.com"], cc: ["internal@example.com"] }); // Download PDF (single or bulk) await serviceInvoices.downloadPdf(companyId, "invoice-id-123"); // Single invoice await serviceInvoices.downloadPdf(companyId); // Bulk download (all invoices in ZIP) // Download XML (single or bulk) await serviceInvoices.downloadXml(companyId, "invoice-id-123"); // Single invoice await serviceInvoices.downloadXml(companyId); // Bulk download (all invoices in ZIP) // Create batch with concurrency control const batchResponse = await serviceInvoices.createBatch(companyId, [ { /* invoice data 1 */ }, { /* invoice data 2 */ } ], { concurrency: 5 }); ``` -------------------------------- ### Quick Start Helpers: Client Creation and API Key Validation Source: https://github.com/nfe/client-nodejs/blob/master/docs/API.md Provides examples for creating an NfeClient from environment variables using `createClientFromEnv` and validating an API key's format with `validateApiKeyFormat`. ```typescript import { createClientFromEnv, validateApiKeyFormat } from 'nfe-io'; // Create client from environment variable // Requires NFE_API_KEY environment variable const nfe = createClientFromEnv('production'); // Validate API key format const validation = validateApiKeyFormat('my-api-key'); if (!validation.valid) { console.error('API key issues:', validation.issues); } ``` -------------------------------- ### Basic Configuration Example Source: https://github.com/nfe/client-nodejs/blob/master/_autodocs/configuracao.md Example of initializing NfeClient with basic API key and environment. ```typescript import { NfeClient } from 'nfe-io'; const nfe = new NfeClient({ apiKey: 'sua-chave-api', environment: 'production' }); ``` -------------------------------- ### getConfig Example Source: https://github.com/nfe/client-nodejs/blob/master/_autodocs/configuracao.md Example of retrieving the current configuration of the NfeClient. ```typescript const config = nfe.getConfig(); console.log('Base URL:', config.baseUrl); console.log('Ambiente:', config.environment); console.log('Timeout:', config.timeout); console.log('Max retries:', config.retryConfig.maxRetries); ``` -------------------------------- ### Environment Variable Example Source: https://github.com/nfe/client-nodejs/blob/master/_autodocs/configuracao.md Example of setting environment variables for API keys and then initializing the SDK. ```bash export NFE_API_KEY="sua-chave-api" export NFE_DATA_API_KEY="sua-chave-dados" # Agora o SDK usa as chaves do ambiente ``` -------------------------------- ### Running examples Source: https://github.com/nfe/client-nodejs/blob/master/README.md Commands to run the provided examples interactively or directly. ```bash # Modo interativo com menu npm run examples # Ou diretamente node examples/run-examples.js ``` -------------------------------- ### updateConfig Example Source: https://github.com/nfe/client-nodejs/blob/master/_autodocs/configuracao.md Example demonstrating how to dynamically update NfeClient configuration after initialization. ```typescript const nfe = new NfeClient({ apiKey: 'chave-1' }); // Mudar para sandbox nfe.updateConfig({ environment: 'sandbox' }); // Aumentar timeout nfe.updateConfig({ timeout: 60000 }); // Atualizar chave API nfe.updateConfig({ apiKey: 'nova-chave' }); ``` -------------------------------- ### File Downloads (PDF/XML) Source: https://github.com/nfe/client-nodejs/blob/master/skills/nfeio-sdk/SKILL.md Example of downloading PDF and XML files for service invoices, which return Buffer objects, and product invoice queries. ```typescript import { writeFileSync } from 'node:fs'; // Service invoice downloads return Buffer const pdf = await nfe.serviceInvoices.downloadPdf(companyId, invoiceId); const xml = await nfe.serviceInvoices.downloadXml(companyId, invoiceId); writeFileSync('invoice.pdf', pdf); writeFileSync('invoice.xml', xml); // Query resources also return Buffer const danfe = await nfe.productInvoiceQuery.downloadPdf(accessKey); ``` -------------------------------- ### NfeClient Constructor Example Source: https://github.com/nfe/client-nodejs/blob/master/_autodocs/api-reference/cliente-nfe.md Examples of how to instantiate the NfeClient with different configurations. ```typescript import { NfeClient } from 'nfe-io'; // Configuração básica const nfe = new NfeClient({ apiKey: 'sua-chave-api', environment: 'production' }); // Com configuração customizada const nfe = new NfeClient({ apiKey: process.env.NFE_API_KEY, environment: 'production', timeout: 60000, retryConfig: { maxRetries: 5, baseDelay: 1000, maxDelay: 30000, backoffMultiplier: 2 } }); // Apenas com chave de dados (para serviços de consulta) const nfe = new NfeClient({ dataApiKey: 'sua-chave-dados' }); ``` -------------------------------- ### Companies - create Example Source: https://github.com/nfe/client-nodejs/blob/master/docs/EXTENSIBILITY_SUMMARY.md Example of creating a new company. ```typescript import { NfeClient } from "@cloud-cli/nfe"; const client = new NfeClient({ apiKey: "YOUR_API_KEY" }); async function createCompany() { try { const company = await client.companies.create({ // ... company details name: "My Company", taxId: "12345678000199", }); console.log("Company created:", company); } catch (error) { console.error("Error creating company:", error); } } ``` -------------------------------- ### Webhooks - create Example Source: https://github.com/nfe/client-nodejs/blob/master/docs/EXTENSIBILITY_SUMMARY.md Example of creating a new webhook subscription. ```typescript import { NfeClient } from "@cloud-cli/nfe"; const client = new NfeClient({ apiKey: "YOUR_API_KEY" }); async function createWebhook() { try { const webhook = await client.webhooks.create({ companyId: "YOUR_COMPANY_ID", url: "https://your.domain.com/webhook", events: ["invoice.created", "invoice.updated"], }); console.log("Webhook created:", webhook); } catch (error) { console.error("Error creating webhook:", error); } } ``` -------------------------------- ### Offset-based Pagination Source: https://github.com/nfe/client-nodejs/blob/master/skills/nfeio-sdk/SKILL.md Example of offset-based pagination for resources like service invoices, companies, people, and webhooks, showing how to specify page index and count. ```typescript const page = await nfe.serviceInvoices.list(companyId, { pageIndex: 0, // 0-based page number pageCount: 50, // Items per page }); // page.data: ServiceInvoiceData[] // page.totalCount: number ``` -------------------------------- ### Advanced Search Examples Source: https://github.com/nfe/client-nodejs/blob/master/openspec/changes/implement-companies-resource/proposal.md Examples of how to use the advanced search methods for companies. ```typescript // Find by tax number const company = await nfe.companies.findByTaxNumber(12345678901234); // Find by name pattern const matches = await nfe.companies.findByName('Acme Corp'); // Get companies with valid certificates const withCerts = await nfe.companies.getCompaniesWithCertificates(); // Get companies with expiring certificates (within 30 days) const expiring = await nfe.companies.getCompaniesWithExpiringCertificates(30); ``` -------------------------------- ### Client.ts - getConfig Example Source: https://github.com/nfe/client-nodejs/blob/master/docs/EXTENSIBILITY_SUMMARY.md Example of retrieving the current NfeClient configuration. ```typescript import { NfeClient } from "@cloud-cli/nfe"; const client = new NfeClient({ apiKey: "YOUR_API_KEY", }); const config = client.getConfig(); console.log(config); // { apiKey: 'YOUR_API_KEY', baseURL: 'https://api.nfse.io/v3', timeout: 30000 } ``` -------------------------------- ### Service Invoices - create Example Source: https://github.com/nfe/client-nodejs/blob/master/docs/EXTENSIBILITY_SUMMARY.md Example of creating a new service invoice. ```typescript import { NfeClient } from "@cloud-cli/nfe"; const client = new NfeClient({ apiKey: "YOUR_API_KEY" }); async function createInvoice() { try { const invoice = await client.serviceInvoices.create({ companyId: "YOUR_COMPANY_ID", // ... other invoice details }); console.log("Invoice created:", invoice); } catch (error) { console.error("Error creating invoice:", error); } } ``` -------------------------------- ### createBatch Example Source: https://github.com/nfe/client-nodejs/blob/master/_autodocs/api-reference/notas-fiscais-servico.md Example demonstrating how to use the createBatch method to create multiple service invoices. ```typescript const notas = [ { borrower: { federalTaxNumber: 11111111111111, name: 'Cliente 1' }, cityServiceCode: '01234', servicesAmount: 500.00 }, { borrower: { federalTaxNumber: 22222222222222, name: 'Cliente 2' }, cityServiceCode: '01234', servicesAmount: 750.00 } ]; const resultado = await nfe.serviceInvoices.createBatch(companyId, notas, { waitForComplete: true, maxConcurrent: 3 }); console.log(`✅ ${resultado.length} notas fiscais criadas em lote`); ``` -------------------------------- ### Companies - retrieve Example Source: https://github.com/nfe/client-nodejs/blob/master/docs/EXTENSIBILITY_SUMMARY.md Example of retrieving a company by ID. ```typescript import { NfeClient } from "@cloud-cli/nfe"; const client = new NfeClient({ apiKey: "YOUR_API_KEY" }); async function getCompany(companyId: string) { try { const company = await client.companies.retrieve(companyId); console.log("Company:", company); } catch (error) { console.error("Error retrieving company:", error); } } ``` -------------------------------- ### Companies - update Example Source: https://github.com/nfe/client-nodejs/blob/master/docs/EXTENSIBILITY_SUMMARY.md Example of updating an existing company. ```typescript import { NfeClient } from "@cloud-cli/nfe"; const client = new NfeClient({ apiKey: "YOUR_API_KEY" }); async function updateCompany(companyId: string) { try { const updatedCompany = await client.companies.update(companyId, { name: "Updated Company Name", }); console.log("Company updated:", updatedCompany); } catch (error) { console.error("Error updating company:", error); } } ``` -------------------------------- ### Index.ts - CommonJS Example Source: https://github.com/nfe/client-nodejs/blob/master/docs/EXTENSIBILITY_SUMMARY.md Example of how to import and use NfeClient with CommonJS. ```javascript const { NfeClient, createClientFromEnv, isEnvironmentSupported, getRuntimeInfo, validateApiKeyFormat, } = require("@cloud-cli/nfe"); // Example usage if (isEnvironmentSupported()) { const runtimeInfo = getRuntimeInfo(); console.log(runtimeInfo); const apiKey = process.env.NFE_API_KEY; if (apiKey && validateApiKeyFormat(apiKey)) { const client = createClientFromEnv(); // Use the client... } } ``` -------------------------------- ### GitHub Actions CI/CD Example Source: https://github.com/nfe/client-nodejs/blob/master/tests/integration/README.md Example configuration for running integration tests automatically via GitHub Actions. ```yaml name: Integration Tests on: schedule: - cron: '0 0 * * *' # Daily workflow_dispatch: # Manual trigger jobs: integration: runs-on: ubuntu-latest steps: - uses: actions/checkout@v4 - uses: actions/setup-node@v4 with: node-version: '18' - run: npm ci - name: Run integration tests env: NFE_API_KEY: ${{ secrets.NFE_DEV_API_KEY }} NFE_TEST_ENVIRONMENT: development RUN_INTEGRATION_TESTS: true run: npm run test:integration ``` -------------------------------- ### Client.ts - updateConfig Example Source: https://github.com/nfe/client-nodejs/blob/master/docs/EXTENSIBILITY_SUMMARY.md Example of dynamically updating the NfeClient configuration. ```typescript import { NfeClient } from "@cloud-cli/nfe"; const client = new NfeClient(); // Update configuration client.updateConfig({ apiKey: "NEW_API_KEY", baseURL: "https://api.new.com/v3", }); ``` -------------------------------- ### Create State Tax Example Source: https://github.com/nfe/client-nodejs/blob/master/docs/API.md Example of how to create a new state tax registration. ```typescript const tax = await nfe.stateTaxes.create('company-id', { taxNumber: '123456789', serie: 1, number: 1, code: 'sP', environmentType: 'production', type: 'nFe', }); console.log('Created:', tax.id); ``` -------------------------------- ### Client.ts - getClientInfo Example Source: https://github.com/nfe/client-nodejs/blob/master/docs/EXTENSIBILITY_SUMMARY.md Example of retrieving diagnostic information about the NfeClient. ```typescript import { NfeClient } from "@cloud-cli/nfe"; const client = new NfeClient(); const clientInfo = client.getClientInfo(); console.log(clientInfo); // { version: '3.0.0', platform: 'node', nodeVersion: '18.17.0', ... } ``` -------------------------------- ### Companies - uploadCertificate Example Source: https://github.com/nfe/client-nodejs/blob/master/docs/EXTENSIBILITY_SUMMARY.md Example of uploading a digital certificate for a company. ```typescript import { NfeClient } from "@cloud-cli/nfe"; import * as fs from 'fs'; const client = new NfeClient({ apiKey: "YOUR_API_KEY" }); async function uploadCert(companyId: string, certPath: string, keyPath: string) { try { const certificate = fs.readFileSync(certPath); const privateKey = fs.readFileSync(keyPath); const result = await client.companies.uploadCertificate(companyId, { certificate, privateKey, }); console.log("Certificate uploaded:", result); } catch (error) { console.error("Error uploading certificate:", error); } } ``` -------------------------------- ### Setup Manual - Credenciais Source: https://github.com/nfe/client-nodejs/blob/master/examples/README.md Configure suas credenciais no arquivo .env.test na raiz do projeto. ```bash NFE_API_KEY=sua-chave-api-aqui NFE_TEST_ENVIRONMENT=development ``` -------------------------------- ### Service Invoices - createAndWait Example Source: https://github.com/nfe/client-nodejs/blob/master/docs/EXTENSIBILITY_SUMMARY.md Example of creating a service invoice and waiting for it to be processed. ```typescript import { NfeClient } from "@cloud-cli/nfe"; const client = new NfeClient({ apiKey: "YOUR_API_KEY" }); async function createAndProcessInvoice(invoiceData: any) { try { const result = await client.serviceInvoices.createAndWait(invoiceData, { companyId: "YOUR_COMPANY_ID", interval: 3000, // Poll every 3 seconds timeout: 120000, // Timeout after 2 minutes }); console.log("Invoice processed:", result); } catch (error) { console.error("Error creating and processing invoice:", error); } } ``` -------------------------------- ### List State Taxes Example Source: https://github.com/nfe/client-nodejs/blob/master/docs/API.md Example of how to list all state tax registrations for a company. ```typescript const result = await nfe.stateTaxes.list('company-id'); for (const tax of result.stateTaxes ?? []) { console.log(tax.id, tax.taxNumber, tax.code, tax.serie, tax.status); } ``` -------------------------------- ### Service Invoices - downloadXml Example Source: https://github.com/nfe/client-nodejs/blob/master/docs/EXTENSIBILITY_SUMMARY.md Example of downloading the XML of a service invoice. ```typescript import { NfeClient } from "@cloud-cli/nfe"; const client = new NfeClient({ apiKey: "YOUR_API_KEY" }); async function downloadInvoiceXml(invoiceId: string) { try { const xmlString = await client.serviceInvoices.downloadXml(invoiceId, { companyId: "YOUR_COMPANY_ID", }); // Process the xmlString... console.log("XML downloaded successfully."); } catch (error) { console.error("Error downloading XML:", error); } } ``` -------------------------------- ### Get current automatic NF-e inbound settings Source: https://github.com/nfe/client-nodejs/blob/master/docs/API.md Example of retrieving the current automatic NF-e inbound settings. ```typescript const settings = await nfe.inboundProductInvoices.getSettings('company-id'); console.log('Status:', settings.status); console.log('Environment:', settings.environmentSEFAZ); console.log('Webhook version:', settings.webhookVersion); console.log('Start NSU:', settings.startFromNsu); ``` -------------------------------- ### Setup Rápido para Testes Source: https://github.com/nfe/client-nodejs/blob/master/README.md Passos para clonar o repositório, instalar dependências, configurar credenciais e testar a conexão. ```bash # 1. Clone e instale git clone https://github.com/nfe/client-nodejs.git cd client-nodejs npm install # 2. Configure suas credenciais (interativo) npm run examples:setup # 3. Teste a conexão npm run examples:test # 4. Execute os exemplos npm run examples ``` -------------------------------- ### Legal People - create Example Source: https://github.com/nfe/client-nodejs/blob/master/docs/EXTENSIBILITY_SUMMARY.md Example of creating a new legal person (company). ```typescript import { NfeClient } from "@cloud-cli/nfe"; const client = new NfeClient({ apiKey: "YOUR_API_KEY" }); async function createLegalPerson() { try { const legalPerson = await client.legalPeople.create({ companyId: "YOUR_COMPANY_ID", name: "Legal Person Name", taxId: "11111111000111", // ... other details }); console.log("Legal person created:", legalPerson); } catch (error) { console.error("Error creating legal person:", error); } } ``` -------------------------------- ### List service invoices for a company Source: https://github.com/nfe/client-nodejs/blob/master/skills/nfeio-sdk/SKILL.md Example of how to list service invoices for a specific company using the NFe client SDK. ```typescript // List service invoices for a company const invoices = await nfe.serviceInvoices.list('company-uuid', { pageIndex: 0, pageCount: 50, }); ``` -------------------------------- ### Webhook Creation and Validation Source: https://github.com/nfe/client-nodejs/blob/master/skills/nfeio-sdk/SKILL.md Example of creating a webhook with specified events and URL, and validating incoming webhook signatures using the provided secret. ```typescript // Create webhook const webhook = await nfe.webhooks.create(companyId, { url: 'https://your-app.com/webhooks/nfe', events: ['invoice.created', 'invoice.issued', 'invoice.cancelled', 'invoice.failed'], active: true, }); // Validate incoming webhook signature (in your handler) const isValid = nfe.webhooks.validateSignature( rawBody, // Request body as string signature, // X-Hub-Signature header value webhook.secret!, // Secret from webhook creation ); ``` -------------------------------- ### Build do SDK Source: https://github.com/nfe/client-nodejs/blob/master/examples/START_HERE.txt Comando para realizar o build do SDK. ```bash npm run build ``` -------------------------------- ### Cursor-based Pagination Source: https://github.com/nfe/client-nodejs/blob/master/skills/nfeio-sdk/SKILL.md Example of cursor-based pagination for resources like product invoices and state taxes, demonstrating the use of 'limit' and 'startingAfter' parameters. ```typescript const page = await nfe.productInvoices.list(companyId, { environment: 'Production', // REQUIRED for product invoices limit: 25, startingAfter: 'last-invoice-id', // Cursor for next page }); ``` -------------------------------- ### Create a legal person under a company Source: https://github.com/nfe/client-nodejs/blob/master/skills/nfeio-sdk/SKILL.md Example of how to create a legal person (company) within a specific company context using the NFe client SDK. ```typescript // Create a legal person under a company const person = await nfe.legalPeople.create('company-uuid', { federalTaxNumber: '11444555000149', // String for people resources name: 'Example Company Ltda', email: 'contact@example.com', }); ``` -------------------------------- ### CI Workflow Source: https://github.com/nfe/client-nodejs/blob/master/openspec/changes/generate-sdk-from-openapi/design.md The CI workflow for the project, including steps for setup, dependency installation, validation, generation, type checking, linting, testing, and building. ```yaml name: CI on: [push, pull_request] jobs: test: runs-on: ubuntu-latest steps: - uses: actions/checkout@v4 - name: Setup Node.js uses: actions/setup-node@v4 with: node-version: '18' cache: 'npm' - name: Install dependencies run: npm ci - name: Validate OpenAPI specs run: npm run validate:spec - name: Generate types run: npm run generate - name: Type check run: npm run typecheck - name: Lint run: npm run lint - name: Test run: npm run test -- --run - name: Build run: npm run build ``` -------------------------------- ### Error Handling Example Source: https://github.com/nfe/client-nodejs/blob/master/skills/nfeio-sdk/SKILL.md Demonstrates how to catch and handle various NFeError types, including specific errors like AuthenticationError, ValidationError, and PollingTimeoutError, as well as generic NfeError. ```typescript import { NfeError, AuthenticationError, ValidationError, NotFoundError, RateLimitError, TimeoutError, PollingTimeoutError, isNfeError, isValidationError, } from 'nfe-io'; try { const invoice = await nfe.serviceInvoices.createAndWait(companyId, data); } catch (error) { if (error instanceof AuthenticationError) { console.error('Check your API key'); } else if (error instanceof ValidationError) { console.error('Invalid data:', error.details); } else if (error instanceof PollingTimeoutError) { console.error('Invoice still processing after timeout'); } else if (isNfeError(error)) { console.error(`${error.type} [${error.statusCode}]: ${error.message}`); console.error('Details:', error.details); } } ``` -------------------------------- ### Using createAndWait for asynchronous invoice processing Source: https://github.com/nfe/client-nodejs/blob/master/skills/nfeio-sdk/SKILL.md Example demonstrating the use of `createAndWait()` for automatically handling polling and waiting for asynchronous invoice creation to complete, with configurable polling options. ```typescript const invoice = await nfe.serviceInvoices.createAndWait(companyId, { cityServiceCode: '2690', description: 'IT Consulting Services', servicesAmount: 1500.00, borrower: { federalTaxNumber: 11444555000149, name: 'Client Company', email: 'client@example.com', }, }, { timeout: 300000, // 5 min (some municipalities are slow) initialDelay: 1000, // 1s before first poll maxDelay: 10000, // Max 10s between polls backoffFactor: 1.5, // Exponential backoff onPoll: (attempt, flowStatus) => { console.log(`Poll #${attempt}: ${flowStatus}`); }, }); console.log('Invoice status:', invoice.flowStatus); // 'Issued' | 'IssueFailed' ``` -------------------------------- ### Teste sua Configuração Source: https://github.com/nfe/client-nodejs/blob/master/examples/README.md Teste a conexão e as credenciais configuradas. ```bash npm run examples:test ``` ```bash node examples/test-connection.js ``` -------------------------------- ### IntelliSense Demo - Basic Usage Source: https://github.com/nfe/client-nodejs/blob/master/docs/EXTENSIBILITY_SUMMARY.md Demonstrates how to leverage JSDoc for IntelliSense in VS Code. ```typescript /** * Represents a user in the system. */ interface User { /** Unique identifier for the user. */ id: number; /** User's full name. */ name: string; /** User's email address. */ email: string; } /** * Fetches a user by their ID. * @param userId The ID of the user to fetch. * @returns A Promise that resolves with the User object. */ async function getUserById(userId: number): Promise { // Implementation details... return { id: userId, name: 'John Doe', email: 'john.doe@example.com' }; } // In VS Code, typing getUserById(1) and then pressing '.' will show available methods/properties. // Hovering over getUserById will show the JSDoc description and parameters. ``` -------------------------------- ### Delete Company Example Source: https://github.com/nfe/client-nodejs/blob/master/_autodocs/api-reference/empresas.md Example of deleting a company. ```typescript await nfe.companies.delete(companyId); console.log('Empresa deletada'); ``` -------------------------------- ### Configuração inicial interativa Source: https://github.com/nfe/client-nodejs/blob/master/examples/START_HERE.txt Comando para iniciar a configuração interativa das credenciais. ```bash npm run examples:setup ``` -------------------------------- ### Update Company Example Source: https://github.com/nfe/client-nodejs/blob/master/_autodocs/api-reference/empresas.md Example of updating company information. ```typescript const atualizada = await nfe.companies.update(companyId, { email: 'novoemail@empresa.com.br', description: 'Descrição atualizada' }); console.log(`Email atualizado: ${atualizada.email}`); ``` -------------------------------- ### Retrieve Company Example Source: https://github.com/nfe/client-nodejs/blob/master/_autodocs/api-reference/empresas.md Example of retrieving company details. ```typescript const empresa = await nfe.companies.retrieve(companyId); console.log(`Nome: ${empresa.name}`); console.log(`CNPJ: ${empresa.federalTaxNumber}`); console.log(`Email: ${empresa.email}`); console.log(`Regime tributário: ${empresa.taxRegime}`); ``` -------------------------------- ### Executar todos os exemplos Source: https://github.com/nfe/client-nodejs/blob/master/examples/START_HERE.txt Comando para executar todos os exemplos disponíveis. ```bash node examples/run-examples.js all ``` -------------------------------- ### Example 1: Basic batch creation Source: https://github.com/nfe/client-nodejs/blob/master/docs/API.md Demonstrates the basic usage of createBatch to create multiple service invoices. ```typescript // Example 1: Basic batch creation const invoicesData = [ { borrower: { federalTaxNumber: 111, name: 'Client 1', email: 'client1@example.com' }, cityServiceCode: '10677', description: 'Service 1', servicesAmount: 1000, }, { borrower: { federalTaxNumber: 222, name: 'Client 2', email: 'client2@example.com' }, cityServiceCode: '10677', description: 'Service 2', servicesAmount: 2000, }, { borrower: { federalTaxNumber: 333, name: 'Client 3', email: 'client3@example.com' }, cityServiceCode: '10677', description: 'Service 3', servicesAmount: 3000, }, ]; const invoices = await nfe.serviceInvoices.createBatch('company-id', invoicesData); console.log(`Created ${invoices.length} invoices`); invoices.forEach(inv => console.log(`- ${inv.number}: R$ ${inv.servicesAmount}`)); ``` -------------------------------- ### List Companies Example Source: https://github.com/nfe/client-nodejs/blob/master/_autodocs/api-reference/empresas.md Example of listing companies with pagination. ```typescript const resultado = await nfe.companies.list({ pageIndex: 0, pageCount: 20 }); console.log(`Total: ${resultado.total}`); for (const empresa of resultado.data) { console.log(`${empresa.name} (${empresa.federalTaxNumber})`); } ``` -------------------------------- ### Instalação com npm Source: https://github.com/nfe/client-nodejs/blob/master/README.md Comando para instalar o SDK usando npm. ```bash npm install nfe-io ``` -------------------------------- ### Create Company Example Source: https://github.com/nfe/client-nodejs/blob/master/_autodocs/api-reference/empresas.md Example of creating a new company. ```typescript const empresa = await nfe.companies.create({ federalTaxNumber: 12345678000190, name: 'Minha Empresa LTDA', email: 'empresa@example.com.br', taxRegime: 1, // Simples Nacional address: { country: 'BRA', postalCode: '01310-100', street: 'Av. Paulista', number: '1578', city: { code: '3550308', name: 'São Paulo' }, state: 'SP' } }); console.log(`Empresa criada: ${empresa.id}`); ``` -------------------------------- ### isTerminalFlowStatus Example Source: https://github.com/nfe/client-nodejs/blob/master/_autodocs/tipos.md Example usage of the isTerminalFlowStatus function. ```typescript if (isTerminalFlowStatus(invoice.flowStatus)) { console.log('Processamento concluído'); } ``` -------------------------------- ### Comandos de Setup de Desenvolvimento Source: https://github.com/nfe/client-nodejs/blob/master/CONTRIBUTING.md Instruções para clonar o repositório, instalar dependências, validar specs OpenAPI, gerar tipos, rodar testes, build e typecheck. ```bash # Clone o repositório git clone https://github.com/nfe/client-nodejs.git cd client-nodejs # Instale dependências npm install # Valide specs OpenAPI npm run validate:spec # Gere tipos do OpenAPI npm run generate # Rode testes npm test # Build npm run build # Typecheck npm run typecheck ``` -------------------------------- ### Delete Legal Person Example Source: https://github.com/nfe/client-nodejs/blob/master/_autodocs/api-reference/pessoas-juridicas.md Example of deleting a legal person. ```typescript await nfe.legalPeople.delete(companyId, personId); console.log('Pessoa deletada'); ``` -------------------------------- ### Setup Inicial com Validação Source: https://github.com/nfe/client-nodejs/blob/master/_autodocs/utilitarios-e-padroes.md Exemplo de configuração inicial do cliente NFE.io com validações. ```typescript import { NfeClient, isEnvironmentSupported, validateApiKeyFormat, ConfigurationError } from 'nfe-io'; async function setupNfeClient(): Promise { // 1. Validar ambiente const envCheck = isEnvironmentSupported(); if (!envCheck.supported) { throw new Error(`Ambiente incompatível: ${envCheck.issues.join(', ')}`); } // 2. Validar chave API const apiKey = process.env.NFE_API_KEY; if (!apiKey) { throw new ConfigurationError('NFE_API_KEY não definida'); } const keyValidation = validateApiKeyFormat(apiKey); if (!keyValidation.valid) { throw new Error(`Chave API inválida: ${keyValidation.issues.join(', ')}`); } // 3. Criar cliente const nfe = new NfeClient({ apiKey, dataApiKey: process.env.NFE_DATA_API_KEY, environment: (process.env.NODE_ENV === 'production') ? 'production' : 'development', timeout: parseInt(process.env.API_TIMEOUT || '30000', 10) }); // 4. Testar conexão const health = await nfe.healthCheck(); if (health.status !== 'ok') { throw new Error(`Falha ao conectar com API: ${JSON.stringify(health.details)}`); } console.log('✅ Cliente NFE.io configurado com sucesso'); return nfe; } // Usar const nfe = await setupNfeClient(); ``` -------------------------------- ### Update Legal Person Example Source: https://github.com/nfe/client-nodejs/blob/master/_autodocs/api-reference/pessoas-juridicas.md Example of updating information for a legal person. ```typescript const atualizada = await nfe.legalPeople.update(companyId, personId, { email: 'novoemail@empresa.com.br' }); console.log('Email atualizado'); ``` -------------------------------- ### Menu de exemplos Source: https://github.com/nfe/client-nodejs/blob/master/examples/START_HERE.txt Comando para executar o menu interativo que permite escolher e executar exemplos. ```bash npm run examples ``` -------------------------------- ### Client.ts - Constructor Example 1 (Default) Source: https://github.com/nfe/client-nodejs/blob/master/docs/EXTENSIBILITY_SUMMARY.md Example of creating an NfeClient instance with default configuration. ```typescript import { NfeClient } from "@cloud-cli/nfe"; const client = new NfeClient(); ``` -------------------------------- ### List States Example Source: https://github.com/nfe/client-nodejs/blob/master/_autodocs/api-reference/enderecos.md Example of how to list all Brazilian states using the listStates method. ```typescript const resultado = await nfe.addresses.listStates(); console.log(resultado.states); // ['AC', 'AL', 'AP', ...] ``` -------------------------------- ### 2. real-world-list-invoices.js - Consulta de Notas Fiscais Source: https://github.com/nfe/client-nodejs/blob/master/examples/README.md Demonstra como listar e consultar notas fiscais existentes, incluindo paginação e detalhes completos. ```bash node examples/real-world-list-invoices.js ``` -------------------------------- ### Instalação com pnpm Source: https://github.com/nfe/client-nodejs/blob/master/README.md Comando para instalar o SDK usando pnpm. ```bash pnpm add nfe-io ``` -------------------------------- ### Retrieve Legal Person Example Source: https://github.com/nfe/client-nodejs/blob/master/_autodocs/api-reference/pessoas-juridicas.md Example of retrieving details of a specific legal person. ```typescript const pessoa = await nfe.legalPeople.retrieve(companyId, personId); console.log(`Nome: ${pessoa.name}`); console.log(`CNPJ: ${pessoa.federalTaxNumber}`); console.log(`Email: ${pessoa.email}`); ``` -------------------------------- ### Client.ts - Constructor Example 2 (API Key) Source: https://github.com/nfe/client-nodejs/blob/master/docs/EXTENSIBILITY_SUMMARY.md Example of creating an NfeClient instance with a specific API key. ```typescript import { NfeClient } from "@cloud-cli/nfe"; const client = new NfeClient({ apiKey: "YOUR_API_KEY", }); ``` -------------------------------- ### Executar exemplo específico Source: https://github.com/nfe/client-nodejs/blob/master/examples/START_HERE.txt Comando para executar um exemplo específico, passando o ID do exemplo como argumento. ```bash node examples/run-examples.js 1 ``` -------------------------------- ### List Legal People Example Source: https://github.com/nfe/client-nodejs/blob/master/_autodocs/api-reference/pessoas-juridicas.md Example of listing all legal people for a company with pagination. ```typescript const resultado = await nfe.legalPeople.list(companyId, { pageIndex: 0, pageCount: 20 }); console.log(`Total: ${resultado.total}`); for (const pessoa of resultado.data) { console.log(`${pessoa.name} (${pessoa.federalTaxNumber})`); } ``` -------------------------------- ### Create Legal Person Example Source: https://github.com/nfe/client-nodejs/blob/master/_autodocs/api-reference/pessoas-juridicas.md Example of creating a new legal person (company/PJ). ```typescript const pessoa = await nfe.legalPeople.create(companyId, { federalTaxNumber: 12345678000190, name: 'Empresa Cliente LTDA', email: 'empresa@cliente.com.br', address: { country: 'BRA', postalCode: '01310-100', street: 'Av. Paulista', number: '1000', city: { code: '3550308', name: 'São Paulo' }, state: 'SP' } }); console.log(`PJ criada: ${pessoa.id}`); ``` -------------------------------- ### Processo de Build Source: https://github.com/nfe/client-nodejs/blob/master/README.md Comando para executar o processo de build, que inclui validação de specs, geração de tipos, typecheck e compilação. ```bash npm run build # → Executa: validate:spec → generate → typecheck → tsup ``` -------------------------------- ### Companies - delete Example Source: https://github.com/nfe/client-nodejs/blob/master/docs/EXTENSIBILITY_SUMMARY.md Example of deleting a company. ```typescript import { NfeClient } from "@cloud-cli/nfe"; const client = new NfeClient({ apiKey: "YOUR_API_KEY" }); async function deleteCompany(companyId: string) { try { const result = await client.companies.delete(companyId); console.log("Company deleted:", result); } catch (error) { console.error("Error deleting company:", error); } } ``` -------------------------------- ### Instalação com yarn Source: https://github.com/nfe/client-nodejs/blob/master/README.md Comando para instalar o SDK usando yarn. ```bash yarn add nfe-io ``` -------------------------------- ### Example 1: Basic invoice creation (may be sync or async) Source: https://github.com/nfe/client-nodejs/blob/master/docs/API.md Demonstrates basic service invoice creation and how to handle both synchronous (201) and asynchronous (202) responses, including polling for async results. ```typescript // Example 1: Basic invoice creation (may be sync or async) const result = await nfe.serviceInvoices.create('company-id', { borrower: { federalTaxNumber: 12345678901, name: 'João da Silva', email: 'joao@example.com', }, cityServiceCode: '10677', description: 'Consulting services', servicesAmount: 1500.00, }); // Check if synchronous (201) or asynchronous (202) if ('id' in result) { // Synchronous - invoice issued immediately console.log('Invoice issued:', result.number); console.log('Status:', result.status); } else { // Asynchronous - needs polling console.log('Processing:', result.flowStatus); console.log('Poll URL:', result.location); // Use pollUntilComplete or createAndWait instead const invoice = await nfe.pollUntilComplete(result.location, { intervalMs: 2000, timeoutMs: 60000, }); console.log('Invoice issued:', invoice.number); } ``` -------------------------------- ### Companies Resource Example Source: https://github.com/nfe/client-nodejs/blob/master/_autodocs/api-reference/cliente-nfe.md Example of how to use the companies resource to create a company. ```typescript const company = await nfe.companies.create({ federalTaxNumber: 12345678000190, name: 'Minha Empresa' }); ``` -------------------------------- ### Example Service Invoice Creation and Waiting Source: https://github.com/nfe/client-nodejs/blob/master/openspec/changes/implement-service-invoices/proposal.md Demonstrates how to create a service invoice and wait for its completion. ```javascript import { createServiceInvoice, createAndWaitServiceInvoice } from "@nfe-io/client-nodejs/dist/core/resources/service-invoices"; async function example() { const companyId = "YOUR_COMPANY_ID"; const invoiceData = { /* ... invoice data ... */ }; // Manual creation const createdInvoice = await createServiceInvoice(companyId, invoiceData); console.log("Invoice created:", createdInvoice); // Create and wait for completion const completedInvoice = await createAndWaitServiceInvoice(companyId, invoiceData, { timeout: 120000, // 120 seconds pollingInterval: 1000, // 1 second }); console.log("Invoice completed:", completedInvoice); } example(); ``` -------------------------------- ### 0. test-connection.js - Teste de Conexão Source: https://github.com/nfe/client-nodejs/blob/master/examples/README.md Script de diagnóstico que verifica sua configuração, credenciais, conexão com a API, empresas disponíveis e recursos do SDK. ```bash node examples/test-connection.js ``` -------------------------------- ### Find Legal Person by Tax Number Example Source: https://github.com/nfe/client-nodejs/blob/master/_autodocs/api-reference/pessoas-juridicas.md Example of finding a legal person by their CNPJ. ```typescript const pessoa = await nfe.legalPeople.findByTaxNumber( companyId, '12.345.678/0001-90' ); if (pessoa) { console.log(`Encontrada: ${pessoa.name}`); } else { console.log('Não encontrada'); } ``` -------------------------------- ### 4. real-world-webhooks.js - Configuração de Webhooks Source: https://github.com/nfe/client-nodejs/blob/master/examples/README.md Demonstra como configurar webhooks para receber eventos, incluindo listagem, criação e exemplo de validação de assinatura. ```bash node examples/real-world-webhooks.js ``` -------------------------------- ### Webhooks - validateSignature Example Source: https://github.com/nfe/client-nodejs/blob/master/docs/EXTENSIBILITY_SUMMARY.md Example of validating a webhook signature. ```typescript import { NfeClient } from "@cloud-cli/nfe"; const client = new NfeClient({ apiKey: "YOUR_API_KEY" }); // Assuming you have the raw request body and signature header const rawBody = "..."; const signature = "..."; const isValid = client.webhooks.validateSignature(rawBody, signature, { companyId: "YOUR_COMPANY_ID", }); console.log("Webhook signature is valid:", isValid); ``` -------------------------------- ### Configuração via Variáveis de Ambiente Source: https://github.com/nfe/client-nodejs/blob/master/README.md Exemplo de configuração do SDK NFE usando variáveis de ambiente. ```bash # Configurar via ambiente export NFE_API_KEY="sua-chave-api" export NFE_DATA_API_KEY="sua-chave-data" # Usar SDK sem passar chaves no código const nfe = new NfeClient({}); ``` -------------------------------- ### Extending SDK - Express Adapter Example Source: https://github.com/nfe/client-nodejs/blob/master/docs/EXTENSIBILITY_SUMMARY.md Example of building an adapter for Express.js to integrate NFE.io functionality. ```typescript import express, { Request, Response } from 'express'; import { NfeClient } from '@cloud-cli/nfe'; const app = express(); app.use(express.json()); const client = new NfeClient({ apiKey: process.env.NFE_API_KEY }); // Example route to create an invoice app.post('/invoices', async (req: Request, res: Response) => { try { const invoiceData = req.body; const companyId = req.headers['x-company-id'] as string; if (!companyId) { return res.status(400).json({ error: 'Missing x-company-id header' }); } const createdInvoice = await client.serviceInvoices.create({ ...invoiceData, companyId, }); res.status(201).json(createdInvoice); } catch (error) { console.error('Error creating invoice via Express:', error); res.status(500).json({ error: 'Failed to create invoice' }); } }); const PORT = process.env.PORT || 3000; app.listen(PORT, () => { console.log(`Server running on port ${PORT}`); }); ``` -------------------------------- ### Configuration with Environment Variables Source: https://github.com/nfe/client-nodejs/blob/master/_autodocs/configuracao.md Example of initializing NfeClient using environment variables for API keys. ```typescript const nfe = new NfeClient({ environment: process.env.NODE_ENV === 'production' ? 'production' : 'development' }); // Usa NFE_API_KEY do ambiente ``` -------------------------------- ### Execução Rápida com Helper Script - Modo Interativo Source: https://github.com/nfe/client-nodejs/blob/master/examples/README.md Use o script helper para executar exemplos em modo interativo. ```bash node examples/run-examples.js ``` -------------------------------- ### ConnectionError Example Source: https://github.com/nfe/client-nodejs/blob/master/_autodocs/erros.md Example of how to catch and handle a ConnectionError, which is thrown for network or connection problems. ```typescript import { ConnectionError } from 'nfe-io'; try { await nfe.companies.list(); } catch (error) { if (error instanceof ConnectionError) { console.error('Erro de conexão com API'); // Verificar conectividade } } ``` -------------------------------- ### Index.ts - ES Modules Example Source: https://github.com/nfe/client-nodejs/blob/master/docs/EXTENSIBILITY_SUMMARY.md Example of how to import and use NfeClient with ES Modules. ```typescript import { NfeClient, createClientFromEnv, isEnvironmentSupported, getRuntimeInfo, validateApiKeyFormat, } from "@cloud-cli/nfe"; // Example usage if (isEnvironmentSupported()) { const runtimeInfo = getRuntimeInfo(); console.log(runtimeInfo); const apiKey = process.env.NFE_API_KEY; if (apiKey && validateApiKeyFormat(apiKey)) { const client = createClientFromEnv(); // Use the client... } } ```