# QuML Player Multi-File Upload Enhancement

## Overview

The QuML Player Multi-File Upload Enhancement enables learners to upload multiple files as part of their responses to questions. This feature supports drag & drop, auto-upload, file preview cards, multiple upload providers (S3, local, custom API), and is fully configurable per question type.

## Features

✅ **Configurable Upload Providers**

- S3 (Amazon Web Services)
- Local file storage
- Custom API endpoints

✅ **Question Type Control**

- Enable uploads for specific question types (SA, LA, MCQ, MMCQ, MTF, ASQ)
- Single active provider configuration
- Per-provider settings

✅ **Multi-File Support**

- Upload multiple files simultaneously
- Drag & drop interface
- Auto-upload on file selection
- File preview cards with thumbnails

✅ **Progress UI**

- Real-time upload progress tracking per file
- Individual file status indicators
- Cancel/retry functionality per file
- File validation and error handling

✅ **Telemetry Integration**

- Sunbird Telemetry V3 compliant events
- Individual file upload tracking
- Multi-file session tracking
- Error reporting per file

✅ **Enhanced Response Handling**

- Multiple upload data integration with user responses
- Backward compatibility with single upload responses
- Array-based upload storage

## Configuration

### Basic Upload Config Schema

```typescript
interface UploadConfig {
  enabled: boolean;
  activeProvider: "s3" | "local" | "custom";
  uploadAllowForQuestionTypes: ("sa" | "la" | "mcq" | "mmcq" | "mtf" | "asq")[];
  providers: UploadProvider;
  maxFileSize?: number; // in bytes, default 10MB
  allowedFileTypes?: string[]; // default: [".pdf", ".doc", ".docx", ".txt", ".jpg", ".jpeg", ".png"]
}
```

### Provider Configurations

#### S3 Provider

```json
{
  "uploadConfig": {
    "enabled": true,
    "activeProvider": "s3",
    "uploadAllowForQuestionTypes": ["sa", "la", "mcq"],
    "providers": {
      "s3": {
        "bucket": "my-learning-bucket",
        "path": "responses/",
        "region": "us-east-1"
      }
    }
  }
}
```

#### Local Provider

```json
{
  "uploadConfig": {
    "enabled": true,
    "activeProvider": "local",
    "uploadAllowForQuestionTypes": ["sa", "la"],
    "providers": {
      "local": {
        "path": "/uploads"
      }
    }
  }
}
```

#### Custom API Provider

```json
{
  "uploadConfig": {
    "enabled": true,
    "activeProvider": "custom",
    "uploadAllowForQuestionTypes": ["sa", "la", "mcq", "mmcq", "mtf", "asq"],
    "providers": {
      "custom": {
        "apiUrl": "https://example.com/upload",
        "headers": {
          "Authorization": "Bearer <token>",
          "X-API-Key": "your-api-key"
        }
      }
    }
  }
}
```

## Usage

### Basic Implementation

```typescript
import { QumlPlayer } from "@your-org/react-quml-player";

const config = {
  // ... your existing config
  config: {
    // ... your existing config.config
    uploadConfig: {
      enabled: true,
      activeProvider: "s3",
      uploadAllowForQuestionTypes: ["sa", "la"],
      providers: {
        s3: {
          bucket: "my-learning-bucket",
          path: "responses/",
        },
      },
    },
  },
};

function MyAssessment() {
  const handleComplete = (results) => {
    // Check for uploads in responses
    Object.values(results.responses).forEach((response) => {
      if (response.upload) {
        console.log("Upload data:", response.upload);
        // Handle upload data
      }
    });
  };

  return (
    <QumlPlayer
      questionSetId="your-question-set-id"
      config={config}
      onComplete={handleComplete}
    />
  );
}
```

### Enhanced Response Structure

When multiple files are uploaded, the response object is extended with uploads array:

```typescript
{
  "questionId": "q123",
  "qType": "SA",
  "values": [{ "body": "User's text answer" }],
  "score": 0,
  "maxScore": 5,
  "timeSpent": 120000,
  "isSkipped": false,
  "isCorrect": false,
  "timeStamp": 1640995200000,
  "uploads": [
    {
      "provider": "s3",
      "url": "https://my-learning-bucket.s3.amazonaws.com/responses/file123.png",
      "fileName": "file123.png",
      "fileSize": 204800,
      "fileType": "image/png",
      "status": "success"
    },
    {
      "provider": "s3",
      "url": "https://my-learning-bucket.s3.amazonaws.com/responses/file124.pdf",
      "fileName": "file124.pdf",
      "fileSize": 1048576,
      "fileType": "application/pdf",
      "status": "success"
    }
  ],
  // Backward compatibility - first upload also stored here
  "upload": {
    "provider": "s3",
    "url": "https://my-learning-bucket.s3.amazonaws.com/responses/file123.png",
    "fileName": "file123.png",
    "fileSize": 204800,
    "fileType": "image/png",
    "status": "success"
  }
}
```

## UI/UX Behavior

### Upload Visibility Rules

The upload option is shown only when:

1. `uploadConfig.enabled = true`
2. Current question type is in `uploadAllowForQuestionTypes`
3. Component receives valid `config` prop

