Aller au contenu principal

Reclamation Approval & Review Process - Brownfield User Story

Story Overview​

Epic: Reclamation Processing Enhancement
Story: Story 2 - Reclamation Approval & Review Process
Story Type: Enhancement (Brownfield)
Priority: High
Estimated Effort: 16 story points

User Story​

As a tax reclamation administrator and reviewer
I want to have a comprehensive approval workflow system with role-based routing, amount threshold management, TF/CFE-specific review processes, and automated notifications
So that I can efficiently manage reclamation approvals through structured review queues while maintaining compliance, audit trails, and seamless integration with existing status workflows and billing systems

Context & Integration​

Current System Integration Points:

  • Extends existing ReclamationService (/Users/ayoub/projects/emtb/apps/api/src/reclamation/reclamation.service.ts)
  • Leverages existing ReclamationStatus enum with integration for approval-related states (EN_ATTENTE, ACCEPTEE, ACCEPTEE_PARTIELLEMENT, REFUSEE)
  • Integrates with Story 1's Status Workflow system for approval status transitions
  • Utilizes existing montantAttendu field for amount-based approval routing
  • Connects with existing Site-Client-Cadastre-ApporteurAffaire relationships for approval context
  • Integrates with existing User model for role-based approval assignments
  • Extends existing ReclamationType enum (TF, CFE) with type-specific approval workflows
  • Maintains compatibility with Facture and FacturePartenaire billing integration points

Existing Functionality to Preserve:

  • All existing CRUD operations and endpoint patterns
  • Current ReclamationService methods (create, findAll, findOne, update, remove, findBySiteId, getReclamationStats)
  • Existing status-based business logic and billing system integration
  • Site-based reclamation queries and complex Prisma relationship loading
  • JSON field management for degrevement, incidenceCfe, and interetMoratoire data
  • Date handling for dateDemande, dateDeDebut, dateFin, dateRetour fields
  • Existing montantAttendu validation and financial calculations

Acceptance Criteria​

AC1: Amount-Based Approval Routing & TF/CFE Threshold Management​

Given I am processing reclamations that require approval
When a reclamation reaches approval-required status
Then the system should:

  • Route reclamations based on montantAttendu thresholds: <5K (supervisor), 5K-25K (manager), 25K+ (director)
  • Apply TF-specific thresholds: Property value assessments require higher approval levels (director approval for 15K+)
  • Implement CFE-specific thresholds: Business impact assessments with different routing (manager approval for 10K+)
  • Automatically assign to appropriate approval queue based on reclamation type and amount
  • Consider Site Client relationship and ApporteurAffaire commission impact in routing decisions
  • Route complex cases (multiple sites, high degrevement impact) to specialized approval teams
  • Validate approval authority based on User role and reclamation characteristics
  • Apply escalation rules for time-sensitive approvals and regulatory deadline compliance
  • Handle cross-threshold scenarios where degrevement calculations change approval requirements
  • Maintain approval routing history and decision audit trails

AC2: Comprehensive Review Dashboard & Queue Management​

Given I am an approver managing reclamation review queues
When I access the approval dashboard
Then the system should:

  • Display organized approval queues by role, amount threshold, and reclamation type (TF/CFE)
  • Show pending approvals with priority ranking, aging analysis, and deadline tracking
  • Provide detailed reclamation context: Site information, Client details, Cadastre data, montantAttendu, degrevement calculations
  • Display TF-specific review data: property assessments, tax year compliance, cadastre validation results
  • Show CFE-specific review data: business impact analysis, incidenceCfe calculations, establishment verification
  • Enable bulk approval actions with validation safeguards and batch processing controls
  • Support approval delegation with proper authorization tracking and responsibility transfer
  • Provide advanced filtering: by status, type, amount range, site, client, approval urgency, assigned reviewer
  • Show approval history and previous reviewer decisions with contextual notes
  • Display integrated billing impact and FacturePartenaire implications for approval decisions

AC3: Advanced Approval Workflow & Decision Management​

