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

verifactu-utils

v1.1.0

Published

Complete TypeScript implementation for Spanish VeriFactu tax compliance system

Downloads

19

Readme

VeriFactu TypeScript

Complete TypeScript implementation for Spanish VeriFactu tax compliance system with AEAT integration.

Features

  • Complete VeriFactu Implementation - Full support for Spanish tax invoice registration
  • AEAT Integration - Direct communication with Spanish tax authority systems
  • Blockchain Management - Invoice chaining and integrity validation
  • XAdES-EPES Digital Signatures - Secure XML signing with certificates
  • Enhanced Tax Calculations - Proper rounding and multi-rate support
  • Rectifying Invoices - Complete support for corrective invoices
  • Batch Processing - High-performance concurrent invoice submission
  • International Support - EU VAT/VIES validation
  • QR Code Generation - Compliant QR codes for invoice verification
  • Comprehensive Error Handling - Structured error codes and recovery
  • Metrics & Monitoring - Built-in performance tracking
  • Production Ready - Enterprise-grade architecture

Quick Start

Installation

npm install
npm run build

Basic Usage

import { VeriFactu } from "./src";

// Initialize the system
const veriFactu = new VeriFactu({
  environment: "test",
  certificatePath: "path/to/certificate.pfx",
  certificatePassword: "password",
  signRecords: true,
});

// Create and register an invoice
const invoice = veriFactu.createInvoice({
  number: "INV-001",
  date: new Date(),
  sellerId: "B12345678",
  sellerName: "My Company SL",
  buyerId: "B87654321",
  buyerName: "Client Company SL",
  items: [
    {
      taxScheme: "RegimenGeneral",
      taxType: "S1",
      taxRate: 21,
      taxBase: 100,
      taxAmount: 21,
    },
  ],
});

const result = await veriFactu.registerInvoice(invoice);
console.log("Registration result:", result);

Configuration

Create a configuration file or use environment variables:

const config = {
  environment: "test", // or 'prod'
  certificatePath: "./certificates/company.pfx",
  certificatePassword: "your_certificate_password",
  signRecords: true,
  systemInfo: {
    nombreSistemaInformatico: "MyERP",
    idSistemaInformatico: "MYERP-001",
    version: "1.0.0",
    numeroInstalacion: "001",
    usoSoloVerifactu: "S",
    usoMultiOTI: "N",
    multiplesOT: "N",
  },
  loggingEnabled: true,
};

Project Structure

src/
├── index.ts                 # Main exports and CLI
├── core/                   # Core business logic
│   ├── Invoice.ts          # Invoice model and validation
│   ├── InvoiceEntry.ts     # Invoice registration logic
│   ├── InvoiceCancellation.ts # Invoice cancellation
│   └── TaxCalculator.ts    # Tax calculation utilities
├── models/                 # Data models and interfaces
│   ├── types.ts           # TypeScript interfaces
│   ├── enums.ts           # Enumerations
│   └── errors.ts          # Error handling
├── blockchain/             # Blockchain management
│   └── Blockchain.ts      # Invoice chaining logic
├── aeat/                   # AEAT integration
│   └── AEATClient.ts      # API communication
├── xml/                    # XML processing
│   ├── XmlGenerator.ts    # XML generation
│   └── XmlSigner.ts       # Digital signatures
├── validation/             # Validation logic
│   ├── NifValidator.ts    # Spanish ID validation
│   └── ConfigValidator.ts # Configuration validation
├── utils/                  # Utilities
│   ├── QRGenerator.ts     # QR code generation
│   ├── Settings.ts        # Configuration management
│   ├── Metrics.ts         # Performance monitoring
│   └── helpers.ts         # Helper functions
├── processing/             # Advanced processing
│   ├── BatchProcessor.ts  # Batch operations
│   └── InvoiceQueue.ts    # Queue management
├── examples/              # Usage examples
│   └── Examples.ts        # Complete examples
└── testing/               # Testing utilities
    └── TestDataGenerator.ts # Test data generation

Examples

Basic Invoice Registration

npm run example:basic
import {
  VeriFactu,
  TipoFactura,
  ClaveRegimen,
  CalificacionOperacion,
} from "./src";

const invoice = new Invoice("INV-001", new Date(), "B72877814");
invoice.invoiceType = TipoFactura.F1;
invoice.sellerName = "WEFINZ GANDIA SL";
invoice.buyerID = "B44531218";
invoice.buyerName = "WEFINZ SOLUTIONS SL";
invoice.taxItems = [
  {
    taxScheme: ClaveRegimen.RegimenGeneral,
    taxType: CalificacionOperacion.S1,
    taxRate: 21,
    taxBase: 100,
    taxAmount: 21,
  },
];

const entry = new InvoiceEntry(invoice);
await entry.save();

Rectifying Invoice