### Upload Process

1. **File Selection**: User drags files to drop zone or clicks to browse (multiple files supported)
2. **Auto Upload**: Files automatically upload when selected (no manual upload button needed)
3. **Validation**: File type and size validation per file
4. **Progress Tracking**: Real-time progress per file with individual status indicators
5. **Preview Cards**: Each file shown as a card with preview, progress, and controls
6. **File Management**: Individual remove/retry options per file
7. **Response Integration**: All upload data added to question response as array

### Question Type Support

- **SA (Short Answer)**: Primary upload option alongside text input
- **LA (Long Answer)**: Primary upload option alongside text area
- **MCQ/MMCQ**: Optional supplementary uploads to selected answers
- **MTF (Match The Following)**: Optional supplementary uploads
- **ASQ (Assertion Reason)**: Optional supplementary uploads

## Telemetry Events

All upload activities generate Sunbird Telemetry V3 compliant events:

### Upload Initiated

```json
{
  "eid": "INTERACT",
  "edata": { "type": "TOUCH", "subtype": "ACTIVATE", "id": "upload_button" },
  "object": { "id": "<questionId>", "type": "Question" },
  "context": { "pdata": { "id": "quml.player" }, "pageid": "<question-page>" },
  "tags": ["<activeProvider>"]
}
```

### Upload Started

```json
{
  "eid": "LOG",
  "edata": { "type": "UPLOAD", "level": "INFO", "message": "Upload started" },
  "object": { "id": "<questionId>", "type": "Question" },
  "tags": ["<provider>"],
  "file": { "name": "<fileName>", "size": "<fileSize>" }
}
```

### Upload Success

```json
{
  "eid": "RESPONSE",
  "edata": { "type": "UPLOAD", "status": "SUCCESS" },
  "object": { "id": "<questionId>", "type": "Question" },
  "tags": ["<provider>"],
  "file": { "name": "<fileName>", "url": "<uploadedUrl>", "size": "<fileSize>" }
}
```

### Upload Failure

```json
{
  "eid": "ERROR",
  "edata": {
    "err": "UPLOAD_FAILED",
    "errtype": "NETWORK",
    "stacktrace": "<errorDetails>"
  },
  "object": { "id": "<questionId>", "type": "Question" },
  "tags": ["<provider>"],
  "file": { "name": "<fileName>" }
}
```

## Implementation Details

### Components

- **`MultiFileUpload`**: Main drag & drop multi-file upload component with auto-upload
- **`FilePreviewCard`**: Individual file preview card with progress and controls
- **`UploadProgress`**: Modal component for upload progress tracking (legacy)
- **`UploadSection`**: Single file upload interface component (legacy)
- **Enhanced Question Renderers**: Updated SA, LA, MCQ renderers with multi-file upload support

### Services

- **`uploadProviders.ts`**: Abstract upload provider implementations
- **`useUpload.ts`**: React hook for single file upload management (legacy)
- **`useMultiFileUpload.ts`**: React hook for multi-file upload management (new)
- **Enhanced telemetry**: Upload-specific event tracking for individual and batch uploads

### Types

Extended TypeScript interfaces for:

- `UploadConfig`: Upload configuration schema
- `UploadData`: Upload response data structure
- `QuestionResponse`: Enhanced with uploads array and backward compatible upload field
- `MultiFileUploadProps`: Multi-file upload component interface
- `FilePreviewCardProps`: File preview card component interface
- Telemetry events for individual and batch upload operations

## Error Handling

The system handles various error scenarios:

- **File Validation Errors**: Size limits, type restrictions
- **Network Errors**: Upload failures, timeouts
- **Provider Errors**: S3 access issues, API failures
- **User Actions**: Upload cancellation, retry operations

## Backward Compatibility

- Existing configurations without `uploadConfig` continue to work
- Legacy file upload behavior is maintained as fallback
- Existing question responses remain unaffected
- No breaking changes to existing APIs

## Security Considerations

- File type validation prevents malicious uploads
- Size limits prevent resource exhaustion
- Provider-specific security (S3 IAM, API authentication)
- Client-side validation with server-side verification recommended

## Extensibility

### Adding New Providers

1. Extend `UploadProvider` interface in types
2. Create provider class extending `BaseUploadProvider`
3. Add provider to `UploadProviderFactory`
4. Update configuration schema

### Custom Upload Logic

The `useUpload` hook can be extended or replaced for custom upload handling while maintaining the same interface.

## Performance Considerations

- Chunked uploads for large files (provider-dependent)
- Progress tracking with minimal re-renders
- File validation before upload starts
- Memory-efficient file handling
- Background upload support

## Testing

Upload functionality can be tested with:

- Mock upload providers for unit tests
- File upload simulation in component tests
- Telemetry event verification
- Error scenario testing
- Progress tracking validation

## Migration Guide

To enable uploads in existing QuML Player implementations:

1. Add `uploadConfig` to your existing configuration
2. Choose and configure your preferred provider
3. Update event handlers to process upload data
4. Test with different question types
5. Monitor telemetry events for upload activities

## Examples

See `/src/examples/uploadConfigExample.ts` for complete configuration examples and usage patterns.