Given I am reviewing reclamations for approval
When I make approval decisions
Then the system should:

  • Support APPROVE, REJECT, REQUEST_INFO, CONDITIONAL_APPROVE decision types
  • Enable detailed approval comments with structured decision rationales and supporting documentation
  • Handle TF-specific approval criteria: property valuation validation, cadastre data completeness, tax authority compliance
  • Manage CFE-specific approval criteria: business activity verification, establishment data validation, regulatory compliance
  • Implement conditional approval with specified conditions and follow-up requirements
  • Support partial approval for CFE reclamations (ACCEPTEE_PARTIELLEMENT) with amount adjustments
  • Validate approval decisions against business rules and regulatory requirements
  • Trigger automatic status transitions per Story 1's workflow system integration
  • Generate approval notifications to stakeholders (clients, site managers, billing teams)
  • Record comprehensive approval audit trails with decision context and business justification

AC4: Integration with Status Workflow & Billing Systems​

Given approval decisions impact reclamation status and billing processes
When approval actions are completed
Then the system should:

  • Seamlessly integrate with Story 1's status workflow for automated status transitions
  • Trigger ACCEPTEE status transition upon approval with billing system integration
  • Handle REFUSEE status transition upon rejection with client notification workflows
  • Support EN_ATTENTE status for REQUEST_INFO decisions with automatic follow-up scheduling
  • Validate montantAttendu adjustments and update degrevement data accordingly
  • Integrate with Facture creation workflow for approved reclamations reaching FACTURATION status
  • Update FacturePartenaire calculations based on approval decisions and commission impacts
  • Maintain Site status synchronization and Client relationship integrity throughout approval process
  • Support ApporteurAffaire commission calculations based on final approved amounts
  • Preserve existing JSON field handling for degrevement, incidenceCfe, and interetMoratoire updates

AC5: Role-Based Approval Authority & Security​

Given different user roles have varying approval authorities
When managing approval assignments and decisions
Then the system should:

  • Enforce role-based approval limits: SUPERVISOR (under 5K), MANAGER (5K-25K), DIRECTOR (25K+)
  • Implement TF/CFE-specific role requirements: TF tax specialists, CFE business analysts
  • Support approval delegation with proper authorization chains and responsibility tracking
  • Validate approval authority before decision execution with comprehensive security checks
  • Track approval assignments and reassignments with audit trails and notification workflows
  • Implement approval conflict resolution for competing decisions and overlapping authority
  • Support emergency approval procedures with enhanced audit requirements and oversight
  • Enforce separation of duties: reclamation creators cannot approve their own submissions
  • Maintain approval authority matrix with dynamic updates based on organizational changes
  • Log all approval-related security events and authorization validations

AC6: Automated Notifications & Communication Workflows​

Given approval processes require stakeholder communication
When approval events occur
Then the system should:

  • Send automatic notifications for new approvals assigned to reviewers
  • Notify submitters of approval decisions with detailed decision context and next steps
  • Alert stakeholders of approval delays and escalation triggers with priority indicators
  • Generate TF-specific notifications: tax authority deadlines, property assessment updates, cadastre changes
  • Send CFE-specific notifications: business impact alerts, establishment verification requirements, regulatory updates
  • Support customizable notification templates with dynamic content based on reclamation context
  • Enable notification escalation chains for overdue approvals and missed deadlines
  • Integrate with external systems: email, SMS, webhook notifications to billing systems
  • Maintain notification delivery tracking and confirmation workflows
  • Support notification preferences by user role and reclamation type with privacy controls

AC7: Evolution Tracking & Comprehensive Audit​

Given regulatory compliance and audit requirements for approval processes
When approval workflow operations occur
Then the system should:

  • Track all approval actions with complete user context, decision rationale, and supporting evidence
  • Maintain immutable approval audit logs with cryptographic integrity verification
  • Record approval workflow rule evaluations and authority validations
  • Log approval routing decisions and threshold-based assignments with business justification
  • Track degrevement data modifications through approval process with before/after comparisons
  • Monitor approval performance metrics: processing times, decision patterns, escalation rates
  • Record integration points with billing systems and financial transaction correlations
  • Support comprehensive audit report generation with regulatory compliance formatting
  • Maintain approval trail export capabilities for tax authority and internal audit requirements
  • Log approval system performance and bottleneck identification for process optimization

AC8: Performance Monitoring & Bottleneck Analysis​

