Skip to main content

Overview

The Invoice class is the core component for creating UBL 2.1 compliant invoice documents. This guide covers the complete workflow from initialization to XML generation.

Basic Invoice Creation

1

Initialize the Invoice

Create a new invoice with an ID and configuration options:
import { Invoice } from 'ubl-builder';

const invoice = new Invoice('SETP990000001', {
  timestamp: Date.now(),
  enviroment: '2', // '1' for production, '2' for testing
  issuer: {
    resolutionNumber: '18764003560527',
    technicalKey: 'fc8eac4...',
    prefix: 'SETP',
    startRange: '990000000',
    endRange: '995000000',
    startDate: '2019-01-19',
    endDate: '2030-01-19'
  },
  software: {
    id: '0d2e2883-...',
    pin: '12345',
    providerNit: '900123456'
  }
});
The invoice ID should include the prefix (e.g., ‘SETP990000001’). The enviroment field controls whether the invoice is for production (‘1’) or testing (‘2’).
2

Set Basic Properties

Configure essential invoice properties:
// Set default XML namespaces
invoice.setDefaultProperties();

// Set UBL version and profile
invoice.setUBLVersionID('UBL 2.1');
invoice.setProfileID('DIAN 2.1');
invoice.setProfileExecutionID('2'); // Testing environment

// Set invoice dates
invoice.setIssueDate('2024-03-06');
invoice.setIssueTime('10:30:45-05:00');
invoice.setDueDate('2024-04-06');

// Set invoice type and currency
invoice.setInvoiceTypeCode('01'); // Standard invoice
invoice.setDocumentCurrencyCode('COP');
Invoice type codes: ‘01’ for standard invoices, ‘02’ for export invoices, ‘03’ for contingency invoices.
3

Add Notes and References

Include additional information:
// Add notes
invoice.addNote('Payment terms: Net 30 days');
invoice.addNote('Goods must be delivered by April 1st');

// Set buyer reference
invoice.setBuyerReference('PO-2024-001');

// Set order reference
invoice.setOrderReference({
  id: 'ORDER-123',
  issueDate: '2024-03-01'
});

// Add invoice period
invoice.addInvoicePeriod({
  startDate: '2024-03-01',
  endDate: '2024-03-31'
});
4

Add Parties

Set up supplier and customer information:
import { 
  AccountingSupplierParty, 
  AccountingCustomerParty,
  Party 
} from 'ubl-builder';

// Create supplier
const supplier = new AccountingSupplierParty({
  party: new Party({
    partyTaxSchemes: [/* ... */],
    partyLegalEntities: [/* ... */],
    postalAddress: /* ... */
  })
});

invoice.setAccountingSupplierParty(supplier);

// Create customer
const customer = new AccountingCustomerParty({
  party: new Party({
    partyTaxSchemes: [/* ... */],
    partyLegalEntities: [/* ... */],
    postalAddress: /* ... */
  })
});

invoice.setAccountingCustomerParty(customer);
See the Working with Parties guide for detailed examples.
5

Add Invoice Lines

Add line items to the invoice:
import { InvoiceLine, Item, Price } from 'ubl-builder';

invoice.addInvoiceLine({
  id: '1',
  invoicedQuantity: '10',
  lineExtensionAmount: '1000.00',
  item: new Item({
    description: 'Professional Services',
    sellersItemIdentification: { id: 'SRV-001' }
  }),
  price: new Price({
    priceAmount: '100.00',
    baseQuantity: '1'
  })
});
6

Add Tax Totals

Calculate and add tax information:
import { TaxTotal, TaxSubtotal, TaxCategory, TaxScheme } from 'ubl-builder';

invoice.addTaxTotal({
  taxAmount: '190.00',
  taxSubtotals: [
    new TaxSubtotal({
      taxableAmount: '1000.00',
      taxAmount: '190.00',
      percent: '19',
      taxCategory: new TaxCategory({
        id: '01',
        percent: '19',
        taxScheme: new TaxScheme({ id: '01', name: 'IVA' })
      })
    })
  ]
});
See the Tax Calculations guide for detailed examples.
7

Set Monetary Totals

Define the invoice totals:
import { LegalMonetaryTotal } from 'ubl-builder';

invoice.setLegalMonetaryTotal({
  lineExtensionAmount: '1000.00',
  taxExclusiveAmount: '1000.00',
  taxInclusiveAmount: '1190.00',
  payableAmount: '1190.00'
});
8

Finalize and Generate XML

Complete the invoice and generate XML:
// Calculate DIAN extensions (for Colombian invoices)
invoice.calculateDianExtension();

// Finalize: sets line count, IDs, CUFE, and QR code
invoice.finalizeDocument();

// Generate XML
const xml = invoice.getXml(true, false);
console.log(xml);
Always call finalizeDocument() before generating XML. This method calculates the CUFE (unique invoice code) and QR code required for Colombian e-invoicing.

