# Frontend Updates for Dealer Claim Management

## Overview

This document outlines the frontend changes needed to support the new backend structure with `workflowType` field for dealer claim management.

## ✅ Completed

1. **Created utility function** (`src/utils/claimRequestUtils.ts`)
   - `isClaimManagementRequest()` - Checks if request is claim management (supports both old and new formats)
   - `getWorkflowType()` - Gets workflow type from request
   - `shouldUseClaimManagementUI()` - Determines if claim-specific UI should be used

## 🔧 Required Updates

### 1. Update RequestDetail Component

**File**: `src/pages/RequestDetail/RequestDetail.tsx`

**Changes Needed**:
- Import `isClaimManagementRequest` from `@/utils/claimRequestUtils`
- Conditionally render `ClaimManagementOverviewTab` instead of `OverviewTab` when it's a claim management request
- Conditionally render `DealerClaimWorkflowTab` instead of `WorkflowTab` when it's a claim management request

**Example**:
```typescript
import { isClaimManagementRequest } from '@/utils/claimRequestUtils';
import { ClaimManagementOverviewTab } from './components/tabs/ClaimManagementOverviewTab';
import { DealerClaimWorkflowTab } from './components/tabs/DealerClaimWorkflowTab';

// In the component:
const isClaimManagement = isClaimManagementRequest(apiRequest);

<TabsContent value="overview">
  {isClaimManagement ? (
    <ClaimManagementOverviewTab
      request={request}
      apiRequest={apiRequest}
      currentUserId={(user as any)?.userId}
      isInitiator={isInitiator}
    />
  ) : (
    <OverviewTab {...overviewProps} />
  )}
</TabsContent>

<TabsContent value="workflow">
  {isClaimManagement ? (
    <DealerClaimWorkflowTab
      request={request}
      user={user}
      isInitiator={isInitiator}
      onRefresh={refreshDetails}
    />
  ) : (
    <WorkflowTab {...workflowProps} />
  )}
</TabsContent>
```

### 2. Create Missing Utility Functions

**File**: `src/pages/RequestDetail/utils/claimDataMapper.ts` (NEW FILE)

**Functions Needed**:
- `mapToClaimManagementRequest(apiRequest, userId)` - Maps backend API response to claim management structure
- `determineUserRole(apiRequest, userId)` - Determines user's role (INITIATOR, DEALER, APPROVER, SPECTATOR)
- Helper functions to extract claim-specific data from API response

**Structure**:
```typescript
export interface ClaimManagementRequest {
  activityInfo: {
    activityName: string;
    activityType: string;
    activityDate: string;
    location: string;
    periodStart?: string;
    periodEnd?: string;
    estimatedBudget?: number;
    closedExpensesBreakdown?: any[];
  };
  dealerInfo: {
    dealerCode: string;
    dealerName: string;
    dealerEmail?: string;
    dealerPhone?: string;
    dealerAddress?: string;
  };
  proposalDetails?: {
    costBreakup: any[];
    totalEstimatedBudget: number;
    timeline: string;
    dealerComments?: string;
  };
  ioDetails?: {
    ioNumber?: string;
    availableBalance?: number;
    blockedAmount?: number;
    remainingBalance?: number;
  };
  dmsDetails?: {
    dmsNumber?: string;
    eInvoiceNumber?: string;
    creditNoteNumber?: string;
  };
  claimAmount?: number;
}

export function mapToClaimManagementRequest(
  apiRequest: any,
  userId: string
): ClaimManagementRequest | null {
  // Extract data from apiRequest.claimDetails (from backend)
  // Map to ClaimManagementRequest structure
}

export function determineUserRole(
  apiRequest: any,
  userId: string
): 'INITIATOR' | 'DEALER' | 'APPROVER' | 'SPECTATOR' {
  // Check if user is initiator
  // Check if user is dealer (from participants or claimDetails)
  // Check if user is approver (from approval levels)
  // Check if user is spectator (from participants)
}
```

