npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2026 – Pkg Stats / Ryan Hefner

@jhrnandez/modulo-facturacion-afip

v1.1.0

Published

Módulo de facturación electrónica para Argentina (AFIP) - Router Express listo para integrar

Downloads

833

Readme

@jhrnandez/modulo-facturacion-afip

Módulo de facturación electrónica para Argentina (AFIP). Exporta un Router de Express listo para montar en cualquier API existente.

Utiliza afipsdk.com como proveedor de la integración con los web services de AFIP.

Instalación

npm install @jhrnandez/modulo-facturacion-afip

Requisito: Tu proyecto debe tener express instalado (v4.18+ o v5).

Configuración

El módulo se configura al crear el router. Solo apiKey es obligatorio:

| Parámetro | Descripción | |-----------|-------------| | apiKey | API key de afipsdk.com (obligatorio) | | taxId | CUIT emisor por defecto (opcional, se puede enviar en cada request) | | environment | 'testing' o 'production' (default: 'testing') | | issuer | Datos del emisor para PDFs (recomendado, se usa como fallback) |

Importante: El campo issuer.grossIncome (Ingresos Brutos) es obligatorio para la generación de PDFs. Si no se configura aquí, debe enviarse en cada request de PDF.

Uso rápido

import express from 'express';
import { createAfipBillingModule } from '@jhrnandez/modulo-facturacion-afip';

const app = express();
app.use(express.json());

// Montar el módulo de facturación
const afipRouter = createAfipBillingModule({
  apiKey: process.env.AFIP_API_KEY!,
  environment: (process.env.AFIP_ENVIRONMENT as 'testing' | 'production') || 'testing',
  // Opcional: CUIT emisor por defecto
  taxId: process.env.AFIP_TAX_ID,
  // Opcional: datos del emisor para PDFs (evita enviarlos en cada request)
  issuer: {
    cuit: 30123456789,
    businessName: 'MI EMPRESA S.A.',
    address: 'Av. Corrientes 1234, CABA',
    ivaCondition: 'Responsable Inscripto',
    grossIncome: 'CM 901-123456-7',       // Obligatorio para PDFs
    activityStartDate: '01/01/2020',       // Obligatorio para PDFs
  },
});

app.use('/api/afip', afipRouter);

app.listen(3000, () => {
  console.log('Servidor corriendo en http://localhost:3000');
});

Endpoints disponibles

| Método | Ruta | Descripción | |--------|------|-------------| | GET | /status | Estado de los servidores de AFIP | | GET | /taxpayer/:cuit | Consultar datos de un contribuyente | | POST | /invoices | Crear una factura electrónica | | GET | /invoices/:type/:point/:number | Consultar un comprobante existente | | POST | /invoices/pdf | Generar PDF de un comprobante |

Ejemplo: Crear una factura

curl -X POST http://localhost:3000/api/afip/invoices \
  -H "Content-Type: application/json" \
  -d '{
    "taxId": "20409378472",
    "receiptType": 6,
    "posNumber": 1,
    "concept": 1,
    "documentType": 99,
    "documentNumber": 0,
    "issueDate": "20260405",
    "currency": "PES",
    "exchangeRate": 1,
    "netUntaxedAmount": 0,
    "netTaxedAmount": 1000,
    "exemptAmount": 0,
    "vatAmount": 210,
    "taxAmount": 0,
    "totalAmount": 1210,
    "vat": [{ "id": 5, "baseAmount": 1000, "amount": 210 }]
  }'

Si configuraste taxId al crear el módulo, no necesitás enviarlo en cada request. Si lo enviás en el body, tiene prioridad sobre el configurado.

Respuesta:

{
  "cae": "12345678901234",
  "expirationDate": "20260415",
  "receiptNumber": 97
}

Ejemplo: Generar PDF

