Saltar al contenido principal

FEL Implementation Plan: Credit Notes, Debit Notes & Cancellations

📋 Overview

This document outlines the complete implementation plan for supporting Credit Notes (NCRE), Debit Notes (NDEB), and Invoice Cancellations (ANULACION) in the FlowPOS FEL system for Guatemala.

🎯 Key Decision: RPAfelApi Integration for ALL Documents

Decision: Use RPAfelApi (production-ready FEL service) for ALL document types, including regular invoices (FACT), not just credit notes, debit notes, and cancellations.

Why All Documents:

  • Consistency - Same certification path for everything
  • Caching Benefits - Invoices get certificate caching too
  • Simpler Architecture - One code path instead of two
  • Better Error Handling - All documents get "already signed" handling
  • Less Code - Easier to maintain

Benefits:

  • ✅ Faster implementation (2-3 days vs 2-3 weeks)
  • ✅ Built-in certificate caching (especially valuable for invoices)
  • ✅ Automatic "already signed" error handling
  • ✅ Production-tested and deployed
  • ✅ Supports all document types (FACT, NCRE, NDEB, ANULACION)

Impact:

  • No XML generation needed - RPAfelApi handles it
  • DTE JSON conversion needed - Convert Invoice to DTE JSON format (for all types)
  • Business logic still needed - Validation, repositories, services, controllers
  • RPAfelApi handles certification - We call the API for all documents
  • Direct certifiers as fallback - Keep existing code as backup

See docs/fel/rpafelapi-integration-implementation.md for RPAfelApi integration details.
See docs/fel/rpafelapi-for-all-documents-analysis.md for full analysis.


🎯 Objectives

  1. Credit Notes (NCRE): Support reversing or partially correcting previously certified invoices
  2. Debit Notes (NDEB): Support increasing the value of previously certified invoices
  3. Cancellations (ANULACION): Support canceling invoices within the same tax period

📊 Current State Analysis

✅ What's Already Implemented

  • FEL Invoice (FACT) generation and certification
  • ✅ XML conversion service (handles FACT documents)
  • ✅ FEL certifier integration (Infile, Digifact)
  • ✅ Event-driven certification on sale creation/update
  • ✅ Sale table with FEL fields (authorization, serial number, number, date, etc.)
  • ✅ DocumentType enum includes CREDIT_NOTE and DEBIT_NOTE
  • RPAfelApi Integration (production-ready FEL service with caching, error handling)

❌ What's Missing

  • ❌ Credit Note (NCRE) support
  • ❌ Debit Note (NDEB) support
  • ❌ Cancellation (ANULACION) support
  • ✅ Database tables for credit/debit notes and cancellations (Phase 1 complete)
  • ❌ DTE JSON conversion for NCRE, NDEB, ANULACION (for RPAfelApi)
  • ❌ Services to handle these document types
  • ❌ Business logic for SAT validation rules
  • ❌ RPAfelApi provider integration

🗄️ Database Schema

Tables Created

1. credit_note Table

Stores credit notes that reverse or partially correct invoices.

Key Fields:

  • id (uuid, PK)
  • business_id (uuid, FK → business)
  • sale_id (uuid, FK → sale) - Required: Links to original sale
  • original_invoice_uuid (varchar) - Required: FEL UUID of original invoice
  • adjustment_reason (text) - Required: Reason for credit note (SAT requirement)
  • detail (json) - Line items (following existing pattern)
  • total_amount (numeric)
  • fel_authorization, fel_serial_number, fel_number, fel_date_dte, etc.
  • Standard fields: status, created_at, created_by, updated_at, updated_by
  • Currency fields: currency_id, currency_code, minor_unit, exchange_rate, currency
  • Customer fields: customer_id, tax_id, tax_name, tax_address, taxpayer_type
  • Location fields: location_id, location_name

Indexes:

  • idx_credit_note_sale_id on sale_id
  • idx_credit_note_original_invoice_uuid on original_invoice_uuid

