Skip to content

Commit 00aaffc

Browse files
feat: add support for CT-e API with new configuration options and resource
- Introduced `cteApiKey` in NfeConfig and RequiredNfeConfig interfaces for CT-e API key management. - Added TransportationInvoicesResource for handling CT-e operations, including enabling/disabling automatic searches, retrieving settings, and managing events. - Implemented comprehensive unit tests for TransportationInvoicesResource covering all functionalities and edge cases. - Updated NfeClient to support multi-API key configuration, including fallback mechanisms for CT-e API key. - Regenerated OpenAPI types and updated generated files with new timestamps.
1 parent 8d4fcfd commit 00aaffc

19 files changed

+1736
-9
lines changed

README.md

Lines changed: 72 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -362,6 +362,72 @@ const filtrado = await nfe.addresses.search({
362362

363363
> **Nota:** A API de Endereços usa um host separado (`address.api.nfe.io`). Você pode configurar uma chave API específica com `addressApiKey`, ou o SDK usará `apiKey` como fallback.
364364
365+
#### 🚚 Notas de Transporte - CT-e (`nfe.transportationInvoices`)
366+
367+
Consultar CT-e (Conhecimento de Transporte Eletrônico) via Distribuição DFe:
368+
369+
```typescript
370+
// Ativar busca automática de CT-e para uma empresa
371+
const settings = await nfe.transportationInvoices.enable('empresa-id');
372+
console.log('Status:', settings.status);
373+
console.log('Iniciando do NSU:', settings.startFromNsu);
374+
375+
// Ativar a partir de um NSU específico
376+
const settings = await nfe.transportationInvoices.enable('empresa-id', {
377+
startFromNsu: 12345
378+
});
379+
380+
// Ativar a partir de uma data específica
381+
const settings = await nfe.transportationInvoices.enable('empresa-id', {
382+
startFromDate: '2024-01-01T00:00:00Z'
383+
});
384+
385+
// Verificar configurações atuais
386+
const config = await nfe.transportationInvoices.getSettings('empresa-id');
387+
console.log('Busca ativa:', config.status);
388+
389+
// Desativar busca automática
390+
await nfe.transportationInvoices.disable('empresa-id');
391+
392+
// Consultar CT-e por chave de acesso (44 dígitos)
393+
const cte = await nfe.transportationInvoices.retrieve(
394+
'empresa-id',
395+
'35240112345678000190570010000001231234567890'
396+
);
397+
console.log('Remetente:', cte.nameSender);
398+
console.log('Valor:', cte.totalInvoiceAmount);
399+
console.log('Emissão:', cte.issuedOn);
400+
401+
// Baixar XML do CT-e
402+
const xml = await nfe.transportationInvoices.downloadXml(
403+
'empresa-id',
404+
'35240112345678000190570010000001231234567890'
405+
);
406+
fs.writeFileSync('cte.xml', xml);
407+
408+
// Consultar evento do CT-e
409+
const evento = await nfe.transportationInvoices.getEvent(
410+
'empresa-id',
411+
'35240112345678000190570010000001231234567890',
412+
'chave-evento'
413+
);
414+
415+
// Baixar XML do evento
416+
const eventoXml = await nfe.transportationInvoices.downloadEventXml(
417+
'empresa-id',
418+
'35240112345678000190570010000001231234567890',
419+
'chave-evento'
420+
);
421+
```
422+
423+
> **Nota:** A API de CT-e usa um host separado (`api.nfse.io`). Você pode configurar uma chave API específica com `cteApiKey`, ou o SDK usará `apiKey` como fallback.
424+
425+
**Pré-requisitos:**
426+
- Empresa deve estar cadastrada com certificado digital A1 válido
427+
- Webhook deve estar configurado para receber notificações de CT-e
428+
429+
---
430+
365431
### Opções de Configuração
366432

367433
```typescript
@@ -373,6 +439,10 @@ const nfe = new NfeClient({
373439
// Se não fornecida, usa apiKey como fallback
374440
addressApiKey: 'sua-chave-address-api',
375441

442+
// Opcional: Chave API específica para consulta de CT-e
443+
// Se não fornecida, usa apiKey como fallback
444+
cteApiKey: 'sua-chave-cte-api',
445+
376446
// Opcional: Ambiente (padrão: 'production')
377447
environment: 'production', // ou 'sandbox'
378448

@@ -400,11 +470,13 @@ O SDK suporta as seguintes variáveis de ambiente:
400470
|----------|-----------|
401471
| `NFE_API_KEY` | Chave API principal (fallback para `apiKey`) |
402472
| `NFE_ADDRESS_API_KEY` | Chave API para endereços (fallback para `addressApiKey`) |
473+
| `NFE_CTE_API_KEY` | Chave API para CT-e (fallback para `cteApiKey`) |
403474

404475
```bash
405476
# Configurar via ambiente
406477
export NFE_API_KEY="sua-chave-api"
407478
export NFE_ADDRESS_API_KEY="sua-chave-address"
479+
export NFE_CTE_API_KEY="sua-chave-cte"
408480

409481
# Usar SDK sem passar chaves no código
410482
const nfe = new NfeClient({});

docs/API.md

Lines changed: 142 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -15,6 +15,7 @@ Complete API reference for the NFE.io Node.js SDK v3.
1515
- [Legal People](#legal-people)
1616
- [Natural People](#natural-people)
1717
- [Webhooks](#webhooks)
18+
- [Transportation Invoices (CT-e)](#transportation-invoices-ct-e)
1819
- [Types](#types)
1920
- [Error Handling](#error-handling)
2021
- [Advanced Usage](#advanced-usage)
@@ -1504,13 +1505,154 @@ const events = await nfe.webhooks.getAvailableEvents();
15041505
// ['invoice.issued', 'invoice.cancelled', ...]
15051506
```
15061507

1508+
---
1509+
1510+
### Transportation Invoices (CT-e)
1511+
1512+
**Resource:** `nfe.transportationInvoices`
1513+
1514+
Manage CT-e (Conhecimento de Transporte Eletrônico) documents via SEFAZ Distribuição DFe.
1515+
1516+
> **Note:** This resource uses a separate API host (`api.nfse.io`). You can configure a specific API key with `cteApiKey`, or the SDK will use `apiKey` as fallback.
1517+
1518+
**Prerequisites:**
1519+
- Company must be registered with a valid A1 digital certificate
1520+
- Webhook must be configured to receive CT-e notifications
1521+
1522+
#### `enable(companyId: string, options?: EnableTransportationInvoiceOptions): Promise<TransportationInvoiceInboundSettings>`
1523+
1524+
Enable automatic CT-e search for a company.
1525+
1526+
```typescript
1527+
// Enable with default settings
1528+
const settings = await nfe.transportationInvoices.enable('company-id');
1529+
1530+
// Enable starting from a specific NSU
1531+
const settings = await nfe.transportationInvoices.enable('company-id', {
1532+
startFromNsu: 12345
1533+
});
1534+
1535+
// Enable starting from a specific date
1536+
const settings = await nfe.transportationInvoices.enable('company-id', {
1537+
startFromDate: '2024-01-01T00:00:00Z'
1538+
});
1539+
```
1540+
1541+
**Options:**
1542+
1543+
| Property | Type | Description |
1544+
|----------|------|-------------|
1545+
| `startFromNsu` | `number` | Start searching from this NSU number |
1546+
| `startFromDate` | `string` | Start searching from this date (ISO 8601) |
1547+
1548+
#### `disable(companyId: string): Promise<TransportationInvoiceInboundSettings>`
1549+
1550+
Disable automatic CT-e search for a company.
1551+
1552+
```typescript
1553+
const settings = await nfe.transportationInvoices.disable('company-id');
1554+
console.log('Status:', settings.status); // 'Disabled'
1555+
```
1556+
1557+
#### `getSettings(companyId: string): Promise<TransportationInvoiceInboundSettings>`
1558+
1559+
Get current automatic CT-e search settings.
1560+
1561+
```typescript
1562+
const settings = await nfe.transportationInvoices.getSettings('company-id');
1563+
console.log('Status:', settings.status);
1564+
console.log('Start NSU:', settings.startFromNsu);
1565+
console.log('Created:', settings.createdOn);
1566+
```
1567+
1568+
**Response:**
1569+
1570+
| Property | Type | Description |
1571+
|----------|------|-------------|
1572+
| `status` | `string` | Current status ('Active', 'Disabled', etc.) |
1573+
| `startFromNsu` | `number` | Starting NSU number |
1574+
| `startFromDate` | `string` | Starting date (if configured) |
1575+
| `createdOn` | `string` | Creation timestamp |
1576+
| `modifiedOn` | `string` | Last modification timestamp |
1577+
1578+
#### `retrieve(companyId: string, accessKey: string): Promise<TransportationInvoiceMetadata>`
1579+
1580+
Retrieve CT-e metadata by its 44-digit access key.
1581+
1582+
```typescript
1583+
const cte = await nfe.transportationInvoices.retrieve(
1584+
'company-id',
1585+
'35240112345678000190570010000001231234567890'
1586+
);
1587+
console.log('Sender:', cte.nameSender);
1588+
console.log('CNPJ:', cte.federalTaxNumberSender);
1589+
console.log('Amount:', cte.totalInvoiceAmount);
1590+
console.log('Issued:', cte.issuedOn);
1591+
```
1592+
1593+
**Response:**
1594+
1595+
| Property | Type | Description |
1596+
|----------|------|-------------|
1597+
| `accessKey` | `string` | 44-digit access key |
1598+
| `type` | `string` | Document type |
1599+
| `status` | `string` | Document status |
1600+
| `nameSender` | `string` | Sender company name |
1601+
| `federalTaxNumberSender` | `string` | Sender CNPJ |
1602+
| `totalInvoiceAmount` | `number` | Total invoice amount |
1603+
| `issuedOn` | `string` | Issue date |
1604+
| `receivedOn` | `string` | Receipt date |
1605+
1606+
#### `downloadXml(companyId: string, accessKey: string): Promise<string>`
1607+
1608+
Download CT-e XML content.
1609+
1610+
```typescript
1611+
const xml = await nfe.transportationInvoices.downloadXml(
1612+
'company-id',
1613+
'35240112345678000190570010000001231234567890'
1614+
);
1615+
fs.writeFileSync('cte.xml', xml);
1616+
```
1617+
1618+
#### `getEvent(companyId: string, accessKey: string, eventKey: string): Promise<TransportationInvoiceMetadata>`
1619+
1620+
Retrieve CT-e event metadata.
1621+
1622+
```typescript
1623+
const event = await nfe.transportationInvoices.getEvent(
1624+
'company-id',
1625+
'35240112345678000190570010000001231234567890',
1626+
'event-key-123'
1627+
);
1628+
console.log('Event type:', event.type);
1629+
console.log('Event status:', event.status);
1630+
```
1631+
1632+
#### `downloadEventXml(companyId: string, accessKey: string, eventKey: string): Promise<string>`
1633+
1634+
Download CT-e event XML content.
1635+
1636+
```typescript
1637+
const eventXml = await nfe.transportationInvoices.downloadEventXml(
1638+
'company-id',
1639+
'35240112345678000190570010000001231234567890',
1640+
'event-key-123'
1641+
);
1642+
fs.writeFileSync('cte-event.xml', eventXml);
1643+
```
1644+
1645+
---
1646+
15071647
## Types
15081648

15091649
### Core Types
15101650

15111651
```typescript
15121652
interface NfeConfig {
15131653
apiKey?: string;
1654+
addressApiKey?: string; // Specific API key for address lookups
1655+
cteApiKey?: string; // Specific API key for CT-e (transportation invoices)
15141656
environment?: 'production' | 'development';
15151657
baseUrl?: string;
15161658
timeout?: number;

examples/setup.js

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -112,6 +112,11 @@ ${companyId ? `NFE_COMPANY_ID=${companyId}` : '# NFE_COMPANY_ID=seu-company-id-a
112112
113113
# Timeout em ms (opcional)
114114
# NFE_TIMEOUT=30000
115+
116+
# Chaves de API específicas (opcional)
117+
# Se não definidas, usa NFE_API_KEY como fallback
118+
# NFE_ADDRESS_API_KEY=sua-chave-address-aqui
119+
# NFE_CTE_API_KEY=sua-chave-cte-aqui
115120
`;
116121

117122
try {

0 commit comments

Comments
 (0)