From a4968ebd0a0f421dab19175a199b7ac3506d301a Mon Sep 17 00:00:00 2001 From: Andre Kutianski Date: Wed, 18 Nov 2026 20:19:31 -0300 Subject: [PATCH 1/6] fix(tax-id): o SDK para de recusar CNPJ e chave de acesso que a API aceita Uma regra unica de CNPJ, CPF e chave de acesso (src/core/utils/tax-id.ts, interno) passa a valer em todos os recursos: - companies.create, update e findByTaxNumber aceitam CNPJ ou CPF que perdeu o zero a esquerda como number. A API completa os zeros (medido em 2026-11-18 com escrita autorizada). CNPJ alfanumerico recebe um erro que aponta a API v3 de empresas. - inboundProductInvoices, productInvoiceQuery, consumerInvoiceQuery e transportationInvoices aceitam letras nas posicoes 7 a 18 da chave (CNPJ alfanumerico do emitente) e enviam a chave em maiusculas. Cada rota da API decide se atende. - legalEntityLookup mantem as letras, confere o DV no cliente (modulo 11 com ASCII - 48) e recusa texto fora da mascara. - legalPeople.findByTaxNumber e naturalPeople.findByTaxNumber comparam pelo valor. Docs, exemplos e skill trocam o CNPJ de exemplo invalido 12345678000190 por 11222333000181 e explicam o formato com letras. A skill tambem corrige as opcoes e os campos da consulta de CNPJ e o padrao de CEP. Evidencia em tests/fixtures/live-contracts/alphanumeric-tax-ids.json. Refs #36 --- MIGRATION.md | 2 +- README.md | 24 +- docs/API.md | 30 +-- docs/recursos/companies.md | 14 ++ docs/recursos/inbound-product-invoices.md | 12 + docs/recursos/legal-entity-lookup.md | 13 + examples/cnpj-lookup.js | 4 +- examples/jsdoc-intellisense-demo.ts | 4 +- examples/product-invoices.js | 2 +- examples/service-invoice-complete.js | 2 +- skills/nfeio-node-sdk/SKILL.md | 6 +- .../references/data-services-and-lookups.md | 57 +++-- .../references/product-invoices-and-taxes.md | 11 +- .../service-invoices-and-polling.md | 13 +- src/core/client.ts | 10 +- src/core/resources/companies.ts | 122 ++++----- src/core/resources/consumer-invoice-query.ts | 35 +-- .../resources/inbound-product-invoices.ts | 84 +++---- src/core/resources/legal-entity-lookup.ts | 60 ++--- src/core/resources/legal-people.ts | 8 +- src/core/resources/natural-people.ts | 6 +- src/core/resources/product-invoice-query.ts | 47 +--- src/core/resources/product-invoices.ts | 2 +- src/core/resources/transportation-invoices.ts | 48 ++-- src/core/utils/tax-id.ts | 238 ++++++++++++++++++ .../live-contracts/alphanumeric-tax-ids.json | 131 ++++++++++ .../integration/companies.integration.test.ts | 28 +++ tests/unit/companies.test.ts | 108 ++++++++ tests/unit/consumer-invoice-query.test.ts | 18 +- tests/unit/legal-entity-lookup.test.ts | 65 ++++- tests/unit/legal-people.test.ts | 21 ++ tests/unit/natural-people.test.ts | 19 ++ tests/unit/resources/companies-search.test.ts | 14 +- .../inbound-product-invoices.test.ts | 25 +- .../resources/product-invoice-query.test.ts | 15 +- .../resources/transportation-invoices.test.ts | 11 + tests/unit/utils/tax-id.test.ts | 168 +++++++++++++ 37 files changed, 1117 insertions(+), 360 deletions(-) create mode 100644 src/core/utils/tax-id.ts create mode 100644 tests/fixtures/live-contracts/alphanumeric-tax-ids.json create mode 100644 tests/unit/utils/tax-id.test.ts diff --git a/MIGRATION.md b/MIGRATION.md index 3d01a62..0126e4f 100644 --- a/MIGRATION.md +++ b/MIGRATION.md @@ -549,7 +549,7 @@ for await (const company of nfe.companies.listIterator()) { } // 🆕 Novo na v3: Métodos de busca -const company = await nfe.companies.findByTaxNumber(12345678000190); // CNPJ +const company = await nfe.companies.findByTaxNumber(11222333000181); // CNPJ const matches = await nfe.companies.findByName('Acme'); // Por nome const withCerts = await nfe.companies.getCompaniesWithCertificates(); const expiring = await nfe.companies.getCompaniesWithExpiringCertificates(30); diff --git a/README.md b/README.md index 91ae9f8..78f110c 100644 --- a/README.md +++ b/README.md @@ -95,7 +95,7 @@ const nfe = new NfeClient({ // Criar uma empresa const empresa = await nfe.companies.create({ - federalTaxNumber: '12345678000190', + federalTaxNumber: 11222333000181, name: 'Minha Empresa Ltda', email: 'empresa@exemplo.com.br', taxRegime: 1, // Simples Nacional @@ -116,7 +116,7 @@ const notaFiscal = await nfe.serviceInvoices.create(empresa.id, { servicesAmount: 1000.00, borrower: { type: 'LegalEntity', - federalTaxNumber: 12345678000190, + federalTaxNumber: 11222333000181, name: 'Empresa Cliente', email: 'cliente@exemplo.com.br', address: { @@ -257,7 +257,7 @@ Gerenciar empresas na sua conta: // Criar empresa (a API exige name, federalTaxNumber, taxRegime e address) const empresa = await nfe.companies.create({ name: 'Nome da Empresa', - federalTaxNumber: 12345678000190, + federalTaxNumber: 11222333000181, taxRegime: 'SimplesNacional', address: { state: 'SP', @@ -302,7 +302,7 @@ Gerenciar pessoas jurídicas (empresas/negócios): ```typescript // Criar pessoa jurídica const pessoa = await nfe.legalPeople.create(empresaId, { - federalTaxNumber: '12345678000190', + federalTaxNumber: '11222333000181', name: 'Nome da Empresa', email: 'empresa@exemplo.com.br', address: { /* ... */ } @@ -312,7 +312,7 @@ const pessoa = await nfe.legalPeople.create(empresaId, { const pessoas = await nfe.legalPeople.list(empresaId); // Buscar por CNPJ -const pessoa = await nfe.legalPeople.findByTaxNumber(empresaId, '12345678000190'); +const pessoa = await nfe.legalPeople.findByTaxNumber(empresaId, '11222333000181'); ``` #### 👤 Pessoas Físicas (`nfe.naturalPeople`) @@ -547,7 +547,7 @@ Ciclo completo de gestão de NF-e (Nota Fiscal Eletrônica de Produto) — emiss const result = await nfe.productInvoices.create('empresa-id', { operationNature: 'Venda de mercadoria', operationType: 'Outgoing', - buyer: { name: 'Empresa LTDA', federalTaxNumber: 12345678000190 }, + buyer: { name: 'Empresa LTDA', federalTaxNumber: 11222333000181 }, items: [{ code: 'PROD-001', description: 'Produto X', quantity: 1, unitAmount: 100 }], payment: [{ paymentDetail: [{ method: 'Cash', amount: 100 }] }], }); @@ -660,7 +660,7 @@ Consultar dados cadastrais de empresas brasileiras (CNPJ) na Receita Federal e n ```typescript // Consulta básica por CNPJ (aceita com ou sem pontuação) -const result = await nfe.legalEntityLookup.getBasicInfo('12.345.678/0001-90'); +const result = await nfe.legalEntityLookup.getBasicInfo('11.222.333/0001-81'); console.log('Razão Social:', result.legalEntity?.name); console.log('Nome Fantasia:', result.legalEntity?.tradeName); console.log('Status:', result.legalEntity?.status); // 'Active' @@ -668,20 +668,20 @@ console.log('Porte:', result.legalEntity?.size); // 'ME', 'EPP', etc. console.log('Cidade:', result.legalEntity?.address?.city?.name); // Consulta com opções -const result = await nfe.legalEntityLookup.getBasicInfo('12345678000190', { +const result = await nfe.legalEntityLookup.getBasicInfo('11222333000181', { updateAddress: false, // Não atualizar endereço via Correios updateCityCode: true, // Atualizar código IBGE da cidade }); // Consultar Inscrição Estadual (IE) por estado -const ieSP = await nfe.legalEntityLookup.getStateTaxInfo('SP', '12345678000190'); +const ieSP = await nfe.legalEntityLookup.getStateTaxInfo('SP', '11222333000181'); for (const tax of ieSP.legalEntity?.stateTaxes ?? []) { console.log(`IE: ${tax.taxNumber} - Status: ${tax.status}`); console.log(` NFe: ${tax.nfe?.status}, CTe: ${tax.cte?.status}`); } // Avaliar IE para emissão de nota fiscal -const invoice = await nfe.legalEntityLookup.getStateTaxForInvoice('MG', '12345678000190'); +const invoice = await nfe.legalEntityLookup.getStateTaxForInvoice('MG', '11222333000181'); for (const tax of invoice.legalEntity?.stateTaxes ?? []) { if (tax.status === 'Abled') { console.log(`Pode emitir com IE: ${tax.taxNumber}`); @@ -689,7 +689,7 @@ for (const tax of invoice.legalEntity?.stateTaxes ?? []) { } // Obter melhor IE sugerida para emissão -const sugestao = await nfe.legalEntityLookup.getSuggestedStateTaxForInvoice('SP', '12345678000190'); +const sugestao = await nfe.legalEntityLookup.getSuggestedStateTaxForInvoice('SP', '11222333000181'); const melhorIE = sugestao.legalEntity?.stateTaxes?.[0]; console.log('IE recomendada:', melhorIE?.taxNumber); ``` @@ -920,7 +920,7 @@ async function emitirNotaFiscal() { servicesAmount: 5000.00, borrower: { type: 'LegalEntity', - federalTaxNumber: 12345678000190, + federalTaxNumber: 11222333000181, name: 'Cliente Exemplo Ltda', email: 'contato@cliente.com.br', address: { diff --git a/docs/API.md b/docs/API.md index 407b998..e31fffb 100644 --- a/docs/API.md +++ b/docs/API.md @@ -237,7 +237,7 @@ Create a new service invoice. Returns either a completed invoice (201) or async interface ServiceInvoiceData { // Required fields borrower: { - federalTaxNumber: number; // CPF (11 digits) or CNPJ (14 digits) + federalTaxNumber: number; // CPF or CNPJ as a number (leading zeros may be lost); alphanumeric CNPJ needs the v3 API name: string; email?: string; address?: { @@ -313,7 +313,7 @@ if ('id' in result) { // Example 2: Invoice with full details const invoice = await nfe.serviceInvoices.create('company-id', { borrower: { - federalTaxNumber: 12345678000190, + federalTaxNumber: 11222333000181, name: 'Acme Corporation', email: 'finance@acme.com', address: { @@ -1070,7 +1070,7 @@ Create a new company with automatic CNPJ/CPF validation. ```typescript const company = await nfe.companies.create({ - federalTaxNumber: 12345678000190, // CNPJ (14 digits) or CPF (11 digits) + federalTaxNumber: 11222333000181, // CNPJ or CPF as a number; one that starts with zero may lose it (01234567999885 → 1234567999885) name: 'My Company', email: 'company@example.com', address: { @@ -1254,8 +1254,8 @@ if (warning) { Find company by federal tax number (CNPJ or CPF). ```typescript -// Search by CNPJ (14 digits) -const company = await nfe.companies.findByTaxNumber(12345678000190); +// Search by CNPJ, as a number (a CNPJ that starts with zero is found by the short number) +const company = await nfe.companies.findByTaxNumber(11222333000181); // Or by CPF (11 digits) const company = await nfe.companies.findByTaxNumber(12345678901); @@ -1338,7 +1338,7 @@ Create a legal person. ```typescript const legalPerson = await nfe.legalPeople.create('company-id', { - federalTaxNumber: '12345678000190', + federalTaxNumber: '11222333000181', name: 'Legal Person Company', email: 'legal@example.com' }); @@ -1383,7 +1383,7 @@ await nfe.legalPeople.delete('company-id', 'person-id'); Find legal person by CNPJ. ```typescript -const person = await nfe.legalPeople.findByTaxNumber('company-id', '12345678000190'); +const person = await nfe.legalPeople.findByTaxNumber('company-id', '11222333000181'); ``` ### Natural People @@ -2081,13 +2081,13 @@ Query Brazilian company (CNPJ) data from Receita Federal and state tax registrie Lookup basic company information by CNPJ from Receita Federal. Returns legal name, trade name, address, phone numbers, economic activities (CNAE), legal nature, partners, and registration status. ```typescript -const result = await nfe.legalEntityLookup.getBasicInfo('12.345.678/0001-90'); +const result = await nfe.legalEntityLookup.getBasicInfo('11.222.333/0001-81'); console.log(result.legalEntity?.name); // 'EMPRESA LTDA' console.log(result.legalEntity?.status); // 'Active' console.log(result.legalEntity?.address?.city?.name); // With options -const result = await nfe.legalEntityLookup.getBasicInfo('12345678000190', { +const result = await nfe.legalEntityLookup.getBasicInfo('11222333000181', { updateAddress: false, updateCityCode: true, }); @@ -2097,7 +2097,7 @@ const result = await nfe.legalEntityLookup.getBasicInfo('12345678000190', { | Parameter | Type | Required | Description | |-----------|------|----------|-------------| -| `federalTaxNumber` | `string` | Yes | CNPJ, with or without punctuation (e.g., `"12345678000190"` or `"12.345.678/0001-90"`) | +| `federalTaxNumber` | `string` | Yes | CNPJ, with or without punctuation (e.g., `"11222333000181"`, `"11.222.333/0001-81"` or the alphanumeric `"12.ABC.345/01DE-35"`). Punctuation is removed and letters are kept, in upper case | | `options` | `LegalEntityBasicInfoOptions` | No | Lookup options | **Options:** @@ -2110,7 +2110,7 @@ const result = await nfe.legalEntityLookup.getBasicInfo('12345678000190', { **Returns:** `LegalEntityBasicInfoResponse` — Company basic information including address, phones, activities, partners. **Throws:** -- `ValidationError` if CNPJ format is invalid (not 14 digits after stripping punctuation) +- `ValidationError` if the CNPJ is out of format (12 letters or digits followed by 2 check digits) or its check digits do not match (checked locally, modulo 11 with ASCII − 48), or when the API answers `400`: the `v2` routes reject an alphanumeric CNPJ with "CNPJ alfanumérico não é suportado nesta versão. Utilize a v3." - `NotFoundError` if no company found for the given CNPJ (HTTP 404) - `AuthenticationError` if API key is invalid (HTTP 401) @@ -2119,7 +2119,7 @@ const result = await nfe.legalEntityLookup.getBasicInfo('12345678000190', { Lookup state tax registration (Inscrição Estadual) by CNPJ and state. Returns tax regime, legal nature, and state tax registration details including fiscal document indicators (NFe, NFSe, CTe, NFCe). ```typescript -const result = await nfe.legalEntityLookup.getStateTaxInfo('SP', '12345678000190'); +const result = await nfe.legalEntityLookup.getStateTaxInfo('SP', '11222333000181'); console.log(result.legalEntity?.taxRegime); // 'SimplesNacional' for (const tax of result.legalEntity?.stateTaxes ?? []) { @@ -2146,7 +2146,7 @@ for (const tax of result.legalEntity?.stateTaxes ?? []) { Evaluate state tax registration for invoice issuance. Returns extended status information (including `UnabledTemp`, `UnabledNotConfirmed`) useful for determining whether product invoices (NF-e) can be issued. ```typescript -const result = await nfe.legalEntityLookup.getStateTaxForInvoice('MG', '12345678000190'); +const result = await nfe.legalEntityLookup.getStateTaxForInvoice('MG', '11222333000181'); for (const tax of result.legalEntity?.stateTaxes ?? []) { if (tax.status === 'Abled') { console.log(`Can issue invoices with IE: ${tax.taxNumber}`); @@ -2172,7 +2172,7 @@ for (const tax of result.legalEntity?.stateTaxes ?? []) { Get the best (suggested) state tax registration for invoice issuance. When multiple registrations are enabled in a state, NFE.io applies evaluation criteria to recommend the optimal IE. ```typescript -const result = await nfe.legalEntityLookup.getSuggestedStateTaxForInvoice('SP', '12345678000190'); +const result = await nfe.legalEntityLookup.getSuggestedStateTaxForInvoice('SP', '11222333000181'); const bestIE = result.legalEntity?.stateTaxes?.[0]; if (bestIE) { console.log(`Recommended IE: ${bestIE.taxNumber} (${bestIE.status})`); @@ -2486,7 +2486,7 @@ Issue a product invoice (NF-e) by posting it to the processing queue. const result = await nfe.productInvoices.create('company-id', { operationNature: 'Venda de mercadoria', operationType: 'Outgoing', - buyer: { name: 'Empresa LTDA', federalTaxNumber: 12345678000190 }, + buyer: { name: 'Empresa LTDA', federalTaxNumber: 11222333000181 }, items: [{ code: 'PROD-001', description: 'Produto X', quantity: 1, unitAmount: 100 }], payment: [{ paymentDetail: [{ method: 'Cash', amount: 100 }] }], }); diff --git a/docs/recursos/companies.md b/docs/recursos/companies.md index 9a22533..9d97db1 100644 --- a/docs/recursos/companies.md +++ b/docs/recursos/companies.md @@ -42,6 +42,20 @@ if (await nfe.companies.exists(company.id)) { } ``` +### O CNPJ (`federalTaxNumber`) + +- **Tipo `number`.** A API v1 de empresas trabalha com o CNPJ (ou CPF) como número. +- **Zero à esquerda.** Um CNPJ que começa com zero perde esse zero como número: + `01234567999885` vira `1234567999885`. O SDK aceita o número assim e confere os dígitos + verificadores depois de completar com zeros; a API faz o mesmo e grava as 14 posições. A + leitura pela v1 devolve o número curto, e regravar a empresa com ele funciona. + `findByTaxNumber` compara pelo valor, então acha a empresa pelo número curto. +- **String só com dígitos.** Em JavaScript sem tipos, uma string de 14 dígitos (CNPJ) ou 11 + (CPF) também é aceita, porque a API v1 aceita. +- **CNPJ alfanumérico** (IN RFB 2.229/2024, com letras nas 12 primeiras posições). A API v1 de + empresas não aceita esse formato; só a API v3 aceita. O SDK lança `ValidationError` antes da + requisição. + ## Iterar todas as empresas ```typescript diff --git a/docs/recursos/inbound-product-invoices.md b/docs/recursos/inbound-product-invoices.md index 24fc488..e7da970 100644 --- a/docs/recursos/inbound-product-invoices.md +++ b/docs/recursos/inbound-product-invoices.md @@ -42,6 +42,18 @@ await nfe.inboundProductInvoices.enableAutoFetch(companyId, { /* config */ }); const settings = await nfe.inboundProductInvoices.getSettings(companyId); ``` +:::warning Emitente com CNPJ alfanumérico +Quando o emitente tem CNPJ alfanumérico (IN RFB 2.229/2024), a chave de acesso tem letras nas +posições 7 a 18. O SDK aceita esse formato, converte as letras para maiúsculas e deixa cada rota +da API decidir: + +- `getProductInvoiceDetails`, `getProductInvoiceEventDetails` e `getJson` usam + `/inbound/productinvoices/{chave}…`, que aceita a chave com letras. +- `getDetails`, `getEventDetails`, `getXml`, `getPdf` e `getEventXml` usam `/inbound/{chave}…`. + Em 18/11/2026, essas rotas ainda respondiam `400` ("access key must have 44 digits") para + chave com letras, e o SDK repassa esse erro como `ValidationError`. +::: + ## Próximos passos - [CT-e](./transportation-invoices.md) diff --git a/docs/recursos/legal-entity-lookup.md b/docs/recursos/legal-entity-lookup.md index 00faaf7..0f2fb7d 100644 --- a/docs/recursos/legal-entity-lookup.md +++ b/docs/recursos/legal-entity-lookup.md @@ -30,6 +30,19 @@ const { legalEntity } = await nfe.legalEntityLookup.getBasicInfo('06990590000123 console.log(legalEntity?.name, legalEntity?.address?.city?.name); ``` +## Formato do CNPJ + +- **Com ou sem máscara.** O SDK remove `.`, `/`, `-` e espaços e converte letras para + maiúsculas antes de montar a URL. `'06.990.590/0001-23'` e `'06990590000123'` dão a mesma + consulta. +- **12 letras ou dígitos e 2 dígitos verificadores** (IN RFB 2.229/2024). O SDK confere os + dígitos verificadores (módulo 11, com o valor ASCII − 48 de cada caractere) e lança + `ValidationError` sem fazer a requisição quando eles não batem. A API também recusa esse + CNPJ, com `400`. +- **CNPJ alfanumérico.** As letras chegam à API, mas este recurso usa a versão `v2` da + consulta, que só aceita CNPJ numérico. A API responde `400` com "CNPJ alfanumérico não é + suportado nesta versão. Utilize a v3.", e o SDK lança `ValidationError` com essa mensagem. + ## Próximos passos - [Consulta CPF](./natural-person-lookup.md) · [Consulta CEP](./addresses.md) diff --git a/examples/cnpj-lookup.js b/examples/cnpj-lookup.js index 560b804..81ebf3a 100644 --- a/examples/cnpj-lookup.js +++ b/examples/cnpj-lookup.js @@ -24,7 +24,7 @@ const client = new NfeClient({ }); // Example CNPJ — replace with a real one for testing -const EXAMPLE_CNPJ = process.env.TEST_CNPJ || '12345678000190'; +const EXAMPLE_CNPJ = process.env.TEST_CNPJ || '11222333000181'; const EXAMPLE_STATE = process.env.TEST_STATE || 'SP'; /** @@ -98,7 +98,7 @@ async function lookupWithOptions() { try { // Formatted CNPJ is accepted — punctuation is stripped automatically - const result = await client.legalEntityLookup.getBasicInfo('12.345.678/0001-90', { + const result = await client.legalEntityLookup.getBasicInfo('11.222.333/0001-81', { updateAddress: false, // Skip postal service address enrichment updateCityCode: true, // But still update city IBGE code }); diff --git a/examples/jsdoc-intellisense-demo.ts b/examples/jsdoc-intellisense-demo.ts index f27958b..6a53ec1 100644 --- a/examples/jsdoc-intellisense-demo.ts +++ b/examples/jsdoc-intellisense-demo.ts @@ -53,7 +53,7 @@ async function demonstrateJSDoc() { type: 'LegalEntity' as const, name: 'Client Name', email: 'client@example.com', - federalTaxNumber: 12345678000190, + federalTaxNumber: 11222333000181, address: { country: 'BRA', postalCode: '01310-100', @@ -141,7 +141,7 @@ async function demonstrateJSDoc() { // Hover to see CNPJ lookup documentation const legalPerson = await nfe.legalPeople.findByTaxNumber( companyId, - '12345678000190' + '11222333000181' ); // Hover to see CPF lookup documentation diff --git a/examples/product-invoices.js b/examples/product-invoices.js index 1ae369c..bbe2826 100644 --- a/examples/product-invoices.js +++ b/examples/product-invoices.js @@ -42,7 +42,7 @@ async function main() { operationType: 'Outgoing', buyer: { name: 'Empresa Exemplo LTDA', - federalTaxNumber: 12345678000190, + federalTaxNumber: 11222333000181, address: { street: 'Rua Exemplo', number: '100', diff --git a/examples/service-invoice-complete.js b/examples/service-invoice-complete.js index e563aec..76fb60c 100644 --- a/examples/service-invoice-complete.js +++ b/examples/service-invoice-complete.js @@ -60,7 +60,7 @@ const createdInvoiceIds = []; function createInvoiceData(description = 'Consulting Services') { return { borrower: { - federalTaxNumber: 12345678901, // CPF (11 digits) or CNPJ (14 digits) + federalTaxNumber: 12345678901, // CPF or CNPJ as a number (a document that starts with zero loses it); alphanumeric CNPJ needs the v3 API name: 'João da Silva', email: 'joao.silva@example.com', }, diff --git a/skills/nfeio-node-sdk/SKILL.md b/skills/nfeio-node-sdk/SKILL.md index 1cd825f..2f50c5d 100644 --- a/skills/nfeio-node-sdk/SKILL.md +++ b/skills/nfeio-node-sdk/SKILL.md @@ -365,7 +365,7 @@ on the live API — fetch the real list with `await nfe.webhooks.fetchEventTypes 1. **Import path**: Use `'nfe-io'` not `'@nfe-io/sdk'`. The JSDoc uses `@nfe-io/sdk` but the npm package is `nfe-io`. -2. **`federalTaxNumber` type varies**: For `companies.create()` it's a **number** (`12345678000190`). For `legalPeople`/`naturalPeople` and lookup resources it's a **string** (`'12345678000190'`). +2. **`federalTaxNumber` type varies**: For `companies.create()` it's a **number** (`11222333000181`). For `legalPeople`/`naturalPeople` and lookup resources it's a **string** (`'11222333000181'`). A CNPJ or CPF that starts with zero loses it as a number (`01234567999885` → `1234567999885`): since 6.0.2 the SDK accepts that short number, as the API does, and `companies.findByTaxNumber` compares by value. Lookups accept the CNPJ with or without punctuation and check the check digits locally. 3. **`serviceInvoices.create()` returns a union**: The return type is `{ status: 'immediate', invoice } | { status: 'async', response }`. Always use `createAndWait()` unless you need manual control. @@ -381,7 +381,9 @@ on the live API — fetch the real list with `await nfe.webhooks.fetchEventTypes 9. **Polling timeout**: Default is 2 minutes. Some municipalities take 3-5 minutes. Set `timeout: 300000` for production use. -10. **Access keys**: Must be exactly 44 numeric digits. Used for query resources and inbound documents. +10. **Access keys**: 44 characters, used for query resources and inbound documents. Positions 7–18 hold the issuer CNPJ, so they may contain letters when the issuer has an alphanumeric CNPJ; since 6.0.2 the SDK accepts that and sends the key upper case. The API decides per route: inbound `getProductInvoiceDetails`, `getProductInvoiceEventDetails` and `getJson` accept it; `getDetails`, `getXml`, `getPdf`, `getEventDetails`, `getEventXml` and the NF-e query still answer `400` (measured 2026-11-18). + +15. **Alphanumeric CNPJ (IN RFB 2.229/2024)**: only the API's v3 family accepts it, and this SDK version calls v1/v2. `legalEntityLookup` sends the letters and the API answers `400` "CNPJ alfanumérico não é suportado nesta versão. Utilize a v3." (a `ValidationError`); `companies.create()`/`update()` reject it locally, because the v1 companies API does not accept it. Detect it with a letter in the first 12 characters. Do not reject the letters F, I, O, U or Q: the Receita Federal accepts all 26. 11. **Correction letters**: `sendCorrectionLetter()` text must be 15-1000 characters, no accents or special characters. diff --git a/skills/nfeio-node-sdk/references/data-services-and-lookups.md b/skills/nfeio-node-sdk/references/data-services-and-lookups.md index 1178d03..a289c71 100644 --- a/skills/nfeio-node-sdk/references/data-services-and-lookups.md +++ b/skills/nfeio-node-sdk/references/data-services-and-lookups.md @@ -70,7 +70,8 @@ Queries NF-e data directly from SEFAZ by access key. No company scope needed. ### retrieve(accessKey): Promise ```typescript -// Access key must be exactly 44 numeric digits +// 44 characters; positions 7–18 (issuer CNPJ) may hold letters since 6.0.2. +// This query route still answers 400 for a key with letters (measured 2026-11-18). const invoice = await nfe.productInvoiceQuery.retrieve('35210512345678000190550010000001231123456789'); ``` @@ -154,33 +155,37 @@ Queries Receita Federal for company data by CNPJ. ### getBasicInfo(cnpj, options?): Promise ```typescript -// CNPJ accepts formatted or raw string -const info = await nfe.legalEntityLookup.getBasicInfo('12.345.678/0001-90'); -const info = await nfe.legalEntityLookup.getBasicInfo('12345678000190'); +// The response wraps the entity: { legalEntity } +const { legalEntity } = await nfe.legalEntityLookup.getBasicInfo('11.222.333/0001-81'); +await nfe.legalEntityLookup.getBasicInfo('11222333000181'); // same query interface LegalEntityBasicInfoOptions { - includePartners?: boolean; // Include partner/shareholder info - includeActivities?: boolean; // Include CNAE economic activities + updateAddress?: boolean; // Update the address from postal service data (default: true) + updateCityCode?: boolean; // With updateAddress: false, update only the city code (default: false) } ``` -**LegalEntityBasicInfo** key fields: +CNPJ input (all four methods), since 6.0.2: +- Punctuation (`.`, `/`, `-`, spaces) is removed and letters go upper case; letters are never stripped. +- Format: 12 letters or digits + 2 check digits. The SDK checks the check digits (modulo 11, ASCII − 48 per character) and throws `ValidationError` without a request when they do not match; the API also answers `400` for them. +- Alphanumeric CNPJ: these methods call the `v2` routes, which accept only numeric CNPJ. The API answers `400` "CNPJ alfanumérico não é suportado nesta versão. Utilize a v3.", raised as `ValidationError`. + +**LegalEntityBasicInfo** key fields (all optional in the type): ```typescript { - federalTaxNumber: string; // CNPJ - name: string; // Legal name (razao social) + federalTaxNumber?: number; // CNPJ as NUMBER on v2: a leading zero is lost (00000000000191 → 191) + name?: string; // Legal name (razao social) tradeName?: string; // Trade name (nome fantasia) - status: LegalEntityStatus; // 'Active' | 'Suspended' | 'Cancelled' | ... - size: LegalEntitySize; // 'ME' | 'EPP' | 'DEMAIS' - unit: LegalEntityUnit; // 'Headoffice' | 'Subsidiary' - natureCode: LegalEntityNatureCode; - taxRegime: LegalEntityTaxRegime; // 'SimplesNacional' | 'MEI' | 'Normal' | 'Unknown' - openingDate?: string; + status?: LegalEntityStatus; // 'Active' | 'Suspended' | 'Cancelled' | ... + size?: LegalEntitySize; // 'ME' | 'EPP' | 'DEMAIS' | 'Unknown' + unit?: LegalEntityUnit; // 'Headoffice' | 'Subsidiary' + legalNature?: LegalEntityNature; + openedOn?: string; email?: string; - capital?: number; // Social capital + shareCapital?: number; // Social capital address?: LegalEntityAddress; phones?: LegalEntityPhone[]; - activities?: LegalEntityEconomicActivity[]; // CNAE codes + economicActivities?: LegalEntityEconomicActivity[]; // CNAE codes partners?: LegalEntityPartner[]; } ``` @@ -195,7 +200,7 @@ type LegalEntityStatus = 'Unknown' | 'Active' | 'Suspended' | 'Cancelled' | 'Una Get state tax registrations (Inscricoes Estaduais) for a specific state: ```typescript -const taxInfo = await nfe.legalEntityLookup.getStateTaxInfo('SP', '12345678000190'); +const taxInfo = await nfe.legalEntityLookup.getStateTaxInfo('SP', '11222333000181'); ``` **BrazilianState** type — all 27 UF codes plus special values: @@ -209,12 +214,13 @@ type BrazilianState = | 'NA'; // Not applicable ``` -Returns state tax registrations with status per state: +Returns `{ legalEntity }` with `taxRegime`, `legalNature` and the registrations in `stateTaxes`: ```typescript interface LegalEntityStateTax { - taxNumber: string; // IE number - state: BrazilianState; - status: LegalEntityStateTaxStatus; // 'Abled' | 'Unabled' | 'Cancelled' | 'Unknown' + taxNumber?: string; // IE number + code?: BrazilianState; // UF of the registration + status?: LegalEntityStateTaxStatus; // 'Abled' | 'Unabled' | 'Cancelled' | 'Unknown' + nfe?: LegalEntityFiscalDocumentInfo; // also nfse, cte, nfce } ``` @@ -269,15 +275,14 @@ type NaturalPersonStatus = ### Address from CEP to Invoice ```typescript -// 1. Look up address by CEP -const { addresses } = await nfe.addresses.lookupByPostalCode('01310-100'); -const addr = addresses[0]; +// 1. Look up address by CEP (returns a single Address) +const addr = await nfe.addresses.lookupByPostalCode('01310-100'); // 2. Use in invoice borrower await nfe.serviceInvoices.createAndWait(companyId, { // ... borrower: { - federalTaxNumber: 12345678000190, + federalTaxNumber: 11222333000181, name: 'Client', address: { country: addr.country, diff --git a/skills/nfeio-node-sdk/references/product-invoices-and-taxes.md b/skills/nfeio-node-sdk/references/product-invoices-and-taxes.md index 6334488..a0a004f 100644 --- a/skills/nfeio-node-sdk/references/product-invoices-and-taxes.md +++ b/skills/nfeio-node-sdk/references/product-invoices-and-taxes.md @@ -292,7 +292,7 @@ await nfe.transportationInvoices.enable(companyId, { ### retrieve(companyId, accessKey): Promise -Get CT-e metadata by 44-digit access key. +Get CT-e metadata by its 44-character access key. This route (`/inbound/{accessKey}`) still answers `400` for a key with letters (alphanumeric CNPJ issuer); the SDK sends it and raises the API error. ### getEvent(companyId, accessKey, eventKey): Promise @@ -328,7 +328,12 @@ interface EnableInboundOptions { ### Document Access Methods -`accessKey` is the 44-digit key; `eventKey` identifies an event of that document. +`accessKey` is the 44-character key; `eventKey` identifies an event of that document. Positions 7–18 +hold the issuer CNPJ and may contain letters (alphanumeric CNPJ): since 6.0.2 the SDK accepts that +and sends the key upper case. Measured on 2026-11-18, the `productinvoices` methods +(`getProductInvoiceDetails`, `getProductInvoiceEventDetails`, `getJson`) accept it; `getDetails`, +`getEventDetails`, `getXml`, `getEventXml` and `getPdf` use `/inbound/{accessKey}`, which still +answers `400` ("access key must have 44 digits"), raised as `ValidationError`. | Method | Returns | |--------|---------| @@ -361,7 +366,7 @@ type ManifestEventType = ### reprocessWebhook(companyId, accessKeyOrNsu): Promise -Resends the webhook notification for a document, identified by its 44-digit access key or by its +Resends the webhook notification for a document, identified by its 44-character access key or by its NSU. --- diff --git a/skills/nfeio-node-sdk/references/service-invoices-and-polling.md b/skills/nfeio-node-sdk/references/service-invoices-and-polling.md index e47f82e..b363505 100644 --- a/skills/nfeio-node-sdk/references/service-invoices-and-polling.md +++ b/skills/nfeio-node-sdk/references/service-invoices-and-polling.md @@ -30,7 +30,7 @@ interface ServiceInvoiceAsyncResponse { description: string; // Service description servicesAmount: number; // Total service amount borrower: { - federalTaxNumber: number; // CNPJ (14 digits) or CPF (11 digits) as NUMBER + federalTaxNumber: number; // CNPJ or CPF as NUMBER (v1); one that starts with zero loses it. Alphanumeric CNPJ: API v3 only name: string; email?: string; address?: { @@ -163,7 +163,7 @@ interface Company { id: string; name: string; tradeName?: string; - federalTaxNumber: number; // CNPJ (14 digits) or CPF (11 digits) as NUMBER + federalTaxNumber: number; // CNPJ or CPF as NUMBER (v1). Short numbers (lost leading zeros) are valid; alphanumeric CNPJ: API v3 only email: string; address?: Address; // Auto-populated: @@ -172,7 +172,7 @@ interface Company { } ``` -Validates CNPJ (14-digit check digit algorithm) and CPF (11-digit check digit algorithm) before sending. +Validates `federalTaxNumber` before sending: a valid CNPJ (14 positions) or CPF (11 positions), checked by its check digits. Since 6.0.2 a number that lost its leading zeros (`1234567999885` for `01234567999885`) is accepted, as the API does (it pads and stores the 14 positions), and so is a string of digits. An alphanumeric CNPJ throws `ValidationError`: the v1 companies API does not accept it. ### list(options?): Promise> @@ -224,8 +224,9 @@ const exp = await nfe.companies.checkCertificateExpiration(companyId); ### Search Helpers ```typescript -// Find company by CNPJ/CPF (returns null if not found) -const company = await nfe.companies.findByTaxNumber(12345678000190); +// Find company by CNPJ/CPF (returns null if not found). Compares by value: +// a CNPJ that starts with zero is found by the short number (1234567999885). +const company = await nfe.companies.findByTaxNumber(11222333000181); // Search by name (returns array) const matches = await nfe.companies.findByName('Example'); @@ -265,7 +266,7 @@ interface LegalPerson { | `createBatch` | `(companyId, items[]): Promise` | | `findByTaxNumber` | `(companyId, taxNumber): Promise` | -`findByTaxNumber` returns `undefined` (not throwing `NotFoundError`) when not found. +`findByTaxNumber` returns `undefined` (not throwing `NotFoundError`) when not found. Since 6.0.2 it compares by value: punctuation is ignored and a record whose number lost its leading zeros still matches. --- diff --git a/src/core/client.ts b/src/core/client.ts index ee8f71c..62f0bd1 100644 --- a/src/core/client.ts +++ b/src/core/client.ts @@ -93,7 +93,7 @@ export { NATURAL_PERSON_API_BASE_URL } from './resources/index.js'; * * // Create a company * const company = await nfe.companies.create({ - * federalTaxNumber: '12345678000190', + * federalTaxNumber: 11222333000181, // v1: number. An alphanumeric CNPJ needs the v3 API * name: 'My Company' * }); * @@ -234,7 +234,7 @@ export class NfeClient { * @example * ```typescript * const company = await nfe.companies.create({ - * federalTaxNumber: '12345678000190', + * federalTaxNumber: 11222333000181, // v1: number. An alphanumeric CNPJ needs the v3 API * name: 'My Company', * email: 'company@example.com' * }); @@ -262,7 +262,7 @@ export class NfeClient { * @example * ```typescript * const legalPerson = await nfe.legalPeople.create(companyId, { - * federalTaxNumber: '12345678000190', + * federalTaxNumber: '11222333000181', * name: 'Legal Person Company' * }); * ``` @@ -549,11 +549,11 @@ export class NfeClient { * @example * ```typescript * // Basic CNPJ lookup - * const result = await nfe.legalEntityLookup.getBasicInfo('12.345.678/0001-90'); + * const result = await nfe.legalEntityLookup.getBasicInfo('11.222.333/0001-81'); * console.log(result.legalEntity?.name); * * // State tax registration - * const stateTax = await nfe.legalEntityLookup.getStateTaxInfo('SP', '12345678000190'); + * const stateTax = await nfe.legalEntityLookup.getStateTaxInfo('SP', '11222333000181'); * ``` */ get legalEntityLookup(): LegalEntityLookupResource { diff --git a/src/core/resources/companies.ts b/src/core/resources/companies.ts index 4831199..92b587d 100644 --- a/src/core/resources/companies.ts +++ b/src/core/resources/companies.ts @@ -18,6 +18,7 @@ import type { import type { HttpClient } from '../http/client.js'; import { ValidationError, NotFoundError } from '../errors/index.js'; import { CertificateValidator } from '../utils/certificate-validator.js'; +import { isAlphanumericCnpj, isSameTaxNumber, isValidCnpj, isValidCpf } from '../utils/tax-id.js'; // Page size for listAll/listIterator: the API caps GET /companies at // pageCount 50 (values above 50 — and also 1 — are rejected with a 400). @@ -111,61 +112,40 @@ function readListedCertificate(company: Company): CompanyCertificateV1 | undefin // ============================================================================ /** - * Validate CNPJ format (14 digits) with check digits - */ -function validateCNPJ(cnpj: number): boolean { - const cnpjStr = cnpj.toString().padStart(14, '0'); - if (cnpjStr.length !== 14) return false; - if (/^(\d)\1{13}$/.test(cnpjStr)) return false; // All same digits - - // Validate first check digit - let sum = 0; - let weight = 5; - for (let i = 0; i < 12; i++) { - sum += parseInt(cnpjStr[i]!) * weight; - weight = weight === 2 ? 9 : weight - 1; - } - const firstDigit = sum % 11 < 2 ? 0 : 11 - (sum % 11); - if (firstDigit !== parseInt(cnpjStr[12]!)) return false; - - // Validate second check digit - sum = 0; - weight = 6; - for (let i = 0; i < 13; i++) { - sum += parseInt(cnpjStr[i]!) * weight; - weight = weight === 2 ? 9 : weight - 1; - } - const secondDigit = sum % 11 < 2 ? 0 : 11 - (sum % 11); - if (secondDigit !== parseInt(cnpjStr[13]!)) return false; - - return true; -} - -/** - * Validate CPF format (11 digits) with check digits + * Valida o `federalTaxNumber` de uma empresa na API v1. + * + * - `number`: válido se, completado com zeros, for CNPJ de 14 posições ou CPF de 11. Um + * documento que começa com zero chega como número curto, e a API o completa: medido em + * 2026-11-18, `POST /v1/companies` com `1234567999885` responde `201` e grava + * `01234567999885`. Até a v6.0.1 o SDK recusava esse número pelo tamanho. + * - `string` só com dígitos (14 para CNPJ, 11 para CPF): aceita em tempo de execução, porque + * a API v1 aceita (`PUT` com a string de 14 posições respondeu `200`). O tipo continua `number`. + * - CNPJ alfanumérico: a API v1 de empresas não o aceita; só a v3. */ -function validateCPF(cpf: number): boolean { - const cpfStr = cpf.toString().padStart(11, '0'); - if (cpfStr.length !== 11) return false; - if (/^(\d)\1{10}$/.test(cpfStr)) return false; // All same digits - - // Validate first check digit - let sum = 0; - for (let i = 0; i < 9; i++) { - sum += parseInt(cpfStr[i]!) * (10 - i); +function validateCompanyTaxNumber(taxNumber: unknown): void { + if (typeof taxNumber === 'number') { + if (isValidCnpj(taxNumber) || isValidCpf(taxNumber)) return; + throw new ValidationError( + `Invalid federalTaxNumber: ${taxNumber}. Expected a valid CNPJ (14 digits) or CPF (11 digits); ` + + 'a number that lost its leading zeros is accepted.' + ); } - const firstDigit = sum % 11 < 2 ? 0 : 11 - (sum % 11); - if (firstDigit !== parseInt(cpfStr[9]!)) return false; - // Validate second check digit - sum = 0; - for (let i = 0; i < 10; i++) { - sum += parseInt(cpfStr[i]!) * (11 - i); + if (typeof taxNumber === 'string') { + if (isAlphanumericCnpj(taxNumber) && isValidCnpj(taxNumber)) { + throw new ValidationError( + 'Alphanumeric CNPJ is not accepted by the v1 companies API. The v3 companies API accepts it.' + ); + } + if (/^\d{14}$/.test(taxNumber) && isValidCnpj(taxNumber)) return; + if (/^\d{11}$/.test(taxNumber) && isValidCpf(taxNumber)) return; + throw new ValidationError( + `Invalid federalTaxNumber: "${taxNumber}". Expected a number, or a string of 14 digits (CNPJ) ` + + 'or 11 digits (CPF) with valid check digits.' + ); } - const secondDigit = sum % 11 < 2 ? 0 : 11 - (sum % 11); - if (secondDigit !== parseInt(cpfStr[10]!)) return false; - return true; + throw new ValidationError('federalTaxNumber must be a number'); } /** @@ -174,23 +154,7 @@ function validateCPF(cpf: number): boolean { function validateCompanyData(data: Partial): void { // Validate required fields for creation if ('federalTaxNumber' in data) { - const taxNumber = data.federalTaxNumber; - if (typeof taxNumber !== 'number') { - throw new ValidationError('federalTaxNumber must be a number'); - } - - const length = taxNumber.toString().length; - if (length === 14) { - if (!validateCNPJ(taxNumber)) { - throw new ValidationError('Invalid CNPJ format. Must be 14 digits and not all same digit.'); - } - } else if (length === 11) { - if (!validateCPF(taxNumber)) { - throw new ValidationError('Invalid CPF format. Must be 11 digits and not all same digit.'); - } - } else { - throw new ValidationError('federalTaxNumber must be 11 digits (CPF) or 14 digits (CNPJ)'); - } + validateCompanyTaxNumber(data.federalTaxNumber); } // Validate email format if provided @@ -259,7 +223,7 @@ export class CompaniesResource { * ```typescript * const company = await nfe.companies.create({ * name: 'Acme Corp', - * federalTaxNumber: 12345678000190, + * federalTaxNumber: 11222333000181, * taxRegime: 'SimplesNacional', * address: { * state: 'SP', @@ -786,12 +750,17 @@ export class CompaniesResource { /** * Find company by federal tax number (CNPJ or CPF) * - * @param taxNumber - Federal tax number (11 digits for CPF, 14 for CNPJ) + * A CNPJ or CPF that starts with zero loses those zeros as a `number` + * (`01234567999885` becomes `1234567999885`). The API v1 returns it that way, and + * this method accepts it: the comparison is by value, not by the count of digits. + * + * @param taxNumber - Federal tax number as a number (CNPJ or CPF, up to 14 digits) * @returns Company if found, null otherwise + * @throws {ValidationError} If `taxNumber` is not a non-negative integer with up to 14 digits * * @example * ```typescript - * const company = await nfe.companies.findByTaxNumber(12345678901234); + * const company = await nfe.companies.findByTaxNumber(11222333000181); * * if (company) { * console.log('Found:', company.name); @@ -801,16 +770,19 @@ export class CompaniesResource { * ``` */ async findByTaxNumber(taxNumber: number): Promise { - // Validate tax number format - const length = taxNumber.toString().length; - if (length !== 11 && length !== 14) { - throw new ValidationError('Tax number must be 11 digits (CPF) or 14 digits (CNPJ)'); + // Until 6.0.1 this required exactly 11 or 14 digits, which refused every + // document that starts with zero. Only the shape is checked here: a search + // for an invalid document simply finds nothing. + if (!Number.isSafeInteger(taxNumber) || taxNumber < 0 || String(taxNumber).length > 14) { + throw new ValidationError( + 'Tax number must be a non-negative integer with up to 14 digits (CNPJ or CPF)' + ); } const companies = await this.listAll(); const found = companies.find((company: Company) => - company.federalTaxNumber === taxNumber + isSameTaxNumber(company.federalTaxNumber, taxNumber) ); return found || null; diff --git a/src/core/resources/consumer-invoice-query.ts b/src/core/resources/consumer-invoice-query.ts index 6c1111e..980753f 100644 --- a/src/core/resources/consumer-invoice-query.ts +++ b/src/core/resources/consumer-invoice-query.ts @@ -8,38 +8,17 @@ import type { HttpClient } from '../http/client.js'; import type { TaxCoupon } from '../types.js'; -import { ValidationError } from '../errors/index.js'; +import { requireAccessKey } from '../utils/tax-id.js'; import { withUnservedRouteNote } from '../utils/unserved-route.js'; // ============================================================================ // Constants // ============================================================================ -/** Regex pattern for valid access key (44 numeric digits) */ -const ACCESS_KEY_PATTERN = /^\d{44}$/; - // ============================================================================ // Validation Helpers // ============================================================================ -/** - * Validates access key format (44 numeric digits) - * @param accessKey - The access key to validate - * @throws {ValidationError} If access key is empty or has invalid format - */ -function validateAccessKey(accessKey: string): void { - if (!accessKey || accessKey.trim() === '') { - throw new ValidationError('Access key is required'); - } - - const normalized = accessKey.trim(); - if (!ACCESS_KEY_PATTERN.test(normalized)) { - throw new ValidationError( - `Invalid access key: "${accessKey}". Expected 44 numeric digits.` - ); - } -} - // ============================================================================ // Resource Implementation // ============================================================================ @@ -90,7 +69,7 @@ export class ConsumerInvoiceQueryResource { /** * Retrieve full CFe-SAT coupon details from SEFAZ by access key * - * @param accessKey - 44-digit numeric access key (Chave de Acesso) + * @param accessKey - 44-character access key (Chave de Acesso; positions 7-18 may hold letters of an alphanumeric CNPJ) * @returns Full coupon details including issuer, buyer, items, totals, and payment * @throws {ValidationError} If access key format is invalid * @throws {NotFoundError} If no coupon matches the access key (HTTP 404) @@ -107,10 +86,10 @@ export class ConsumerInvoiceQueryResource { * ``` */ async retrieve(accessKey: string): Promise { - validateAccessKey(accessKey); + const key = requireAccessKey(accessKey); const response = await withUnservedRouteNote( 'GET /v1/consumerinvoices/coupon/{accessKey}', - () => this.http.get(`/v1/consumerinvoices/coupon/${accessKey.trim()}`) + () => this.http.get(`/v1/consumerinvoices/coupon/${key}`) ); return response.data; } @@ -118,7 +97,7 @@ export class ConsumerInvoiceQueryResource { /** * Download the raw CFe XML for a consumer invoice by access key * - * @param accessKey - 44-digit numeric access key (Chave de Acesso) + * @param accessKey - 44-character access key (Chave de Acesso; positions 7-18 may hold letters of an alphanumeric CNPJ) * @returns Buffer containing the XML binary content * @throws {ValidationError} If access key format is invalid * @throws {NotFoundError} If no coupon matches the access key (HTTP 404) @@ -133,12 +112,12 @@ export class ConsumerInvoiceQueryResource { * ``` */ async downloadXml(accessKey: string): Promise { - validateAccessKey(accessKey); + const key = requireAccessKey(accessKey); const response = await withUnservedRouteNote( 'GET /v1/consumerinvoices/coupon/{accessKey}.xml', () => this.http.getBuffer( - `/v1/consumerinvoices/coupon/${accessKey.trim()}.xml`, + `/v1/consumerinvoices/coupon/${key}.xml`, // Mesmo motivo do productInvoiceQuery: sem o JSON de segunda escolha, o // erro volta 406 de corpo vazio em vez da mensagem da API. 'application/xml, application/json;q=0.9' diff --git a/src/core/resources/inbound-product-invoices.ts b/src/core/resources/inbound-product-invoices.ts index a0d79c1..0c9449d 100644 --- a/src/core/resources/inbound-product-invoices.ts +++ b/src/core/resources/inbound-product-invoices.ts @@ -15,14 +15,12 @@ import type { ManifestEventType } from '../types.js'; import { ValidationError } from '../errors/index.js'; +import { requireAccessKey } from '../utils/tax-id.js'; // ============================================================================ // Constants // ============================================================================ -/** Regex pattern for valid access key (44 numeric digits) */ -const ACCESS_KEY_PATTERN = /^\d{44}$/; - /** Default manifest event type: Ciência da Operação */ const DEFAULT_MANIFEST_EVENT_TYPE: ManifestEventType = 210210; @@ -41,24 +39,6 @@ function validateCompanyId(companyId: string): void { } } -/** - * Validates access key format (44 numeric digits) - * @param accessKey - The access key to validate - * @throws {ValidationError} If access key format is invalid - */ -function validateAccessKey(accessKey: string): void { - if (!accessKey || accessKey.trim() === '') { - throw new ValidationError('Access key is required'); - } - - const normalized = accessKey.trim(); - if (!ACCESS_KEY_PATTERN.test(normalized)) { - throw new ValidationError( - `Invalid access key: "${accessKey}". Expected 44 numeric digits.` - ); - } -} - /** * Validates event key is not empty * @param eventKey - The event key to validate @@ -247,11 +227,11 @@ export class InboundProductInvoicesResource { /** * Get details of an inbound NF-e/CT-e by access key (webhook v1 format) * - * Retrieves the metadata of an inbound document using its 44-digit access key. + * Retrieves the metadata of an inbound document using its 44-character access key. * This is the generic endpoint that works for both NF-e and CT-e documents. * * @param companyId - The company ID that received the document - * @param accessKey - The 44-digit access key + * @param accessKey - The 44-character access key * @returns Promise with the inbound invoice metadata * @throws {ValidationError} If company ID or access key is invalid * @throws {NotFoundError} If the document is not found @@ -272,10 +252,10 @@ export class InboundProductInvoicesResource { accessKey: string ): Promise { validateCompanyId(companyId); - validateAccessKey(accessKey); + const key = requireAccessKey(accessKey); const response = await this.http.get( - `/v2/companies/${companyId}/inbound/${accessKey.trim()}` + `/v2/companies/${companyId}/inbound/${key}` ); return response.data; @@ -284,11 +264,11 @@ export class InboundProductInvoicesResource { /** * Get details of an inbound NF-e by access key (webhook v2 format) * - * Retrieves the metadata of an NF-e document using its 44-digit access key. + * Retrieves the metadata of an NF-e document using its 44-character access key. * This endpoint returns additional `productInvoices` array compared to the v1 format. * * @param companyId - The company ID that received the document - * @param accessKey - The 44-digit access key + * @param accessKey - The 44-character access key * @returns Promise with the inbound product invoice metadata (includes productInvoices array) * @throws {ValidationError} If company ID or access key is invalid * @throws {NotFoundError} If the document is not found @@ -308,14 +288,14 @@ export class InboundProductInvoicesResource { accessKey: string ): Promise { validateCompanyId(companyId); - validateAccessKey(accessKey); + const key = requireAccessKey(accessKey); // Plural `/inbound/productinvoices/` here and in the three methods below, as the platform // serves it. The singular form answers 404 with an empty body even without credentials, like an // invented path (measured 2026-10-14). The local spec consulta-nfe-distribuicao-v1.yaml // (vintage b487823) still says singular; upstream fixed it in nfe/docs@51d8816. const response = await this.http.get( - `/v2/companies/${companyId}/inbound/productinvoices/${accessKey.trim()}` + `/v2/companies/${companyId}/inbound/productinvoices/${key}` ); return response.data; @@ -331,7 +311,7 @@ export class InboundProductInvoicesResource { * Retrieves the metadata of an event associated with an inbound document. * * @param companyId - The company ID that received the document - * @param accessKey - The 44-digit access key of the parent document + * @param accessKey - The 44-character access key of the parent document * @param eventKey - The event key * @returns Promise with the event metadata * @throws {ValidationError} If any parameter is invalid @@ -353,11 +333,11 @@ export class InboundProductInvoicesResource { eventKey: string ): Promise { validateCompanyId(companyId); - validateAccessKey(accessKey); + const key = requireAccessKey(accessKey); validateEventKey(eventKey); const response = await this.http.get( - `/v2/companies/${companyId}/inbound/${accessKey.trim()}/events/${eventKey.trim()}` + `/v2/companies/${companyId}/inbound/${key}/events/${eventKey.trim()}` ); return response.data; @@ -370,7 +350,7 @@ export class InboundProductInvoicesResource { * Returns the webhook v2 format with `productInvoices` array. * * @param companyId - The company ID that received the document - * @param accessKey - The 44-digit access key of the parent document + * @param accessKey - The 44-character access key of the parent document * @param eventKey - The event key * @returns Promise with the product invoice event metadata * @throws {ValidationError} If any parameter is invalid @@ -393,11 +373,11 @@ export class InboundProductInvoicesResource { eventKey: string ): Promise { validateCompanyId(companyId); - validateAccessKey(accessKey); + const key = requireAccessKey(accessKey); validateEventKey(eventKey); const response = await this.http.get( - `/v2/companies/${companyId}/inbound/productinvoices/${accessKey.trim()}/events/${eventKey.trim()}` + `/v2/companies/${companyId}/inbound/productinvoices/${key}/events/${eventKey.trim()}` ); return response.data; @@ -418,7 +398,7 @@ export class InboundProductInvoicesResource { * (tests/fixtures/live-contracts/inbound-download.json). * * @param companyId - The company ID that received the document - * @param accessKey - The 44-digit access key + * @param accessKey - The 44-character access key * @returns Promise com o file-resource (`publicTemporaryUri`) * @throws {ValidationError} If company ID or access key is invalid * @throws {NotFoundError} If the document is not found @@ -431,10 +411,10 @@ export class InboundProductInvoicesResource { */ async getXml(companyId: string, accessKey: string): Promise { validateCompanyId(companyId); - validateAccessKey(accessKey); + const key = requireAccessKey(accessKey); const response = await this.http.get( - `/v2/companies/${companyId}/inbound/${accessKey.trim()}/xml` + `/v2/companies/${companyId}/inbound/${key}/xml` ); return response.data; @@ -451,7 +431,7 @@ export class InboundProductInvoicesResource { * (tests/fixtures/live-contracts/inbound-download.json). * * @param companyId - The company ID that received the document - * @param accessKey - The 44-digit access key of the parent document + * @param accessKey - The 44-character access key of the parent document * @param eventKey - The event key * @returns Promise with the event XML content as a string * @throws {ValidationError} If any parameter is invalid @@ -469,11 +449,11 @@ export class InboundProductInvoicesResource { eventKey: string ): Promise { validateCompanyId(companyId); - validateAccessKey(accessKey); + const key = requireAccessKey(accessKey); validateEventKey(eventKey); const response = await this.http.get( - `/v2/companies/${companyId}/inbound/${accessKey.trim()}/events/${eventKey.trim()}/xml` + `/v2/companies/${companyId}/inbound/${key}/events/${eventKey.trim()}/xml` ); return response.data; @@ -490,7 +470,7 @@ export class InboundProductInvoicesResource { * (tests/fixtures/live-contracts/inbound-download.json). * * @param companyId - The company ID that received the document - * @param accessKey - The 44-digit access key + * @param accessKey - The 44-character access key * @returns Promise com o file-resource (`publicTemporaryUri`) * @throws {ValidationError} If company ID or access key is invalid * @throws {NotFoundError} If the document is not found @@ -503,10 +483,10 @@ export class InboundProductInvoicesResource { */ async getPdf(companyId: string, accessKey: string): Promise { validateCompanyId(companyId); - validateAccessKey(accessKey); + const key = requireAccessKey(accessKey); const response = await this.http.get( - `/v2/companies/${companyId}/inbound/${accessKey.trim()}/pdf` + `/v2/companies/${companyId}/inbound/${key}/pdf` ); return response.data; @@ -518,7 +498,7 @@ export class InboundProductInvoicesResource { * Gets the structured JSON data of an NF-e document. * * @param companyId - The company ID that received the document - * @param accessKey - The 44-digit access key + * @param accessKey - The 44-character access key * @returns Promise with the NF-e metadata in JSON format * @throws {ValidationError} If company ID or access key is invalid * @throws {NotFoundError} If the document is not found @@ -538,10 +518,10 @@ export class InboundProductInvoicesResource { accessKey: string ): Promise { validateCompanyId(companyId); - validateAccessKey(accessKey); + const key = requireAccessKey(accessKey); const response = await this.http.get( - `/v2/companies/${companyId}/inbound/productinvoices/${accessKey.trim()}/json` + `/v2/companies/${companyId}/inbound/productinvoices/${key}/json` ); return response.data; @@ -563,7 +543,7 @@ export class InboundProductInvoicesResource { * - `210240` — Operação não Realizada (operation not performed) * * @param companyId - The company ID - * @param accessKey - The 44-digit access key of the NF-e + * @param accessKey - The 44-character access key of the NF-e * @param tpEvent - Manifest event type (defaults to 210210) * @returns Promise with the manifest response * @throws {ValidationError} If company ID or access key is invalid @@ -591,10 +571,10 @@ export class InboundProductInvoicesResource { tpEvent: ManifestEventType = DEFAULT_MANIFEST_EVENT_TYPE ): Promise { validateCompanyId(companyId); - validateAccessKey(accessKey); + const key = requireAccessKey(accessKey); const response = await this.http.post( - `/v2/companies/${companyId}/inbound/${accessKey.trim()}/manifest?tpEvent=${tpEvent}` + `/v2/companies/${companyId}/inbound/${key}/manifest?tpEvent=${tpEvent}` ); return response.data; @@ -608,10 +588,10 @@ export class InboundProductInvoicesResource { * Reprocess webhook for an inbound NF-e by access key or NSU * * Triggers reprocessing of the webhook notification for a specific document, - * identified either by its 44-digit access key or by its NSU number. + * identified either by its 44-character access key or by its NSU number. * * @param companyId - The company ID - * @param accessKeyOrNsu - The 44-digit access key or NSU number + * @param accessKeyOrNsu - The 44-character access key or NSU number * @returns Promise with the product invoice metadata * @throws {ValidationError} If company ID or identifier is empty * @throws {NotFoundError} If the document is not found diff --git a/src/core/resources/legal-entity-lookup.ts b/src/core/resources/legal-entity-lookup.ts index 15f4dec..67700f4 100644 --- a/src/core/resources/legal-entity-lookup.ts +++ b/src/core/resources/legal-entity-lookup.ts @@ -20,6 +20,7 @@ import type { LegalEntityStateTaxForInvoiceResponse, } from '../types.js'; import { ValidationError } from '../errors/index.js'; +import { requireCnpj } from '../utils/tax-id.js'; // ============================================================================ // Constants @@ -41,37 +42,22 @@ const VALID_BRAZILIAN_STATES: ReadonlySet = new Set([ // ============================================================================ /** - * Normalizes a federal tax number (CNPJ) by stripping all non-digit characters. + * Validates a federal tax number (CNPJ), numeric or alphanumeric (IN RFB 2.229/2024). * - * @param federalTaxNumber - Raw CNPJ string, with or without punctuation - * @returns Digits-only CNPJ string - */ -function normalizeFederalTaxNumber(federalTaxNumber: string): string { - return federalTaxNumber.replace(/\D/g, ''); -} - -/** - * Validates a federal tax number (CNPJ) format. - * Strips non-digit characters and checks for exactly 14 digits. + * Removes `.`, `/`, `-` and spaces, converts letters to upper case and checks the + * format and the check digits. Letters are kept: until 6.0.1 this function stripped + * every non-digit character, which corrupted an alphanumeric CNPJ. + * + * An alphanumeric CNPJ is sent as is. The v2 routes answer `400` with + * "CNPJ alfanumérico não é suportado nesta versão. Utilize a v3." (measured on + * 2026-11-18), and that message reaches the caller as a `ValidationError`. * * @param federalTaxNumber - CNPJ string to validate - * @returns Normalized digits-only CNPJ string - * @throws {ValidationError} If input is empty or not exactly 14 digits after normalization + * @returns Normalized CNPJ, ready for the URL + * @throws {ValidationError} If input is empty, out of format or has invalid check digits */ function validateFederalTaxNumber(federalTaxNumber: string | undefined | null): string { - if (!federalTaxNumber || federalTaxNumber.trim() === '') { - throw new ValidationError('Federal tax number (CNPJ) is required'); - } - - const normalized = normalizeFederalTaxNumber(federalTaxNumber); - - if (normalized.length !== 14) { - throw new ValidationError( - `Invalid federal tax number format: "${federalTaxNumber}". Expected 14 digits (e.g., "12345678000190" or "12.345.678/0001-90"), got ${normalized.length} digit(s).` - ); - } - - return normalized; + return requireCnpj(federalTaxNumber); } /** @@ -116,7 +102,7 @@ function validateState(state: string | undefined | null): BrazilianState { * * @example Basic CNPJ lookup * ```typescript - * const result = await nfe.legalEntityLookup.getBasicInfo('12.345.678/0001-90'); + * const result = await nfe.legalEntityLookup.getBasicInfo('11.222.333/0001-81'); * console.log(result.legalEntity?.name); // 'EMPRESA LTDA' * console.log(result.legalEntity?.status); // 'Active' * console.log(result.legalEntity?.address?.city?.name); // 'São Paulo' @@ -124,7 +110,7 @@ function validateState(state: string | undefined | null): BrazilianState { * * @example State tax registration lookup * ```typescript - * const result = await nfe.legalEntityLookup.getStateTaxInfo('SP', '12345678000190'); + * const result = await nfe.legalEntityLookup.getStateTaxInfo('SP', '11222333000181'); * for (const tax of result.legalEntity?.stateTaxes ?? []) { * console.log(`IE: ${tax.taxNumber} - Status: ${tax.status}`); * } @@ -132,7 +118,7 @@ function validateState(state: string | undefined | null): BrazilianState { * * @example Best IE for invoice issuance * ```typescript - * const result = await nfe.legalEntityLookup.getSuggestedStateTaxForInvoice('SP', '12345678000190'); + * const result = await nfe.legalEntityLookup.getSuggestedStateTaxForInvoice('SP', '11222333000181'); * const bestIE = result.legalEntity?.stateTaxes?.[0]; * console.log(`Best IE: ${bestIE?.taxNumber} (${bestIE?.status})`); * ``` @@ -156,24 +142,24 @@ export class LegalEntityLookupResource { * legal name, trade name, address, phone numbers, economic activities (CNAE), * legal nature, partners, registration status, and share capital. * - * @param federalTaxNumber - CNPJ number, with or without punctuation (e.g., "12345678000190" or "12.345.678/0001-90") + * @param federalTaxNumber - CNPJ number, with or without punctuation (e.g., "11222333000181", "11.222.333/0001-81" or the alphanumeric "12.ABC.345/01DE-35") * @param options - Optional lookup configuration * @returns Promise with company basic information - * @throws {ValidationError} If CNPJ format is invalid (not 14 digits) + * @throws {ValidationError} If the CNPJ is out of format (12 letters or digits + 2 check digits) or has invalid check digits * @throws {NotFoundError} If no company found for the given CNPJ * @throws {AuthenticationError} If API key is invalid or missing * * @example * ```typescript * // Simple lookup - * const result = await nfe.legalEntityLookup.getBasicInfo('12345678000190'); + * const result = await nfe.legalEntityLookup.getBasicInfo('11222333000181'); * console.log(result.legalEntity?.name); * * // With formatted CNPJ - * const result = await nfe.legalEntityLookup.getBasicInfo('12.345.678/0001-90'); + * const result = await nfe.legalEntityLookup.getBasicInfo('11.222.333/0001-81'); * * // Disable address update from postal service - * const result = await nfe.legalEntityLookup.getBasicInfo('12345678000190', { + * const result = await nfe.legalEntityLookup.getBasicInfo('11222333000181', { * updateAddress: false, * updateCityCode: true * }); @@ -217,7 +203,7 @@ export class LegalEntityLookupResource { * * @example * ```typescript - * const result = await nfe.legalEntityLookup.getStateTaxInfo('SP', '12345678000190'); + * const result = await nfe.legalEntityLookup.getStateTaxInfo('SP', '11222333000181'); * console.log(result.legalEntity?.taxRegime); // 'SimplesNacional' * * for (const tax of result.legalEntity?.stateTaxes ?? []) { @@ -256,7 +242,7 @@ export class LegalEntityLookupResource { * * @example * ```typescript - * const result = await nfe.legalEntityLookup.getStateTaxForInvoice('MG', '12345678000190'); + * const result = await nfe.legalEntityLookup.getStateTaxForInvoice('MG', '11222333000181'); * for (const tax of result.legalEntity?.stateTaxes ?? []) { * if (tax.status === 'Abled') { * console.log(`Can issue invoices with IE: ${tax.taxNumber}`); @@ -297,7 +283,7 @@ export class LegalEntityLookupResource { * * @example * ```typescript - * const result = await nfe.legalEntityLookup.getSuggestedStateTaxForInvoice('SP', '12345678000190'); + * const result = await nfe.legalEntityLookup.getSuggestedStateTaxForInvoice('SP', '11222333000181'); * const bestIE = result.legalEntity?.stateTaxes?.[0]; * if (bestIE) { * console.log(`Recommended IE: ${bestIE.taxNumber} (${bestIE.status})`); diff --git a/src/core/resources/legal-people.ts b/src/core/resources/legal-people.ts index 6f6d881..9f51706 100644 --- a/src/core/resources/legal-people.ts +++ b/src/core/resources/legal-people.ts @@ -23,6 +23,7 @@ */ import type { HttpClient } from '../http/client.js'; +import { isSameTaxNumber } from '../utils/tax-id.js'; import type { LegalPerson, ResourceId, ListResponse } from '../types.js'; /** @@ -191,14 +192,15 @@ export class LegalPeopleResource { * Find legal person by federal tax number (CNPJ) * * @param companyId - Company ID - * @param federalTaxNumber - CNPJ (only numbers) + * @param federalTaxNumber - CNPJ, with or without punctuation. The comparison is by value, so a + * record whose number lost its leading zeros still matches * @returns Legal person or undefined if not found * * @example * ```typescript * const person = await nfe.legalPeople.findByTaxNumber( * 'company-id', - * '12345678901234' + * '11222333000181' * ); * if (person) { * console.log('Found:', person.name); @@ -214,7 +216,7 @@ export class LegalPeopleResource { return people.find( (person: LegalPerson) => - person.federalTaxNumber?.toString() === federalTaxNumber + isSameTaxNumber(person.federalTaxNumber, federalTaxNumber) ); } } diff --git a/src/core/resources/natural-people.ts b/src/core/resources/natural-people.ts index a713078..2d15452 100644 --- a/src/core/resources/natural-people.ts +++ b/src/core/resources/natural-people.ts @@ -23,6 +23,7 @@ */ import type { HttpClient } from '../http/client.js'; +import { isSameTaxNumber } from '../utils/tax-id.js'; import type { NaturalPerson, ResourceId, ListResponse } from '../types.js'; /** @@ -191,7 +192,8 @@ export class NaturalPeopleResource { * Find natural person by federal tax number (CPF) * * @param companyId - Company ID - * @param federalTaxNumber - CPF (only numbers) + * @param federalTaxNumber - CPF, with or without punctuation. The comparison is by value, so a + * record whose number lost its leading zeros still matches * @returns Natural person or undefined if not found * * @example @@ -214,7 +216,7 @@ export class NaturalPeopleResource { return people.find( (person: NaturalPerson) => - person.federalTaxNumber?.toString() === federalTaxNumber + isSameTaxNumber(person.federalTaxNumber, federalTaxNumber) ); } } diff --git a/src/core/resources/product-invoice-query.ts b/src/core/resources/product-invoice-query.ts index a4a7a9e..2bc8447 100644 --- a/src/core/resources/product-invoice-query.ts +++ b/src/core/resources/product-invoice-query.ts @@ -11,7 +11,7 @@ import type { ProductInvoiceDetails, ProductInvoiceEventsResponse, } from '../types.js'; -import { ValidationError } from '../errors/index.js'; +import { requireAccessKey } from '../utils/tax-id.js'; // ============================================================================ // Constants @@ -20,9 +20,6 @@ import { ValidationError } from '../errors/index.js'; /** Base URL for NF-e Query API */ export const NFE_QUERY_API_BASE_URL = 'https://nfe.api.nfe.io'; -/** Regex pattern for valid access key (44 numeric digits) */ -const ACCESS_KEY_PATTERN = /^\d{44}$/; - /** * `Accept` dos downloads por chave de acesso. * @@ -46,24 +43,6 @@ const ACCEPT_XML = 'application/xml, application/json;q=0.9'; // Validation Helpers // ============================================================================ -/** - * Validates access key format (44 numeric digits) - * @param accessKey - The access key to validate - * @throws {ValidationError} If access key is empty or has invalid format - */ -function validateAccessKey(accessKey: string): void { - if (!accessKey || accessKey.trim() === '') { - throw new ValidationError('Access key is required'); - } - - const normalized = accessKey.trim(); - if (!ACCESS_KEY_PATTERN.test(normalized)) { - throw new ValidationError( - `Invalid access key: "${accessKey}". Expected 44 numeric digits.` - ); - } -} - // ============================================================================ // Resource Implementation // ============================================================================ @@ -105,7 +84,7 @@ export class ProductInvoiceQueryResource { /** * Retrieve full product invoice (NF-e) details from SEFAZ by access key * - * @param accessKey - 44-digit numeric access key (Chave de Acesso) + * @param accessKey - 44-character access key (Chave de Acesso; positions 7-18 may hold letters of an alphanumeric CNPJ) * @returns Full invoice details including issuer, buyer, items, totals, transport, and payment * @throws {ValidationError} If access key format is invalid * @throws {NotFoundError} If no invoice matches the access key (HTTP 404) @@ -122,9 +101,9 @@ export class ProductInvoiceQueryResource { * ``` */ async retrieve(accessKey: string): Promise { - validateAccessKey(accessKey); + const key = requireAccessKey(accessKey); const response = await this.http.get( - `/v2/productinvoices/${accessKey.trim()}` + `/v2/productinvoices/${key}` ); return response.data; } @@ -132,7 +111,7 @@ export class ProductInvoiceQueryResource { /** * Download the DANFE PDF for a product invoice by access key * - * @param accessKey - 44-digit numeric access key (Chave de Acesso) + * @param accessKey - 44-character access key (Chave de Acesso; positions 7-18 may hold letters of an alphanumeric CNPJ) * @returns Buffer containing the PDF binary content * @throws {ValidationError} If access key format is invalid * @throws {NotFoundError} If no invoice matches the access key (HTTP 404) @@ -147,9 +126,9 @@ export class ProductInvoiceQueryResource { * ``` */ async downloadPdf(accessKey: string): Promise { - validateAccessKey(accessKey); + const key = requireAccessKey(accessKey); const response = await this.http.getBuffer( - `/v2/productinvoices/${accessKey.trim()}.pdf`, + `/v2/productinvoices/${key}.pdf`, ACCEPT_PDF ); return response.data; @@ -158,7 +137,7 @@ export class ProductInvoiceQueryResource { /** * Download the raw NF-e XML for a product invoice by access key * - * @param accessKey - 44-digit numeric access key (Chave de Acesso) + * @param accessKey - 44-character access key (Chave de Acesso; positions 7-18 may hold letters of an alphanumeric CNPJ) * @returns Buffer containing the XML binary content * @throws {ValidationError} If access key format is invalid * @throws {NotFoundError} If no invoice matches the access key (HTTP 404) @@ -173,9 +152,9 @@ export class ProductInvoiceQueryResource { * ``` */ async downloadXml(accessKey: string): Promise { - validateAccessKey(accessKey); + const key = requireAccessKey(accessKey); const response = await this.http.getBuffer( - `/v2/productinvoices/${accessKey.trim()}.xml`, + `/v2/productinvoices/${key}.xml`, ACCEPT_XML ); return response.data; @@ -186,7 +165,7 @@ export class ProductInvoiceQueryResource { * * Events include cancellations, corrections, manifestations, etc. * - * @param accessKey - 44-digit numeric access key (Chave de Acesso) + * @param accessKey - 44-character access key (Chave de Acesso; positions 7-18 may hold letters of an alphanumeric CNPJ) * @returns Events response with an array of fiscal events and query timestamp * @throws {ValidationError} If access key format is invalid * @throws {NotFoundError} If no invoice matches the access key (HTTP 404) @@ -203,9 +182,9 @@ export class ProductInvoiceQueryResource { * ``` */ async listEvents(accessKey: string): Promise { - validateAccessKey(accessKey); + const key = requireAccessKey(accessKey); const response = await this.http.get( - `/v2/productinvoices/events/${accessKey.trim()}` + `/v2/productinvoices/events/${key}` ); return response.data; } diff --git a/src/core/resources/product-invoices.ts b/src/core/resources/product-invoices.ts index 234a6cb..e56a3d2 100644 --- a/src/core/resources/product-invoices.ts +++ b/src/core/resources/product-invoices.ts @@ -80,7 +80,7 @@ function buildQueryString(params: Record): st * const result = await nfe.productInvoices.create('company-id', { * operationNature: 'Venda de mercadoria', * operationType: 'Outgoing', - * buyer: { name: 'Empresa LTDA', federalTaxNumber: 12345678000190 }, + * buyer: { name: 'Empresa LTDA', federalTaxNumber: 11222333000181 }, * items: [{ code: 'PROD-001', description: 'Produto X', quantity: 1, unitAmount: 100 }], * payment: [{ paymentDetail: [{ method: 'Cash', amount: 100 }] }], * }); diff --git a/src/core/resources/transportation-invoices.ts b/src/core/resources/transportation-invoices.ts index bd51ee7..055852f 100644 --- a/src/core/resources/transportation-invoices.ts +++ b/src/core/resources/transportation-invoices.ts @@ -13,6 +13,7 @@ import type { InboundFileResource } from '../types.js'; import { ValidationError } from '../errors/index.js'; +import { requireAccessKey } from '../utils/tax-id.js'; // ============================================================================ // Constants @@ -21,31 +22,10 @@ import { ValidationError } from '../errors/index.js'; /** Base URL for CT-e API */ export const CTE_API_BASE_URL = 'https://api.nfse.io'; -/** Regex pattern for valid access key (44 numeric digits) */ -const ACCESS_KEY_PATTERN = /^\d{44}$/; - // ============================================================================ // Validation Helpers // ============================================================================ -/** - * Validates access key format (44 numeric digits) - * @param accessKey - The CT-e access key to validate - * @throws {ValidationError} If access key format is invalid - */ -function validateAccessKey(accessKey: string): void { - if (!accessKey || accessKey.trim() === '') { - throw new ValidationError('Access key is required'); - } - - const normalized = accessKey.trim(); - if (!ACCESS_KEY_PATTERN.test(normalized)) { - throw new ValidationError( - `Invalid access key: "${accessKey}". Expected 44 numeric digits.` - ); - } -} - /** * Validates company ID is not empty * @param companyId - The company ID to validate @@ -224,10 +204,10 @@ export class TransportationInvoicesResource { /** * Retrieve CT-e metadata by access key * - * Gets the metadata of a CT-e document by its 44-digit access key. + * Gets the metadata of a CT-e document by its 44-character access key. * * @param companyId - The company ID that received the CT-e - * @param accessKey - The 44-digit CT-e access key + * @param accessKey - The 44-character CT-e access key * @returns Promise with the CT-e metadata * @throws {ValidationError} If company ID or access key is invalid * @throws {NotFoundError} If the CT-e is not found @@ -249,10 +229,10 @@ export class TransportationInvoicesResource { accessKey: string ): Promise { validateCompanyId(companyId); - validateAccessKey(accessKey); + const key = requireAccessKey(accessKey); const response = await this.http.get( - `/v2/companies/${companyId}/inbound/${accessKey.trim()}` + `/v2/companies/${companyId}/inbound/${key}` ); return response.data; @@ -270,7 +250,7 @@ export class TransportationInvoicesResource { * (tests/fixtures/live-contracts/inbound-download.json). * * @param companyId - The company ID that received the CT-e - * @param accessKey - The 44-digit CT-e access key + * @param accessKey - The 44-character CT-e access key * @returns Promise com o file-resource (`publicTemporaryUri`) * @throws {ValidationError} If company ID or access key is invalid * @throws {NotFoundError} If the CT-e is not found @@ -286,10 +266,10 @@ export class TransportationInvoicesResource { */ async downloadXml(companyId: string, accessKey: string): Promise { validateCompanyId(companyId); - validateAccessKey(accessKey); + const key = requireAccessKey(accessKey); const response = await this.http.get( - `/v2/companies/${companyId}/inbound/${accessKey.trim()}/xml` + `/v2/companies/${companyId}/inbound/${key}/xml` ); return response.data; @@ -305,7 +285,7 @@ export class TransportationInvoicesResource { * Gets the metadata of an event related to a CT-e document. * * @param companyId - The company ID that received the CT-e - * @param accessKey - The 44-digit CT-e access key + * @param accessKey - The 44-character CT-e access key * @param eventKey - The event key * @returns Promise with the event metadata * @throws {ValidationError} If any parameter is invalid @@ -327,14 +307,14 @@ export class TransportationInvoicesResource { eventKey: string ): Promise { validateCompanyId(companyId); - validateAccessKey(accessKey); + const key = requireAccessKey(accessKey); if (!eventKey || eventKey.trim() === '') { throw new ValidationError('Event key is required'); } const response = await this.http.get( - `/v2/companies/${companyId}/inbound/${accessKey.trim()}/events/${eventKey.trim()}` + `/v2/companies/${companyId}/inbound/${key}/events/${eventKey.trim()}` ); return response.data; @@ -346,7 +326,7 @@ export class TransportationInvoicesResource { * Gets the XML content of a CT-e event. * * @param companyId - The company ID that received the CT-e - * @param accessKey - The 44-digit CT-e access key + * @param accessKey - The 44-character CT-e access key * @param eventKey - The event key * @returns Promise com o file-resource (`publicTemporaryUri`) * @throws {ValidationError} If any parameter is invalid @@ -373,14 +353,14 @@ export class TransportationInvoicesResource { eventKey: string ): Promise { validateCompanyId(companyId); - validateAccessKey(accessKey); + const key = requireAccessKey(accessKey); if (!eventKey || eventKey.trim() === '') { throw new ValidationError('Event key is required'); } const response = await this.http.get( - `/v2/companies/${companyId}/inbound/${accessKey.trim()}/events/${eventKey.trim()}/xml` + `/v2/companies/${companyId}/inbound/${key}/events/${eventKey.trim()}/xml` ); return response.data; diff --git a/src/core/utils/tax-id.ts b/src/core/utils/tax-id.ts new file mode 100644 index 0000000..6dc55ad --- /dev/null +++ b/src/core/utils/tax-id.ts @@ -0,0 +1,238 @@ +/** + * NFE.io SDK — CNPJ, CPF e chave de acesso: normalização e validação no cliente. + * + * Uma regra só para todos os recursos. Até a v6.0.1, cada recurso validava do seu jeito: + * `companies` media o número com `toString().length` e recusava documento que começa com + * zero; a consulta de CNPJ fazia `replace(/\D/g, '')` e arrancava as letras; quatro + * recursos exigiam chave de acesso só com dígitos. + * + * Princípio: a validação local nunca recusa um valor que a API aceita. + * + * - **CNPJ** (IN RFB 2.229/2024): 12 letras ou dígitos e 2 dígitos verificadores. O DV é o + * módulo 11 com o valor ASCII − 48 de cada caractere; para dígitos, é o cálculo de sempre. + * As 26 letras valem (a Receita não veda nenhuma). + * - **`number` perdeu os zeros à esquerda** na conversão, então é completado com zeros antes + * de validar. A API faz o mesmo: medido em 2026-11-18, `POST /v1/companies` com + * `1234567999885` responde `201` e grava `01234567999885`. + * - **Chave de acesso**: as posições 7 a 20 trazem o CNPJ do emitente, então as posições 7 a + * 18 podem ter letras. + * + * Interno nesta versão: export público é superfície nova e fica para uma minor. + */ + +import { ValidationError } from '../errors/index.js'; + +const CNPJ_LENGTH = 14; +const CPF_LENGTH = 11; + +/** Formato do CNPJ depois de normalizado: 12 letras ou dígitos e 2 dígitos verificadores. */ +const CNPJ_PATTERN = /^[0-9A-Z]{12}[0-9]{2}$/; + +/** Chave de acesso de 44 posições: letras só nas posições 7 a 18 (o CNPJ do emitente). */ +const ACCESS_KEY_PATTERN = /^\d{6}[0-9A-Z]{12}\d{26}$/; + +/** Separadores de máscara que a normalização remove. Letras nunca são removidas. */ +const MASK_CHARACTERS = /[.\-/\s]/g; + +/** Pesos do módulo 11 do CNPJ, para o primeiro e o segundo dígito verificador. */ +const CNPJ_FIRST_WEIGHTS = [5, 4, 3, 2, 9, 8, 7, 6, 5, 4, 3, 2] as const; +const CNPJ_SECOND_WEIGHTS = [6, 5, 4, 3, 2, 9, 8, 7, 6, 5, 4, 3, 2] as const; + +/** + * Converte um `number` em string de dígitos completada com zeros até `length`. + * Valor que não é inteiro seguro e não negativo vira string sem completar, e a validação o recusa. + */ +function numberToDigits(value: number, length: number): string { + if (!Number.isSafeInteger(value) || value < 0) { + return String(value); + } + return String(value).padStart(length, '0'); +} + +/** Valor de um caractere no cálculo do DV: código ASCII − 48 (`'0'`→0, `'A'`→17, `'Z'`→42). */ +function charValue(text: string, index: number): number { + return text.charCodeAt(index) - 48; +} + +/** Módulo 11: resto 0 ou 1 dá dígito 0; os demais dão 11 − resto. */ +function mod11Digit(sum: number): number { + const rest = sum % 11; + return rest < 2 ? 0 : 11 - rest; +} + +function cnpjCheckDigits(base: string): string { + let sum = 0; + CNPJ_FIRST_WEIGHTS.forEach((weight, i) => { + sum += charValue(base, i) * weight; + }); + const first = mod11Digit(sum); + + const withFirst = `${base}${first}`; + sum = 0; + CNPJ_SECOND_WEIGHTS.forEach((weight, i) => { + sum += charValue(withFirst, i) * weight; + }); + const second = mod11Digit(sum); + + return `${first}${second}`; +} + +function cpfCheckDigit(cpf: string, length: number): number { + let sum = 0; + for (let i = 0; i < length; i++) { + sum += charValue(cpf, i) * (length + 1 - i); + } + return mod11Digit(sum); +} + +// ============================================================================ +// CNPJ +// ============================================================================ + +/** + * Normaliza um CNPJ sem perder letras. + * + * - `string`: remove `.`, `/`, `-` e espaços, e converte para maiúsculas. + * - `number`: completa com zeros à esquerda até 14 posições. + * + * @example + * normalizeCnpj('12.abc.345/01de-35'); // '12ABC34501DE35' + * normalizeCnpj(1234567999885); // '01234567999885' + */ +export function normalizeCnpj(value: string | number): string { + if (typeof value === 'number') { + return numberToDigits(value, CNPJ_LENGTH); + } + return value.replace(MASK_CHARACTERS, '').toUpperCase(); +} + +/** + * Confere formato e dígitos verificadores de um CNPJ, numérico ou alfanumérico. + * Recusa 14 caracteres iguais. + */ +export function isValidCnpj(value: string | number): boolean { + const cnpj = normalizeCnpj(value); + if (!CNPJ_PATTERN.test(cnpj)) return false; + if (/^(.)\1{13}$/.test(cnpj)) return false; + return cnpj.slice(12) === cnpjCheckDigits(cnpj.slice(0, 12)); +} + +/** Diz se o CNPJ tem letra nas 12 primeiras posições. Um `number` nunca é alfanumérico. */ +export function isAlphanumericCnpj(value: string | number): boolean { + if (typeof value === 'number') return false; + return /[A-Z]/.test(normalizeCnpj(value).slice(0, 12)); +} + +/** + * Normaliza e valida um CNPJ recebido como argumento de método. + * + * @returns O CNPJ normalizado, pronto para entrar numa URL + * @throws {ValidationError} Se estiver vazio, fora do formato ou com DV inválido + */ +export function requireCnpj(value: string | number | null | undefined): string { + if (value === null || value === undefined || (typeof value === 'string' && value.trim() === '')) { + throw new ValidationError('Federal tax number (CNPJ) is required'); + } + + const cnpj = normalizeCnpj(value); + if (!CNPJ_PATTERN.test(cnpj)) { + throw new ValidationError( + `Invalid federal tax number format: "${value}". Expected 14 characters after removing punctuation: ` + + '12 letters or digits followed by 2 check digits (e.g., "11222333000181", "11.222.333/0001-81" ' + + 'or the alphanumeric "12.ABC.345/01DE-35").' + ); + } + if (!isValidCnpj(cnpj)) { + throw new ValidationError( + `Invalid federal tax number: "${value}". The CNPJ check digits do not match.` + ); + } + return cnpj; +} + +// ============================================================================ +// CPF +// ============================================================================ + +/** + * Normaliza um CPF. + * + * - `string`: remove `.`, `/`, `-` e espaços. + * - `number`: completa com zeros à esquerda até 11 posições. + */ +export function normalizeCpf(value: string | number): string { + if (typeof value === 'number') { + return numberToDigits(value, CPF_LENGTH); + } + return value.replace(MASK_CHARACTERS, ''); +} + +/** Confere formato (11 dígitos) e dígitos verificadores de um CPF. Recusa 11 dígitos iguais. */ +export function isValidCpf(value: string | number): boolean { + const cpf = normalizeCpf(value); + if (!/^\d{11}$/.test(cpf)) return false; + if (/^(\d)\1{10}$/.test(cpf)) return false; + return cpf[9] === String(cpfCheckDigit(cpf, 9)) && cpf[10] === String(cpfCheckDigit(cpf, 10)); +} + +// ============================================================================ +// Comparação +// ============================================================================ + +/** + * Diz se dois valores de CNPJ ou CPF são o mesmo documento. + * + * Documento numérico compara pelo valor, então `1234567999885` e `'01234567999885'` são iguais: + * a API v1 devolve como `number` o que perdeu o zero à esquerda. Documento com letra compara + * pelo texto normalizado. Valor que não é `string` nem `number` nunca é igual a nada. + */ +export function isSameTaxNumber(a: unknown, b: unknown): boolean { + const asText = (value: unknown): string | undefined => { + if (typeof value === 'number') + return Number.isSafeInteger(value) && value >= 0 ? String(value) : undefined; + if (typeof value === 'string') return value.replace(MASK_CHARACTERS, '').toUpperCase(); + return undefined; + }; + const left = asText(a); + const right = asText(b); + if (left === undefined || right === undefined || left === '' || right === '') return false; + if (/^\d+$/.test(left) && /^\d+$/.test(right)) { + return left.replace(/^0+(?=\d)/, '') === right.replace(/^0+(?=\d)/, ''); + } + return left === right; +} + +// ============================================================================ +// Chave de acesso +// ============================================================================ + +/** Normaliza uma chave de acesso: remove espaços das pontas e converte para maiúsculas. */ +export function normalizeAccessKey(value: string): string { + return value.trim().toUpperCase(); +} + +/** Confere o formato da chave de acesso de 44 posições. Não confere o DV da chave: isso é da API. */ +export function isValidAccessKey(value: string): boolean { + return ACCESS_KEY_PATTERN.test(normalizeAccessKey(value)); +} + +/** + * Normaliza e valida uma chave de acesso recebida como argumento de método. + * + * @returns A chave normalizada, pronta para entrar numa URL + * @throws {ValidationError} Se estiver vazia ou fora do formato + */ +export function requireAccessKey(value: string | null | undefined): string { + if (!value || value.trim() === '') { + throw new ValidationError('Access key is required'); + } + + const key = normalizeAccessKey(value); + if (!ACCESS_KEY_PATTERN.test(key)) { + throw new ValidationError( + `Invalid access key: "${value}". Expected 44 characters: digits only, except positions 7 to 18, ` + + 'which hold the issuer CNPJ and may contain letters (alphanumeric CNPJ).' + ); + } + return key; +} diff --git a/tests/fixtures/live-contracts/alphanumeric-tax-ids.json b/tests/fixtures/live-contracts/alphanumeric-tax-ids.json new file mode 100644 index 0000000..b068988 --- /dev/null +++ b/tests/fixtures/live-contracts/alphanumeric-tax-ids.json @@ -0,0 +1,131 @@ +{ + "probe": "CNPJ alfanumérico (IN RFB 2.229/2024), chave de acesso com letras e CNPJ que perdeu o zero à esquerda", + "capturedOn": "2026-11-18", + "change": "fix-tax-id-validation", + "note": "Status e corpo vêm de respostas reais; os valores são sintéticos. CNPJ alfanumérico: 12ABC34501DE35, exemplo público da Receita Federal (DV válido, inexistente na base). Chave de acesso: montada com esse CNPJ e DV calculado com ASCII - 48. CNPJ com zero à esquerda: 01234567999885, sintético; a consulta de CNPJ confirmou que não existe na Receita. Ids de empresa e de conta foram trocados por placeholders.", + "method": "GET só de leitura, salvo o grupo companiesV1LeadingZero, que escreveu na conta do time com autorização (uma empresa criada, regravada e excluída).", + "accessKeyWithLetters": { + "key": "35260612ABC34501DE35550010000000031100000033", + "cases": [ + { + "route": "GET /v2/companies/{companyId}/inbound/productinvoices/{accessKey}", + "host": "api.nfse.io", + "status": 404, + "body": { "errors": [{ "message": "Key {accessKey} for companyId {companyId} and accountId {accountId} does not exist" }] }, + "reading": "formato aceito; a mesma resposta de uma chave numérica inexistente" + }, + { + "route": "GET /v2/companies/{companyId}/inbound/productinvoices/{accessKey}/json e …/events/{eventKey}", + "host": "api.nfse.io", + "status": 404, + "body": { "errors": [{ "message": "Key {accessKey} for companyId {companyId} and accountId {accountId} does not exist" }] }, + "reading": "as sub-rotas de productinvoices também aceitam o formato" + }, + { + "route": "GET /v2/companies/{companyId}/inbound/{accessKey}", + "host": "api.nfse.io", + "status": 400, + "body": { "errors": [{ "message": "access key must have 44 digits" }] }, + "reading": "a rota raiz recusa o formato; com chave numérica sintética de DV válido responde 404" + }, + { + "route": "GET /v2/companies/{companyId}/inbound/{accessKey}/xml, /pdf, /events/{eventKey} e /events/{eventKey}/xml", + "host": "api.nfse.io", + "status": 400, + "body": { "errors": [{ "message": "access key must have 44 digits" }] }, + "reading": "todas as sub-rotas da raiz recusam o formato" + }, + { + "route": "GET /v2/productinvoices/{accessKey}", + "host": "nfe.api.nfe.io", + "credential": "data", + "status": 400, + "body": { "errors": [{ "message": "accessKey can only to contain 44 numbers" }] }, + "reading": "a consulta de NF-e ainda não tem versão alfanumérica" + } + ] + }, + "legalEntityLookup": { + "credential": "data", + "host": "legalentity.api.nfe.io", + "cases": [ + { + "route": "GET /v1/legalentities/basicInfo/12ABC34501DE35", + "status": 400, + "body": { "errors": [{ "code": 40001, "message": "CNPJ alfanumérico não é suportado nesta versão. Utilize a v3." }] } + }, + { + "route": "GET /v2/legalentities/basicInfo/12ABC34501DE35", + "status": 400, + "body": { "errors": [{ "code": 40001, "message": "CNPJ alfanumérico não é suportado nesta versão. Utilize a v3." }] }, + "reading": "a rota que o SDK usa; o SDK repassa esta mensagem como ValidationError" + }, + { + "route": "GET /v2/legalentities/stateTaxForInvoice/SP/12ABC34501DE35", + "status": 400, + "body": { "errors": [{ "code": 40001, "message": "CNPJ alfanumérico não é suportado nesta versão. Utilize a v3." }] } + }, + { + "route": "GET /v3/legalentities/basicInfo/12ABC34501DE35", + "status": 404, + "body": { "errors": [{ "message": "CNPJ not found in Serpro." }] }, + "reading": "formato aceito; o CNPJ de exemplo não existe na base" + }, + { + "route": "GET /v3/legalentities/basicInfo/12ABC34501DE36", + "status": 400, + "body": { "errors": [{ "message": "cnpj is null, white space or not valid" }] }, + "reading": "a API valida o DV; a v2 responde o mesmo para CNPJ numérico com DV inválido" + }, + { + "route": "GET /v3/legalentities/basicInfo/12.ABC.345%2F01DE-35", + "status": 307, + "headers": { "location": "/v3/legalentities/basicInfo/12.ABC.345/01DE-35" }, + "reading": "a barra da máscara quebra o path; o SDK remove a máscara antes de montar a URL" + } + ] + }, + "companiesV1LeadingZero": { + "host": "api.nfe.io", + "cnpj": "01234567999885", + "cases": [ + { + "route": "POST /v1/companies", + "body": { "federalTaxNumber": 1234567999886 }, + "status": 400, + "response": { "errors": [{ "code": 40032, "message": "federal tax number is not valid" }] }, + "reading": "DV inválido depois de completar com zeros; nada foi criado" + }, + { + "route": "POST /v1/companies", + "body": { "federalTaxNumber": 1234567999885 }, + "status": 201, + "responseFederalTaxNumber": 1234567999885, + "reading": "a API aceita o número que perdeu o zero" + }, + { + "route": "GET /v3/companies/{companyId}", + "host": "api.nfse.io", + "status": 200, + "responseFederalTaxNumber": "01234567999885", + "reading": "o valor gravado tem as 14 posições" + }, + { + "route": "PUT /v1/companies/{companyId}", + "body": "o objeto lido pela v1, com federalTaxNumber 1234567999885", + "status": 200 + }, + { + "route": "PUT /v1/companies/{companyId}", + "body": { "federalTaxNumber": "01234567999885" }, + "status": 200, + "reading": "a v1 também aceita a string de 14 posições" + }, + { + "route": "DELETE /v1/companies/{companyId}", + "status": 204, + "reading": "exclusão lógica: a empresa continua na conta com status Inactive" + } + ] + } +} diff --git a/tests/integration/companies.integration.test.ts b/tests/integration/companies.integration.test.ts index 9b4c4bd..b1cdf46 100644 --- a/tests/integration/companies.integration.test.ts +++ b/tests/integration/companies.integration.test.ts @@ -57,6 +57,34 @@ describe.skipIf(skipIfNoApiKey())('Companies Integration Tests', () => { logTestInfo('Company created', { id: company.id }); }); + // Um CNPJ que começa com zero chega como número curto. Medido em 2026-11-18: a API completa os + // zeros (201), grava as 14 posições, devolve o número curto e aceita regravar a empresa com ele. + // Até a v6.0.1 o SDK recusava os três passos no cliente. CNPJ sintético 01234567999885: a + // consulta de CNPJ confirmou que ele não existe na Receita. + itEscreveNaConta( + 'should create, read back and update a company whose CNPJ starts with zero', + { timeout: INTEGRATION_TEST_CONFIG.timeout }, + async () => { + const leadingZeroCnpj = 1234567999885; // 01234567999885 + const created = await client.companies.create({ + ...TEST_COMPANY_DATA, + name: `Test Company zero a esquerda ${Date.now()}`, + federalTaxNumber: leadingZeroCnpj, + }); + createdCompanyIds.push(created.id); + expect(created.federalTaxNumber).toBe(leadingZeroCnpj); + + const read = await client.companies.retrieve(created.id); + expect(read.federalTaxNumber).toBe(leadingZeroCnpj); + + const updated = await client.companies.update(created.id, { + ...read, + tradeName: 'Regravada com o numero curto', + }); + expect(updated.federalTaxNumber).toBe(leadingZeroCnpj); + } + ); + itEscreveNaConta('should retrieve a company by id', { timeout: INTEGRATION_TEST_CONFIG.timeout }, async () => { // Create company first const companyData = { diff --git a/tests/unit/companies.test.ts b/tests/unit/companies.test.ts index 76cd199..4d7b9ca 100644 --- a/tests/unit/companies.test.ts +++ b/tests/unit/companies.test.ts @@ -296,6 +296,114 @@ describe('CompaniesResource', () => { }); }); + // Medido com escrita autorizada em 2026-11-18 (CNPJ sintético 01234567999885, inexistente na + // Receita): `POST /v1/companies` com o número curto responde 201, o `PUT` com o objeto lido + // responde 200, e o `PUT` com a string de 14 posições também. Até a v6.0.1 o SDK recusava os + // três casos no cliente. + describe('federalTaxNumber: zero à esquerda e CNPJ alfanumérico', () => { + const LEADING_ZERO_CNPJ = 1234567999885; // 01234567999885 + const LEADING_ZERO_CPF = 1234567890; // 01234567890 + const body = { name: 'Empresa', email: 'e@example.com' }; + + function mockWrite(method: 'post' | 'put', federalTaxNumber: unknown) { + vi.mocked(mockHttpClient[method]).mockResolvedValue({ + data: { companies: createMockCompany({ federalTaxNumber: federalTaxNumber as number }) }, + status: method === 'post' ? 201 : 200, + headers: {}, + } as any); + } + + it('create aceita CNPJ que perdeu o zero à esquerda', async () => { + mockWrite('post', LEADING_ZERO_CNPJ); + await companies.create({ ...body, federalTaxNumber: LEADING_ZERO_CNPJ }); + expect(mockHttpClient.post).toHaveBeenCalledWith('/companies', { + ...body, + federalTaxNumber: LEADING_ZERO_CNPJ, + }); + }); + + it('create aceita CPF que perdeu o zero à esquerda', async () => { + mockWrite('post', LEADING_ZERO_CPF); + await companies.create({ ...body, federalTaxNumber: LEADING_ZERO_CPF }); + expect(mockHttpClient.post).toHaveBeenCalledTimes(1); + }); + + it('create aceita o CNPJ como string só de dígitos, como a API', async () => { + mockWrite('post', LEADING_ZERO_CNPJ); + await companies.create({ ...body, federalTaxNumber: '01234567999885' as unknown as number }); + expect(mockHttpClient.post).toHaveBeenCalledWith('/companies', { + ...body, + federalTaxNumber: '01234567999885', + }); + }); + + it('update aceita CNPJ e CPF que perderam o zero à esquerda', async () => { + mockWrite('put', LEADING_ZERO_CNPJ); + await companies.update(TEST_COMPANY_ID, { federalTaxNumber: LEADING_ZERO_CNPJ }); + await companies.update(TEST_COMPANY_ID, { federalTaxNumber: LEADING_ZERO_CPF }); + expect(mockHttpClient.put).toHaveBeenCalledTimes(2); + }); + + it('ler e regravar a empresa não lança erro local', async () => { + const current = createMockCompany({ id: TEST_COMPANY_ID, federalTaxNumber: LEADING_ZERO_CNPJ }); + vi.mocked(mockHttpClient.get).mockResolvedValue({ + data: { companies: current }, + status: 200, + headers: {}, + } as any); + mockWrite('put', LEADING_ZERO_CNPJ); + + const read = await companies.retrieve(TEST_COMPANY_ID); + await companies.update(TEST_COMPANY_ID, { ...read, tradeName: 'Novo nome' }); + + expect(mockHttpClient.put).toHaveBeenCalledWith( + `/companies/${TEST_COMPANY_ID}`, + expect.objectContaining({ federalTaxNumber: LEADING_ZERO_CNPJ, tradeName: 'Novo nome' }) + ); + }); + + it('CNPJ alfanumérico lança ValidationError apontando a API v3, sem requisição', async () => { + const promise = companies.create({ ...body, federalTaxNumber: '12ABC34501DE35' as unknown as number }); + await expect(promise).rejects.toThrow(ValidationError); + await expect( + companies.create({ ...body, federalTaxNumber: '12ABC34501DE35' as unknown as number }) + ).rejects.toThrow('The v3 companies API accepts it'); + expect(mockHttpClient.post).not.toHaveBeenCalled(); + }); + + it('número curto com DV inválido depois de completar continua recusado', async () => { + await expect( + companies.create({ ...body, federalTaxNumber: 1234567999886 }) + ).rejects.toThrow(ValidationError); + expect(mockHttpClient.post).not.toHaveBeenCalled(); + }); + + it('findByTaxNumber acha a empresa pelo número curto, venha ele como número ou string', async () => { + vi.mocked(mockHttpClient.get).mockResolvedValue({ + data: { + companies: [ + createMockCompany({ id: 'company-1', federalTaxNumber: 11222333000181 }), + createMockCompany({ id: 'company-2', federalTaxNumber: LEADING_ZERO_CNPJ }), + createMockCompany({ id: 'company-3', federalTaxNumber: '00000000000191' as unknown as number }), + ], + page: 1, + }, + status: 200, + headers: {}, + } as any); + + expect((await companies.findByTaxNumber(LEADING_ZERO_CNPJ))?.id).toBe('company-2'); + expect((await companies.findByTaxNumber(191))?.id).toBe('company-3'); + }); + + it('findByTaxNumber recusa o que não é inteiro não negativo de até 14 dígitos', async () => { + await expect(companies.findByTaxNumber(-1)).rejects.toThrow(ValidationError); + await expect(companies.findByTaxNumber(1.5)).rejects.toThrow(ValidationError); + await expect(companies.findByTaxNumber(123456789012345)).rejects.toThrow(ValidationError); + expect(mockHttpClient.get).not.toHaveBeenCalled(); + }); + }); + describe('Error Handling', () => { it('should propagate HTTP client errors', async () => { const error = new Error('Network error'); diff --git a/tests/unit/consumer-invoice-query.test.ts b/tests/unit/consumer-invoice-query.test.ts index 47dfd88..554423c 100644 --- a/tests/unit/consumer-invoice-query.test.ts +++ b/tests/unit/consumer-invoice-query.test.ts @@ -104,12 +104,12 @@ describe('ConsumerInvoiceQueryResource', () => { it('should reject non-numeric access key', async () => { await expect(resource.retrieve('3524011234567800019059000000001234123456789X')).rejects.toThrow(ValidationError); - await expect(resource.retrieve('3524011234567800019059000000001234123456789X')).rejects.toThrow('Expected 44 numeric digits'); + await expect(resource.retrieve('3524011234567800019059000000001234123456789X')).rejects.toThrow('Expected 44 characters'); }); it('should reject access key with wrong length (43 digits)', async () => { await expect(resource.retrieve('3524011234567800019059000000001234123456789')).rejects.toThrow(ValidationError); - await expect(resource.retrieve('3524011234567800019059000000001234123456789')).rejects.toThrow('Expected 44 numeric digits'); + await expect(resource.retrieve('3524011234567800019059000000001234123456789')).rejects.toThrow('Expected 44 characters'); }); it('should reject access key with wrong length (45 digits)', async () => { @@ -131,6 +131,20 @@ describe('ConsumerInvoiceQueryResource', () => { await expect(resource.downloadXml('')).rejects.toThrow(ValidationError); await expect(resource.downloadXml('abc')).rejects.toThrow(ValidationError); }); + + // A chave do CF-e também traz o CNPJ do emitente nas posições 7 a 20. + it('sends an access key with letters in the issuer CNPJ upper case', async () => { + const alphaKey = '35260612ABC34501DE35590010000000031100000037'; + vi.mocked(mockHttpClient.get).mockResolvedValue({ + data: createMockCoupon(), + status: 200, + headers: {}, + } as HttpResponse); + + await resource.retrieve(alphaKey.toLowerCase()); + + expect(mockHttpClient.get).toHaveBeenCalledWith(`/v1/consumerinvoices/coupon/${alphaKey}`); + }); }); // -------------------------------------------------------------------------- diff --git a/tests/unit/legal-entity-lookup.test.ts b/tests/unit/legal-entity-lookup.test.ts index 0992bf2..eece4e5 100644 --- a/tests/unit/legal-entity-lookup.test.ts +++ b/tests/unit/legal-entity-lookup.test.ts @@ -13,8 +13,8 @@ import type { // Test Data // ============================================================================ -const VALID_CNPJ_DIGITS = '12345678000190'; -const VALID_CNPJ_FORMATTED = '12.345.678/0001-90'; +const VALID_CNPJ_DIGITS = '11222333000181'; +const VALID_CNPJ_FORMATTED = '11.222.333/0001-81'; const createMockBasicInfoResponse = ( overrides: Partial = {} @@ -149,14 +149,61 @@ describe('LegalEntityLookupResource', () => { await expect(resource.getBasicInfo(' ')).rejects.toThrow('Federal tax number (CNPJ) is required'); }); - it('should reject CNPJ with fewer than 14 digits', async () => { + it('should reject CNPJ with fewer than 14 characters', async () => { await expect(resource.getBasicInfo('1234567800019')).rejects.toThrow(ValidationError); - await expect(resource.getBasicInfo('1234567800019')).rejects.toThrow('Expected 14 digits'); + await expect(resource.getBasicInfo('1234567800019')).rejects.toThrow('Expected 14 characters'); }); - it('should reject CNPJ with more than 14 digits', async () => { + it('should reject CNPJ with more than 14 characters', async () => { await expect(resource.getBasicInfo('123456780001901')).rejects.toThrow(ValidationError); - await expect(resource.getBasicInfo('123456780001901')).rejects.toThrow('Expected 14 digits'); + await expect(resource.getBasicInfo('123456780001901')).rejects.toThrow('Expected 14 characters'); + }); + + // CNPJ alfanumérico (IN RFB 2.229/2024). Até a v6.0.1, `replace(/\D/g, '')` arrancava as + // letras e acusava "got 9 digit(s)"; a mensagem certa é a da API. + it('keeps the letters of an alphanumeric CNPJ and normalizes mask and case', async () => { + vi.mocked(mockHttpClient.get).mockResolvedValue({ + data: createMockBasicInfoResponse(), + status: 200, + headers: {}, + }); + + await resource.getBasicInfo('12.abc.345/01de-35'); + + expect(mockHttpClient.get).toHaveBeenCalledWith( + '/v2/legalentities/basicInfo/12ABC34501DE35', + undefined + ); + }); + + it('rejects an invalid check digit before any request', async () => { + await expect(resource.getBasicInfo('12ABC34501DE36')).rejects.toThrow(ValidationError); + await expect(resource.getStateTaxInfo('SP', '12ABC34501DE36')).rejects.toThrow( + 'check digits do not match' + ); + expect(mockHttpClient.get).not.toHaveBeenCalled(); + }); + + it('rejects text outside the CNPJ mask', async () => { + await expect(resource.getBasicInfo('CNPJ 11.222.333/0001-81')).rejects.toThrow( + '12 letters or digits followed by 2 check digits' + ); + expect(mockHttpClient.get).not.toHaveBeenCalled(); + }); + + it('lets the API answer the version boundary for an alphanumeric CNPJ', async () => { + // Resposta medida em 2026-11-18 na v2 da consulta de CNPJ. + vi.mocked(mockHttpClient.get).mockRejectedValue( + new ValidationError('CNPJ alfanumérico não é suportado nesta versão. Utilize a v3.', { + errors: [{ code: 40001, message: 'CNPJ alfanumérico não é suportado nesta versão. Utilize a v3.' }], + }) + ); + + await expect(resource.getBasicInfo('12ABC34501DE35')).rejects.toThrow('Utilize a v3'); + expect(mockHttpClient.get).toHaveBeenCalledWith( + '/v2/legalentities/basicInfo/12ABC34501DE35', + undefined + ); }); it('should accept valid 14-digit CNPJ', async () => { @@ -383,10 +430,10 @@ describe('LegalEntityLookupResource', () => { }; vi.mocked(mockHttpClient.get).mockResolvedValue(mockResponse); - await resource.getBasicInfo('12.345.678/0001-90'); + await resource.getBasicInfo('11.222.333/0001-81'); expect(mockHttpClient.get).toHaveBeenCalledWith( - '/v2/legalentities/basicInfo/12345678000190', + '/v2/legalentities/basicInfo/11222333000181', undefined ); }); @@ -440,7 +487,7 @@ describe('LegalEntityLookupResource', () => { }; vi.mocked(mockHttpClient.get).mockResolvedValue(mockResponse); - await resource.getStateTaxInfo('SP', '12.345.678/0001-90'); + await resource.getStateTaxInfo('SP', '11.222.333/0001-81'); expect(mockHttpClient.get).toHaveBeenCalledWith( `/v2/legalentities/stateTaxInfo/SP/${VALID_CNPJ_DIGITS}` diff --git a/tests/unit/legal-people.test.ts b/tests/unit/legal-people.test.ts index d4a144e..235acd2 100644 --- a/tests/unit/legal-people.test.ts +++ b/tests/unit/legal-people.test.ts @@ -116,6 +116,27 @@ describe('LegalPeopleResource', () => { }); }); + // A v1 devolve federalTaxNumber como número; um CNPJ que começa com zero chega sem ele. + // Até a v6.0.1 a busca comparava texto e não achava o registro. + describe('findByTaxNumber', () => { + it('acha o registro numérico pela string com zero à esquerda e máscara', async () => { + vi.mocked(mockHttpClient.get).mockResolvedValue({ + data: { + legalPeople: [ + createMockLegalPerson({ id: 'p1', federalTaxNumber: 11222333000181 as unknown as string }), + createMockLegalPerson({ id: 'p2', federalTaxNumber: 1234567999885 as unknown as string }), + ], + }, + status: 200, + headers: {}, + } as any); + + expect((await legalPeople.findByTaxNumber(TEST_COMPANY_ID, '01234567999885'))?.id).toBe('p2'); + expect((await legalPeople.findByTaxNumber(TEST_COMPANY_ID, '01.234.567/9998-85'))?.id).toBe('p2'); + expect(await legalPeople.findByTaxNumber(TEST_COMPANY_ID, '99999999000191')).toBeUndefined(); + }); + }); + describe('error handling', () => { it('should propagate errors from http client', async () => { const error = new Error('Network error'); diff --git a/tests/unit/natural-people.test.ts b/tests/unit/natural-people.test.ts index dca44c2..61c7638 100644 --- a/tests/unit/natural-people.test.ts +++ b/tests/unit/natural-people.test.ts @@ -116,6 +116,25 @@ describe('NaturalPeopleResource', () => { }); }); + // A v1 devolve federalTaxNumber como número; um CPF que começa com zero chega sem ele. + describe('findByTaxNumber', () => { + it('acha o registro numérico pela string com zero à esquerda e máscara', async () => { + vi.mocked(mockHttpClient.get).mockResolvedValue({ + data: { + naturalPeople: [ + createMockNaturalPerson({ id: 'p1', federalTaxNumber: 1234567890 as unknown as string }), + ], + }, + status: 200, + headers: {}, + } as any); + + expect((await naturalPeople.findByTaxNumber(TEST_COMPANY_ID, '01234567890'))?.id).toBe('p1'); + expect((await naturalPeople.findByTaxNumber(TEST_COMPANY_ID, '012.345.678-90'))?.id).toBe('p1'); + expect(await naturalPeople.findByTaxNumber(TEST_COMPANY_ID, '98765432100')).toBeUndefined(); + }); + }); + describe('error handling', () => { it('should propagate errors from http client', async () => { const error = new Error('Network error'); diff --git a/tests/unit/resources/companies-search.test.ts b/tests/unit/resources/companies-search.test.ts index 4a3e5c4..49f20f1 100644 --- a/tests/unit/resources/companies-search.test.ts +++ b/tests/unit/resources/companies-search.test.ts @@ -68,10 +68,16 @@ describe('CompaniesResource - Search Helpers', () => { expect(company).toBeNull(); }); - it('should reject invalid tax number length', async () => { - await expect( - companies.findByTaxNumber(123) - ).rejects.toThrow(ValidationError); + // Até a v6.0.1 este teste exigia erro para 3 dígitos. Mas um documento que começa com zero + // vira número curto: o CNPJ 00000000000191 chega como 191. Desde a 6.0.2 só a forma é + // conferida, e uma busca que não acha devolve null. + it('accepts a short number: the document may have lost its leading zeros', async () => { + await expect(companies.findByTaxNumber(123)).resolves.toBeNull(); + }); + + it('rejects what is not a non-negative integer with up to 14 digits', async () => { + await expect(companies.findByTaxNumber(-123)).rejects.toThrow(ValidationError); + await expect(companies.findByTaxNumber(123456789012345)).rejects.toThrow(ValidationError); }); it('should accept 11-digit CPF', async () => { diff --git a/tests/unit/resources/inbound-product-invoices.test.ts b/tests/unit/resources/inbound-product-invoices.test.ts index 014cfea..59b9f2d 100644 --- a/tests/unit/resources/inbound-product-invoices.test.ts +++ b/tests/unit/resources/inbound-product-invoices.test.ts @@ -63,7 +63,7 @@ describe('InboundProductInvoicesResource', () => { it('should throw ValidationError for invalid access key format', async () => { await expect(resource.getDetails(testCompanyId, '12345')).rejects.toThrow(ValidationError); - await expect(resource.getDetails(testCompanyId, '12345')).rejects.toThrow(/Expected 44 numeric digits/); + await expect(resource.getDetails(testCompanyId, '12345')).rejects.toThrow(/Expected 44 characters/); }); it('should throw ValidationError for empty access key', async () => { @@ -84,6 +84,29 @@ describe('InboundProductInvoicesResource', () => { await expect(resource.getEventDetails(testCompanyId, validAccessKey, ' ')).rejects.toThrow(ValidationError); }); + // Emitente com CNPJ alfanumérico: letras nas posições 7 a 18. Medido em 2026-11-18, a rota + // /inbound/productinvoices/{chave} aceita o formato (404 para chave inexistente, igual à + // numérica); a rota /inbound/{chave} ainda recusa com 400. O SDK envia e a API decide. + it('accepts an access key with letters in the issuer CNPJ and sends it upper case', async () => { + const alphaKey = '35260612ABC34501DE35550010000000031100000033'; + mockHttpClient.get.mockResolvedValue({ data: {}, status: 200, headers: {} }); + + await resource.getProductInvoiceDetails(testCompanyId, alphaKey.toLowerCase()); + await resource.getDetails(testCompanyId, ` ${alphaKey} `); + + expect(mockHttpClient.get).toHaveBeenNthCalledWith( + 1, + `/v2/companies/${testCompanyId}/inbound/productinvoices/${alphaKey}` + ); + expect(mockHttpClient.get).toHaveBeenNthCalledWith(2, `/v2/companies/${testCompanyId}/inbound/${alphaKey}`); + }); + + it('still rejects a letter outside the issuer CNPJ positions', async () => { + const alphaKey = '35260612ABC34501DE35550010000000031100000033'; + await expect(resource.getDetails(testCompanyId, `${alphaKey.slice(0, 43)}X`)).rejects.toThrow(ValidationError); + expect(mockHttpClient.get).not.toHaveBeenCalled(); + }); + it('should throw ValidationError for empty accessKeyOrNsu on reprocessWebhook', async () => { await expect(resource.reprocessWebhook(testCompanyId, '')).rejects.toThrow(ValidationError); await expect(resource.reprocessWebhook(testCompanyId, '')).rejects.toThrow(/Access key or NSU is required/); diff --git a/tests/unit/resources/product-invoice-query.test.ts b/tests/unit/resources/product-invoice-query.test.ts index 03d0a6d..e3e9628 100644 --- a/tests/unit/resources/product-invoice-query.test.ts +++ b/tests/unit/resources/product-invoice-query.test.ts @@ -54,12 +54,12 @@ describe('ProductInvoiceQueryResource', () => { it('should throw ValidationError for non-numeric access key', async () => { await expect(resource.retrieve('a'.repeat(44))).rejects.toThrow(ValidationError); - await expect(resource.retrieve('a'.repeat(44))).rejects.toThrow(/Expected 44 numeric digits/); + await expect(resource.retrieve('a'.repeat(44))).rejects.toThrow(/Expected 44 characters/); }); it('should throw ValidationError for too-short access key', async () => { await expect(resource.retrieve('12345')).rejects.toThrow(ValidationError); - await expect(resource.retrieve('12345')).rejects.toThrow(/Expected 44 numeric digits/); + await expect(resource.retrieve('12345')).rejects.toThrow(/Expected 44 characters/); }); it('should throw ValidationError for too-long access key', async () => { @@ -77,6 +77,17 @@ describe('ProductInvoiceQueryResource', () => { await expect(resource.retrieve(validAccessKey)).resolves.toBeDefined(); }); + // A consulta de NF-e v2 responde 400 para chave com letras (medido em 2026-11-18). O SDK não + // recusa no cliente: envia a chave normalizada e a mensagem da API chega ao chamador. + it('sends an access key with letters in the issuer CNPJ upper case', async () => { + const alphaKey = '35260612ABC34501DE35550010000000031100000033'; + mockHttpClient.get.mockResolvedValue({ data: {}, status: 200, headers: {} }); + + await resource.retrieve(alphaKey.toLowerCase()); + + expect(mockHttpClient.get).toHaveBeenCalledWith(`/v2/productinvoices/${alphaKey}`); + }); + it('should validate access key on all methods', async () => { const badKey = 'invalid'; await expect(resource.retrieve(badKey)).rejects.toThrow(ValidationError); diff --git a/tests/unit/resources/transportation-invoices.test.ts b/tests/unit/resources/transportation-invoices.test.ts index 610063d..f87b60f 100644 --- a/tests/unit/resources/transportation-invoices.test.ts +++ b/tests/unit/resources/transportation-invoices.test.ts @@ -249,6 +249,17 @@ describe('TransportationInvoicesResource', () => { await expect(resource.retrieve(testCompanyId, '')).rejects.toThrow(/Access key is required/); }); + // A chave do CT-e traz o CNPJ do emitente nas posições 7 a 20. A rota /inbound/{chave} ainda + // recusa letras (400, medido em 2026-11-18 na NF-e); o SDK envia e a API decide. + it('sends an access key with letters in the issuer CNPJ upper case', async () => { + const alphaKey = '35260612ABC34501DE35570010000000031100000035'; + mockHttpClient.get.mockResolvedValue({ data: mockMetadata, status: 200, headers: {} }); + + await resource.retrieve(testCompanyId, alphaKey.toLowerCase()); + + expect(mockHttpClient.get).toHaveBeenCalledWith(`/v2/companies/${testCompanyId}/inbound/${alphaKey}`); + }); + it('should throw ValidationError for whitespace-only access key', async () => { await expect(resource.retrieve(testCompanyId, ' ')).rejects.toThrow(ValidationError); }); diff --git a/tests/unit/utils/tax-id.test.ts b/tests/unit/utils/tax-id.test.ts new file mode 100644 index 0000000..1a76a54 --- /dev/null +++ b/tests/unit/utils/tax-id.test.ts @@ -0,0 +1,168 @@ +/** + * Regra única de CNPJ, CPF e chave de acesso (change fix-tax-id-validation). + * + * Vetores: + * - `12ABC34501DE35`: exemplo público da Receita Federal para o CNPJ alfanumérico; + * - `FIOUQ123000109`: sintético com F, I, O, U e Q, que a Receita aceita; + * - `01234567999885`: sintético que começa com zero; a consulta de CNPJ confirmou que não + * existe na Receita (2026-11-18); + * - a chave de acesso é sintética, montada com o CNPJ de exemplo da Receita. + */ + +import { describe, expect, it } from 'vitest'; +import { ValidationError } from '../../../src/core/errors/index.js'; +import { + isAlphanumericCnpj, + isValidAccessKey, + isValidCnpj, + isValidCpf, + normalizeAccessKey, + normalizeCnpj, + normalizeCpf, + requireAccessKey, + requireCnpj, +} from '../../../src/core/utils/tax-id.js'; + +const ALPHA_KEY = '35260612ABC34501DE35550010000000031100000033'; + +/** Cálculo numérico usado até a v6.0.1 (`companies.ts`), para provar equivalência. */ +function legacyNumericCnpjIsValid(cnpj: number): boolean { + const cnpjStr = cnpj.toString().padStart(14, '0'); + if (cnpjStr.length !== 14) return false; + if (/^(\d)\1{13}$/.test(cnpjStr)) return false; + let sum = 0; + let weight = 5; + for (let i = 0; i < 12; i++) { + sum += parseInt(cnpjStr[i]!) * weight; + weight = weight === 2 ? 9 : weight - 1; + } + const firstDigit = sum % 11 < 2 ? 0 : 11 - (sum % 11); + if (firstDigit !== parseInt(cnpjStr[12]!)) return false; + sum = 0; + weight = 6; + for (let i = 0; i < 13; i++) { + sum += parseInt(cnpjStr[i]!) * weight; + weight = weight === 2 ? 9 : weight - 1; + } + const secondDigit = sum % 11 < 2 ? 0 : 11 - (sum % 11); + return secondDigit === parseInt(cnpjStr[13]!); +} + +describe('tax-id: CNPJ', () => { + it('aceita o exemplo alfanumérico da Receita e recusa o DV errado', () => { + expect(isValidCnpj('12ABC34501DE35')).toBe(true); + expect(isValidCnpj('12ABC34501DE36')).toBe(false); + }); + + it('aceita as 26 letras, inclusive F, I, O, U e Q', () => { + expect(isValidCnpj('FIOUQ123000109')).toBe(true); + }); + + it('aceita o CNPJ numérico tradicional e recusa sequência repetida', () => { + expect(isValidCnpj('11222333000181')).toBe(true); + expect(isValidCnpj(11222333000181)).toBe(true); + expect(isValidCnpj('11111111111111')).toBe(false); + expect(isValidCnpj('00000000000000')).toBe(false); + }); + + it('completa com zeros o number que perdeu o zero à esquerda', () => { + expect(normalizeCnpj(1234567999885)).toBe('01234567999885'); + expect(isValidCnpj(1234567999885)).toBe(true); + expect(isValidCnpj(1234567999886)).toBe(false); + }); + + it('não completa string curta: string precisa ter 14 posições depois da normalização', () => { + expect(isValidCnpj('1234567999885')).toBe(false); + }); + + it('normaliza máscara e minúsculas sem perder letras', () => { + expect(normalizeCnpj('12.abc.345/01de-35')).toBe('12ABC34501DE35'); + expect(normalizeCnpj(' 11.222.333/0001-81 ')).toBe('11222333000181'); + expect(isValidCnpj('12.abc.345/01de-35')).toBe(true); + }); + + it('recusa formato com letra nos dígitos verificadores ou tamanho errado', () => { + expect(isValidCnpj('12ABC34501DEA5')).toBe(false); + expect(isValidCnpj('12ABC34501DE3')).toBe(false); + expect(isValidCnpj('CNPJ 11.222.333/0001-81')).toBe(false); + }); + + it('recusa number que não é inteiro seguro e não negativo', () => { + expect(isValidCnpj(-11222333000181)).toBe(false); + expect(isValidCnpj(11222333000181.5)).toBe(false); + expect(isValidCnpj(Number.NaN)).toBe(false); + }); + + it('detecta CNPJ alfanumérico pelas 12 primeiras posições', () => { + expect(isAlphanumericCnpj('12.ABC.345/01DE-35')).toBe(true); + expect(isAlphanumericCnpj('12abc34501de35')).toBe(true); + expect(isAlphanumericCnpj('11222333000181')).toBe(false); + expect(isAlphanumericCnpj(11222333000181)).toBe(false); + }); + + it('dá o mesmo resultado que o cálculo numérico antigo para os CNPJs da suíte', () => { + const numerics = [ + 11222333000181, 12345678000276, 11111111000111, 11122233344455, 11223344000155, + 12345678000190, 12345678901234, 33333333000133, 98765432000110, 98765432109876, + 11444555000149, 1234567999885, 191, + ]; + for (const cnpj of numerics) { + expect(isValidCnpj(cnpj), String(cnpj)).toBe(legacyNumericCnpjIsValid(cnpj)); + } + }); + + describe('requireCnpj', () => { + it('devolve o CNPJ normalizado', () => { + expect(requireCnpj('12.abc.345/01de-35')).toBe('12ABC34501DE35'); + expect(requireCnpj(1234567999885)).toBe('01234567999885'); + }); + + it('lança ValidationError para vazio, formato e DV', () => { + expect(() => requireCnpj('')).toThrow('Federal tax number (CNPJ) is required'); + expect(() => requireCnpj(' ')).toThrow(ValidationError); + expect(() => requireCnpj(undefined)).toThrow(ValidationError); + expect(() => requireCnpj('CNPJ 11.222.333/0001-81')).toThrow( + '12 letters or digits followed by 2 check digits' + ); + expect(() => requireCnpj('12ABC34501DE36')).toThrow('check digits do not match'); + }); + }); +}); + +describe('tax-id: CPF', () => { + it('valida o CPF e completa com zeros o number', () => { + expect(normalizeCpf(1234567890)).toBe('01234567890'); + expect(isValidCpf(1234567890)).toBe(true); + expect(isValidCpf('012.345.678-90')).toBe(true); + expect(isValidCpf('01234567891')).toBe(false); + expect(isValidCpf('11111111111')).toBe(false); + }); + + it('não arranca letras: string com letra não vira CPF válido', () => { + expect(isValidCpf('A01234567890')).toBe(false); + }); +}); + +describe('tax-id: chave de acesso', () => { + it('aceita letras nas posições 7 a 18 e normaliza para maiúsculas', () => { + expect(isValidAccessKey(ALPHA_KEY)).toBe(true); + expect(normalizeAccessKey(` ${ALPHA_KEY.toLowerCase()} `)).toBe(ALPHA_KEY); + expect(requireAccessKey(ALPHA_KEY.toLowerCase())).toBe(ALPHA_KEY); + }); + + it('continua aceitando a chave numérica', () => { + expect(isValidAccessKey('35240112345678000190550010000001231234567890')).toBe(true); + }); + + it('recusa letra fora do CNPJ', () => { + expect(isValidAccessKey(`${ALPHA_KEY.slice(0, 43)}X`)).toBe(false); + expect(isValidAccessKey(`A${ALPHA_KEY.slice(1)}`)).toBe(false); + expect(isValidAccessKey(`${ALPHA_KEY.slice(0, 20)}A${ALPHA_KEY.slice(21)}`)).toBe(false); + }); + + it('lança ValidationError para vazio e formato', () => { + expect(() => requireAccessKey('')).toThrow('Access key is required'); + expect(() => requireAccessKey('123')).toThrow(ValidationError); + expect(() => requireAccessKey('123')).toThrow('positions 7 to 18'); + }); +}); From b10517cc3906aee952e37fb7e872f5f59af4a4d7 Mon Sep 17 00:00:00 2001 From: Andre Kutianski Date: Wed, 18 Nov 2026 20:19:57 -0300 Subject: [PATCH 2/6] fix(inbound): ManifestEventType aceita 210200, a Confirmacao da Operacao A documentacao chamava o 210220 de Confirmacao da Operacao. O 210220 e Desconhecimento da Operacao: envia-lo registra na SEFAZ, em nome do destinatario, que a operacao nao e reconhecida. A Confirmacao e o 210200, que faltava no tipo. - ManifestEventType passa a ser 210200 | 210210 | 210220 | 210240, o enum que a plataforma declara para a rota de manifestacao. A mudanca e aditiva, e o padrao continua 210210. - JSDoc, README, docs/API.md, skill e exemplo trazem os quatro codigos, o aviso e um exemplo de Confirmacao com 210200. Saem os exemplos com 210220 e 210240 (a rota responde 400 para 210240). - Teste unitario de manifest com tpEvent=210200 e teste de tipo em tests/types/manifest-event-type.test-d.ts. --- README.md | 14 +++++++--- docs/API.md | 26 ++++++++++++------- examples/inbound-product-invoices.js | 3 ++- .../references/product-invoices-and-taxes.md | 13 +++++++++- .../resources/inbound-product-invoices.ts | 14 +++++++--- src/core/types.ts | 16 +++++++++--- tests/types/manifest-event-type.test-d.ts | 22 ++++++++++++++++ .../inbound-product-invoices.test.ts | 12 +++++++++ 8 files changed, 97 insertions(+), 23 deletions(-) create mode 100644 tests/types/manifest-event-type.test-d.ts diff --git a/README.md b/README.md index 78f110c..e26067e 100644 --- a/README.md +++ b/README.md @@ -499,11 +499,11 @@ await nfe.inboundProductInvoices.manifest( '35240112345678000190550010000001231234567890' ); -// Manifestar com evento específico +// Confirmar a operação: a Confirmação da Operação é 210200 (o 210220 é Desconhecimento) await nfe.inboundProductInvoices.manifest( 'empresa-id', '35240112345678000190550010000001231234567890', - 210220 // Confirmação da Operação + 210200 ); // Consultar evento da NF-e @@ -534,10 +534,18 @@ await nfe.inboundProductInvoices.reprocessWebhook('empresa-id', '35240...'); | Código | Evento | |--------|--------| +| `210200` | Confirmação da Operação | | `210210` | Ciência da Operação (padrão) | -| `210220` | Confirmação da Operação | +| `210220` | **Desconhecimento da Operação** | | `210240` | Operação não Realizada | +> ⚠️ **`210220` é Desconhecimento da Operação, não Confirmação.** Enviá-lo por engano registra na +> SEFAZ, em nome do destinatário, uma declaração formal de que a operação não é reconhecida, +> visível para o emissor e para o fisco. Até a 6.0.1, este README o chamava de Confirmação, o que +> estava errado. A Confirmação da Operação é `210200`, que o tipo `ManifestEventType` aceita desde +> a 6.0.2. Segundo a documentação da plataforma, a rota de manifestação responde `400` para +> `210240`, porque o evento exige justificativa e a rota não tem corpo para enviá-la. + #### 📦 NF-e de Produto - Emissão (`nfe.productInvoices`) Ciclo completo de gestão de NF-e (Nota Fiscal Eletrônica de Produto) — emissão, listagem, consulta, cancelamento, carta de correção (CC-e), inutilização e download de arquivos (PDF/XML): diff --git a/docs/API.md b/docs/API.md index e31fffb..ab057d2 100644 --- a/docs/API.md +++ b/docs/API.md @@ -1910,18 +1910,11 @@ await nfe.inboundProductInvoices.manifest( '35240112345678000190550010000001231234567890' ); -// Confirmação da Operação +// Confirmação da Operação is 210200 (210220 is Desconhecimento) await nfe.inboundProductInvoices.manifest( 'company-id', '35240112345678000190550010000001231234567890', - 210220 -); - -// Operação não Realizada -await nfe.inboundProductInvoices.manifest( - 'company-id', - '35240112345678000190550010000001231234567890', - 210240 + 210200 ); ``` @@ -1929,10 +1922,23 @@ await nfe.inboundProductInvoices.manifest( | Code | Event | |------|-------| +| `210200` | Confirmação da Operação (confirmation — "goods received as described") | | `210210` | Ciência da Operação (awareness, default) | -| `210220` | Confirmação da Operação (confirmation) | +| `210220` | Desconhecimento da Operação (disowned — "I do not recognize this transaction") | | `210240` | Operação não Realizada (operation not performed) | +:::danger Códigos de manifestação: confira antes de enviar +`210220` é **Desconhecimento da Operação**, não Confirmação. Enviá-lo por engano registra na +SEFAZ, em nome do destinatário, uma declaração formal de que a operação **não é reconhecida** — +visível para o emissor e para o fisco, e não reversível pelo mesmo canal. Até a 6.0.1, esta +documentação o chamava de Confirmação, o que estava errado. + +Confirmação da Operação é **`210200`**, que o tipo `ManifestEventType` aceita desde a 6.0.2. +::: + +Segundo a documentação da plataforma, esta rota responde `400` para `210240`: o evento exige +justificativa, e a rota não tem corpo para enviá-la. + #### `reprocessWebhook(companyId: string, accessKeyOrNsu: string): Promise` Reprocess a webhook notification by access key or NSU. diff --git a/examples/inbound-product-invoices.js b/examples/inbound-product-invoices.js index 9019a50..fcf41b0 100644 --- a/examples/inbound-product-invoices.js +++ b/examples/inbound-product-invoices.js @@ -156,8 +156,9 @@ async function downloadPdf(companyId, accessKey) { */ async function sendManifest(companyId, accessKey, tpEvent = 210210) { const eventNames = { + 210200: 'Confirmação da Operação', 210210: 'Ciência da Operação', - 210220: 'Confirmação da Operação', + 210220: 'Desconhecimento da Operação (NÃO é Confirmação; a Confirmação é 210200)', 210240: 'Operação não Realizada', }; const eventName = eventNames[tpEvent] || `Event ${tpEvent}`; diff --git a/skills/nfeio-node-sdk/references/product-invoices-and-taxes.md b/skills/nfeio-node-sdk/references/product-invoices-and-taxes.md index a0a004f..289d1a8 100644 --- a/skills/nfeio-node-sdk/references/product-invoices-and-taxes.md +++ b/skills/nfeio-node-sdk/references/product-invoices-and-taxes.md @@ -359,11 +359,22 @@ Sends the Manifestação do Destinatário. `tpEvent` defaults to `210210`: ```typescript type ManifestEventType = + | 210200 // Confirmação da Operação (confirmation: "goods received as described"), since 6.0.2 | 210210 // Ciência da Operação (awareness, default) - | 210220 // Confirmação da Operação (confirmation) + | 210220 // Desconhecimento da Operação (disowned: "I do not recognize this operation") | 210240; // Operação não Realizada (not performed) + +// Confirm an operation +await nfe.inboundProductInvoices.manifest(companyId, accessKey, 210200); ``` +**`210220` is NOT Confirmação da Operação.** It is Desconhecimento: sending it by mistake registers +at SEFAZ, on behalf of the recipient, a formal statement that the operation is not recognized, +visible to the issuer and to the tax authority. The SDK docs called it "Confirmação" until 6.0.1. +Confirmação da Operação is `210200`, accepted by `ManifestEventType` since 6.0.2: never send +`210220` to confirm. According to the platform documentation, this route answers `400` for +`210240`, because the event requires a justification and the route has no body for it. + ### reprocessWebhook(companyId, accessKeyOrNsu): Promise Resends the webhook notification for a document, identified by its 44-character access key or by its diff --git a/src/core/resources/inbound-product-invoices.ts b/src/core/resources/inbound-product-invoices.ts index 0c9449d..6dd3176 100644 --- a/src/core/resources/inbound-product-invoices.ts +++ b/src/core/resources/inbound-product-invoices.ts @@ -538,9 +538,15 @@ export class InboundProductInvoicesResource { * Defaults to "Ciência da Operação" (210210) if no event type is specified. * * **Event types:** + * - `210200` — Confirmação da Operação (confirmation). Accepted by the type since 6.0.2. * - `210210` — Ciência da Operação (awareness, default) - * - `210220` — Confirmação da Operação (confirmation) - * - `210240` — Operação não Realizada (operation not performed) + * - `210220` — **Desconhecimento da Operação**: the recipient does NOT recognize the operation. + * It is NOT "Confirmação da Operação", as this documentation said until 6.0.1. Sending it by + * mistake registers at SEFAZ a formal statement that the operation is not recognized, + * visible to the issuer and to the tax authority. + * - `210240` — Operação não Realizada (operation not performed). According to the platform + * documentation, this route answers `400` for it: the event requires a justification, and + * this route has no body to carry it. * * @param companyId - The company ID * @param accessKey - The 44-character access key of the NF-e @@ -556,12 +562,12 @@ export class InboundProductInvoicesResource { * ); * ``` * - * @example Confirm operation + * @example Confirm the operation (Confirmação da Operação is 210200, not 210220) * ```typescript * const result = await nfe.inboundProductInvoices.manifest( * 'company-id', * '35240112345678000190550010000001231234567890', - * 210220 + * 210200 * ); * ``` */ diff --git a/src/core/types.ts b/src/core/types.ts index b13faaf..745c0a0 100644 --- a/src/core/types.ts +++ b/src/core/types.ts @@ -920,13 +920,21 @@ export interface EnableInboundOptions { } /** - * Manifest event types for Manifestação do Destinatário + * Manifest event types for Manifestação do Destinatário. The values are the `tpEvent` enum + * the platform declares for the manifest route: `[210200, 210210, 210220, 210240]`. * + * - `210200` — Confirmação da Operação (confirmation of the operation). Missing from this type + * until 6.0.1, which pushed callers to the wrong code. * - `210210` — Ciência da Operação (awareness of the operation) - * - `210220` — Confirmação da Operação (confirmation of the operation) - * - `210240` — Operação não Realizada (operation not performed) + * - `210220` — **Desconhecimento da Operação** (the recipient does NOT recognize the operation). + * Until 6.0.1 this documentation called it "Confirmação da Operação", which is wrong. Sending + * it by mistake registers at SEFAZ, on behalf of the recipient, a formal statement that the + * operation is not recognized, visible to the issuer and to the tax authority. + * - `210240` — Operação não Realizada (operation not performed). The platform documents that + * the `/manifest` route answers `400` for it: the event requires a justification, and this + * route has no body to carry it. */ -export type ManifestEventType = 210210 | 210220 | 210240; +export type ManifestEventType = 210200 | 210210 | 210220 | 210240; // ============================================================================ // Product Invoice Query Types (consulta-nf) diff --git a/tests/types/manifest-event-type.test-d.ts b/tests/types/manifest-event-type.test-d.ts new file mode 100644 index 0000000..d7a385e --- /dev/null +++ b/tests/types/manifest-event-type.test-d.ts @@ -0,0 +1,22 @@ +/** + * Alignment guard: `ManifestEventType` amarrado ao enum de `tpEvent` que a plataforma declara na + * rota de manifestação: `[210200, 210210, 210220, 210240]`. + * + * Até a 6.0.1 o tipo não tinha o `210200` (Confirmação da Operação), e a documentação chamava o + * `210220` (Desconhecimento da Operação) de Confirmação. Enviar o `210220` por engano registra na + * SEFAZ que a operação não é reconhecida. Se alguém remover o `210200` ou mudar o conjunto, este + * teste quebra em vez de driftar em silêncio. + */ + +import { describe, it, expectTypeOf } from 'vitest'; +import type { ManifestEventType } from '../../src/index.js'; + +describe('ManifestEventType: alinhamento com o enum da plataforma', () => { + it('tem exatamente os quatro códigos da manifestação do destinatário', () => { + expectTypeOf().toEqualTypeOf<210200 | 210210 | 210220 | 210240>(); + }); + + it('aceita o 210200, a Confirmação da Operação', () => { + expectTypeOf<210200>().toMatchTypeOf(); + }); +}); diff --git a/tests/unit/resources/inbound-product-invoices.test.ts b/tests/unit/resources/inbound-product-invoices.test.ts index 59b9f2d..7d0b5fc 100644 --- a/tests/unit/resources/inbound-product-invoices.test.ts +++ b/tests/unit/resources/inbound-product-invoices.test.ts @@ -455,6 +455,18 @@ describe('InboundProductInvoicesResource', () => { ); }); + // Confirmação da Operação é 210200. Até a 6.0.1 o tipo não o aceitava, e a documentação + // chamava o 210220 (Desconhecimento) de Confirmação. + it('should send manifest with tpEvent=210200 (Confirmação da Operação)', async () => { + mockHttpClient.post.mockResolvedValue({ data: 'ok', status: 200, headers: {} }); + + await resource.manifest(testCompanyId, validAccessKey, 210200); + + expect(mockHttpClient.post).toHaveBeenCalledWith( + `/v2/companies/${testCompanyId}/inbound/${validAccessKey}/manifest?tpEvent=210200` + ); + }); + it('should send manifest with explicit tpEvent=210220', async () => { const mockResponse: HttpResponse = { data: 'ok', From ee889455a6a1e9c8f3b69590ea1194e52b72fe75 Mon Sep 17 00:00:00 2001 From: Andre Kutianski Date: Wed, 18 Nov 2026 20:20:30 -0300 Subject: [PATCH 3/6] test(types): test:types passa a conferir os testes de tipo O vitest --typecheck so confere os arquivos do programa do TypeScript, e o tsconfig.json inclui so src/. Os tests/types/*.test-d.ts ficavam de fora e nenhum erro de tipo aparecia: expectTypeOf<1>().toEqualTypeOf<2>() passava. O CI e o publish.yml rodam esse comando. O vitest.config.ts aponta typecheck.tsconfig para o tsconfig.test-types.json (novo), que inclui os testes de tipo. A assercao falsa agora falha, e os cinco arquivos de tipo passam sem mudanca. --- tsconfig.test-types.json | 9 +++++++++ vitest.config.ts | 6 ++++++ 2 files changed, 15 insertions(+) create mode 100644 tsconfig.test-types.json diff --git a/tsconfig.test-types.json b/tsconfig.test-types.json new file mode 100644 index 0000000..0f14f7d --- /dev/null +++ b/tsconfig.test-types.json @@ -0,0 +1,9 @@ +{ + "extends": "./tsconfig.json", + "compilerOptions": { + "noEmit": true, + "rootDir": "." + }, + "include": ["src/**/*", "tests/types/**/*.test-d.ts"], + "exclude": ["node_modules", "dist", "**/*.test.ts", "**/*.spec.ts"] +} diff --git a/vitest.config.ts b/vitest.config.ts index e186a7f..cd12e93 100644 --- a/vitest.config.ts +++ b/vitest.config.ts @@ -8,6 +8,12 @@ export default defineConfig({ // client-ruby (que apontam de volta para este repo), coletando os mesmos // testes 3-4x e corrompendo o .test-temp compartilhado (flake). include: ['tests/**/*.test.ts', 'tests/**/*.spec.ts'], + // O `--typecheck` só confere os arquivos do programa do TypeScript. O tsconfig.json inclui só + // src/, então os tests/types/*.test-d.ts ficavam de fora e nenhum erro de tipo aparecia (uma + // asserção falsa passava). Este tsconfig inclui os testes de tipo. + typecheck: { + tsconfig: './tsconfig.test-types.json', + }, coverage: { provider: 'v8', reporter: ['text', 'json', 'html'], From c5358aa614ec4cf35579b2d9daf0386c260822e0 Mon Sep 17 00:00:00 2001 From: Andre Kutianski Date: Wed, 18 Nov 2026 20:20:59 -0300 Subject: [PATCH 4/6] docs: cita a documentacao da plataforma no lugar de referencias internas Onze pontos de versoes anteriores citavam fontes internas: o CHANGELOG, a skill, JSDoc, comentarios em src/ e docs/recursos/municipal-taxes.md. Passam a citar a documentacao da plataforma, sem mudar o sentido. O pacote publicado deixa de levar essas referencias (conferido com npm pack). --- CHANGELOG.md | 8 ++++---- docs/recursos/municipal-taxes.md | 2 +- .../references/product-invoices-and-taxes.md | 4 ++-- .../references/rtc-nfce-and-account-resources.md | 4 ++-- src/core/resources/consumer-invoice-query.ts | 2 +- src/core/resources/inbound-product-invoices.ts | 2 +- src/core/resources/municipal-taxes.ts | 2 +- src/core/resources/service-invoices.ts | 2 +- src/core/utils/unserved-route.ts | 2 +- 9 files changed, 14 insertions(+), 14 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index ee740cb..4d5b216 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -32,8 +32,8 @@ e este projeto adere ao [Versionamento Semântico](https://semver.org/lang/pt-BR `404` de corpo vazio mesmo sem credencial, igual a um path inventado; o plural responde `401` sem credencial, e `200` com ela nos dois métodos de leitura sondados (`getProductInvoiceDetails` e `getJson`). A spec local `consulta-nfe-distribuicao-v1.yaml` ainda - diz singular; o upstream corrigiu em `nfe/docs@51d8816`. Cinco testes unitários afirmavam o - path errado e foram corrigidos junto. + diz singular; a spec atualizada da plataforma já traz o plural. Cinco testes unitários + afirmavam o path errado e foram corrigidos junto. O bug era latente. Em 30 dias de log de gateway (2026-09-14 a 10-14), o plural teve 28.543 respostas `200` e o singular, 9 respostas `404`, nenhuma com User-Agent do SDK. Evidência em @@ -61,7 +61,7 @@ e este projeto adere ao [Versionamento Semântico](https://semver.org/lang/pt-BR ### Documentação - **`municipalTaxes.update` é um PUT que substitui a inscrição, e nada avisava.** Pela - documentação da plataforma (`nfe/docs@b9e7953`), omitir `taxNumber` apaga o número da + documentação da plataforma, omitir `taxNumber` apaga o número da inscrição, e omitir `environment` volta para `Development`. `rpsNumber` e `lastRpsSent` são a exceção: omitidos, preservam o contador de RPS; enviados, sobrescrevem o contador, inclusive para trás. O JSDoc, `docs/recursos/municipal-taxes.md` e a skill agora mostram o roteiro: ler @@ -271,7 +271,7 @@ reescrita. O parâmetro era opcional e a documentação prometia um ZIP com todas as notas. A rota não existe: `/serviceinvoices/pdf` responde `404 "service invoice with id (pdf) was not found"`, porque o servidor casa a rota `/{id}` e lê `pdf` como identificador. Não está - na spec `nf-servico-v1` nem no `nfeio-docs`. Nota de migração em `MIGRATION.md`. + na spec `nf-servico-v1` nem na documentação da plataforma. Nota de migração em `MIGRATION.md`. - **O erro da API parava de chegar ao chamador.** `extractErrorMessage` só lia `message`/`error`/`detail`/`details`. A plataforma usa quatro envelopes: diff --git a/docs/recursos/municipal-taxes.md b/docs/recursos/municipal-taxes.md index f12bc6f..6393a7e 100644 --- a/docs/recursos/municipal-taxes.md +++ b/docs/recursos/municipal-taxes.md @@ -47,7 +47,7 @@ console.log(created.id); ## Atualizar: o PUT substitui a inscrição `update` é um **PUT de substituição**, não uma atualização dos campos enviados. -Segundo a documentação da plataforma (`nfe/docs@b9e7953`, 14/10/2026): +Segundo a documentação da plataforma (14/10/2026): - `taxNumber` omitido é **apagado**; - `environment` omitido volta para `Development`; diff --git a/skills/nfeio-node-sdk/references/product-invoices-and-taxes.md b/skills/nfeio-node-sdk/references/product-invoices-and-taxes.md index 289d1a8..3bd1df6 100644 --- a/skills/nfeio-node-sdk/references/product-invoices-and-taxes.md +++ b/skills/nfeio-node-sdk/references/product-invoices-and-taxes.md @@ -164,8 +164,8 @@ interface NfeStateTax { } ``` -The enum values follow the spec's casing (state codes such as `'sP'`), which is questioned -upstream in nfe/docs#338. +The enum values follow the spec's casing (state codes such as `'sP'`), which has been +reported to the platform team. | Method | Signature | |--------|-----------| diff --git a/skills/nfeio-node-sdk/references/rtc-nfce-and-account-resources.md b/skills/nfeio-node-sdk/references/rtc-nfce-and-account-resources.md index dc12393..f107b48 100644 --- a/skills/nfeio-node-sdk/references/rtc-nfce-and-account-resources.md +++ b/skills/nfeio-node-sdk/references/rtc-nfce-and-account-resources.md @@ -64,8 +64,8 @@ delete(companyId, municipalTaxId): Promise `create`, `retrieve` and `update` return the registration itself (since 6.0.1; the API wraps it as `{ municipalTax: {…} }` and the SDK unwraps it). -**`update` is a PUT that replaces the registration**, per the platform documentation -(nfe/docs@b9e7953): an omitted `taxNumber` is erased and an omitted `environment` falls back to +**`update` is a PUT that replaces the registration**, per the platform documentation: +an omitted `taxNumber` is erased and an omitted `environment` falls back to `Development`. Read, change, send the whole object back — and **omit `rpsNumber`/`lastRpsSent`**, which an omitted value preserves; sending them overwrites the RPS counter, even backwards: diff --git a/src/core/resources/consumer-invoice-query.ts b/src/core/resources/consumer-invoice-query.ts index 980753f..fdd16fa 100644 --- a/src/core/resources/consumer-invoice-query.ts +++ b/src/core/resources/consumer-invoice-query.ts @@ -27,7 +27,7 @@ import { withUnservedRouteNote } from '../utils/unserved-route.js'; * Consumer Invoice Query Resource * * @deprecated **A plataforma não serve nenhuma das duas rotas deste recurso.** - * Elas estão declaradas na spec `consulta-nf-consumidor` e no `nfeio-docs`, em + * Elas estão declaradas na spec `consulta-nf-consumidor` e na documentação da plataforma, em * `nfe.api.nfe.io` — e respondem `404` de corpo vazio, sem `content-type`, * idêntico ao de um path inventado no mesmo host. Confirmação independente: o * `404` vem **inclusive sem credencial**, enquanto uma rota servida no mesmo host diff --git a/src/core/resources/inbound-product-invoices.ts b/src/core/resources/inbound-product-invoices.ts index 6dd3176..153f73e 100644 --- a/src/core/resources/inbound-product-invoices.ts +++ b/src/core/resources/inbound-product-invoices.ts @@ -293,7 +293,7 @@ export class InboundProductInvoicesResource { // Plural `/inbound/productinvoices/` here and in the three methods below, as the platform // serves it. The singular form answers 404 with an empty body even without credentials, like an // invented path (measured 2026-10-14). The local spec consulta-nfe-distribuicao-v1.yaml - // (vintage b487823) still says singular; upstream fixed it in nfe/docs@51d8816. + // still says singular; the platform's current spec already uses the plural. const response = await this.http.get( `/v2/companies/${companyId}/inbound/productinvoices/${key}` ); diff --git a/src/core/resources/municipal-taxes.ts b/src/core/resources/municipal-taxes.ts index e647fce..87577f2 100644 --- a/src/core/resources/municipal-taxes.ts +++ b/src/core/resources/municipal-taxes.ts @@ -72,7 +72,7 @@ export class MunicipalTaxesResource { * Update a municipal tax registration. * * **This is a PUT that replaces the registration, not a partial update.** Per the platform - * documentation (nfe/docs@b9e7953, 2026-10-14), an omitted `taxNumber` is erased and an + * documentation (as of 2026-10-14), an omitted `taxNumber` is erased and an * omitted `environment` falls back to `Development`; other omitted fields are not guaranteed to * keep their value. Read the registration, change what you need and send the whole object back. * diff --git a/src/core/resources/service-invoices.ts b/src/core/resources/service-invoices.ts index 4bfbd4e..e5f97ae 100644 --- a/src/core/resources/service-invoices.ts +++ b/src/core/resources/service-invoices.ts @@ -488,7 +488,7 @@ export class ServiceInvoicesResource { * opcional e o ramo sem id montava `/serviceinvoices/pdf`, que o servidor casa * com a rota `/{id}` e trata como identificador literal: * `404 "service invoice with id (pdf) was not found"`. A rota não está na spec - * `nf-servico-v1` nem no `nfeio-docs` — nunca houve caminho válido. + * `nf-servico-v1` nem na documentação da plataforma — nunca houve caminho válido. */ async downloadPdf(companyId: string, invoiceId: string): Promise { const response = await this.http.get( diff --git a/src/core/utils/unserved-route.ts b/src/core/utils/unserved-route.ts index 1286a53..0faf9f7 100644 --- a/src/core/utils/unserved-route.ts +++ b/src/core/utils/unserved-route.ts @@ -1,7 +1,7 @@ /** * NFE.io SDK — rotas declaradas na spec que a plataforma não serve. * - * Algumas rotas existem na OpenAPI (e no `nfeio-docs`) e simplesmente não são + * Algumas rotas existem na OpenAPI (e na documentação da plataforma) e simplesmente não são * roteadas em produção. O chamador recebe `404` e não tem como distinguir isso de * "esse dado não existe" — vai procurar defeito nos próprios dados, ou reportar * como bug do SDK. From 620b133896c7a59c79baaf877384e38f4268d0fc Mon Sep 17 00:00:00 2001 From: Andre Kutianski Date: Wed, 18 Nov 2026 20:21:33 -0300 Subject: [PATCH 5/6] chore(release): v6.0.2 Versao 6.0.2 no package.json e no package-lock.json; src/version.ts regenerado. Entrada 6.0.2 no CHANGELOG: CNPJ alfanumerico, primeira parte (zero a esquerda, chave de acesso com letras e consulta de CNPJ, com as mensagens de erro novas); manifestacao (210220 e Desconhecimento, e ManifestEventType ganha o 210200); o gate test:types; e o que ja estava em [Nao lancado] (paginas conferidas e frontmatter de maquina). Links de comparacao para v6.0.2. Sai o arquivo VERSION da raiz: parado em 4.0.0 e sem leitor. A versao vem do package.json, e tests/unit/version.test.ts guarda a concordancia. --- CHANGELOG.md | 112 +++++++++++++++++++++++++++++++++++++++++++++- VERSION | 1 - package-lock.json | 4 +- package.json | 2 +- src/version.ts | 2 +- 5 files changed, 115 insertions(+), 6 deletions(-) delete mode 100644 VERSION diff --git a/CHANGELOG.md b/CHANGELOG.md index 4d5b216..df8c953 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -7,14 +7,123 @@ e este projeto adere ao [Versionamento Semântico](https://semver.org/lang/pt-BR ## [Não lançado] +## [6.0.2] - 2026-11-18 + +> **CNPJ alfanumérico (IN RFB 2.229/2024), primeira parte: o SDK para de recusar no cliente o que +> a API aceita.** Uma regra só passa a valer para CNPJ, CPF e chave de acesso em todos os +> recursos. O acesso à família v3 da API, a única que aceita CNPJ alfanumérico, vem numa minor. +> Evidência em `tests/fixtures/live-contracts/alphanumeric-tax-ids.json`. +> +> **Manifestação do destinatário: o `210220` é Desconhecimento da Operação, não Confirmação.** A +> documentação errava o código. A Confirmação é o `210200`, que o tipo `ManifestEventType` passa a +> aceitar. +> +> Nada novo é exportado. A única mudança de tipo é aditiva: `ManifestEventType` ganha o `210200`. + +### Corrigido + +- **`companies` aceita CNPJ ou CPF que começa com zero.** Como `number`, o documento perde o + zero: `01234567999885` vira `1234567999885`. `create`, `update` e `findByTaxNumber` recusavam + esse número pelo tamanho. A API completa os zeros. Medido em 2026-11-18, com escrita + autorizada: + - `POST /v1/companies` com o número curto respondeu `201`; + - a v3 devolveu o CNPJ gravado com as 14 posições; + - o `PUT` com o objeto lido respondeu `200`. + + Agora o SDK completa com zeros e confere os dígitos verificadores, e `findByTaxNumber` compara + pelo valor. Em JavaScript sem tipos, uma string só de dígitos (14 para CNPJ, 11 para CPF) + também é aceita, como na API. O tipo continua `number`. +- **A chave de acesso de emitente com CNPJ alfanumérico deixa de ser recusada no cliente.** Com + CNPJ alfanumérico, as posições 7 a 18 da chave têm letras. `inboundProductInvoices`, + `productInvoiceQuery`, `consumerInvoiceQuery` e `transportationInvoices` exigiam 44 dígitos. + Agora aceitam letras nessas posições e enviam a chave em maiúsculas. Cada rota da API decide se + atende (medido em 2026-11-18): + - as rotas `/inbound/productinvoices/…` aceitam a chave; + - as rotas `/inbound/{chave}…` e a consulta de NF-e ainda respondem `400`, e o SDK repassa a + mensagem como `ValidationError`. +- **A consulta de CNPJ deixa de arrancar as letras.** `legalEntityLookup` fazia + `replace(/\D/g, '')`: um CNPJ alfanumérico virava 9 dígitos, e o erro dizia "got 9 digit(s)". + Agora a normalização tira só `.`, `/`, `-` e espaços e converte letras para maiúsculas. O CNPJ + alfanumérico chega à API, que responde `400` com "CNPJ alfanumérico não é suportado nesta + versão. Utilize a v3.". O SDK lança `ValidationError` com essa mensagem. +- **`legalPeople.findByTaxNumber` e `naturalPeople.findByTaxNumber` comparam pelo valor.** Um + registro que a API devolve como número sem o zero à esquerda passa a ser achado pela string com + o zero, com ou sem máscara. +- **`ManifestEventType` aceita o `210200`, a Confirmação da Operação.** O tipo tinha só `210210`, + `210220` e `210240`: em TypeScript, confirmar uma operação não compilava sem forçar o tipo, e a + documentação mandava usar o `210220`, que é Desconhecimento (veja Documentação). Agora o tipo + tem os quatro códigos que a plataforma declara para a rota de manifestação: + `210200 | 210210 | 210220 | 210240`. A mudança é aditiva: o código que compilava continua + compilando, e o padrão continua `210210`. O SDK só repassa o código à API. + +### Alterado + +- **A consulta de CNPJ confere os dígitos verificadores no cliente.** Um DV inválido lança + `ValidationError` sem requisição. Antes, a API respondia `400`, que já virava `ValidationError`. + O cálculo é o módulo 11 com o valor ASCII − 48 de cada caractere: para dígitos, dá o resultado + de sempre, e as 26 letras valem. +- **A consulta de CNPJ recusa texto fora da máscara.** `'CNPJ 11.222.333/0001-81'` passava, + porque o `\D` descartava tudo o que não era dígito. Agora falha no cliente. +- **Mensagens de erro novas**, para quem compara texto: + - chave de acesso: `Expected 44 characters: digits only, except positions 7 to 18, which hold the issuer CNPJ and may contain letters (alphanumeric CNPJ).`; + - CNPJ fora do formato: `Expected 14 characters after removing punctuation: 12 letters or digits followed by 2 check digits …`; + - CNPJ com DV inválido: `The CNPJ check digits do not match.`; + - `companies` com CNPJ alfanumérico: `Alphanumeric CNPJ is not accepted by the v1 companies API. The v3 companies API accepts it.`; + - `companies` com documento inválido: `Invalid federalTaxNumber: … Expected a valid CNPJ (14 digits) or CPF (11 digits); a number that lost its leading zeros is accepted.`; + - `companies.findByTaxNumber`: `Tax number must be a non-negative integer with up to 14 digits (CNPJ or CPF)`. + ### Documentação +- **O código `210220` da manifestação é Desconhecimento da Operação, não Confirmação.** O JSDoc de + `ManifestEventType` e de `inboundProductInvoices.manifest`, o README, `docs/API.md`, a skill e + o exemplo `examples/inbound-product-invoices.js` chamavam o `210220` de "Confirmação da + Operação". Isso está errado: enviá-lo registra na SEFAZ, em nome do destinatário, uma + declaração formal de que a operação não é reconhecida, visível para o emissor e para o fisco. + Um cliente quase o enviou seguindo a documentação. + - O texto agora traz os quatro códigos e o aviso. + - A Confirmação da Operação é `210200`. O README, `docs/API.md`, o JSDoc e a skill mostram como + enviá-la, e o tipo passa a aceitar o código (veja Corrigido). + - Segundo a documentação da plataforma, a rota de manifestação responde `400` para `210240`, + porque o evento exige justificativa. Os exemplos que manifestavam `210220` e `210240` saíram. + - Nada muda em tempo de execução. +- **Exemplos com CNPJ inválido.** O CNPJ de exemplo `12345678000190` tem DV inválido, e a API + sempre o recusou. Com esta versão, a consulta de CNPJ também o recusa no cliente. Ele aparecia + no README, no `MIGRATION.md`, em `docs/API.md`, nos exemplos, no JSDoc, na skill e nos testes, + em consultas de CNPJ, em `companies.create`, em pessoas e no comprador de NF-e. Agora esses + exemplos usam `11222333000181`, e o `companies.create` do README passou a usar `number`. +- **Formato do CNPJ nas páginas.** As páginas de consulta de CNPJ, de empresas e de NF-e de + entrada explicam o formato com letras, a normalização e que o CNPJ alfanumérico exige a API v3. + A página de NF-e de entrada lista quais métodos já aceitam a chave com letras. +- **Skill publicada (`skills/nfeio-node-sdk/`).** + - A skill registra a regra da 6.0.2: zero à esquerda, chave de acesso com letras e quais rotas + a aceitam, e CNPJ alfanumérico só na família v3 da API. + - A seção de consulta de CNPJ trazia opções que não existem (`includePartners`, + `includeActivities`). As opções reais são `updateAddress` e `updateCityCode`. + - Ela também trazia campos com nome ou tipo errado. O certo é `federalTaxNumber` como `number`, + e não `string`, mais `openedOn`, `shareCapital`, `economicActivities` e `legalNature`. + - O padrão "Address from CEP" desestruturava `{ addresses }`, mas `lookupByPostalCode` devolve + um `Address`. - **As páginas de `docs/` que o portal espelha foram conferidas contra o código.** Havia assinaturas e retornos de antes da 6.0.0 nas páginas de NF-e, NFS-e, inscrição estadual, consulta de CNPJ e pessoas, e em `downloads.md`, que ainda prometia "Buffer sempre" e "ZIP por empresa". Também foram corrigidos exemplos que não compilavam em modo estrito. `docs/API.md`, `docs/EXTENDING.md` e `docs/EXTENSIBILITY_SUMMARY.md` são da v3 e ganharam aviso de legado no topo, sem reescrever o conteúdo. +- **Frontmatter de máquina nas páginas de `docs/`.** Cada página traz `tags` e + `integration: [sdk]`, que o portal de documentação usa como facetas de busca. + +### Manutenção + +- **Sai o arquivo `VERSION` da raiz.** Ele estava parado em `4.0.0` desde a v4, e nada o lia: + nem o build, nem os testes, nem o workflow de publicação, nem o pacote publicado. A versão tem + uma fonte só, o `package.json`; `src/version.ts` é gerado dele, e `tests/unit/version.test.ts` + falha se as duas divergirem. +- **`npm run test:types` passa a conferir os tipos.** O comando roda `vitest --typecheck`, que só + confere os arquivos do programa do TypeScript. O `tsconfig.json` inclui só `src/`, então os + arquivos `tests/types/*.test-d.ts` ficavam de fora e nenhum erro de tipo aparecia: a asserção + falsa `expectTypeOf<1>().toEqualTypeOf<2>()` passava. O CI e o workflow de publicação rodam esse + comando. Agora o `vitest.config.ts` aponta o typecheck para o `tsconfig.test-types.json`, que + inclui os testes de tipo. Os quatro guardas de tipo que já existiam passam sem mudança. ## [6.0.1] - 2026-10-16 @@ -1365,7 +1474,8 @@ SDK JavaScript legado com API baseada em callbacks. ## Links -[Não lançado]: https://github.com/nfe/client-nodejs/compare/v6.0.1...HEAD +[Não lançado]: https://github.com/nfe/client-nodejs/compare/v6.0.2...HEAD +[6.0.2]: https://github.com/nfe/client-nodejs/compare/v6.0.1...v6.0.2 [6.0.1]: https://github.com/nfe/client-nodejs/compare/v6.0.0...v6.0.1 [6.0.0]: https://github.com/nfe/client-nodejs/compare/v5.2.0...v6.0.0 [5.2.0]: https://github.com/nfe/client-nodejs/compare/v5.1.0...v5.2.0 diff --git a/VERSION b/VERSION deleted file mode 100644 index fcdb2e1..0000000 --- a/VERSION +++ /dev/null @@ -1 +0,0 @@ -4.0.0 diff --git a/package-lock.json b/package-lock.json index efc9146..fc826f9 100644 --- a/package-lock.json +++ b/package-lock.json @@ -1,12 +1,12 @@ { "name": "nfe-io", - "version": "6.0.1", + "version": "6.0.2", "lockfileVersion": 3, "requires": true, "packages": { "": { "name": "nfe-io", - "version": "6.0.1", + "version": "6.0.2", "license": "MIT", "devDependencies": { "@types/node": "^22.19.21", diff --git a/package.json b/package.json index 2d4fdfd..ca34709 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "nfe-io", - "version": "6.0.1", + "version": "6.0.2", "description": "Official NFE.io SDK for Node.js - TypeScript native with zero runtime dependencies", "keywords": [ "nfe", diff --git a/src/version.ts b/src/version.ts index e711043..5fa1fd4 100644 --- a/src/version.ts +++ b/src/version.ts @@ -11,4 +11,4 @@ export const PACKAGE_NAME = 'nfe-io'; /** Versão desta build, vinda do `package.json`. */ -export const VERSION = '6.0.1'; +export const VERSION = '6.0.2'; From 21c41c279106e77d98c118ca28f1d8d01f2a7e4d Mon Sep 17 00:00:00 2001 From: Andre Kutianski Date: Wed, 18 Nov 2026 20:41:52 -0300 Subject: [PATCH 6/6] docs: CNPJ de exemplo sintetico, que nao existe na Receita O CNPJ de exemplo 11222333000181 existe na Receita e esta ativo. Os exemplos de consulta devolviam dados reais, e o companies.create do README cadastraria esse CNPJ. README, MIGRATION, docs/, skill, exemplos, JSDoc, a mensagem de erro do CNPJ fora do formato e os testes passam a usar 11222333999952 (11.222.333/9999-52): o DV e valido, e a consulta de CNPJ responde 404 (conferido em 2026-11-18). Os dados das escritas de teste (TEST_COMPANY_DATA da integracao e test-company.json) tambem saem do CNPJ real. --- CHANGELOG.md | 5 ++-- MIGRATION.md | 2 +- README.md | 24 +++++++++---------- docs/API.md | 24 +++++++++---------- docs/recursos/companies.md | 2 +- examples/cnpj-lookup.js | 4 ++-- examples/jsdoc-intellisense-demo.ts | 4 ++-- examples/product-invoices.js | 2 +- skills/nfeio-node-sdk/SKILL.md | 2 +- .../references/data-services-and-lookups.md | 8 +++---- .../service-invoices-and-polling.md | 2 +- src/core/client.ts | 10 ++++---- src/core/resources/companies.ts | 4 ++-- src/core/resources/legal-entity-lookup.ts | 20 ++++++++-------- src/core/resources/legal-people.ts | 2 +- src/core/resources/product-invoices.ts | 2 +- src/core/utils/tax-id.ts | 2 +- test-company.json | 2 +- tests/integration/setup.ts | 4 +++- tests/unit/companies.test.ts | 2 +- tests/unit/legal-entity-lookup.test.ts | 12 +++++----- tests/unit/legal-people.test.ts | 2 +- tests/unit/utils/tax-id.test.ts | 20 ++++++++-------- 23 files changed, 82 insertions(+), 79 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index df8c953..155b60a 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -62,7 +62,7 @@ e este projeto adere ao [Versionamento Semântico](https://semver.org/lang/pt-BR `ValidationError` sem requisição. Antes, a API respondia `400`, que já virava `ValidationError`. O cálculo é o módulo 11 com o valor ASCII − 48 de cada caractere: para dígitos, dá o resultado de sempre, e as 26 letras valem. -- **A consulta de CNPJ recusa texto fora da máscara.** `'CNPJ 11.222.333/0001-81'` passava, +- **A consulta de CNPJ recusa texto fora da máscara.** `'CNPJ 11.222.333/9999-52'` passava, porque o `\D` descartava tudo o que não era dígito. Agora falha no cliente. - **Mensagens de erro novas**, para quem compara texto: - chave de acesso: `Expected 44 characters: digits only, except positions 7 to 18, which hold the issuer CNPJ and may contain letters (alphanumeric CNPJ).`; @@ -90,7 +90,8 @@ e este projeto adere ao [Versionamento Semântico](https://semver.org/lang/pt-BR sempre o recusou. Com esta versão, a consulta de CNPJ também o recusa no cliente. Ele aparecia no README, no `MIGRATION.md`, em `docs/API.md`, nos exemplos, no JSDoc, na skill e nos testes, em consultas de CNPJ, em `companies.create`, em pessoas e no comprador de NF-e. Agora esses - exemplos usam `11222333000181`, e o `companies.create` do README passou a usar `number`. + exemplos usam `11222333999952`, um CNPJ sintético: o DV é válido, e a consulta de CNPJ não o + encontra na Receita. O `companies.create` do README passou a usar `number`. - **Formato do CNPJ nas páginas.** As páginas de consulta de CNPJ, de empresas e de NF-e de entrada explicam o formato com letras, a normalização e que o CNPJ alfanumérico exige a API v3. A página de NF-e de entrada lista quais métodos já aceitam a chave com letras. diff --git a/MIGRATION.md b/MIGRATION.md index 0126e4f..4fb9e61 100644 --- a/MIGRATION.md +++ b/MIGRATION.md @@ -549,7 +549,7 @@ for await (const company of nfe.companies.listIterator()) { } // 🆕 Novo na v3: Métodos de busca -const company = await nfe.companies.findByTaxNumber(11222333000181); // CNPJ +const company = await nfe.companies.findByTaxNumber(11222333999952); // CNPJ const matches = await nfe.companies.findByName('Acme'); // Por nome const withCerts = await nfe.companies.getCompaniesWithCertificates(); const expiring = await nfe.companies.getCompaniesWithExpiringCertificates(30); diff --git a/README.md b/README.md index e26067e..7014e3f 100644 --- a/README.md +++ b/README.md @@ -95,7 +95,7 @@ const nfe = new NfeClient({ // Criar uma empresa const empresa = await nfe.companies.create({ - federalTaxNumber: 11222333000181, + federalTaxNumber: 11222333999952, name: 'Minha Empresa Ltda', email: 'empresa@exemplo.com.br', taxRegime: 1, // Simples Nacional @@ -116,7 +116,7 @@ const notaFiscal = await nfe.serviceInvoices.create(empresa.id, { servicesAmount: 1000.00, borrower: { type: 'LegalEntity', - federalTaxNumber: 11222333000181, + federalTaxNumber: 11222333999952, name: 'Empresa Cliente', email: 'cliente@exemplo.com.br', address: { @@ -257,7 +257,7 @@ Gerenciar empresas na sua conta: // Criar empresa (a API exige name, federalTaxNumber, taxRegime e address) const empresa = await nfe.companies.create({ name: 'Nome da Empresa', - federalTaxNumber: 11222333000181, + federalTaxNumber: 11222333999952, taxRegime: 'SimplesNacional', address: { state: 'SP', @@ -302,7 +302,7 @@ Gerenciar pessoas jurídicas (empresas/negócios): ```typescript // Criar pessoa jurídica const pessoa = await nfe.legalPeople.create(empresaId, { - federalTaxNumber: '11222333000181', + federalTaxNumber: '11222333999952', name: 'Nome da Empresa', email: 'empresa@exemplo.com.br', address: { /* ... */ } @@ -312,7 +312,7 @@ const pessoa = await nfe.legalPeople.create(empresaId, { const pessoas = await nfe.legalPeople.list(empresaId); // Buscar por CNPJ -const pessoa = await nfe.legalPeople.findByTaxNumber(empresaId, '11222333000181'); +const pessoa = await nfe.legalPeople.findByTaxNumber(empresaId, '11222333999952'); ``` #### 👤 Pessoas Físicas (`nfe.naturalPeople`) @@ -555,7 +555,7 @@ Ciclo completo de gestão de NF-e (Nota Fiscal Eletrônica de Produto) — emiss const result = await nfe.productInvoices.create('empresa-id', { operationNature: 'Venda de mercadoria', operationType: 'Outgoing', - buyer: { name: 'Empresa LTDA', federalTaxNumber: 11222333000181 }, + buyer: { name: 'Empresa LTDA', federalTaxNumber: 11222333999952 }, items: [{ code: 'PROD-001', description: 'Produto X', quantity: 1, unitAmount: 100 }], payment: [{ paymentDetail: [{ method: 'Cash', amount: 100 }] }], }); @@ -668,7 +668,7 @@ Consultar dados cadastrais de empresas brasileiras (CNPJ) na Receita Federal e n ```typescript // Consulta básica por CNPJ (aceita com ou sem pontuação) -const result = await nfe.legalEntityLookup.getBasicInfo('11.222.333/0001-81'); +const result = await nfe.legalEntityLookup.getBasicInfo('11.222.333/9999-52'); console.log('Razão Social:', result.legalEntity?.name); console.log('Nome Fantasia:', result.legalEntity?.tradeName); console.log('Status:', result.legalEntity?.status); // 'Active' @@ -676,20 +676,20 @@ console.log('Porte:', result.legalEntity?.size); // 'ME', 'EPP', etc. console.log('Cidade:', result.legalEntity?.address?.city?.name); // Consulta com opções -const result = await nfe.legalEntityLookup.getBasicInfo('11222333000181', { +const result = await nfe.legalEntityLookup.getBasicInfo('11222333999952', { updateAddress: false, // Não atualizar endereço via Correios updateCityCode: true, // Atualizar código IBGE da cidade }); // Consultar Inscrição Estadual (IE) por estado -const ieSP = await nfe.legalEntityLookup.getStateTaxInfo('SP', '11222333000181'); +const ieSP = await nfe.legalEntityLookup.getStateTaxInfo('SP', '11222333999952'); for (const tax of ieSP.legalEntity?.stateTaxes ?? []) { console.log(`IE: ${tax.taxNumber} - Status: ${tax.status}`); console.log(` NFe: ${tax.nfe?.status}, CTe: ${tax.cte?.status}`); } // Avaliar IE para emissão de nota fiscal -const invoice = await nfe.legalEntityLookup.getStateTaxForInvoice('MG', '11222333000181'); +const invoice = await nfe.legalEntityLookup.getStateTaxForInvoice('MG', '11222333999952'); for (const tax of invoice.legalEntity?.stateTaxes ?? []) { if (tax.status === 'Abled') { console.log(`Pode emitir com IE: ${tax.taxNumber}`); @@ -697,7 +697,7 @@ for (const tax of invoice.legalEntity?.stateTaxes ?? []) { } // Obter melhor IE sugerida para emissão -const sugestao = await nfe.legalEntityLookup.getSuggestedStateTaxForInvoice('SP', '11222333000181'); +const sugestao = await nfe.legalEntityLookup.getSuggestedStateTaxForInvoice('SP', '11222333999952'); const melhorIE = sugestao.legalEntity?.stateTaxes?.[0]; console.log('IE recomendada:', melhorIE?.taxNumber); ``` @@ -928,7 +928,7 @@ async function emitirNotaFiscal() { servicesAmount: 5000.00, borrower: { type: 'LegalEntity', - federalTaxNumber: 11222333000181, + federalTaxNumber: 11222333999952, name: 'Cliente Exemplo Ltda', email: 'contato@cliente.com.br', address: { diff --git a/docs/API.md b/docs/API.md index ab057d2..4a65d79 100644 --- a/docs/API.md +++ b/docs/API.md @@ -313,7 +313,7 @@ if ('id' in result) { // Example 2: Invoice with full details const invoice = await nfe.serviceInvoices.create('company-id', { borrower: { - federalTaxNumber: 11222333000181, + federalTaxNumber: 11222333999952, name: 'Acme Corporation', email: 'finance@acme.com', address: { @@ -1070,7 +1070,7 @@ Create a new company with automatic CNPJ/CPF validation. ```typescript const company = await nfe.companies.create({ - federalTaxNumber: 11222333000181, // CNPJ or CPF as a number; one that starts with zero may lose it (01234567999885 → 1234567999885) + federalTaxNumber: 11222333999952, // CNPJ or CPF as a number; one that starts with zero may lose it (01234567999885 → 1234567999885) name: 'My Company', email: 'company@example.com', address: { @@ -1255,7 +1255,7 @@ Find company by federal tax number (CNPJ or CPF). ```typescript // Search by CNPJ, as a number (a CNPJ that starts with zero is found by the short number) -const company = await nfe.companies.findByTaxNumber(11222333000181); +const company = await nfe.companies.findByTaxNumber(11222333999952); // Or by CPF (11 digits) const company = await nfe.companies.findByTaxNumber(12345678901); @@ -1338,7 +1338,7 @@ Create a legal person. ```typescript const legalPerson = await nfe.legalPeople.create('company-id', { - federalTaxNumber: '11222333000181', + federalTaxNumber: '11222333999952', name: 'Legal Person Company', email: 'legal@example.com' }); @@ -1383,7 +1383,7 @@ await nfe.legalPeople.delete('company-id', 'person-id'); Find legal person by CNPJ. ```typescript -const person = await nfe.legalPeople.findByTaxNumber('company-id', '11222333000181'); +const person = await nfe.legalPeople.findByTaxNumber('company-id', '11222333999952'); ``` ### Natural People @@ -2087,13 +2087,13 @@ Query Brazilian company (CNPJ) data from Receita Federal and state tax registrie Lookup basic company information by CNPJ from Receita Federal. Returns legal name, trade name, address, phone numbers, economic activities (CNAE), legal nature, partners, and registration status. ```typescript -const result = await nfe.legalEntityLookup.getBasicInfo('11.222.333/0001-81'); +const result = await nfe.legalEntityLookup.getBasicInfo('11.222.333/9999-52'); console.log(result.legalEntity?.name); // 'EMPRESA LTDA' console.log(result.legalEntity?.status); // 'Active' console.log(result.legalEntity?.address?.city?.name); // With options -const result = await nfe.legalEntityLookup.getBasicInfo('11222333000181', { +const result = await nfe.legalEntityLookup.getBasicInfo('11222333999952', { updateAddress: false, updateCityCode: true, }); @@ -2103,7 +2103,7 @@ const result = await nfe.legalEntityLookup.getBasicInfo('11222333000181', { | Parameter | Type | Required | Description | |-----------|------|----------|-------------| -| `federalTaxNumber` | `string` | Yes | CNPJ, with or without punctuation (e.g., `"11222333000181"`, `"11.222.333/0001-81"` or the alphanumeric `"12.ABC.345/01DE-35"`). Punctuation is removed and letters are kept, in upper case | +| `federalTaxNumber` | `string` | Yes | CNPJ, with or without punctuation (e.g., `"11222333999952"`, `"11.222.333/9999-52"` or the alphanumeric `"12.ABC.345/01DE-35"`). Punctuation is removed and letters are kept, in upper case | | `options` | `LegalEntityBasicInfoOptions` | No | Lookup options | **Options:** @@ -2125,7 +2125,7 @@ const result = await nfe.legalEntityLookup.getBasicInfo('11222333000181', { Lookup state tax registration (Inscrição Estadual) by CNPJ and state. Returns tax regime, legal nature, and state tax registration details including fiscal document indicators (NFe, NFSe, CTe, NFCe). ```typescript -const result = await nfe.legalEntityLookup.getStateTaxInfo('SP', '11222333000181'); +const result = await nfe.legalEntityLookup.getStateTaxInfo('SP', '11222333999952'); console.log(result.legalEntity?.taxRegime); // 'SimplesNacional' for (const tax of result.legalEntity?.stateTaxes ?? []) { @@ -2152,7 +2152,7 @@ for (const tax of result.legalEntity?.stateTaxes ?? []) { Evaluate state tax registration for invoice issuance. Returns extended status information (including `UnabledTemp`, `UnabledNotConfirmed`) useful for determining whether product invoices (NF-e) can be issued. ```typescript -const result = await nfe.legalEntityLookup.getStateTaxForInvoice('MG', '11222333000181'); +const result = await nfe.legalEntityLookup.getStateTaxForInvoice('MG', '11222333999952'); for (const tax of result.legalEntity?.stateTaxes ?? []) { if (tax.status === 'Abled') { console.log(`Can issue invoices with IE: ${tax.taxNumber}`); @@ -2178,7 +2178,7 @@ for (const tax of result.legalEntity?.stateTaxes ?? []) { Get the best (suggested) state tax registration for invoice issuance. When multiple registrations are enabled in a state, NFE.io applies evaluation criteria to recommend the optimal IE. ```typescript -const result = await nfe.legalEntityLookup.getSuggestedStateTaxForInvoice('SP', '11222333000181'); +const result = await nfe.legalEntityLookup.getSuggestedStateTaxForInvoice('SP', '11222333999952'); const bestIE = result.legalEntity?.stateTaxes?.[0]; if (bestIE) { console.log(`Recommended IE: ${bestIE.taxNumber} (${bestIE.status})`); @@ -2492,7 +2492,7 @@ Issue a product invoice (NF-e) by posting it to the processing queue. const result = await nfe.productInvoices.create('company-id', { operationNature: 'Venda de mercadoria', operationType: 'Outgoing', - buyer: { name: 'Empresa LTDA', federalTaxNumber: 11222333000181 }, + buyer: { name: 'Empresa LTDA', federalTaxNumber: 11222333999952 }, items: [{ code: 'PROD-001', description: 'Produto X', quantity: 1, unitAmount: 100 }], payment: [{ paymentDetail: [{ method: 'Cash', amount: 100 }] }], }); diff --git a/docs/recursos/companies.md b/docs/recursos/companies.md index 9d97db1..13e6d72 100644 --- a/docs/recursos/companies.md +++ b/docs/recursos/companies.md @@ -33,7 +33,7 @@ o pré-requisito de toda emissão — e precisa de inscrição ```typescript const company = await nfe.companies.create({ name: 'Minha Empresa LTDA', - federalTaxNumber: 11222333000181, + federalTaxNumber: 11222333999952, email: 'fiscal@empresa.com', }); diff --git a/examples/cnpj-lookup.js b/examples/cnpj-lookup.js index 81ebf3a..b8e4e2c 100644 --- a/examples/cnpj-lookup.js +++ b/examples/cnpj-lookup.js @@ -24,7 +24,7 @@ const client = new NfeClient({ }); // Example CNPJ — replace with a real one for testing -const EXAMPLE_CNPJ = process.env.TEST_CNPJ || '11222333000181'; +const EXAMPLE_CNPJ = process.env.TEST_CNPJ || '11222333999952'; const EXAMPLE_STATE = process.env.TEST_STATE || 'SP'; /** @@ -98,7 +98,7 @@ async function lookupWithOptions() { try { // Formatted CNPJ is accepted — punctuation is stripped automatically - const result = await client.legalEntityLookup.getBasicInfo('11.222.333/0001-81', { + const result = await client.legalEntityLookup.getBasicInfo('11.222.333/9999-52', { updateAddress: false, // Skip postal service address enrichment updateCityCode: true, // But still update city IBGE code }); diff --git a/examples/jsdoc-intellisense-demo.ts b/examples/jsdoc-intellisense-demo.ts index 6a53ec1..ec01539 100644 --- a/examples/jsdoc-intellisense-demo.ts +++ b/examples/jsdoc-intellisense-demo.ts @@ -53,7 +53,7 @@ async function demonstrateJSDoc() { type: 'LegalEntity' as const, name: 'Client Name', email: 'client@example.com', - federalTaxNumber: 11222333000181, + federalTaxNumber: 11222333999952, address: { country: 'BRA', postalCode: '01310-100', @@ -141,7 +141,7 @@ async function demonstrateJSDoc() { // Hover to see CNPJ lookup documentation const legalPerson = await nfe.legalPeople.findByTaxNumber( companyId, - '11222333000181' + '11222333999952' ); // Hover to see CPF lookup documentation diff --git a/examples/product-invoices.js b/examples/product-invoices.js index bbe2826..409d07d 100644 --- a/examples/product-invoices.js +++ b/examples/product-invoices.js @@ -42,7 +42,7 @@ async function main() { operationType: 'Outgoing', buyer: { name: 'Empresa Exemplo LTDA', - federalTaxNumber: 11222333000181, + federalTaxNumber: 11222333999952, address: { street: 'Rua Exemplo', number: '100', diff --git a/skills/nfeio-node-sdk/SKILL.md b/skills/nfeio-node-sdk/SKILL.md index 2f50c5d..7b30e78 100644 --- a/skills/nfeio-node-sdk/SKILL.md +++ b/skills/nfeio-node-sdk/SKILL.md @@ -365,7 +365,7 @@ on the live API — fetch the real list with `await nfe.webhooks.fetchEventTypes 1. **Import path**: Use `'nfe-io'` not `'@nfe-io/sdk'`. The JSDoc uses `@nfe-io/sdk` but the npm package is `nfe-io`. -2. **`federalTaxNumber` type varies**: For `companies.create()` it's a **number** (`11222333000181`). For `legalPeople`/`naturalPeople` and lookup resources it's a **string** (`'11222333000181'`). A CNPJ or CPF that starts with zero loses it as a number (`01234567999885` → `1234567999885`): since 6.0.2 the SDK accepts that short number, as the API does, and `companies.findByTaxNumber` compares by value. Lookups accept the CNPJ with or without punctuation and check the check digits locally. +2. **`federalTaxNumber` type varies**: For `companies.create()` it's a **number** (`11222333999952`). For `legalPeople`/`naturalPeople` and lookup resources it's a **string** (`'11222333999952'`). A CNPJ or CPF that starts with zero loses it as a number (`01234567999885` → `1234567999885`): since 6.0.2 the SDK accepts that short number, as the API does, and `companies.findByTaxNumber` compares by value. Lookups accept the CNPJ with or without punctuation and check the check digits locally. 3. **`serviceInvoices.create()` returns a union**: The return type is `{ status: 'immediate', invoice } | { status: 'async', response }`. Always use `createAndWait()` unless you need manual control. diff --git a/skills/nfeio-node-sdk/references/data-services-and-lookups.md b/skills/nfeio-node-sdk/references/data-services-and-lookups.md index a289c71..e17b627 100644 --- a/skills/nfeio-node-sdk/references/data-services-and-lookups.md +++ b/skills/nfeio-node-sdk/references/data-services-and-lookups.md @@ -156,8 +156,8 @@ Queries Receita Federal for company data by CNPJ. ```typescript // The response wraps the entity: { legalEntity } -const { legalEntity } = await nfe.legalEntityLookup.getBasicInfo('11.222.333/0001-81'); -await nfe.legalEntityLookup.getBasicInfo('11222333000181'); // same query +const { legalEntity } = await nfe.legalEntityLookup.getBasicInfo('11.222.333/9999-52'); +await nfe.legalEntityLookup.getBasicInfo('11222333999952'); // same query interface LegalEntityBasicInfoOptions { updateAddress?: boolean; // Update the address from postal service data (default: true) @@ -200,7 +200,7 @@ type LegalEntityStatus = 'Unknown' | 'Active' | 'Suspended' | 'Cancelled' | 'Una Get state tax registrations (Inscricoes Estaduais) for a specific state: ```typescript -const taxInfo = await nfe.legalEntityLookup.getStateTaxInfo('SP', '11222333000181'); +const taxInfo = await nfe.legalEntityLookup.getStateTaxInfo('SP', '11222333999952'); ``` **BrazilianState** type — all 27 UF codes plus special values: @@ -282,7 +282,7 @@ const addr = await nfe.addresses.lookupByPostalCode('01310-100'); await nfe.serviceInvoices.createAndWait(companyId, { // ... borrower: { - federalTaxNumber: 11222333000181, + federalTaxNumber: 11222333999952, name: 'Client', address: { country: addr.country, diff --git a/skills/nfeio-node-sdk/references/service-invoices-and-polling.md b/skills/nfeio-node-sdk/references/service-invoices-and-polling.md index b363505..82a7291 100644 --- a/skills/nfeio-node-sdk/references/service-invoices-and-polling.md +++ b/skills/nfeio-node-sdk/references/service-invoices-and-polling.md @@ -226,7 +226,7 @@ const exp = await nfe.companies.checkCertificateExpiration(companyId); ```typescript // Find company by CNPJ/CPF (returns null if not found). Compares by value: // a CNPJ that starts with zero is found by the short number (1234567999885). -const company = await nfe.companies.findByTaxNumber(11222333000181); +const company = await nfe.companies.findByTaxNumber(11222333999952); // Search by name (returns array) const matches = await nfe.companies.findByName('Example'); diff --git a/src/core/client.ts b/src/core/client.ts index 62f0bd1..ed7025e 100644 --- a/src/core/client.ts +++ b/src/core/client.ts @@ -93,7 +93,7 @@ export { NATURAL_PERSON_API_BASE_URL } from './resources/index.js'; * * // Create a company * const company = await nfe.companies.create({ - * federalTaxNumber: 11222333000181, // v1: number. An alphanumeric CNPJ needs the v3 API + * federalTaxNumber: 11222333999952, // v1: number. An alphanumeric CNPJ needs the v3 API * name: 'My Company' * }); * @@ -234,7 +234,7 @@ export class NfeClient { * @example * ```typescript * const company = await nfe.companies.create({ - * federalTaxNumber: 11222333000181, // v1: number. An alphanumeric CNPJ needs the v3 API + * federalTaxNumber: 11222333999952, // v1: number. An alphanumeric CNPJ needs the v3 API * name: 'My Company', * email: 'company@example.com' * }); @@ -262,7 +262,7 @@ export class NfeClient { * @example * ```typescript * const legalPerson = await nfe.legalPeople.create(companyId, { - * federalTaxNumber: '11222333000181', + * federalTaxNumber: '11222333999952', * name: 'Legal Person Company' * }); * ``` @@ -549,11 +549,11 @@ export class NfeClient { * @example * ```typescript * // Basic CNPJ lookup - * const result = await nfe.legalEntityLookup.getBasicInfo('11.222.333/0001-81'); + * const result = await nfe.legalEntityLookup.getBasicInfo('11.222.333/9999-52'); * console.log(result.legalEntity?.name); * * // State tax registration - * const stateTax = await nfe.legalEntityLookup.getStateTaxInfo('SP', '11222333000181'); + * const stateTax = await nfe.legalEntityLookup.getStateTaxInfo('SP', '11222333999952'); * ``` */ get legalEntityLookup(): LegalEntityLookupResource { diff --git a/src/core/resources/companies.ts b/src/core/resources/companies.ts index 92b587d..43f1c76 100644 --- a/src/core/resources/companies.ts +++ b/src/core/resources/companies.ts @@ -223,7 +223,7 @@ export class CompaniesResource { * ```typescript * const company = await nfe.companies.create({ * name: 'Acme Corp', - * federalTaxNumber: 11222333000181, + * federalTaxNumber: 11222333999952, * taxRegime: 'SimplesNacional', * address: { * state: 'SP', @@ -760,7 +760,7 @@ export class CompaniesResource { * * @example * ```typescript - * const company = await nfe.companies.findByTaxNumber(11222333000181); + * const company = await nfe.companies.findByTaxNumber(11222333999952); * * if (company) { * console.log('Found:', company.name); diff --git a/src/core/resources/legal-entity-lookup.ts b/src/core/resources/legal-entity-lookup.ts index 67700f4..3b7af1d 100644 --- a/src/core/resources/legal-entity-lookup.ts +++ b/src/core/resources/legal-entity-lookup.ts @@ -102,7 +102,7 @@ function validateState(state: string | undefined | null): BrazilianState { * * @example Basic CNPJ lookup * ```typescript - * const result = await nfe.legalEntityLookup.getBasicInfo('11.222.333/0001-81'); + * const result = await nfe.legalEntityLookup.getBasicInfo('11.222.333/9999-52'); * console.log(result.legalEntity?.name); // 'EMPRESA LTDA' * console.log(result.legalEntity?.status); // 'Active' * console.log(result.legalEntity?.address?.city?.name); // 'São Paulo' @@ -110,7 +110,7 @@ function validateState(state: string | undefined | null): BrazilianState { * * @example State tax registration lookup * ```typescript - * const result = await nfe.legalEntityLookup.getStateTaxInfo('SP', '11222333000181'); + * const result = await nfe.legalEntityLookup.getStateTaxInfo('SP', '11222333999952'); * for (const tax of result.legalEntity?.stateTaxes ?? []) { * console.log(`IE: ${tax.taxNumber} - Status: ${tax.status}`); * } @@ -118,7 +118,7 @@ function validateState(state: string | undefined | null): BrazilianState { * * @example Best IE for invoice issuance * ```typescript - * const result = await nfe.legalEntityLookup.getSuggestedStateTaxForInvoice('SP', '11222333000181'); + * const result = await nfe.legalEntityLookup.getSuggestedStateTaxForInvoice('SP', '11222333999952'); * const bestIE = result.legalEntity?.stateTaxes?.[0]; * console.log(`Best IE: ${bestIE?.taxNumber} (${bestIE?.status})`); * ``` @@ -142,7 +142,7 @@ export class LegalEntityLookupResource { * legal name, trade name, address, phone numbers, economic activities (CNAE), * legal nature, partners, registration status, and share capital. * - * @param federalTaxNumber - CNPJ number, with or without punctuation (e.g., "11222333000181", "11.222.333/0001-81" or the alphanumeric "12.ABC.345/01DE-35") + * @param federalTaxNumber - CNPJ number, with or without punctuation (e.g., "11222333999952", "11.222.333/9999-52" or the alphanumeric "12.ABC.345/01DE-35") * @param options - Optional lookup configuration * @returns Promise with company basic information * @throws {ValidationError} If the CNPJ is out of format (12 letters or digits + 2 check digits) or has invalid check digits @@ -152,14 +152,14 @@ export class LegalEntityLookupResource { * @example * ```typescript * // Simple lookup - * const result = await nfe.legalEntityLookup.getBasicInfo('11222333000181'); + * const result = await nfe.legalEntityLookup.getBasicInfo('11222333999952'); * console.log(result.legalEntity?.name); * * // With formatted CNPJ - * const result = await nfe.legalEntityLookup.getBasicInfo('11.222.333/0001-81'); + * const result = await nfe.legalEntityLookup.getBasicInfo('11.222.333/9999-52'); * * // Disable address update from postal service - * const result = await nfe.legalEntityLookup.getBasicInfo('11222333000181', { + * const result = await nfe.legalEntityLookup.getBasicInfo('11222333999952', { * updateAddress: false, * updateCityCode: true * }); @@ -203,7 +203,7 @@ export class LegalEntityLookupResource { * * @example * ```typescript - * const result = await nfe.legalEntityLookup.getStateTaxInfo('SP', '11222333000181'); + * const result = await nfe.legalEntityLookup.getStateTaxInfo('SP', '11222333999952'); * console.log(result.legalEntity?.taxRegime); // 'SimplesNacional' * * for (const tax of result.legalEntity?.stateTaxes ?? []) { @@ -242,7 +242,7 @@ export class LegalEntityLookupResource { * * @example * ```typescript - * const result = await nfe.legalEntityLookup.getStateTaxForInvoice('MG', '11222333000181'); + * const result = await nfe.legalEntityLookup.getStateTaxForInvoice('MG', '11222333999952'); * for (const tax of result.legalEntity?.stateTaxes ?? []) { * if (tax.status === 'Abled') { * console.log(`Can issue invoices with IE: ${tax.taxNumber}`); @@ -283,7 +283,7 @@ export class LegalEntityLookupResource { * * @example * ```typescript - * const result = await nfe.legalEntityLookup.getSuggestedStateTaxForInvoice('SP', '11222333000181'); + * const result = await nfe.legalEntityLookup.getSuggestedStateTaxForInvoice('SP', '11222333999952'); * const bestIE = result.legalEntity?.stateTaxes?.[0]; * if (bestIE) { * console.log(`Recommended IE: ${bestIE.taxNumber} (${bestIE.status})`); diff --git a/src/core/resources/legal-people.ts b/src/core/resources/legal-people.ts index 9f51706..d44b18d 100644 --- a/src/core/resources/legal-people.ts +++ b/src/core/resources/legal-people.ts @@ -200,7 +200,7 @@ export class LegalPeopleResource { * ```typescript * const person = await nfe.legalPeople.findByTaxNumber( * 'company-id', - * '11222333000181' + * '11222333999952' * ); * if (person) { * console.log('Found:', person.name); diff --git a/src/core/resources/product-invoices.ts b/src/core/resources/product-invoices.ts index e56a3d2..ecc0ee1 100644 --- a/src/core/resources/product-invoices.ts +++ b/src/core/resources/product-invoices.ts @@ -80,7 +80,7 @@ function buildQueryString(params: Record): st * const result = await nfe.productInvoices.create('company-id', { * operationNature: 'Venda de mercadoria', * operationType: 'Outgoing', - * buyer: { name: 'Empresa LTDA', federalTaxNumber: 11222333000181 }, + * buyer: { name: 'Empresa LTDA', federalTaxNumber: 11222333999952 }, * items: [{ code: 'PROD-001', description: 'Produto X', quantity: 1, unitAmount: 100 }], * payment: [{ paymentDetail: [{ method: 'Cash', amount: 100 }] }], * }); diff --git a/src/core/utils/tax-id.ts b/src/core/utils/tax-id.ts index 6dc55ad..ae77b0f 100644 --- a/src/core/utils/tax-id.ts +++ b/src/core/utils/tax-id.ts @@ -138,7 +138,7 @@ export function requireCnpj(value: string | number | null | undefined): string { if (!CNPJ_PATTERN.test(cnpj)) { throw new ValidationError( `Invalid federal tax number format: "${value}". Expected 14 characters after removing punctuation: ` + - '12 letters or digits followed by 2 check digits (e.g., "11222333000181", "11.222.333/0001-81" ' + + '12 letters or digits followed by 2 check digits (e.g., "11222333999952", "11.222.333/9999-52" ' + 'or the alphanumeric "12.ABC.345/01DE-35").' ); } diff --git a/test-company.json b/test-company.json index 51a5bd1..81cfbae 100644 --- a/test-company.json +++ b/test-company.json @@ -1,5 +1,5 @@ { - "federalTaxNumber": 11222333000181, + "federalTaxNumber": 11222333999952, "name": "Test Company via curl", "email": "test@example.com", "taxRegime": 1, diff --git a/tests/integration/setup.ts b/tests/integration/setup.ts index 8462bc9..ef5745a 100644 --- a/tests/integration/setup.ts +++ b/tests/integration/setup.ts @@ -95,7 +95,9 @@ export const ALLOW_ACCOUNT_WRITES = process.env.NFE_ALLOW_ACCOUNT_WRITES === 'tr // Test data helpers for integration tests export const TEST_COMPANY_DATA = { - federalTaxNumber: 11222333000181, // Valid CNPJ with proper check digits + // CNPJ sintético: DV válido e inexistente na Receita (consulta de CNPJ → 404 em 2026-11-18). + // Não usar CNPJ real aqui: estes dados criam empresas na conta. + federalTaxNumber: 11222333999952, name: 'Empresa Teste SDK v3', email: 'teste-sdk@example.com', taxRegime: 1 as const, // Simples Nacional diff --git a/tests/unit/companies.test.ts b/tests/unit/companies.test.ts index 4d7b9ca..8b5f072 100644 --- a/tests/unit/companies.test.ts +++ b/tests/unit/companies.test.ts @@ -382,7 +382,7 @@ describe('CompaniesResource', () => { vi.mocked(mockHttpClient.get).mockResolvedValue({ data: { companies: [ - createMockCompany({ id: 'company-1', federalTaxNumber: 11222333000181 }), + createMockCompany({ id: 'company-1', federalTaxNumber: 11222333999952 }), createMockCompany({ id: 'company-2', federalTaxNumber: LEADING_ZERO_CNPJ }), createMockCompany({ id: 'company-3', federalTaxNumber: '00000000000191' as unknown as number }), ], diff --git a/tests/unit/legal-entity-lookup.test.ts b/tests/unit/legal-entity-lookup.test.ts index eece4e5..42cbdfa 100644 --- a/tests/unit/legal-entity-lookup.test.ts +++ b/tests/unit/legal-entity-lookup.test.ts @@ -13,8 +13,8 @@ import type { // Test Data // ============================================================================ -const VALID_CNPJ_DIGITS = '11222333000181'; -const VALID_CNPJ_FORMATTED = '11.222.333/0001-81'; +const VALID_CNPJ_DIGITS = '11222333999952'; +const VALID_CNPJ_FORMATTED = '11.222.333/9999-52'; const createMockBasicInfoResponse = ( overrides: Partial = {} @@ -185,7 +185,7 @@ describe('LegalEntityLookupResource', () => { }); it('rejects text outside the CNPJ mask', async () => { - await expect(resource.getBasicInfo('CNPJ 11.222.333/0001-81')).rejects.toThrow( + await expect(resource.getBasicInfo('CNPJ 11.222.333/9999-52')).rejects.toThrow( '12 letters or digits followed by 2 check digits' ); expect(mockHttpClient.get).not.toHaveBeenCalled(); @@ -430,10 +430,10 @@ describe('LegalEntityLookupResource', () => { }; vi.mocked(mockHttpClient.get).mockResolvedValue(mockResponse); - await resource.getBasicInfo('11.222.333/0001-81'); + await resource.getBasicInfo('11.222.333/9999-52'); expect(mockHttpClient.get).toHaveBeenCalledWith( - '/v2/legalentities/basicInfo/11222333000181', + '/v2/legalentities/basicInfo/11222333999952', undefined ); }); @@ -487,7 +487,7 @@ describe('LegalEntityLookupResource', () => { }; vi.mocked(mockHttpClient.get).mockResolvedValue(mockResponse); - await resource.getStateTaxInfo('SP', '11.222.333/0001-81'); + await resource.getStateTaxInfo('SP', '11.222.333/9999-52'); expect(mockHttpClient.get).toHaveBeenCalledWith( `/v2/legalentities/stateTaxInfo/SP/${VALID_CNPJ_DIGITS}` diff --git a/tests/unit/legal-people.test.ts b/tests/unit/legal-people.test.ts index 235acd2..8975a34 100644 --- a/tests/unit/legal-people.test.ts +++ b/tests/unit/legal-people.test.ts @@ -123,7 +123,7 @@ describe('LegalPeopleResource', () => { vi.mocked(mockHttpClient.get).mockResolvedValue({ data: { legalPeople: [ - createMockLegalPerson({ id: 'p1', federalTaxNumber: 11222333000181 as unknown as string }), + createMockLegalPerson({ id: 'p1', federalTaxNumber: 11222333999952 as unknown as string }), createMockLegalPerson({ id: 'p2', federalTaxNumber: 1234567999885 as unknown as string }), ], }, diff --git a/tests/unit/utils/tax-id.test.ts b/tests/unit/utils/tax-id.test.ts index 1a76a54..553a42a 100644 --- a/tests/unit/utils/tax-id.test.ts +++ b/tests/unit/utils/tax-id.test.ts @@ -59,8 +59,8 @@ describe('tax-id: CNPJ', () => { }); it('aceita o CNPJ numérico tradicional e recusa sequência repetida', () => { - expect(isValidCnpj('11222333000181')).toBe(true); - expect(isValidCnpj(11222333000181)).toBe(true); + expect(isValidCnpj('11222333999952')).toBe(true); + expect(isValidCnpj(11222333999952)).toBe(true); expect(isValidCnpj('11111111111111')).toBe(false); expect(isValidCnpj('00000000000000')).toBe(false); }); @@ -77,32 +77,32 @@ describe('tax-id: CNPJ', () => { it('normaliza máscara e minúsculas sem perder letras', () => { expect(normalizeCnpj('12.abc.345/01de-35')).toBe('12ABC34501DE35'); - expect(normalizeCnpj(' 11.222.333/0001-81 ')).toBe('11222333000181'); + expect(normalizeCnpj(' 11.222.333/9999-52 ')).toBe('11222333999952'); expect(isValidCnpj('12.abc.345/01de-35')).toBe(true); }); it('recusa formato com letra nos dígitos verificadores ou tamanho errado', () => { expect(isValidCnpj('12ABC34501DEA5')).toBe(false); expect(isValidCnpj('12ABC34501DE3')).toBe(false); - expect(isValidCnpj('CNPJ 11.222.333/0001-81')).toBe(false); + expect(isValidCnpj('CNPJ 11.222.333/9999-52')).toBe(false); }); it('recusa number que não é inteiro seguro e não negativo', () => { - expect(isValidCnpj(-11222333000181)).toBe(false); - expect(isValidCnpj(11222333000181.5)).toBe(false); + expect(isValidCnpj(-11222333999952)).toBe(false); + expect(isValidCnpj(11222333999952.5)).toBe(false); expect(isValidCnpj(Number.NaN)).toBe(false); }); it('detecta CNPJ alfanumérico pelas 12 primeiras posições', () => { expect(isAlphanumericCnpj('12.ABC.345/01DE-35')).toBe(true); expect(isAlphanumericCnpj('12abc34501de35')).toBe(true); - expect(isAlphanumericCnpj('11222333000181')).toBe(false); - expect(isAlphanumericCnpj(11222333000181)).toBe(false); + expect(isAlphanumericCnpj('11222333999952')).toBe(false); + expect(isAlphanumericCnpj(11222333999952)).toBe(false); }); it('dá o mesmo resultado que o cálculo numérico antigo para os CNPJs da suíte', () => { const numerics = [ - 11222333000181, 12345678000276, 11111111000111, 11122233344455, 11223344000155, + 11222333999952, 12345678000276, 11111111000111, 11122233344455, 11223344000155, 12345678000190, 12345678901234, 33333333000133, 98765432000110, 98765432109876, 11444555000149, 1234567999885, 191, ]; @@ -121,7 +121,7 @@ describe('tax-id: CNPJ', () => { expect(() => requireCnpj('')).toThrow('Federal tax number (CNPJ) is required'); expect(() => requireCnpj(' ')).toThrow(ValidationError); expect(() => requireCnpj(undefined)).toThrow(ValidationError); - expect(() => requireCnpj('CNPJ 11.222.333/0001-81')).toThrow( + expect(() => requireCnpj('CNPJ 11.222.333/9999-52')).toThrow( '12 letters or digits followed by 2 check digits' ); expect(() => requireCnpj('12ABC34501DE36')).toThrow('check digits do not match');