2. debit_note Table

Stores debit notes that increase invoice values.

Key Fields:

  • Same structure as credit_note
  • original_invoice_uuid (varchar) - Required: FEL UUID of original invoice
  • adjustment_reason (text) - Required: Reason for debit note

Indexes:

  • idx_debit_note_sale_id on sale_id
  • idx_debit_note_original_invoice_uuid on original_invoice_uuid

3. fel_cancellation Table

Stores cancellation requests and results.

Key Fields:

  • id (uuid, PK)
  • business_id (uuid, FK → business)
  • sale_id (uuid, FK → sale) - Required: Links to sale being cancelled
  • original_invoice_uuid (varchar) - Required: FEL UUID of invoice to cancel
  • cancel_uuid (varchar) - FEL UUID of cancellation document (after certification)
  • cancellation_reason (text) - Required: Reason for cancellation (SAT requirement)
  • cancellation_date (timestamptz) - Required: When cancellation was requested
  • original_invoice_date (timestamptz) - Required: Date of original invoice
  • status (varchar) - pending, certified, rejected, failed
  • request_xml (text) - XML sent to certifier (for debugging)
  • response_xml (text) - XML response from certifier (for debugging)
  • error_message (text) - Error details if cancellation failed

Indexes:

  • idx_fel_cancellation_sale_id on sale_id
  • idx_fel_cancellation_original_invoice_uuid on original_invoice_uuid
  • idx_fel_cancellation_status on status

🔧 Implementation Phases

Phase 1: Database & Types ✅

Status:COMPLETED

  • Create migration for credit_note, debit_note, fel_cancellation tables
  • Add indexes for performance
  • Update TypeScript database types (already generated)
  • Create TypeScript interfaces for new document types

Phase 1.5: RPAfelApi Integration for ALL Documents ✅

Status:COMPLETED

Scope: Integrate RPAfelApi for ALL document types (FACT, NCRE, NDEB, ANULACION)

Tasks:

  • Create ProviderRpaFelApiService
  • Create XmlToDteJsonService (handles FACT, NCRE, NDEB, ANULACION)
  • Update FelService with RPAfelApi routing
  • Update FelService.processSaleEvent to use RPAfelApi for invoices (uses feature flag)
  • Update ProviderService to register RPAfelApi
  • Update FelModule to register new services
  • Add environment variables (USE_RPA_FEL_API, RPA_FEL_API_URL) - TODO: Add to .env files
  • Test with FACT documents (invoices) first
  • Enable for invoices via feature flag
  • Keep direct certifiers as fallback

Priority: High - Do this first, then add NCRE/NDEB/ANULACION support

Files:

  • packages/backend/database/src/migrations/2025-12-18t00:00:00.000z-fel-credit-debit-cancellation-tables.mjs
  • packages/backend/database/src/types/database.types.ts (update)
  • apps/backend/src/fel/domain/fel.interface.ts (extend)

Phase 2: TypeScript Interfaces & Types ✅

Status:COMPLETED

2.1 Extend FEL Interfaces

File: apps/backend/src/fel/domain/fel.interface.ts

// Extend existing Invoice interface
export interface FelDocument extends Invoice {
documentType: 'FACT' | 'NCRE' | 'NDEB' | 'ANULACION';
originalInvoiceUuid?: string; // For NCRE/NDEB/ANULACION
cancellationReason?: string; // For ANULACION
adjustmentReason?: string; // For NCRE/NDEB
}

// New interfaces
export interface CreditNoteDocument extends FelDocument {
documentType: 'NCRE';
originalInvoiceUuid: string;
adjustmentReason: string;
}

export interface DebitNoteDocument extends FelDocument {
documentType: 'NDEB';
originalInvoiceUuid: string;
adjustmentReason: string;
}

export interface CancellationDocument {
originalInvoiceUuid: string;
cancellationReason: string;
cancellationDate: string;
originalInvoiceDate: string;
issuerTaxId: string;
receiverTaxId: string;
}

