# Additional Approver Handling in Dealer Claim Email Templates

## Overview
This document explains how the dealer claim email notification system handles additional approvers that are added dynamically between fixed workflow steps.

---

## How Additional Approvers Work

### 1. **Additional Approver Detection**
Additional approvers are identified by their `levelName` containing "Additional Approver". The system uses this to:
- Exclude them from dealer-specific templates
- Use appropriate templates for their notifications
- Track them in the approval chain

### 2. **Step Number Shifting**
When additional approvers are added:
- **Before Step 1**: Dealer Proposal Submission remains Step 1
- **Between Step 1 and Step 2**: Additional approver becomes Step 2, Requestor Evaluation shifts to Step 3
- **Between Step 2 and Step 3**: Additional approver inserted, subsequent steps shift
- And so on...

The system handles this by:
- Using `levelName` to identify steps (not just `levelNumber`)
- Finding the next PENDING level dynamically (not just sequential)
- Detecting additional approvers by checking `levelName`

---

## Email Notification Scenarios

### Scenario 1: Dealer Submits Proposal (Step 1)

#### **Initiator Notification**
- **When**: Dealer proposal is approved (Step 1 → Step 2)
- **Template**: `dealerProposalSubmitted.template.ts`
- **Notification Type**: `proposal_submitted`
- **Handles Additional Approvers**: ✅ Yes
  - If next approver is additional: Shows "Additional Approver" as next approver name
  - If next approver is Step 2: Shows "Requestor Evaluation" approver name
  - Uses `nextLevel` which is found dynamically (handles step shifts)

#### **Next Approver Notification**
- **When**: Next approver is assigned (could be Step 2 or Additional Approver)
- **Template**: 
  - If Additional Approver: `approvalRequest.template.ts` or `multiApproverRequest.template.ts`
  - If Step 2 (Requestor): `approvalRequest.template.ts` or `multiApproverRequest.template.ts`
- **Notification Type**: `assignment`
- **Handles Additional Approvers**: ✅ Yes
  - Additional approvers get standard approval request template
  - Not dealer-specific (correct behavior)

---

### Scenario 2: Additional Approver Added Between Step 1 and Step 2

**Workflow Structure:**
```
Step 1: Dealer Proposal Submission (Dealer)
Step 2: Additional Approver (New Approver) ← Added dynamically
Step 3: Requestor Evaluation (Initiator) ← Shifted from Step 2
Step 4: Department Lead Approval
...
```

**Email Flow:**
1. **Dealer submits proposal** → Step 1 approved
2. **Initiator gets email**: 
   - Template: `dealerProposalSubmitted.template.ts`
   - Shows: "Next approver: Additional Approver" (if metadata includes `nextApproverIsAdditional`)
3. **Additional Approver gets email**:
   - Template: `approvalRequest.template.ts` (standard approval request)
   - Type: `assignment`
   - Shows approval chain if multiple approvers exist
4. **Additional Approver approves** → Step 2 approved
5. **Initiator gets email**:
   - Template: `approvalConfirmation.template.ts` (standard approval confirmation)
   - Type: `approval`
6. **Requestor (Step 3) gets email**:
   - Template: `approvalRequest.template.ts` (standard approval request)
   - Type: `assignment`

---

### Scenario 3: Dealer Submits Completion Documents (Step 4)

#### **Initiator Notification**
- **When**: Dealer completion documents are approved (Step 4 → Step 5)
- **Template**: `completionDocumentsSubmitted.template.ts`
- **Notification Type**: `completion_submitted`
- **Handles Additional Approvers**: ✅ Yes
  - If next approver is additional: Shows "Additional Approver" as next approver name
  - If next approver is Step 5: Shows "Requestor Claim Approval" approver name

---

## Key Implementation Details

### 1. **Dynamic Next Level Finding**
```typescript
// In dealerClaimApproval.service.ts
// First try sequential approach
let nextLevel = await ApprovalLevel.findOne({
  where: { 
    requestId: level.requestId,
    levelNumber: currentLevelNumber + 1
  }
});

// If sequential level doesn't exist, search for next PENDING level
// This handles cases where additional approvers are added dynamically
if (!nextLevel) {
  nextLevel = await ApprovalLevel.findOne({
    where: { 
      requestId: level.requestId,
      levelNumber: { [Op.gt]: currentLevelNumber },
      status: ApprovalStatus.PENDING
    },
    order: [['levelNumber', 'ASC']]
  });
}
```

### 2. **Additional Approver Detection**
```typescript
// Check if next approver is an additional approver
const nextLevelName = nextLevel ? ((nextLevel as any).levelName || '').toLowerCase() : '';
const isNextAdditionalApprover = nextLevelName.includes('additional approver');
```

### 3. **Template Selection Logic**

#### **Assignment Notifications** (`notification.service.ts`)
```typescript
case 'assignment':
  // Check if this is a dealer proposal step
  const levelName = currentLevel ? (currentLevel.levelName || '').toLowerCase() : '';
  const isAdditionalApprover = levelName.includes('additional approver');
  
  const isDealerProposalStep = currentLevel && !isAdditionalApprover && (
    (currentLevel.levelName && (
      currentLevel.levelName.toLowerCase().includes('dealer') && 
      currentLevel.levelName.toLowerCase().includes('proposal')
    )) ||
    (currentLevel.levelNumber === 1 && requestData.workflowType === 'CLAIM_MANAGEMENT')
  );
  
  if (isDealerProposalStep) {
    // Use dealer-specific template
    await emailNotificationService.sendDealerProposalRequired(...);
  } else {
    // Use standard approval request template (works for additional approvers)
    await emailNotificationService.sendApprovalRequest(...);
  }
```

