Aller au contenu principal

User Story: Automated Invoice Generation & Management - Billing & Partners Epic

Story Overview​

Story ID: BILL-001
Story Type: Brownfield Enhancement
Epic: Billing & Partners Management Enhancement
Priority: High
Estimated Effort: 13 story points

User Story Statement:
As a financial administrator, I want an automated invoice generation system that creates invoices from reclamations at FACTURATION status with sequential numbering, accurate financial calculations, and comprehensive workflow management so that billing processes are streamlined, auditable, and financially accurate while preserving existing invoice functionality.

Business Context​

Current State Analysis​

  • Existing System: Manual invoice creation through FactureService with basic CRUD operations
  • Technology Stack: NestJS/Prisma with established Facture model and FactureStatus enum
  • Integration Points: Facture ↔ Reclamation (N:1), complex includes with Site/Client/Cadastre relationships
  • Existing Patterns: Controller/Service architecture, generateFactureNumber() method, financial field calculations, status enum handling

Enhancement Goals​

  • Automate invoice generation when reclamation status reaches FACTURATION
  • Implement robust sequential invoice numbering system with collision detection
  • Add sophisticated financial calculation engine for all totals (HT, TTC, degrevement, etc.)
  • Create comprehensive invoice status workflow (A_FACTURER → FACTUREE → REGLEE)
  • Establish payment tracking and reconciliation capabilities
  • Maintain complete backward compatibility with existing invoice APIs

Acceptance Criteria​

AC1: Automatic Invoice Generation Trigger​

Given a reclamation with financial data (degrevement, interetMoratoire, incidenceCfe)
When the reclamation status is updated to FACTURATION
Then the system should:

  • Automatically create a Facture record linked to the reclamation
  • Generate unique sequential invoice number with format FACT_YYYY_MM_NNNNNN (6-digit sequence)
  • Set initial status to A_FACTURER with proper date timestamps
  • Calculate all financial totals using enhanced calculation engine
  • Preserve existing Facture model relationships and include patterns
  • Trigger invoice generation workflow with proper error handling
  • Log invoice creation event with complete audit trail

AC2: Sequential Invoice Numbering System​

Given invoice generation requests
When creating new invoices
Then the system should:

  • Generate sequential numbers within monthly periods (FACT_2024_01_000001, FACT_2024_01_000002, etc.)
  • Handle concurrent invoice creation with database-level sequence collision prevention
  • Reset sequence counter at the beginning of each month
  • Provide invoice number validation and uniqueness enforcement
  • Support manual invoice number override with validation checks
  • Maintain invoice numbering audit log for compliance
  • Handle edge cases like system clock changes and timezone considerations

AC3: Enhanced Financial Calculation Engine​

Given reclamation financial data
When calculating invoice totals
Then the system should:

  • Parse degrevement JSON structure to calculate totalDegrevement (handle both object and array formats)
  • Extract interetMoratoire data to compute totalInteretMoratoire with proper decimal precision
  • Calculate totalIncidenceCfe from incidenceCfe JSON field for CFE-type reclamations
  • Compute totalHt as base amount before tax calculations
  • Apply standard tax rates (20%) to derive accurate totalTtc from totalHt
  • Validate calculation integrity with cross-checks and business rule enforcement
  • Handle different reclamation types (TF vs CFE) with type-specific calculation rules
  • Support calculation auditing with step-by-step breakdown logging

AC4: Invoice Status Workflow Management​

Given invoice lifecycle management requirements
When managing invoice status transitions
Then the system should:

  • Implement status workflow: A_FACTURER → FACTUREE → REGLEE with validation rules
  • Track status change history with timestamps, reasons, and user attribution
  • Support bulk status updates for multiple invoices with transaction safety
  • Handle payment date tracking when transitioning to REGLEE status
  • Prevent invalid status transitions with clear error messaging
  • Integrate with existing FactureStatus enum (A_FACTURER, EN_ATTENTE, REGLEE, N_A)
  • Provide status-based invoice filtering and reporting capabilities