Given approval process efficiency is critical for business operations
When managing approval workflows
Then the system should:

  • Monitor approval queue processing times and identify bottlenecks in real-time
  • Track approval routing efficiency and threshold-based assignment effectiveness
  • Analyze approval decision patterns and identify process improvement opportunities
  • Monitor TF/CFE-specific approval timelines and regulatory compliance metrics
  • Generate performance dashboards for approval managers with actionable insights
  • Alert on approval delays and escalation threshold breaches with automated notifications
  • Track approver workload distribution and capacity management analytics
  • Measure approval decision quality and consistency across different reviewers
  • Monitor integration performance with Status Workflow and billing systems
  • Support approval process optimization recommendations based on performance data analysis

Technical Requirements​

Database Schema Changes (Additive Only)​

-- Approval workflow configuration
CREATE TABLE reclamation_approval_thresholds (
id SERIAL PRIMARY KEY,
reclamation_type VARCHAR(10) NOT NULL, -- TF or CFE
min_amount DECIMAL(12,2) DEFAULT 0,
max_amount DECIMAL(12,2),
required_role VARCHAR(50) NOT NULL,
approval_level INTEGER NOT NULL, -- 1=Supervisor, 2=Manager, 3=Director
auto_assignment_queue VARCHAR(100),
escalation_hours INTEGER DEFAULT 48,
special_conditions JSONB, -- Complex routing rules
tf_specific_rules JSONB, -- TF property assessment rules
cfe_specific_rules JSONB, -- CFE business impact rules
is_active BOOLEAN DEFAULT TRUE,
created_at TIMESTAMP DEFAULT NOW(),
updated_at TIMESTAMP DEFAULT NOW(),
CONSTRAINT unique_threshold_rule UNIQUE(reclamation_type, min_amount, max_amount)
);

-- Approval assignments and queue management
CREATE TABLE reclamation_approval_assignments (
id SERIAL PRIMARY KEY,
reclamation_id INTEGER NOT NULL REFERENCES reclamations(id) ON DELETE CASCADE,
assigned_to_user_id INTEGER NOT NULL REFERENCES users(id),
assigned_by_user_id INTEGER REFERENCES users(id),
approval_queue VARCHAR(100) NOT NULL,
assignment_reason VARCHAR(200),
priority_level INTEGER DEFAULT 1, -- 1=Normal, 2=High, 3=Urgent
estimated_amount DECIMAL(12,2), -- Snapshot of montantAttendu at assignment
deadline_date TIMESTAMP,
escalation_date TIMESTAMP,
status VARCHAR(30) DEFAULT 'PENDING', -- PENDING, IN_REVIEW, COMPLETED, ESCALATED
tf_cfe_context JSONB, -- Type-specific assignment context
site_context JSONB, -- Site and Client context
degrevement_snapshot JSONB, -- Degrevement data at assignment
assignment_metadata JSONB, -- Routing decision data
created_at TIMESTAMP DEFAULT NOW(),
updated_at TIMESTAMP DEFAULT NOW(),
INDEX idx_assignment_user_status (assigned_to_user_id, status),
INDEX idx_assignment_reclamation (reclamation_id),
INDEX idx_assignment_queue_priority (approval_queue, priority_level, deadline_date)
);

-- Approval decisions and actions
CREATE TABLE reclamation_approval_decisions (
id SERIAL PRIMARY KEY,
reclamation_id INTEGER NOT NULL REFERENCES reclamations(id) ON DELETE CASCADE,
assignment_id INTEGER REFERENCES reclamation_approval_assignments(id) ON DELETE CASCADE,
decision_type VARCHAR(30) NOT NULL, -- APPROVE, REJECT, REQUEST_INFO, CONDITIONAL_APPROVE
decision_by_user_id INTEGER NOT NULL REFERENCES users(id),
decision_rationale TEXT NOT NULL,
approved_amount DECIMAL(12,2), -- Final approved montantAttendu
conditions TEXT, -- For conditional approvals
supporting_documents JSONB, -- Document references and validation
tf_specific_validation JSONB, -- TF property and tax validation results
cfe_specific_validation JSONB, -- CFE business and establishment validation
degrevement_adjustments JSONB, -- Degrevement data changes
billing_impact_analysis JSONB, -- Financial impact calculations
regulatory_compliance_notes TEXT,
approval_authority_validation JSONB, -- Role and threshold validation
integration_triggers JSONB, -- Status workflow and billing integration data
decision_timestamp TIMESTAMP DEFAULT NOW(),
effective_date TIMESTAMP, -- When decision takes effect
review_required BOOLEAN DEFAULT FALSE,
reviewed_by_user_id INTEGER REFERENCES users(id),
review_timestamp TIMESTAMP,
created_at TIMESTAMP DEFAULT NOW()
);