const rectifyingInvoice = new Invoice("RECT-001", new Date(), "B72877814");
rectifyingInvoice.invoiceType = TipoFactura.R1;
rectifyingInvoice.rectifyingDetails = {
  tipoRectificativa: TipoRectificativa.S,
  facturasRectificadas: [
    {
      idEmisorFacturaRectificada: "B72877814",
      numSerieFacturaRectificada: "ORIG-001",
      fechaExpedicionFacturaRectificada: "15-11-2024",
    },
  ],
};

Batch Processing

npm run example:batch
import { EnhancedBatchProcessor, TestDataGenerator } from "./src";

const invoices = TestDataGenerator.generateTestBatch(50, "B72877814");
const stats = await EnhancedBatchProcessor.processBatch(invoices, {
  maxConcurrent: 10,
  validateBeforeSubmit: true,
});

console.log(`Processed ${stats.totalInvoices} invoices`);
console.log(
  `Success rate: ${((stats.successfulInvoices / stats.totalInvoices) * 100).toFixed(2)}%`
);

QR Code Generation

import { buildQrUrl, renderQrPng } from "./src";

const qrUrl = buildQrUrl({
  nif: "B72877814",
  numserie: "INV-001",
  fecha: "15-11-2024",
  importe: 121.0,
  env: "test",
});

await renderQrPng(qrUrl, "./invoice-qr.png");

API Reference

Core Classes

Invoice

Main invoice model with validation and tax calculations.

const invoice = new Invoice(number: string, date: Date, sellerId: string);
invoice.addTaxItem(taxItem: TaxItem);
const validation = await invoice.validate();

InvoiceEntry

Handles invoice registration with AEAT.

const entry = new InvoiceEntry(invoice);
await entry.save();
console.log(entry.status, entry.csv);

Blockchain

Manages invoice chaining and integrity.

const blockchain = Blockchain.Get(sellerId);
await blockchain.Add(registro);
const integrity = await blockchain.validateIntegrity();

AEATClient

Communicates with Spanish tax authority.

const client = new AEATClient();
const response = await client.sendRegistroAlta(xmlString);

Configuration

Settings

Global configuration management.

Settings.Current.environment = "test";
Settings.Current.certificatePath = "path/to/cert.pfx";
await Settings.Save();

Utilities

NifValidator

Spanish tax ID validation.

const isValid = NifValidator.validateNif("12345678Z");
const isValidCif = NifValidator.validateCif("B12345678");

TaxCalculator

Enhanced tax calculations.

const taxAmount = TaxCalculator.calculateTaxAmount(base, rate);
const validation = TaxCalculator.validateTaxRates(taxItems);

Testing

Run the comprehensive self-test:

npm run selftest

Run specific examples:

npm run example:basic
npm run example:batch
npm run example:complete

Configuration Options

| Option | Type | Description | Default | | ----------------------- | --------------------------- | --------------------------- | -------- | | environment | 'test' \| 'prod' | AEAT environment | 'test' | | certificatePath | string | Path to PKCS#12 certificate | - | | certificatePassword | string | Certificate password | - | | signRecords | boolean | Enable XML signing | false | | loggingEnabled | boolean | Enable console logging | false | | skipNifAEATValidation | boolean | Skip NIF validation | false | | impuesto | 'IVA' \| 'IGIC' \| 'IPSI' | Tax type | 'IVA' |

Error Handling

The system provides structured error handling:

try {
  await invoiceEntry.save();
} catch (error) {
  if (error instanceof VeriFactuError) {
    console.log(`Error [${error.code}]: ${error.message}`);
    // Handle specific error types
    switch (error.code) {
      case VeriFactuErrorCode.VALIDATION_ERROR:
        // Handle validation errors
        break;
      case VeriFactuErrorCode.NETWORK_ERROR:
        // Handle network errors
        break;
    }
  }
}

Production Deployment

  1. Certificate Setup: Obtain valid certificates from AEAT
  2. Environment Configuration: Set environment: 'prod'
  3. Logging: Enable comprehensive logging
  4. Monitoring: Use built-in metrics system
  5. Error Handling: Implement proper error recovery
  6. Backup: Ensure blockchain data is backed up

Environment Variables

VERIFACTU_ENVIRONMENT=prod
VERIFACTU_CERT_PATH=/path/to/production.pfx
VERIFACTU_CERT_PASSWORD=production_password
VERIFACTU_LOGGING=true

License

MIT License - see LICENSE file for details.

Support

For issues and questions:

  1. Check the examples in /src/examples/
  2. Run self-tests to verify setup
  3. Review AEAT documentation
  4. Open GitHub issues for bugs

Contributing

  1. Fork the repository
  2. Create feature branch
  3. Add tests for new functionality
  4. Ensure all tests pass
  5. Submit pull request

Changelog

v1.0.0

  • Initial release
  • Complete VeriFactu implementation
  • AEAT integration
  • Blockchain management
  • Digital signatures
  • Batch processing
  • International support