import React, { useState } from 'react'; import { useMutation, useQueryClient } from 'react-query'; import { useAuth } from '../contexts/AuthContext'; import { usersAPI } from '../services/api'; import { DocumentArrowUpIcon, UserPlusIcon, DocumentTextIcon, ExclamationTriangleIcon, CheckCircleIcon, } from '@heroicons/react/24/outline'; import LoadingSpinner from '../components/LoadingSpinner'; import toast from 'react-hot-toast'; const UserImport = () => { const { isSuperAdmin, isTrainer } = useAuth(); const queryClient = useQueryClient(); const [file, setFile] = useState(null); const [preview, setPreview] = useState(null); const [loading, setLoading] = useState(false); const [importResults, setImportResults] = useState(null); const importUsersMutation = useMutation( (data) => usersAPI.importUsers(data), { onSuccess: (response) => { setImportResults(response.data); queryClient.invalidateQueries(['users']); toast.success('Users imported successfully!'); setLoading(false); }, onError: (error) => { toast.error(error.response?.data?.error || 'Failed to import users'); setLoading(false); }, } ); const handleFileChange = (e) => { const selectedFile = e.target.files[0]; if (selectedFile) { if (selectedFile.type !== 'text/csv' && !selectedFile.name.endsWith('.csv')) { toast.error('Please select a valid CSV file'); return; } setFile(selectedFile); // Preview the file const reader = new FileReader(); reader.onload = (event) => { const csvContent = event.target.result; const lines = csvContent.split('\n').slice(0, 6); // Show first 5 rows setPreview(lines.join('\n')); }; reader.readAsText(selectedFile); } }; const handleSubmit = async (e) => { e.preventDefault(); if (!file) { toast.error('Please select a CSV file'); return; } setLoading(true); const formData = new FormData(); formData.append('file', file); formData.append('role', 'trainee'); formData.append('defaultPassword', 'changeme123'); importUsersMutation.mutate(formData); }; const downloadTemplate = () => { const template = `firstName,lastName,email,phone John,Doe,john.doe@example.com,+1234567890 Jane,Smith,jane.smith@example.com,+1234567891 Mike,Johnson,mike.johnson@example.com,+1234567892`; const blob = new Blob([template], { type: 'text/csv' }); const url = window.URL.createObjectURL(blob); const a = document.createElement('a'); a.href = url; a.download = 'trainees_template.csv'; a.click(); window.URL.revokeObjectURL(url); }; if (!isSuperAdmin && !isTrainer) { return (

Access Denied

You don't have permission to import users.

); } return (

Import Trainees

Upload a CSV file to create trainee accounts

{/* Upload Section */}

Upload CSV File

CSV files only

{file && (

Selected: {file.name}

)}

Important Notes

  • All imported users will have the role "trainee"
  • Default password will be "changeme123"
  • Users will be prompted to change password on first login
  • Duplicate emails will be skipped
{/* Preview Section */}

File Preview

{preview ? (

CSV Preview (first 5 rows):

                {preview}
              
) : (

No file selected

Upload a CSV file to see preview

)} {/* CSV Format Instructions */}

Required CSV Format:

Header row: firstName,lastName,email,phone

Example: John,Doe,john@example.com,+1234567890

Note: Phone number is optional

{/* Import Results */} {importResults && (

Import Results

Successfully Created

{importResults.created}

Skipped (Duplicates)

{importResults.skipped}

Errors

{importResults.errors}

{importResults.errorDetails && importResults.errorDetails.length > 0 && (

Error Details:

    {importResults.errorDetails.map((error, index) => (
  • • {error}
  • ))}
)}
)}
); }; export default UserImport;