-- Approval notifications and communications
CREATE TABLE reclamation_approval_notifications (
id SERIAL PRIMARY KEY,
reclamation_id INTEGER NOT NULL REFERENCES reclamations(id) ON DELETE CASCADE,
assignment_id INTEGER REFERENCES reclamation_approval_assignments(id) ON DELETE CASCADE,
decision_id INTEGER REFERENCES reclamation_approval_decisions(id) ON DELETE CASCADE,
notification_type VARCHAR(50) NOT NULL, -- ASSIGNMENT, DECISION, ESCALATION, REMINDER
recipient_user_id INTEGER REFERENCES users(id),
recipient_email VARCHAR(255),
webhook_url VARCHAR(500),
notification_subject VARCHAR(255),
notification_body TEXT,
tf_cfe_context JSONB, -- Type-specific notification context
approval_context JSONB, -- Approval-specific data and links
delivery_method VARCHAR(20) DEFAULT 'EMAIL', -- EMAIL, SMS, IN_APP, WEBHOOK
delivery_status VARCHAR(20) DEFAULT 'PENDING', -- PENDING, SENT, DELIVERED, FAILED
delivery_attempts INTEGER DEFAULT 0,
delivery_timestamp TIMESTAMP,
failure_reason TEXT,
read_timestamp TIMESTAMP,
action_taken BOOLEAN DEFAULT FALSE,
created_at TIMESTAMP DEFAULT NOW(),
INDEX idx_notification_recipient_status (recipient_user_id, delivery_status),
INDEX idx_notification_reclamation (reclamation_id),
INDEX idx_notification_type_date (notification_type, created_at)
);

-- Approval workflow rules and business logic
CREATE TABLE reclamation_approval_workflow_rules (
id SERIAL PRIMARY KEY,
rule_name VARCHAR(100) NOT NULL,
reclamation_type VARCHAR(10) NOT NULL, -- TF or CFE
conditions JSONB NOT NULL, -- Complex rule conditions (amount, site, client criteria)
actions JSONB NOT NULL, -- Actions to take when conditions met
routing_logic JSONB, -- Approval routing and assignment logic
notification_config JSONB, -- Notification settings and templates
escalation_rules JSONB, -- Time-based escalation configuration
tf_specific_logic JSONB, -- TF property and tax-specific rules
cfe_specific_logic JSONB, -- CFE business and establishment-specific rules
integration_hooks JSONB, -- Status workflow and billing system integration
priority INTEGER DEFAULT 100, -- Rule execution priority
is_active BOOLEAN DEFAULT TRUE,
effective_from TIMESTAMP DEFAULT NOW(),
effective_until TIMESTAMP,
created_by_user_id INTEGER REFERENCES users(id),
created_at TIMESTAMP DEFAULT NOW(),
updated_at TIMESTAMP DEFAULT NOW(),
CONSTRAINT unique_workflow_rule_name UNIQUE(rule_name)
);

-- Approval performance and analytics
CREATE TABLE reclamation_approval_metrics (
id SERIAL PRIMARY KEY,
reclamation_id INTEGER NOT NULL REFERENCES reclamations(id) ON DELETE CASCADE,
assignment_id INTEGER REFERENCES reclamation_approval_assignments(id) ON DELETE CASCADE,
metric_type VARCHAR(50) NOT NULL, -- ASSIGNMENT_TIME, REVIEW_TIME, DECISION_TIME, ESCALATION_EVENT
metric_value DECIMAL(10,2), -- Time in hours or other numeric metrics
measurement_timestamp TIMESTAMP DEFAULT NOW(),
additional_data JSONB, -- Context and additional measurement data
bottleneck_indicators JSONB, -- Performance bottleneck analysis data
efficiency_scores JSONB, -- Process efficiency measurements
created_at TIMESTAMP DEFAULT NOW(),
INDEX idx_metrics_type_date (metric_type, measurement_timestamp),
INDEX idx_metrics_reclamation (reclamation_id),
INDEX idx_metrics_assignment (assignment_id)
);