### 4. **Proposal Submitted Notification**
```typescript
// In dealerClaimApproval.service.ts
// When dealer proposal is approved
if (isDealerProposalApproval && (wf as any).initiatorId) {
  // Get next approver (could be Step 2 or Additional Approver)
  const nextApproverData = nextLevel ? await User.findByPk((nextLevel as any).approverId) : null;
  
  // Check if next approver is additional
  const nextLevelName = nextLevel ? ((nextLevel as any).levelName || '').toLowerCase() : '';
  const isNextAdditionalApprover = nextLevelName.includes('additional approver');
  
  // Send proposal_submitted notification (not approval notification)
  await notificationService.sendToUsers([(wf as any).initiatorId], {
    type: 'proposal_submitted', // NOT 'approval'
    metadata: {
      proposalData: {
        nextApproverIsAdditional: isNextAdditionalApprover
      },
      nextApproverId: nextApproverData ? nextApproverData.userId : undefined
    }
  });
}
```

---

## Email Template Behavior

### ✅ **Templates That Handle Additional Approvers**

1. **Dealer Proposal Submitted** (`dealerProposalSubmitted.template.ts`)
   - Shows next approver name (or "Additional Approver" if applicable)
   - Works correctly when next approver is additional

2. **Completion Documents Submitted** (`completionDocumentsSubmitted.template.ts`)
   - Shows next approver name (or "Additional Approver" if applicable)
   - Works correctly when next approver is additional

3. **Approval Request** (`approvalRequest.template.ts` / `multiApproverRequest.template.ts`)
   - Used for additional approvers
   - Shows approval chain if multiple approvers exist
   - Works correctly for all approvers (fixed and additional)

4. **Approval Confirmation** (`approvalConfirmation.template.ts`)
   - Used when additional approvers approve
   - Shows next approver in chain
   - Works correctly

### ❌ **Templates That Should NOT Be Used for Additional Approvers**

1. **Dealer Proposal Required** (`dealerProposalRequired.template.ts`)
   - Only for dealer (Step 1)
   - Additional approvers excluded via `!isAdditionalApprover` check

---

## Testing Scenarios

### Test Case 1: No Additional Approvers
- **Step 1** (Dealer) → Gets `dealerProposalRequired` template ✅
- **Step 1 approved** → Initiator gets `dealerProposalSubmitted` template ✅
- **Step 2** (Requestor) → Gets `approvalRequest` template ✅

### Test Case 2: Additional Approver Between Step 1 and Step 2
- **Step 1** (Dealer) → Gets `dealerProposalRequired` template ✅
- **Step 1 approved** → Initiator gets `dealerProposalSubmitted` template with "Additional Approver" as next ✅
- **Step 2** (Additional Approver) → Gets `approvalRequest` template ✅
- **Step 2 approved** → Initiator gets `approvalConfirmation` template ✅
- **Step 3** (Requestor) → Gets `approvalRequest` template ✅

### Test Case 3: Multiple Additional Approvers
- **Step 1** (Dealer) → Gets `dealerProposalRequired` template ✅
- **Step 1 approved** → Initiator gets `dealerProposalSubmitted` template ✅
- **Step 2** (Additional Approver 1) → Gets `multiApproverRequest` template (if multiple approvers) ✅
- **Step 2 approved** → Next approver notified ✅
- **Step 3** (Additional Approver 2) → Gets `multiApproverRequest` template ✅
- And so on...

---

## Summary

### ✅ **What Works Correctly**

1. **Dealer Assignment**: Uses dealer-specific template (not multi-level approval)
2. **Proposal Submitted**: Initiator gets `proposal_submitted` template (not multi-level approval)
3. **Additional Approvers**: Get standard approval request templates
4. **Next Approver Detection**: Dynamically finds next approver (handles step shifts)
5. **Template Selection**: Correctly identifies dealer steps vs additional approvers

### 🔧 **Key Logic**

- **Dealer Proposal Step Detection**: Checks `levelName` contains "dealer" and "proposal" OR `levelNumber === 1` AND `workflowType === 'CLAIM_MANAGEMENT'`
- **Additional Approver Detection**: Checks `levelName` contains "additional approver"
- **Next Level Finding**: Uses dynamic search for next PENDING level (not just sequential)
- **Template Selection**: Excludes additional approvers from dealer-specific templates

### 📧 **Email Flow**

```
Dealer Submits Proposal
  ↓
Step 1 Approved (System)
  ↓
Initiator: proposal_submitted email ✅ (NOT multi-level approval)
Next Approver: assignment email ✅ (Standard approval request)
  ↓
If Next is Additional Approver:
  - Gets standard approval request template ✅
  - Shows in approval chain ✅
  - When approved, next approver gets assignment ✅
```

---

## Files Modified

1. **`dealerClaimApproval.service.ts`**
   - Added detection for additional approvers
   - Changed notification type from `approval` to `proposal_submitted` for dealer proposal
   - Added `nextApproverIsAdditional` metadata

2. **`notification.service.ts`**
   - Added check to exclude additional approvers from dealer-specific templates
   - Improved dealer proposal step detection

3. **`emailNotification.service.ts`**
   - Updated to handle `nextApproverIsAdditional` flag
   - Shows "Additional Approver" when next approver is additional

---

## Conclusion

The system now correctly handles additional approvers:
- ✅ Initiator gets `proposal_submitted` template (not multi-level approval)
- ✅ Additional approvers get standard approval request templates
- ✅ Next approver is correctly identified even when steps shift
- ✅ All templates work seamlessly with dynamic approval chains