AC5: Payment Tracking & Reconciliation​

Given invoice payment management needs
When processing invoice payments
Then the system should:

  • Track dateReglement automatically when status changes to REGLEE
  • Calculate payment periods and aging reports for outstanding invoices
  • Support partial payment tracking with remaining balance calculations
  • Generate payment reconciliation reports with financial accuracy
  • Handle payment method tracking and reference number storage
  • Integrate with existing getFactureStats() method for enhanced reporting
  • Provide overdue invoice identification and notification triggers

AC6: Integration with Reclamation Billing Process​

Given the reclamation approval workflow
When reclamations transition to FACTURATION status
Then the system should:

  • Automatically detect FACTURATION status changes via event-driven architecture
  • Validate reclamation data completeness before invoice generation
  • Handle batch invoice generation for multiple reclamations
  • Support manual invoice generation override with proper authorization
  • Maintain reclamation-to-invoice relationship integrity with cascade handling
  • Preserve existing findByReclamationId() functionality with enhanced invoice data

Technical Implementation Details​

Database Schema Enhancements​

Backward Compatible Additions:

  • Add invoiceSequenceNumber field to Facture model for sequential tracking
  • Add paymentReference and paymentMethod optional fields
  • Add calculationAuditLog JSON field for financial calculation transparency
  • Create MonthlyInvoiceSequence table for concurrent sequence management

Service Layer Enhancements​

Existing Methods to Preserve:

  • All current FactureService methods (create, findAll, findOne, update, remove, findByReclamationId, getFactureStats)
  • Existing generateFactureNumber() method (enhanced but backward compatible)
  • Current include patterns and relationship loading

New Service Methods:

  • generateInvoiceFromReclamation(reclamationId) - Core automation method
  • calculateFinancialTotals(reclamation) - Enhanced calculation engine
  • generateSequentialNumber() - Advanced numbering system
  • updateInvoiceStatus(id, newStatus, paymentDetails) - Workflow management
  • getInvoicesByStatusWorkflow() - Status-based filtering
  • generatePaymentReconciliationReport() - Financial reconciliation

API Endpoints​

Preserve Existing:

  • GET /factures (enhanced with workflow filters)
  • POST /factures (maintained for manual creation)
  • GET /factures/:id (enhanced with calculation audit)
  • PATCH /factures/:id (enhanced status workflow validation)
  • DELETE /factures/:id (maintained with cascade checks)

New Endpoints:

  • POST /factures/generate-from-reclamation/:reclamationId
  • PATCH /factures/:id/status (dedicated status workflow endpoint)
  • GET /factures/by-status-workflow
  • GET /factures/payment-reconciliation
  • GET /factures/overdue-report

Test Automation Requirements​

Invoice Generation Test Suite​

Automated Test Coverage:

  • Unit Tests: Sequential numbering collision handling, financial calculation accuracy, status workflow validation
  • Integration Tests: Reclamation-to-invoice automation, database transaction integrity, concurrent generation scenarios
  • End-to-End Tests: Complete invoice lifecycle from reclamation FACTURATION to payment REGLEE

Financial Calculation Validation​

Test Scenarios:

  • Degrevement calculation accuracy with various JSON structures (object vs array formats)
  • Tax calculation precision with decimal handling and rounding rules
  • Cross-validation between totalHt and totalTtc calculations
  • Edge cases: zero amounts, negative corrections, maximum precision limits
  • Multi-currency support preparation (future-proofing)

Invoice Numbering System Tests​

Comprehensive Coverage:

  • Sequential number generation under normal conditions
  • Concurrent invoice creation stress testing (100+ simultaneous requests)
  • Month boundary transition handling (December 31 → January 1 scenarios)
  • System recovery after database failures or sequence corruption
  • Manual number override validation and conflict resolution

Status Workflow Integration Tests​

Workflow Validation:

  • Valid status transitions with proper business rule enforcement
  • Invalid transition prevention with clear error responses
  • Bulk status update transaction safety and rollback scenarios
  • Payment date tracking accuracy during status changes
  • Status history audit trail completeness and integrity

