Skip to main content

Overview

Invoices in Tresa Contafy represent CFDI (Comprobante Fiscal Digital por Internet) documents that record income transactions. Each invoice is linked to a specific profile (RFC) and contains all fiscal information required by SAT.
Invoices track both issued and received CFDIs, enabling comprehensive income management and tax reporting.

Why Invoices Matter

CFDI invoices are the legal backbone of Mexican tax compliance:
  • Legal Requirement: All commercial transactions must be documented with CFDIs
  • Tax Deductions: Only valid CFDIs qualify for tax deductions
  • Audit Trail: Complete transaction history for SAT audits
  • Payment Tracking: Support for partial payments (PPD) and payment complements

Data Structure

interface InvoiceAttributes {
  id: string;                    // UUID primary key
  profile_id: string;            // Profile (RFC) reference
  uuid: string;                  // SAT fiscal folio (unique)
  fecha: Date;                   // Invoice date
  mes: number;                   // Month (1-12)
  año: number;                   // Year
  
  // Financial amounts
  total: number;                 // Total with taxes
  subtotal: number;              // Subtotal before taxes
  iva: number;                   // IVA calculated
  iva_amount: number;            // IVA transferred
  retencion_iva_amount: number;  // IVA withheld
  retencion_isr_amount: number;  // ISR withheld
  
  // Invoice type
  tipo: 'PUE' | 'PPD' | 'COMPLEMENTO_PAGO';
  
  // Issuer information
  rfc_emisor: string;
  nombre_emisor: string;
  regimen_fiscal_emisor: string | null;
  
  // Recipient information
  rfc_receptor: string;
  nombre_receptor: string;
  regimen_fiscal_receptor: string | null;
  
  // Content
  concepto: string | null;       // Description/concept
  
  // Payment tracking
  pagos: PagoParcial[];          // Partial payments (PPD)
  complemento_pago: ComplementoPago | null;  // Payment complement
  
  // Validation
  validacion: EstadoValidacionCFDI;
  
  created_at: Date;
  updated_at: Date;
}

Invoice Types

PUE

Pago en Una ExhibiciónSingle payment invoices where payment is made in full at time of issuance.

PPD

Pago en Parcialidades o DiferidoDeferred or partial payment invoices that will be paid over time.

COMPLEMENTO_PAGO

Payment ComplementSpecial CFDI documenting partial payments made against PPD invoices.

Financial Fields Explained

  • subtotal: Amount before taxes (base imponible)
  • total: Final amount including all taxes and withholdings
  • iva: Calculated IVA (usually total - subtotal as fallback)
  • iva_amount: IVA transferred to the recipient (TotalImpuestosTrasladados)
  • Typically 16% of subtotal in Mexico
  • Appears in the Impuestos > Traslados section of CFDI XML
  • retencion_iva_amount: IVA withheld (Impuesto code 002)
  • retencion_isr_amount: ISR withheld (Impuesto code 001)
  • Common in professional services and contractor payments

Payment Tracking

For PPD invoices, Tresa tracks payment status using two mechanisms:

Partial Payments Array

interface PagoParcial {
  fechaPago: Date | string;
  formaPago: string;        // e.g., "03" (transferencia)
  monedaPago: string;       // e.g., "MXN"
  monto: number;
  numOperacion?: string;    // Transaction reference
  numParcialidad?: number;  // Payment number (1, 2, 3...)
  complementoUUID?: string; // Related complement UUID
  origen?: 'COMPLEMENTO' | 'MANUAL';
}

Payment Complement Structure

interface ComplementoPago {
  pagos: ComplementoPagoItem[];
}

interface ComplementoPagoItem {
  fechaPago: Date;
  formaPago: string;
  monedaPago: string;
  tipoCambio: number;
  monto: number;
  numOperacion?: string;
  facturasRelacionadas: FacturaRelacionada[];
}

interface FacturaRelacionada {
  uuid: string;              // Related PPD invoice UUID
  monedaDR: string;
  tipoCambioDR: number;
  metodoPagoDR: string;
  numParcialidad: number;
  impSaldoAnt: number;       // Previous balance
  impPagado: number;         // Amount paid
  impSaldoInsoluto: number;  // Remaining balance
}
Payment complements automatically update the pagos array of related PPD invoices when processed.

Validation System

