# User Export Feature

Provides user data export functionality, allowing authenticated users to download a complete archive of their personal data including all vehicles, fuel logs, documents, maintenance records, and associated files.

## Overview

This feature creates a TAR.GZ archive containing all user data in JSON format plus actual files (vehicle images, document PDFs). The export is synchronous and streams directly to the client for immediate download.

## Architecture

```
user-export/
├── domain/
│   ├── user-export.types.ts            # Type definitions
│   ├── user-export.service.ts          # Main service
│   └── user-export-archive.service.ts  # Archive creation logic
└── api/
    ├── user-export.controller.ts       # HTTP handlers
    └── user-export.routes.ts           # Route definitions
```

## Archive Structure

```
motovaultpro_export_YYYY-MM-DDTHH-MM-SS.tar.gz
├── manifest.json                       # Archive metadata
├── data/
│   ├── vehicles.json                   # All user vehicles
│   ├── fuel-logs.json                  # All fuel logs
│   ├── documents.json                  # All document metadata
│   ├── maintenance-records.json        # All maintenance records
│   └── maintenance-schedules.json      # All maintenance schedules
└── files/
    ├── vehicle-images/
    │   └── {vehicleId}/
    │       └── {filename}              # Actual vehicle image files
    └── documents/
        └── {documentId}/
            └── {filename}              # Actual document files
```

## API Endpoints

### Download User Export

Downloads a complete archive of all user data.

**Endpoint:** `GET /api/user/export`

**Authentication:** Required (JWT)

**Response:**
- Content-Type: `application/gzip`
- Content-Disposition: `attachment; filename="motovaultpro_export_YYYY-MM-DDTHH-MM-SS.tar.gz"`
- Streaming download

**Example:**
```bash
curl -H "Authorization: Bearer <token>" \
  https://app.motovaultpro.com/api/user/export \
  --output my_data.tar.gz
```

## Manifest Format

The manifest.json file contains metadata about the export:

```json
{
  "version": "1.0.0",
  "createdAt": "2025-12-26T10:30:00.000Z",
  "applicationVersion": "1.0.0",
  "userId": "auth0|123456",
  "contents": {
    "vehicles": {
      "count": 3,
      "withImages": 2
    },
    "fuelLogs": {
      "count": 45
    },
    "documents": {
      "count": 8,
      "withFiles": 7
    },
    "maintenanceRecords": {
      "count": 12
    },
    "maintenanceSchedules": {
      "count": 5
    }
  },
  "files": {
    "vehicleImages": 2,
    "documentFiles": 7,
    "totalSizeBytes": 15728640
  },
  "warnings": [
    "1 vehicle images not found"
  ]
}
```

## Data Export Details

### Vehicles
All vehicles owned by the user, including:
- Basic information (make, model, year, VIN)
- Vehicle details (engine, transmission, trim)
- Image metadata (if available)
- Odometer readings

### Fuel Logs
All fuel log entries including:
- Date and odometer readings
- Fuel quantity and cost
- Station and location information
- Calculated MPG (if available)

### Documents
Document metadata plus actual files:
- Document type and title
- Issue and expiration dates
- Associated files (PDFs, images)
- Storage metadata

### Maintenance Records
All maintenance history:
- Service category and subtypes
- Date and odometer reading
- Cost and shop information
- Notes

### Maintenance Schedules
All maintenance schedules:
- Interval-based schedules
- Last service information
- Next due dates/mileage
- Notification settings

## Implementation Details

### User Scoping
All data is strictly scoped to the authenticated user via `userId`. No data from other users is included.

### File Handling
- Vehicle images: Read from `/app/data/documents/{bucket}/{key}`
- Document files: Read from `/app/data/documents/{bucket}/{key}`
- Missing files are logged but don't fail the export
- Warnings are included in the manifest

### Temporary Storage
- Working directory: `/tmp/user-export-work/export-{userId}-{timestamp}/`
- Archive created in `/tmp/user-export-work/`
- Cleanup happens automatically after stream completes

### Streaming
The archive is streamed directly to the client to minimize memory usage for large exports.

### Error Handling
- Missing files are logged as warnings
- Export continues even if some files are missing
- Cleanup happens in `finally` block and stream event handlers

## Dependencies

### Internal
- `VehiclesRepository` - Vehicle data access
- `FuelLogsRepository` - Fuel log data access
- `DocumentsRepository` - Document metadata access
- `MaintenanceRepository` - Maintenance data access

### External
- `tar` - TAR.GZ archive creation
- `fs/promises` - File system operations

## Testing

Unit tests should cover:
- Archive creation with various data sets
- Missing file handling
- Manifest generation
- Cleanup on success and error

Integration tests should cover:
- Complete export workflow
- Authentication enforcement
- Streaming download
- File integrity

## Security Considerations

- User authentication required
- Data strictly scoped to authenticated user
- No cross-user data leakage possible
- Temporary files cleaned up after download
- Archive contains only user's own data

## Performance

- Synchronous operation (immediate response)
- Streaming reduces memory footprint
- Parallel file operations where possible
- Cleanup prevents disk space accumulation

## Future Enhancements

Potential improvements:
- Import functionality to restore exported data
- Selective export (e.g., only vehicles)
- Export format options (JSON only, without files)
- Scheduled exports
- Export history tracking