Advanced Configuration

Payment Terms

Add payment terms to specify how and when payment should be made:
import { PaymentMeans } from 'ubl-builder';

invoice.addPaymentMeans({
  id: '1',
  paymentMeansCode: '10', // Cash
  paymentDueDate: '2024-04-06'
});

Prepaid Payments

Record advance or prepaid amounts:
import { PrepaidPayment } from 'ubl-builder';

invoice.addPrepaidPayment({
  id: '1',
  paidAmount: '500.00',
  paidDate: '2024-02-15'
});

Allowances and Charges

Add discounts or additional charges:
import { AllowanceCharge } from 'ubl-builder';

// Add a discount
invoice.addAllowanceCharge({
  chargeIndicator: false,
  allowanceChargeReason: 'Volume discount',
  amount: '50.00',
  baseAmount: '1000.00'
});

// Add a charge
invoice.addAllowanceCharge({
  chargeIndicator: true,
  allowanceChargeReason: 'Shipping fee',
  amount: '25.00'
});

Currency Exchange Rates

For multi-currency invoices:
import { PaymentExchangeRate } from 'ubl-builder';

invoice.setPaymentCurrencyCode('USD');
invoice.setPaymentExchangeRate({
  sourceCurrencyCode: 'COP',
  targetCurrencyCode: 'USD',
  calculationRate: '3850.00',
  date: '2024-03-06'
});

Colombian DIAN Extensions

For Colombian e-invoicing compliance, the library automatically handles DIAN extensions:
// Calculate DIAN extensions (invoice control, software provider, etc.)
invoice.calculateDianExtension();

// This creates:
// - Invoice control with resolution and range
// - Software provider information
// - Software security code (hashed)
// - Authorization provider (DIAN)

// After finalization, retrieve the QR code:
const qrCode = invoice.getQRCode();
See the DIAN Extensions guide for complete details.

Helper Methods

Finding Tax Totals

Retrieve tax amounts by scheme ID:
// Get IVA tax amount
const ivaAmount = invoice.findTaxTotalById('01'); // Returns '190.00'

// Get INC tax amount
const incAmount = invoice.findTaxTotalById('04'); // Returns '0.00' if not set

// Get ICA tax amount
const icaAmount = invoice.findTaxTotalById('03');

Getting Invoice ID

const invoiceId = invoice.getID(); // Returns 'SETP990000001'
const invoiceIdObj = invoice.getID(false); // Returns UdtIdentifier object

Complete Example

import { 
  Invoice,
  AccountingSupplierParty,
  AccountingCustomerParty,
  Party,
  PartyTaxScheme,
  PartyLegalEntity,
  TaxScheme,
  PostalAddress,
  Country,
  InvoiceLine,
  Item,
  Price,
  TaxTotal,
  TaxSubtotal,
  TaxCategory,
  LegalMonetaryTotal
} from 'ubl-builder';

const invoice = new Invoice('SETP990000001', {
  timestamp: Date.now(),
  enviroment: '2',
  issuer: {
    resolutionNumber: '18764003560527',
    technicalKey: 'fc8eac425...',
    prefix: 'SETP',
    startRange: '990000000',
    endRange: '995000000',
    startDate: '2019-01-19',
    endDate: '2030-01-19'
  },
  software: {
    id: '0d2e2883-...',
    pin: '12345',
    providerNit: '900123456'
  }
});

// Basic setup
invoice.setDefaultProperties();
invoice.setUBLVersionID('UBL 2.1');
invoice.setProfileID('DIAN 2.1');
invoice.setIssueDate('2024-03-06');
invoice.setIssueTime('10:30:45-05:00');
invoice.setInvoiceTypeCode('01');
invoice.setDocumentCurrencyCode('COP');

// Add supplier and customer (simplified)
invoice.setAccountingSupplierParty(/* ... */);
invoice.setAccountingCustomerParty(/* ... */);

// Add invoice line
invoice.addInvoiceLine({
  id: '1',
  invoicedQuantity: '10',
  lineExtensionAmount: '1000.00',
  item: new Item({ description: 'Services' }),
  price: new Price({ priceAmount: '100.00' })
});

// Add tax
invoice.addTaxTotal({
  taxAmount: '190.00',
  taxSubtotals: [/* ... */]
});

// Set totals
invoice.setLegalMonetaryTotal({
  lineExtensionAmount: '1000.00',
  taxExclusiveAmount: '1000.00',
  taxInclusiveAmount: '1190.00',
  payableAmount: '1190.00'
});

// Finalize and generate
invoice.calculateDianExtension();
invoice.finalizeDocument();
const xml = invoice.getXml(true);

Next Steps

Working with Parties

Learn how to add supplier, customer, and other party information

Tax Calculations

Master tax totals, subtotals, categories, and schemes

DIAN Extensions

Configure Colombian e-invoicing extensions

API Reference

Explore the complete API documentation

Build docs developers (and LLMs) love