2.2 Update Database Types

File: packages/backend/database/src/types/database.types.ts

Add interfaces for:

  • CreditNote
  • DebitNote
  • FelCancellation

Phase 3: RPAfelApi Integration & DTE JSON Conversion

Status:PENDING

3.1 Create RPAfelApi Provider

File: apps/backend/src/fel/infrastructure/provider-rpafelapi.service.ts (NEW)

Purpose:

  • HTTP client for RPAfelApi
  • Handles certification requests
  • Transforms responses to match existing format

Key Features:

  • ✅ Certificate caching (handled by RPAfelApi)
  • ✅ "Already signed" error handling (automatic)
  • ✅ Support for all document types (FACT, NCRE, NDEB, ANULACION)

Implementation: See docs/fel/rpafelapi-integration-implementation.md for complete code.

3.2 Create DTE JSON Converter

File: apps/backend/src/fel/application/xml-to-dte-json.service.ts (NEW)

Purpose:

  • Convert Invoice object to DTE JSON structure (RPAfelApi format)
  • Handle all document types (FACT, NCRE, NDEB, ANULACION)
  • Map fields correctly for RPAfelApi

Key Methods:

convertInvoiceToDteJson(invoice: Invoice, rpaUUID: string): DTEJson
convertCreditNoteToDteJson(creditNote: CreditNoteDocument, rpaUUID: string): DTEJson
convertDebitNoteToDteJson(debitNote: DebitNoteDocument, rpaUUID: string): DTEJson
convertCancellationToDteJson(cancellation: CancellationDocument): DTEJson

DTE JSON Structure:

RPAfelApi expects DTE JSON format (not XML). Structure includes:

  • DatosGenerales with Tipo, FechaHoraEmision, CodigoMoneda
  • Emisor with tax ID, name, address
  • Receptor with tax ID, name, address
  • Items with line items
  • Totales with totals
  • For NCRE/NDEB: Reference to original invoice UUID
  • For ANULACION: Cancellation details

Note: RPAfelApi handles XML generation internally. We only need to provide DTE JSON.

Implementation: See docs/fel/rpafelapi-integration-implementation.md for complete code.


Phase 4: Business Logic & Services

Status:IN PROGRESS (Validation Service ✅, Business Services Pending)

4.1 Validation Service ✅

File: apps/backend/src/fel/application/fel-validation.service.tsCREATED

Status:COMPLETED

Responsibilities:

  • ✅ Validate same-month cancellation rule
  • ✅ Check if invoice can be cancelled (no credit notes exist)
  • ✅ Validate credit note doesn't exceed original invoice amount
  • ✅ Validate debit note doesn't create new taxes
  • ✅ Check invoice is certified before allowing notes/cancellation

Key Methods:

async validateCancellation(saleId: string, cancellationDate: Date): Promise<ValidationResult>
async validateCreditNote(saleId: string, amount: number, originalInvoiceUuid: string): Promise<ValidationResult>
async validateDebitNote(saleId: string, originalInvoiceUuid: string): Promise<ValidationResult>
async isInvoiceCertified(saleId: string): Promise<boolean>
async getOriginalInvoiceUuid(saleId: string): Promise<string | null>

4.2 Credit Note Service ✅

File: apps/backend/src/fel/application/fel-credit-note.service.tsCREATED

Status:COMPLETED

Responsibilities:

  • ✅ Create credit note records
  • ✅ Build credit note Invoice document
  • ✅ Certify credit notes via FEL (via FelService)
  • ⏳ Handle inventory reversals (TODO: implement)
  • ⏳ Update accounting entries (TODO: implement)

Key Methods:

async createCreditNote(data: InsertableCreditNote): Promise<SelectableCreditNote>
async certifyCreditNote(creditNoteId: string): Promise<void>
async processCertifiedCreditNote(creditNote: SelectableCreditNote): Promise<void>
async getCreditNoteById(id: string): Promise<SelectableCreditNote | null>
async getCreditNotesBySaleId(saleId: string): Promise<SelectableCreditNote[]>