Service Layer Enhancements​

// Extends existing ReclamationService
class ReclamationApprovalService {
// Amount-based approval routing with TF/CFE specialization
async routeForApproval(reclamationId: number): Promise<ApprovalAssignment>
async getApprovalThreshold(montantAttendu: number, type: ReclamationType): Promise<ApprovalThreshold>

// Review dashboard and queue management
async getApprovalQueue(userId: number, filters: ApprovalQueueFilters): Promise<ApprovalQueue>
async getApprovalDashboard(userId: number): Promise<ApprovalDashboard>
async bulkApprovalActions(assignments: number[], action: BulkApprovalAction): Promise<BulkResult>

// Approval workflow and decision management
async makeApprovalDecision(assignmentId: number, decision: ApprovalDecision): Promise<ApprovalResult>
async requestAdditionalInfo(assignmentId: number, request: InfoRequest): Promise<InfoRequestResult>
async delegateApproval(assignmentId: number, targetUserId: number): Promise<DelegationResult>

// Integration with Status Workflow (Story 1)
async triggerStatusTransition(decisionId: number): Promise<StatusTransitionResult>
async validateApprovalImpact(reclamationId: number): Promise<ApprovalImpactAnalysis>

// Performance monitoring and analytics
async getApprovalMetrics(filters: MetricsFilters): Promise<ApprovalMetrics>
async identifyBottlenecks(timeRange: DateRange): Promise<BottleneckAnalysis>
async generatePerformanceReport(reportConfig: PerformanceReportConfig): Promise<PerformanceReport>
}

API Endpoints (Additive)​

// New approval-specific endpoints
POST /reclamations/:id/submit-for-approval // Submit reclamation for approval
GET /reclamations/approval-queue // Get user's approval queue
POST /reclamations/approval/:assignmentId // Make approval decision
PATCH /reclamations/approval/:assignmentId // Update assignment (delegate, prioritize)
GET /reclamations/approval-dashboard // Get approval dashboard
POST /reclamations/approval/bulk-actions // Bulk approval actions
GET /reclamations/approval-metrics // Get approval performance metrics
GET /reclamations/:id/approval-history // Get reclamation approval history

// Enhanced existing endpoints with approval context
GET /reclamations // Include approval status in response
GET /reclamations/:id // Include full approval context and history

Integration Points​

  • Status Workflow Integration: Seamless connection with Story 1's status transition system
  • Billing System Integration: Automatic Facture creation triggers upon approval
  • User Management Integration: Role-based approval authority validation
  • Notification System Integration: Multi-channel approval notifications
  • Audit System Integration: Comprehensive approval audit trails
  • Performance Monitoring Integration: Real-time bottleneck identification and process optimization

Test Automation Requirements​

Approval Routing Tests​

describe('Amount-Based Approval Routing', () => {
test('Routes TF reclamation <5K to supervisor queue')
test('Routes CFE reclamation 5K-25K to manager queue')
test('Routes high-value reclamation 25K+ to director queue')
test('Applies TF-specific threshold overrides for property assessments')
test('Handles CFE business impact routing with custom thresholds')
test('Escalates complex multi-site reclamations appropriately')
test('Validates approval authority based on user role and amount')
test('Handles dynamic threshold changes without disrupting active approvals')
})

describe('TF vs CFE Approval Workflow Differences', () => {
test('TF workflow requires cadastre validation before approval')
test('CFE workflow includes business activity verification')
test('TF property assessment approval follows specialized routing')
test('CFE establishment data validation in approval process')
test('TF tax year compliance checks during approval')
test('CFE regulatory compliance validation for business impact')
test('Different degrevement calculation validation for TF vs CFE')
})

Review Dashboard Tests​

