User Story: Automated Billing Integration - Reclamation Processing Epic
Story Overview​
Story ID: REC-003
Story Type: Brownfield Enhancement
Epic: Reclamation Processing Enhancement
Dependencies: Story 1 (Status Workflow), Story 2 (Approval Process)
User Story Statement:
As a financial administrator, I want the system to automatically generate invoices when reclamations reach FACTURATION status so that billing processes are streamlined, accurate, and integrated with the existing approval workflow.
Business Context​
Current State Analysis​
- Existing System: Manual invoice creation through separate Facture and FacturePartenaire CRUD operations
- Technology Stack: NestJS/Prisma with established billing entities (Facture, FacturePartenaire)
- Integration Points: Reclamation → Facture (1:N), Reclamation → FacturePartenaire (1:N)
- Existing Patterns: Service/Controller architecture, complex Prisma includes, JSON field handling
Enhancement Goals​
- Automate facture creation when reclamation status transitions to FACTURATION
- Implement sophisticated billing calculation logic using montantAttendu and degrevement JSON data
- Generate partner invoices automatically based on client/site/apporteur relationships
- Ensure financial accuracy and reconciliation capabilities
- Maintain existing billing API compatibility
Acceptance Criteria​
AC1: Automatic Facture Creation Trigger​
Given a reclamation with montantAttendu and degrevement data
When the reclamation status is updated to FACTURATION (via Status Workflow or Approval Process)
Then the system should:
- Automatically create a Facture record linked to the reclamation
- Calculate billing amounts based on degrevement JSON structure
- Set facture status to A_FACTURER
- Generate unique facture number using existing pattern (FACT_YYYYMMDDHHMM)
- Preserve all existing Facture entity relationships and includes
AC2: Billing Calculation Logic​
Given a reclamation with financial data
When automatic billing is triggered
Then the system should:
- Parse degrevement JSON data for tax reduction calculations
- Calculate totalDegrevement from degrevement.montant or degrevement.details arrays
- Calculate totalInteretMoratoire from interetMoratoire JSON field
- Calculate totalIncidenceCfe from incidenceCfe JSON field if type is CFE
- Derive totalHt as base calculation amount
- Apply appropriate tax calculations for totalTtc
- Handle both TF and CFE reclamation types with different calculation rules
- Validate calculations against montantAttendu for accuracy checks
AC3: Partner Invoice Generation​
Given a reclamation with associated site having apporteursAffaires
When facture is automatically created
Then the system should:
- Generate FacturePartenaire records for each relevant partner
- Calculate partner amounts based on commission percentages
- Link FacturePartenaire to client, site, reclamation, and apporteurAffaire
- Set appropriate partner invoice status (A_REGLER)
- Generate dossier numbers and maintain partner billing relationships
AC4: Integration with Status Workflow​
Given the Status Workflow system is operational
When reclamation transitions through status workflow to FACTURATION
Then the billing integration should:
- Hook into status transition events seamlessly
- Validate billing prerequisites before allowing FACTURATION status
- Create comprehensive audit trail of billing actions
- Handle rollback scenarios if billing creation fails
- Maintain workflow state consistency
AC5: Integration with Approval Process​
Given the Approval Process system is operational
When approved reclamations reach FACTURATION status
Then the billing integration should:
- Honor approval workflow decisions and restrictions
- Apply approved amounts and adjustments in calculations
- Maintain approval audit trail in billing records
- Handle partial approvals with appropriate billing adjustments
AC6: Financial Accuracy and Reconciliation​
Given automated billing operations
When invoices are generated
Then the system should:
- Implement validation rules for calculation accuracy
- Provide reconciliation reports comparing expected vs. actual amounts
- Flag discrepancies for manual review
- Maintain detailed financial audit logs
- Support correction workflows for billing errors
AC7: Existing System Compatibility​
Given existing Facture and FacturePartenaire functionality
When automated billing is implemented
Then the system must:
- Preserve all existing API endpoints (/factures, /factures-partenaires)
- Maintain existing service method signatures and behaviors
- Support manual invoice creation alongside automated processes
- Preserve existing Prisma includes and relationship loading
- Maintain backward compatibility with existing UI components
Technical Implementation Requirements​
Service Layer Enhancements​
ReclamationService Extensions​
// New methods to add to existing ReclamationService
async triggerAutomaticBilling(reclamationId: number): Promise<BillingResult>
async validateBillingPrerequisites(reclamationId: number): Promise<ValidationResult>
async calculateBillingAmounts(reclamation: ReclamationWithIncludes): Promise<BillingCalculation>
FactureService Integration​
// New method to add to existing FactureService
async createAutomaticFacture(reclamationId: number, calculationData: BillingCalculation): Promise<Facture>
async validateAutomaticBilling(facture: Facture): Promise<ValidationResult>
FacturePartenaireService Integration​
// New method to add to existing FacturePartenaireService
async createPartnerInvoices(reclamationId: number, facture: Facture): Promise<FacturePartenaire[]>
async calculatePartnerCommissions(siteWithPartners: Site): Promise<PartnerCommission[])
Database Schema Enhancements​
Facture Model Extensions (Additive Only)​
model Facture {
// ... existing fields preserved
// New fields for automation tracking
isAutomaticallyGenerated Boolean? @default(false)
billingCalculationData Json? // Store calculation details for audit
validationStatus String? // VALIDATED, FLAGGED, MANUAL_REVIEW
reconciliationData Json? // Store reconciliation details
}
Status Transition Audit Trail​
model ReclamationStatusHistory {
id Int @id @default(autoincrement())
reclamationId Int
reclamation Reclamation @relation(fields: [reclamationId], references: [id])
fromStatus ReclamationStatus?
toStatus ReclamationStatus
triggeredBilling Boolean @default(false)
billingDetails Json? // Store billing trigger details
userId Int? // User who triggered the change
createdAt DateTime @default(now())
}
Event-Driven Architecture​
Status Transition Events​
interface ReclamationStatusChangeEvent {
reclamationId: number;
previousStatus: ReclamationStatus;
newStatus: ReclamationStatus;
triggeredBy: 'workflow' | 'approval' | 'manual';
userId?: number;
timestamp: Date;
}
interface BillingTriggeredEvent {
reclamationId: number;
factureId: number;
partnerInvoiceIds: number[];
calculationData: BillingCalculation;
timestamp: Date;
}
Error Handling and Recovery​
Billing Transaction Management​
- Implement database transactions for atomic billing operations
- Provide rollback mechanisms if partner invoice creation fails
- Handle partial success scenarios with appropriate cleanup
- Implement retry logic for transient failures
Validation and Error Prevention​
- Pre-validate reclamation data before billing trigger
- Check for existing invoices to prevent duplicates
- Validate partner relationships and commission data
- Ensure montantAttendu and JSON data completeness
Test Automation Requirements​
Unit Tests​
Service Layer Testing​
describe('ReclamationBillingIntegration', () => {
describe('triggerAutomaticBilling', () => {
it('should create facture when reclamation reaches FACTURATION', async () => {
// Test automatic facture creation
});
it('should calculate billing amounts from degrevement JSON', async () => {
// Test billing calculation logic
});
it('should handle TF vs CFE calculation differences', async () => {
// Test type-specific calculations
});
it('should create partner invoices for all site partners', async () => {
// Test partner invoice generation
});
it('should handle missing or invalid financial data gracefully', async () => {
// Test error scenarios
});
});
});
Calculation Logic Testing​
describe('BillingCalculationService', () => {
describe('calculateFromDegrevement', () => {
it('should parse degrevement JSON and calculate totalDegrevement', async () => {
const mockDegrevement = {
details: [
{ year: 2023, montant: 1000, type: 'TF' },
{ year: 2024, montant: 1500, type: 'TF' }
]
};
// Test calculation
});
it('should handle complex degrevement structures', async () => {
// Test various JSON structures
});
it('should calculate interest and penalties correctly', async () => {
// Test interetMoratoire calculations
});
});
});
Integration Tests​
End-to-End Billing Workflow​
describe('Billing Integration E2E', () => {
it('should complete full billing workflow from status change to invoice generation', async () => {
// 1. Create test reclamation with financial data
// 2. Trigger status change to FACTURATION
// 3. Verify automatic facture creation
// 4. Verify partner invoices created
// 5. Validate all calculations and relationships
});
it('should integrate with status workflow system', async () => {
// Test integration with Story 1 status transitions
});
it('should integrate with approval process system', async () => {
// Test integration with Story 2 approvals
});
it('should maintain existing API compatibility', async () => {
// Test that existing endpoints still work
});
});
Financial Accuracy Tests​
Calculation Validation​
describe('Financial Accuracy Validation', () => {
it('should match calculated amounts with expected montantAttendu', async () => {
// Test financial reconciliation
});
it('should flag discrepancies for manual review', async () => {
// Test discrepancy detection
});
it('should maintain audit trail for all calculations', async () => {
// Test audit logging
});
it('should handle different tax scenarios correctly', async () => {
// Test various tax calculation scenarios
});
});
Performance and Load Tests​
Billing Performance​
describe('Billing Performance', () => {
it('should handle bulk billing operations efficiently', async () => {
// Test performance with multiple simultaneous billing triggers
});
it('should not impact existing reclamation query performance', async () => {
// Test that new includes/joins don't slow down existing operations
});
});
Evolution Tracking and Audit Trail​
Comprehensive Audit Requirements​
Billing Operation Logging​
- Log all automatic billing triggers with full context
- Track calculation steps and intermediate results
- Record all partner invoice generations
- Maintain financial reconciliation audit trail
- Store user actions and system-triggered events
Status Transition Integration​
- Record billing triggers in status history
- Link billing operations to specific status changes
- Track workflow progression with billing context
- Maintain approval decision audit trail
Evolution Tracking Schema​
interface BillingAuditEntry {
id: string;
reclamationId: number;
operation: 'BILLING_TRIGGERED' | 'FACTURE_CREATED' | 'PARTNER_INVOICE_CREATED' | 'CALCULATION_PERFORMED';
details: {
calculationData?: BillingCalculation;
factureId?: number;
partnerInvoiceIds?: number[];
validationResults?: ValidationResult[];
errors?: BillingError[];
};
triggeredBy: 'STATUS_WORKFLOW' | 'APPROVAL_PROCESS' | 'MANUAL';
userId?: number;
timestamp: Date;
correlationId: string; // Link related operations
}
Monitoring and Alerting Requirements​
Financial Accuracy Monitoring​
- Monitor billing calculation accuracy vs. expected amounts
- Alert on discrepancies exceeding configured thresholds
- Track billing failure rates and error patterns
- Monitor partner commission calculation accuracy
Integration Health Monitoring​
- Monitor status workflow integration points
- Track approval process integration performance
- Alert on billing automation failures
- Monitor database transaction success rates
Business Metrics Tracking​
- Track automatic vs. manual invoice creation ratios
- Monitor billing processing times and efficiency gains
- Measure financial reconciliation accuracy improvements
- Track partner invoice generation success rates
Backward Compatibility Verification​
Existing API Preservation Tests​
describe('Backward Compatibility', () => {
it('should preserve all existing facture endpoints', async () => {
// Test GET /factures, POST /factures, etc.
});
it('should preserve all existing facture-partenaire endpoints', async () => {
// Test existing partner invoice APIs
});
it('should maintain existing service method signatures', async () => {
// Test that existing methods still work as expected
});
it('should preserve existing Prisma includes and relationships', async () => {
// Test that existing relationship loading still works
});
});
Data Migration Safety​
- Ensure new fields are nullable and have defaults
- Verify existing data integrity after schema changes
- Test rollback scenarios for new database fields
- Validate existing queries continue to work
Success Metrics​
Technical Success Indicators​
- 100% of FACTURATION status transitions trigger automatic billing
- 100% calculation accuracy for standard degrevement structures
- Zero breaking changes to existing APIs
- < 200ms additional latency for billing operations
- 100% test coverage for billing calculation logic
Business Success Indicators​
- 90% reduction in manual invoice creation time
- 99% financial accuracy in automated calculations
- 100% partner invoice generation success rate
- Zero data integrity issues with existing records
- Full audit trail availability for compliance
Integration Success Indicators​
- Seamless integration with Status Workflow (Story 1)
- Complete integration with Approval Process (Story 2)
- Zero disruption to existing billing workflows
- Successful handling of all edge cases and error scenarios
Definition of Done​
Development Complete​
- Automatic facture creation implemented and tested
- Billing calculation logic supports all financial scenarios
- Partner invoice generation working with commission calculations
- Integration with Status Workflow and Approval Process functional
- Comprehensive error handling and rollback mechanisms
- Full audit trail and monitoring implementation
Quality Assurance Complete​
- All automated tests passing (unit, integration, E2E)
- Financial accuracy validation in all scenarios
- Performance impact assessment within acceptable limits
- Backward compatibility verification successful
- Load testing completed for billing operations
Production Readiness​
- Monitoring and alerting configured
- Database migrations tested and reversible
- Feature flags implemented for gradual rollout
- Documentation updated for new billing automation
- Support team trained on new billing processes
Estimated Effort: 13-16 story points
Technical Risk: Medium (complex financial calculations and integrations)
Business Impact: High (significant automation and accuracy improvements)
Dependencies: Stories 1 & 2 must be completed first
Next Steps: This story should be implemented after Status Workflow (Story 1) and Approval Process (Story 2) are completed, as it relies on their event systems and status transition mechanisms.