4.3 Debit Note Service ✅

File: apps/backend/src/fel/application/fel-debit-note.service.tsCREATED

Status:COMPLETED

Responsibilities:

  • ✅ Create debit note records
  • ✅ Build debit note Invoice document
  • ✅ Certify debit notes via FEL (via FelService)
  • ⏳ Update accounting entries (TODO: implement)

Key Methods:

async createDebitNote(data: InsertableDebitNote): Promise<SelectableDebitNote>
async certifyDebitNote(debitNoteId: string): Promise<void>
async getDebitNoteById(id: string): Promise<SelectableDebitNote | null>
async getDebitNotesBySaleId(saleId: string): Promise<SelectableDebitNote[]>

4.4 Cancellation Service ✅

File: apps/backend/src/fel/application/fel-cancellation.service.tsCREATED

Status:COMPLETED

Responsibilities:

  • ✅ Validate cancellation eligibility
  • ✅ Create cancellation records
  • ✅ Build cancellation document
  • ✅ Certify cancellations via FEL (via FelService)
  • ⏳ Update sale status to cancelled (TODO: implement)
  • ⏳ Reverse inventory and accounting entries (TODO: implement)
  • ⏳ Void payments (TODO: implement)

Key Methods:

async requestCancellation(saleId: string, cancellationReason: string, createdBy: string): Promise<SelectableFelCancellation>
async certifyCancellation(cancellationId: string): Promise<void>
async processCertifiedCancellation(cancellation: SelectableFelCancellation): Promise<void>
async getCancellationById(id: string): Promise<SelectableFelCancellation | null>
async getCancellationsBySaleId(saleId: string): Promise<SelectableFelCancellation[]>

4.5 Update FelService

File: apps/backend/src/fel/application/fel.service.ts

Changes:

  • Add routing logic for RPAfelApi (when USE_RPA_FEL_API=true)
  • Extend certifyDocument to handle NCRE, NDEB, ANULACION
  • Add certifyViaRpaFelApi method for RPAfelApi path
  • Keep existing direct certifier path as fallback
  • Add event handlers for credit/debit note certification
  • Add cancellation event handler

Key Implementation:

async certifyDocument(params: ICertifyDocumentParameters): Promise<undefined> {
// Check if using RPAfelApi
const useRpaFelApi =
process.env.USE_RPA_FEL_API === 'true' ||
felProviderData.providerName === 'rpafelapi';

if (useRpaFelApi) {
return await this.certifyViaRpaFelApi(document, business, taxId);
}

// Use direct certifier (existing logic)
// ...
}

Benefits:

  • ✅ RPAfelApi handles caching automatically
  • ✅ RPAfelApi handles "already signed" errors
  • ✅ Can fallback to direct certifiers if needed

Phase 5: Repositories

Status:COMPLETED

  • Create CreditNoteRepository
  • Create DebitNoteRepository
  • Create FelCancellationRepository
  • Create domain interfaces for all repositories
  • Register repositories in FelModule

5.1 Credit Note Repository

File: apps/backend/src/fel/infrastructure/credit-note.repository.ts (NEW)

Methods:

  • create(data)
  • findById(id)
  • findBySaleId(saleId)
  • findByOriginalInvoiceUuid(uuid)
  • update(id, data)

5.2 Debit Note Repository

File: apps/backend/src/fel/infrastructure/debit-note.repository.ts (NEW)

Methods:

  • Same as credit note repository

5.3 Cancellation Repository

File: apps/backend/src/fel/infrastructure/fel-cancellation.repository.ts (NEW)

Methods:

  • create(data)
  • findById(id)
  • findBySaleId(saleId)
  • findByOriginalInvoiceUuid(uuid)
  • update(id, data)

Phase 6: Controllers & DTOs