curl -X POST http://localhost:3000/api/afip/invoices/pdf \
  -H "Content-Type: application/json" \
  -d '{
    "receiptType": 6,
    "voucherNumber": 97,
    "salesPoint": 1,
    "issueDate": "27/02/2026",
    "caeDueDate": "12/03/2026",
    "cae": 12345678901234,
    "receiverName": "CONSUMIDOR FINAL",
    "receiverAddress": "-",
    "receiverDocumentType": 99,
    "receiverDocumentNumber": 0,
    "receiverIvaCondition": "Consumidor Final",
    "saleCondition": "Contado",
    "currencyId": "ARS",
    "currencyRate": 1,
    "concept": 1,
    "items": [
      { "code": "001", "description": "Servicio de consultoría", "quantity": 1, "unitPrice": 1210, "subtotal": 1210 }
    ],
    "vatAmount": 210,
    "tributesAmount": 0,
    "totalAmount": 1210
  }'

Si configuraste issuer al crear el módulo, no necesitás enviarlo en cada request. Si lo enviás, tiene prioridad sobre el configurado.

Respuesta:

{
  "id": "019ca6aa-7f1b-70d2-a9c3-1f5e8b62d4c1",
  "file": "https://afip-sdk-pdf-storage.s3.amazonaws.com/019ca6aa.pdf",
  "fileExpiration": "2026-03-01T20:00:00.000Z",
  "fileName": "invoice_b_0001_00000097.pdf",
  "createdAt": "2026-02-28T20:00:00.000Z"
}

Templates de PDF disponibles

| receiptType | Template | Descripción | |:---:|---|---| | 1 | invoice-a | Factura A | | 6 | invoice-b | Factura B | | 11 | invoice-c | Factura C | | 2 | debit-note-a | Nota de Débito A | | 7 | debit-note-b | Nota de Débito B | | 12 | debit-note-c | Nota de Débito C | | 3 | credit-note-a | Nota de Crédito A | | 8 | credit-note-b | Nota de Crédito B | | 13 | credit-note-c | Nota de Crédito C |

Ejemplo: Consultar contribuyente

curl http://localhost:3000/api/afip/taxpayer/20123456789

Tipos exportados

El módulo exporta todas las interfaces de dominio para que puedas tipar tu código:

import type {
  Invoice,
  Taxpayer,
  AfipStatus,
  CreateInvoiceResult,
  CreatePdfParams,
  PdfResult,
  PdfIssuer,
  PdfItem,
  AfipSdkConfig,
} from '@jhrnandez/modulo-facturacion-afip';

Novedades v1.1.0

  • grossIncome y activityStartDate obligatorios para PDFs: El servicio de PDFs de afipsdk.com requiere estos campos. Si no se configuran en issuer, la generación de PDFs fallará con error 400.
  • Ajuste automático de fecha: Al crear un comprobante, el módulo consulta la fecha del último comprobante autorizado. Si la fecha solicitada es anterior, se ajusta automáticamente para evitar el error AFIP [10016].
  • Corrección de campos AFIP: CondicionIVAReceptorId (antes CondicionIVAReceptor), IVA se envuelve en { AlicIva: [...] } y Tributos en { Tributo: [...] } según requiere el WS.
  • Consulta de comprobantes mejorada: FECompConsultar ahora maneja correctamente las distintas estructuras de respuesta de IVA y Tributos.

Arquitectura

El módulo está construido con Arquitectura Hexagonal y DDD:

src/
├── domain/          → Entidades, Value Objects e Interfaces (puertos)
├── application/     → Casos de Uso y Schemas de validación (Zod)
└── infrastructure/  → Adaptador HTTP (afipsdk), Controladores y Router

API de AfipSDK

Este módulo utiliza la API REST de AfipSDK:

  1. Autenticación (POST /api/v1/afip/auth) → obtiene Token de Acceso (TA)
  2. Ejecución (POST /api/v1/afip/requests) → ejecuta métodos en los web services de AFIP
  3. PDFs (POST /api/v1/pdfs) → genera PDFs de comprobantes (usa API key directamente)

Los tokens se cachean automáticamente hasta su expiración (~12 horas).

Web services utilizados

| Web Service | ID | Uso | |---|---|---| | Factura Electrónica | wsfe | Crear facturas, consultar comprobantes, verificar estado | | Padrón A13 | ws_sr_padron_a13 | Consultar datos de contribuyentes |

Licencia

ISC