Reclamation Integration Tests​

Automation Validation:

  • Automatic trigger when reclamation reaches FACTURATION status
  • Data completeness validation before invoice generation
  • Error handling for incomplete or invalid reclamation data
  • Batch processing scenarios with multiple reclamations
  • Manual override capabilities with proper authorization checks

Evolution Tracking & Audit Trail​

Invoice Lifecycle Audit​

Comprehensive Tracking:

  • Invoice creation events with source reclamation details
  • All status changes with timestamps, user attribution, and business justification
  • Financial calculation audit log with step-by-step breakdown
  • Payment tracking with method, reference, and reconciliation data
  • System-generated vs manual invoice differentiation

Financial Reconciliation Audit​

Accountability Measures:

  • Complete calculation transparency with input data preservation
  • Cross-reference validation between invoice totals and reclamation amounts
  • Payment reconciliation audit trail with bank reference integration
  • Month-end closing procedures with invoice sequence validation
  • Regulatory compliance reporting for financial audit requirements

Performance & Monitoring​

System Health Tracking:

  • Invoice generation performance metrics and response time monitoring
  • Financial calculation accuracy validation with automated cross-checks
  • Sequential numbering system integrity monitoring
  • Payment processing workflow efficiency tracking
  • Error rate monitoring with automated alerting for critical issues

Risk Mitigation & Rollback Plan​

Primary Risks & Mitigations​

  • Invoice Numbering Conflicts: Database-level sequence management with transaction isolation
  • Financial Calculation Errors: Multi-level validation with audit logging and rollback capabilities
  • Performance Impact: Optimized queries with existing include patterns and background processing for batch operations
  • Backward Compatibility: All existing APIs preserved with enhanced functionality transparently added

Rollback Strategy​

  • Database Migrations: All schema changes are additive and reversible
  • Feature Toggles: New automation features can be disabled via configuration without system impact
  • API Compatibility: Existing endpoints maintain identical behavior with optional enhancements
  • Data Integrity: Complete audit trail enables precise rollback to any previous state

Definition of Done​

Functional Completeness​

  • All acceptance criteria met with comprehensive test validation
  • Existing invoice CRUD functionality verified through automated regression testing
  • Financial calculation accuracy validated with precision testing and edge case coverage
  • Invoice numbering system stress-tested under concurrent load scenarios

Technical Quality​

  • NestJS service architecture patterns followed with proper dependency injection
  • Prisma ORM integration maintained with enhanced relationship handling
  • Swagger documentation updated with new endpoints and enhanced existing documentation
  • Error handling comprehensive with proper HTTP status codes and user-friendly messages

Integration & Compatibility​

  • Reclamation workflow integration seamless with FACTURATION status trigger
  • Existing Client/Site/Cadastre relationships preserved and enhanced
  • ApporteurAffaire integration prepared for Story 2 (Partner Commission)
  • Performance benchmarks met with no degradation in existing operations

Monitoring & Audit​

  • Complete audit trail implementation with regulatory compliance readiness
  • Financial reconciliation reports accurate and exportable
  • System monitoring implemented with alerting for critical invoice processing errors
  • Evolution tracking enabled for future enhancement stories

Story Manager Handoff​

"This brownfield enhancement story delivers automated invoice generation while maintaining complete system integrity. Key implementation considerations:

  • Backward Compatibility Priority: All existing FactureService methods and API endpoints remain unchanged with transparent enhancements
  • Financial Accuracy Critical: Multi-level validation ensures calculation integrity with comprehensive audit trails
  • Sequential Numbering Robustness: Database-level sequence management prevents collision scenarios under high concurrency
  • Reclamation Integration: Event-driven architecture enables seamless automation while supporting manual overrides
  • Audit & Compliance: Complete lifecycle tracking meets financial regulatory requirements with exportable reports

The implementation extends existing NestJS/Prisma patterns and prepares integration points for Stories 2 and 3 in the billing epic."