Status:COMPLETED

  • Create CreateCreditNoteDto
  • Create CreateDebitNoteDto
  • Create RequestCancellationDto
  • Extend FelController with credit note endpoints
  • Extend FelController with debit note endpoints
  • Extend FelController with cancellation endpoints

6.1 DTOs

Files:

  • apps/backend/src/fel/interfaces/dtos/create-credit-note.dto.ts
  • apps/backend/src/fel/interfaces/dtos/create-debit-note.dto.ts
  • apps/backend/src/fel/interfaces/dtos/request-cancellation.dto.ts

6.2 Controllers

File: apps/backend/src/fel/interfaces/fel.controller.ts (extend existing or create new)

Endpoints:

POST   /fel/credit-notes
GET /fel/credit-notes/:id
GET /fel/credit-notes/sale/:saleId
POST /fel/credit-notes/:id/certify

POST /fel/debit-notes
GET /fel/debit-notes/:id
GET /fel/debit-notes/sale/:saleId
POST /fel/debit-notes/:id/certify

POST /fel/cancellations
GET /fel/cancellations/:id
GET /fel/cancellations/sale/:saleId
POST /fel/cancellations/:id/certify

Phase 7: Events & Event Handlers ✅

Status:COMPLETED

  • Create OnCreateCreditNoteEvent
  • Create OnCertifyCreditNoteEvent
  • Create OnCreateDebitNoteEvent
  • Create OnCertifyDebitNoteEvent
  • Create OnRequestCancellationEvent
  • Create OnCertifyCancellationEvent
  • Add event emission in services
  • Create event handlers in InventoriesService for inventory reversal
  • Handle credit note inventory reversal
  • Handle cancellation inventory reversal

7.1 Events ✅

Files:ALL CREATED

  • apps/backend/src/fel/application/events/on-create-credit-note.event.ts
  • apps/backend/src/fel/application/events/on-certify-credit-note.event.ts
  • apps/backend/src/fel/application/events/on-create-debit-note.event.ts
  • apps/backend/src/fel/application/events/on-certify-debit-note.event.ts
  • apps/backend/src/fel/application/events/on-request-cancellation.event.ts
  • apps/backend/src/fel/application/events/on-certify-cancellation.event.ts

7.2 Event Handlers ✅

Files:IMPLEMENTED IN InventoriesService

  • ✅ Event handlers added to apps/backend/src/inventories/application/inventories.service.ts
    • handleOnCertifyCreditNoteEvent - Reverses inventory on credit note certification
    • handleOnCertifyCancellationEvent - Reverses inventory on cancellation certification

Responsibilities:

  • ✅ Update inventory on credit note certification (via event handler)
  • ✅ Update inventory on cancellation certification (via event handler)
  • ⏳ Reverse accounting entries (TODO: if needed)
  • ⏳ Update sale status on cancellation (TODO: add cancelled status to enum or use flag)

Phase 8: Frontend Integration

Status:PENDING

8.1 Pages/Components

Files:

  • apps/frontend-pwa/src/components/sales/CreditNotePage.tsx (NEW)
  • apps/frontend-pwa/src/components/sales/DebitNotePage.tsx (NEW)
  • apps/frontend-pwa/src/components/sales/InvoiceCancellationPage.tsx (NEW)
  • apps/frontend-pwa/src/components/sales/InvoiceDetailPage.tsx (extend with cancellation button)

8.2 Services

File: apps/frontend-pwa/src/services/felService.ts (extend)

Methods:

  • createCreditNote(data)
  • createDebitNote(data)
  • requestCancellation(saleId, reason)
  • certifyCreditNote(id)
  • certifyDebitNote(id)
  • certifyCancellation(id)

8.3 i18n Translations

Files:

  • apps/frontend-pwa/src/i18n/locales/en.json (add translations)
  • apps/frontend-pwa/src/i18n/locales/es.json (add translations)

📐 SAT Validation Rules