### 3. Update ClaimManagementOverviewTab

**File**: `src/pages/RequestDetail/components/tabs/ClaimManagementOverviewTab.tsx`

**Changes Needed**:
- Import the new utility functions from `claimDataMapper.ts`
- Remove TODO comments
- Ensure it properly handles both old and new API response formats

### 4. Update API Service

**File**: `src/services/workflowApi.ts`

**Changes Needed**:
- Add `workflowType` field to `CreateWorkflowFromFormPayload` interface
- Include `workflowType: 'CLAIM_MANAGEMENT'` when creating claim management requests
- Update response types to include `workflowType` field

**Example**:
```typescript
export interface CreateWorkflowFromFormPayload {
  templateId?: string | null;
  templateType: 'CUSTOM' | 'TEMPLATE';
  workflowType?: string;  // NEW: 'CLAIM_MANAGEMENT' | 'NON_TEMPLATIZED' | etc.
  title: string;
  // ... rest of fields
}
```

### 5. Update ClaimManagementWizard

**File**: `src/components/workflow/ClaimManagementWizard/ClaimManagementWizard.tsx`

**Changes Needed**:
- When submitting, include `workflowType: 'CLAIM_MANAGEMENT'` in the payload
- Update to call the new backend API endpoint for creating claim requests

### 6. Update Request List Components

**Files**:
- `src/pages/MyRequests/components/RequestCard.tsx`
- `src/pages/Requests/components/RequestCard.tsx`
- `src/pages/OpenRequests/components/RequestCard.tsx`

**Changes Needed**:
- Display template/workflow type badge based on `workflowType` field
- Support both old (`templateType`) and new (`workflowType`) formats

**Example**:
```typescript
const workflowType = request.workflowType || 
  (request.templateType === 'claim-management' ? 'CLAIM_MANAGEMENT' : 'NON_TEMPLATIZED');

{workflowType === 'CLAIM_MANAGEMENT' && (
  <Badge variant="secondary">Claim Management</Badge>
)}
```

### 7. Create API Service for Claim Management

**File**: `src/services/dealerClaimApi.ts` (NEW FILE)

**Endpoints Needed**:
- `createClaimRequest(data)` - POST `/api/v1/dealer-claims`
- `getClaimDetails(requestId)` - GET `/api/v1/dealer-claims/:requestId`
- `submitProposal(requestId, data)` - POST `/api/v1/dealer-claims/:requestId/proposal`
- `submitCompletion(requestId, data)` - POST `/api/v1/dealer-claims/:requestId/completion`
- `updateIODetails(requestId, data)` - PUT `/api/v1/dealer-claims/:requestId/io`

### 8. Update Type Definitions

**File**: `src/types/index.ts`

**Changes Needed**:
- Add `workflowType?: string` to request interfaces
- Update `ClaimFormData` interface to match backend structure

## 📋 Implementation Order

1. ✅ Create `claimRequestUtils.ts` (DONE)
2. ⏳ Create `claimDataMapper.ts` with mapping functions
3. ⏳ Update `RequestDetail.tsx` to conditionally render claim components
4. ⏳ Update `workflowApi.ts` to include `workflowType`
5. ⏳ Update `ClaimManagementWizard.tsx` to send `workflowType`
6. ⏳ Create `dealerClaimApi.ts` for claim-specific endpoints
7. ⏳ Update request card components to show workflow type
8. ⏳ Test end-to-end flow

## 🔄 Backward Compatibility

The frontend should support both:
- **Old Format**: `templateType: 'claim-management'`
- **New Format**: `workflowType: 'CLAIM_MANAGEMENT'`

The `isClaimManagementRequest()` utility function handles both formats automatically.

## 📝 Notes

- All existing claim management UI components are already created
- The main work is connecting them to the new backend API structure
- The `workflowType` field allows the system to support multiple template types in the future
- All requests (claim management, non-templatized, future templates) will appear in "My Requests" and "Open Requests" automatically