Each invoice includes a validation state:
interface EstadoValidacionCFDI {
  rfcVerificado: boolean;           // RFC matches profile
  regimenFiscalVerificado: boolean; // Tax regime verified
  uuidDuplicado: boolean;           // Duplicate check
  advertencias: string[];           // Warning messages
  errores: string[];                // Error messages
  valido: boolean;                  // Overall valid status
}

Validation Rules

Validation behavior is controlled by the profile’s validaciones_habilitadas configuration:
  1. RFC Verification: Ensures RFC matches expected issuer/recipient
  2. Tax Regime Check: Validates regime code exists in SAT catalogs
  3. UUID Uniqueness: Prevents duplicate invoice imports
  4. Amount Consistency: Verifies tax calculations are correct

Relationships

Profile Relationship

Invoice.belongsTo(Profile, {
  foreignKey: 'profile_id',
  as: 'profile',
  onDelete: 'CASCADE',
  onUpdate: 'CASCADE',
});
Invoices belong to a single profile and cascade delete when the profile is removed.

Indexes

Optimized for common query patterns:
indexes: [
  { fields: ['profile_id'] },     // List by profile
  { fields: ['uuid'] },           // Find by SAT UUID
  { fields: ['fecha'] },          // Date range queries
  { fields: ['mes', 'año'] },     // Monthly reports
]

Usage Examples

Upload CFDI XML

POST /api/profiles/:profileId/invoices/upload
Content-Type: multipart/form-data
Authorization: Bearer <token>

- xml: [invoice.xml file]
The system automatically:
  1. Parses the XML using the CFDI parser
  2. Extracts all fiscal information
  3. Validates against profile configuration
  4. Stores the invoice with validation results

Query Invoices

GET /api/profiles/:profileId/invoices?mes=3&año=2026
Authorization: Bearer <token>
Response:
{
  "message": "Facturas obtenidas exitosamente",
  "data": [
    {
      "id": "770e8400-e29b-41d4-a716-446655440000",
      "profile_id": "550e8400-e29b-41d4-a716-446655440000",
      "uuid": "12345678-1234-1234-1234-123456789012",
      "fecha": "2026-03-15T14:30:00.000Z",
      "mes": 3,
      "año": 2026,
      "total": 11600.00,
      "subtotal": 10000.00,
      "iva": 1600.00,
      "iva_amount": 1600.00,
      "retencion_iva_amount": 0.00,
      "retencion_isr_amount": 0.00,
      "tipo": "PUE",
      "rfc_emisor": "AAA010101AAA",
      "nombre_emisor": "Empresa SA de CV",
      "regimen_fiscal_emisor": "601",
      "rfc_receptor": "PEXJ850101XXX",
      "nombre_receptor": "Juan Pérez",
      "regimen_fiscal_receptor": "612",
      "concepto": "Servicios de consultoría",
      "pagos": [],
      "complemento_pago": null,
      "validacion": {
        "rfcVerificado": true,
        "regimenFiscalVerificado": true,
        "uuidDuplicado": false,
        "advertencias": [],
        "errores": [],
        "valido": true
      },
      "created_at": "2026-03-15T14:35:00.000Z",
      "updated_at": "2026-03-15T14:35:00.000Z"
    }
  ],
  "count": 1,
  "total": 11600.00
}

Get Invoice by UUID

GET /api/invoices/uuid/:uuid
Authorization: Bearer <token>
UUID search works across all profiles owned by the authenticated user.

Best Practices

Validate Before Import

Enable all validation rules to catch issues early and maintain data quality.

Track Payment Status

For PPD invoices, monitor payment complements to maintain accurate records.

Use SAT Sync

Enable automatic downloads to capture all CFDIs without manual uploads.

Archive Properly

Store original XML files alongside database records for compliance.

Common Queries

Monthly Income Report

GET /api/profiles/:profileId/metrics?mes=3&año=2026&tipo=ingreso
Returns aggregated income data for the specified period.

Pending Payments (PPD)

GET /api/profiles/:profileId/invoices?tipo=PPD&estado_pago=NO_PAGADO
Filters PPD invoices that haven’t been fully paid.

Validation Errors

GET /api/profiles/:profileId/invoices?valido=false
Returns invoices with validation errors for review.

Profiles

RFC entities that own invoices

Expenses

Complementary expense tracking

Subscriptions

Plan limits on invoice storage

Build docs developers (and LLMs) love