Credit Note (NCRE) Rules

  1. ✅ Must reference original invoice UUID
  2. ✅ Cannot exceed original invoice amount
  3. ✅ Must include adjustment reason
  4. ✅ Original invoice must be certified
  5. ✅ Can be issued in any tax period (unlike cancellations)

Debit Note (NDEB) Rules

  1. ✅ Must reference original invoice UUID
  2. ✅ Cannot create new taxes not in original invoice
  3. ✅ Must include adjustment reason
  4. ✅ Original invoice must be certified
  5. ✅ Increases receivables

Cancellation (ANULACION) Rules

  1. CRITICAL: Only allowed in same tax period as original invoice
  2. ✅ Must reference original invoice UUID
  3. ✅ Must include cancellation reason
  4. ✅ Original invoice must be certified
  5. ✅ Cannot cancel if credit note exists
  6. ✅ Only issuer can cancel
  7. ✅ Cancellation does NOT generate taxes
  8. ✅ Cancelled invoice does not appear in sales ledger
  9. ⚠️ SAT Error 9019: Cannot cancel if invoice was already included in tax return (Planilla del IVA FEL)
    • Note: This validation cannot be performed before attempting cancellation
    • SAT's system must be queried to check if invoice is in tax return
    • Error handling provides user-friendly message when this occurs
    • Frontend should warn users about this limitation

🔄 Workflow Diagrams

Credit Note Workflow (Updated for RPAfelApi)

User creates credit note

Validate: Invoice certified? Amount valid?

Create credit_note record (status: draft)

Convert Invoice to DTE JSON (XmlToDteJsonService)

Call RPAfelApi /generateCertificateToSign

RPAfelApi handles:
- Certificate caching (if Infile)
- "Already signed" errors (automatic)
- XML generation (internal)
- FEL certification

On success: Update credit_note with FEL data

Reverse inventory

Update accounting entries

Emit OnCertifyCreditNoteEvent

Debit Note Workflow (Updated for RPAfelApi)

User creates debit note

Validate: Invoice certified? Taxes valid?

Create debit_note record (status: draft)

Convert Invoice to DTE JSON (XmlToDteJsonService)

Call RPAfelApi /generateCertificateToSign

RPAfelApi handles:
- Certificate caching (if Infile)
- "Already signed" errors (automatic)
- XML generation (internal)
- FEL certification

On success: Update debit_note with FEL data

Update accounting entries

Emit OnCertifyDebitNoteEvent

Cancellation Workflow (Updated for RPAfelApi)

User requests cancellation

Validate: Same month? No credit note? Invoice certified?

Create fel_cancellation record (status: pending)

Convert Cancellation to DTE JSON (XmlToDteJsonService)

Call RPAfelApi /voidCertificate (or /generateCertificateToSign for ANULACION)

RPAfelApi handles:
- Certificate caching (if applicable)
- "Already signed" errors (automatic)
- XML generation (internal)
- FEL certification

On success: Update fel_cancellation with cancel_uuid

Update sale.status = 'cancelled'

Reverse inventory

Reverse accounting entries

Void payments

Emit OnCertifyCancellationEvent

🧪 Testing Strategy

Unit Tests

  • DTE JSON conversion for NCRE, NDEB, ANULACION (XmlToDteJsonService)
  • Validation logic (SAT rules, business rules)
  • Business rule enforcement
  • RPAfelApi provider response transformation

Integration Tests

  • End-to-end credit note creation and certification via RPAfelApi
  • End-to-end debit note creation and certification via RPAfelApi
  • End-to-end cancellation request and certification via RPAfelApi
  • Error handling (same-month validation, RPAfelApi errors, etc.)
  • Fallback to direct certifiers if RPAfelApi unavailable

