Skip to main content

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.ts βœ… CREATED

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.ts βœ… CREATED

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.ts βœ… CREATED

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.ts βœ… CREATED

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)