describe('Review Dashboard Functionality', () => {
test('Displays approval queue organized by role and amount')
test('Shows aging analysis and deadline tracking')
test('Filters approvals by status, type, amount range, client')
test('Supports bulk approval actions with validation')
test('Enables approval delegation with proper authorization')
test('Shows integrated billing impact for approval decisions')
test('Displays TF/CFE-specific review context and data')
test('Performance loads large approval queues efficiently')
})

describe('Notification System Tests', () => {
test('Sends assignment notifications to designated approvers')
test('Notifies stakeholders of approval decisions')
test('Escalates overdue approvals with appropriate alerts')
test('Handles TF-specific deadline notifications')
test('Manages CFE regulatory compliance notifications')
test('Supports notification delivery tracking and confirmation')
test('Integrates with external notification systems (email, SMS)')
})

Integration with Status Workflow Tests​

describe('Status Workflow Integration', () => {
test('Approval triggers ACCEPTEE status transition')
test('Rejection triggers REFUSEE status with proper workflow')
test('REQUEST_INFO decision sets EN_ATTENTE status correctly')
test('Conditional approval maintains status workflow integrity')
test('Partial CFE approval updates to ACCEPTEE_PARTIELLEMENT')
test('Status transition validation during approval process')
test('Billing system integration triggers at appropriate status')
test('Maintains existing status workflow compatibility')
})

describe('Performance and Bottleneck Monitoring', () => {
test('Monitors approval queue processing times')
test('Identifies bottlenecks in approval routing')
test('Tracks approval decision patterns and quality')
test('Measures approver workload distribution')
test('Analyzes escalation rates and effectiveness')
test('Generates performance optimization recommendations')
test('Monitors integration performance with billing systems')
test('Alerts on approval delay thresholds and SLA breaches')
})

Evolution Tracking Tests​

describe('Comprehensive Audit and Compliance', () => {
test('Records all approval actions with complete context')
test('Maintains immutable approval audit logs')
test('Tracks approval authority validations')
test('Logs degrevement modifications through approval process')
test('Records integration points with billing systems')
test('Generates regulatory compliance audit reports')
test('Supports audit trail export for tax authorities')
test('Validates cryptographic integrity of approval logs')
})

describe('Backward Compatibility Validation', () => {
test('Existing reclamation CRUD operations remain unchanged')
test('ReclamationService methods preserve existing functionality')
test('Status-based business logic continues to work correctly')
test('Billing system integration maintains existing patterns')
test('Site-based reclamation queries perform optimally')
test('JSON field handling preserves existing behavior')
test('Complex Prisma relationship loading remains efficient')
test('Existing API response formats are maintained')
})

Definition of Done​

Core Functionality​

  • Amount-based approval routing implemented with TF/CFE specialization
  • Review dashboard with comprehensive queue management functionality
  • Approval workflow with decision management and validation
  • Integration with Story 1's Status Workflow system
  • Role-based approval authority enforcement with security validation

Integration & Compatibility​

  • Seamless integration with existing ReclamationService methods
  • Billing system integration triggers working correctly
  • User management and role-based security implemented
  • Notification system with multi-channel support operational
  • All existing reclamation functionality preserved and tested

Performance & Monitoring​

  • Approval process performance monitoring implemented
  • Bottleneck identification and alerting operational
  • Real-time dashboard performance optimized for large datasets
  • Integration performance with Status Workflow and billing systems validated

Testing & Quality Assurance​

  • Comprehensive test automation covering all approval workflows
  • TF vs CFE approval workflow differences thoroughly tested
  • Review dashboard functionality validated under load
  • Integration with Status Workflow extensively tested
  • Performance and bottleneck monitoring validated
  • Evolution tracking and audit compliance verified

Documentation & Compliance​

  • API documentation updated with approval endpoints
  • Approval workflow business rules documented
  • Audit trail export functionality implemented for regulatory compliance
  • Performance monitoring setup and alerting configured
  • Integration points with existing systems documented and validated

Story Dependencies​

Depends On:

  • Story 1: Reclamation Status Workflow Automation (for status transition integration)

Supports:

  • Story 3: Automated Billing Integration (provides approval context for billing triggers)

Integration Requirements:

  • Must maintain full compatibility with existing ReclamationService patterns
  • Requires User model enhancements for role-based approval authority
  • Needs notification system integration for approval communications
  • Must integrate seamlessly with existing Site/Client/Facture relationships