Test Cases

  1. Credit Note:

    • ✅ Create credit note for certified invoice
    • ✅ Reject credit note exceeding original amount
    • ✅ Reject credit note for uncertified invoice
    • ✅ Verify inventory reversal on certification
  2. Debit Note:

    • ✅ Create debit note for certified invoice
    • ✅ Reject debit note with new taxes
    • ✅ Verify accounting updates
  3. Cancellation:

    • ✅ Cancel invoice in same month
    • ✅ Reject cancellation in different month
    • ✅ Reject cancellation if credit note exists
    • ✅ Verify inventory reversal
    • ✅ Verify payment voiding

📝 Documentation Tasks

  • Create XML examples document (docs/fel/xml-examples.md)
  • Update API documentation
  • Create user guide for credit/debit notes
  • Create troubleshooting guide
  • Document SAT compliance requirements

🚀 Deployment Checklist

  • Run migration in staging
  • Test with FEL certifier sandbox
  • Verify XML structure with SAT
  • Test all workflows end-to-end
  • Update frontend translations
  • Deploy to production
  • Monitor FEL certification logs

📚 References


🎯 Success Criteria

  • ✅ Credit notes can be created and certified
  • ✅ Debit notes can be created and certified
  • ✅ Invoices can be cancelled within same month
  • ✅ All SAT validation rules are enforced
  • ✅ Inventory and accounting are correctly updated
  • ✅ XML structure matches SAT requirements
  • ✅ Frontend UI is intuitive and complete


🔄 Updated Architecture: RPAfelApi Integration

Decision: Use RPAfelApi for Certification

Why:

  • ✅ Production-ready and deployed
  • ✅ Built-in certificate caching
  • ✅ Automatic "already signed" error handling
  • ✅ Supports all document types (FACT, NCRE, NDEB, ANULACION)
  • ✅ Faster implementation than building everything

Impact on Implementation:

  • No XML generation needed for NCRE/NDEB/ANULACION (RPAfelApi handles it)
  • DTE JSON conversion needed (Invoice → DTE JSON format)
  • Business logic still needed (validation, repositories, services, controllers)
  • RPAfelApi handles certification (we just call the API)

Updated Flow (Unified for All Documents)

User creates invoice/credit note/debit note/cancellation

Validate (SAT rules, business logic)

Create database record (sale/credit_note/debit_note/fel_cancellation)

Convert Invoice/Document to DTE JSON (XmlToDteJsonService)

Call RPAfelApi /generateCertificateToSign (ProviderRpaFelApiService)

RPAfelApi handles:
- Certificate caching (especially for Infile)
- "Already signed" errors (automatic)
- XML generation (internal)
- FEL certification

Update database record with FEL data

Emit events (inventory updates, accounting updates, etc.)

Key Points:

  • Same flow for ALL documents (FACT, NCRE, NDEB, ANULACION)
  • Consistent behavior across all document types
  • All documents benefit from caching and error handling

Key Changes from Original Plan

  1. Phase 3 Updated:

    • ❌ Remove XML generation for NCRE/NDEB/ANULACION
    • ✅ Add DTE JSON conversion
    • ✅ Add RPAfelApi provider
  2. Phase 1.5 Added:

    • RPAfelApi integration (should be done early)
  3. Simplified:

    • Less code to write (RPAfelApi handles complex parts)
    • Focus on business logic and data management
    • Faster time to market

Last Updated: 2025-12-18
Status: Phase 1 ✅, Phase 1.5 ✅, Phase 2 ✅, Phase 3 ✅, Phase 4 ✅, Phase 5 ✅, Phase 6 ✅, Phase 7 ✅ Complete. Phase 8 (Frontend) Pending
Note:

  • ✅ Core RPAfelApi infrastructure is complete and ready for testing
  • ✅ Validation service and repositories are implemented
  • ✅ Business logic services (credit note, debit note, cancellation) are implemented
  • ✅ DTOs and controllers are created with full REST API
  • ✅ Event handlers for inventory reversal are implemented
  • ✅ All events are created and emitted
  • ⏳ Frontend integration is pending
  • ⏳ Some optional TODO items remain (accounting updates, payment voiding, sale status update)