All files / src/views UploadView.tsx

0% Statements 0/233
0% Branches 0/1
0% Functions 0/1
0% Lines 0/233

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                             
import { useCallback, useState, useEffect } from 'react'
import { useDropzone } from 'react-dropzone'
import { Box, Typography, Paper, CircularProgress, Alert, Button, Chip, Grid } from '@mui/material'
import {
  CloudUpload,
  CheckCircle,
  Error,
  HourglassEmpty,
  Visibility,
} from '@mui/icons-material'
import { useAppDispatch, useAppSelector } from '../store'
import { uploadDocument, removeDocument, addDocuments, setCurrentDocument } from '../store/documentSlice'
import { Layout } from '../components/Layout'
import { FilePreview } from '../components/FilePreview'
import { getTestFilesList, loadTestFile, filterSupportedFiles } from '../services/testFilesApi'
import type { Document } from '../types'
 
export default function UploadView() {
  const dispatch = useAppDispatch()
  const { documents, error, progressById, extractionById } = useAppSelector((state) => state.document)
  const [previewDocument, setPreviewDocument] = useState<Document | null>(null)
  const [bootstrapped, setBootstrapped] = useState(false)
 
  const onDrop = useCallback(
    (acceptedFiles: File[]) => {
      acceptedFiles.forEach((file) => {
        dispatch(uploadDocument(file))
          .unwrap()
          .then(async (doc) => {
            if (!extractionById[doc.id]) {
              const { extractDocument } = await import('../store/documentSlice')
              dispatch(extractDocument(doc.id))
            }
          })
          .catch(() => {})
      })
    },
    [dispatch, extractionById]
  )
 
  const { getRootProps, getInputProps, isDragActive } = useDropzone({
    onDrop,
    accept: {
      'application/pdf': ['.pdf'],
      'image/*': ['.png', '.jpg', '.jpeg', '.tiff'],
      'text/plain': ['.txt'],
      'text/markdown': ['.md'],
      'application/vnd.openxmlformats-officedocument.wordprocessingml.document': ['.docx'],
    },
    multiple: true,
  })
 
  const getStatusIcon = (status: string) => {
    switch (status) {
      case 'completed':
        return <CheckCircle color="success" />
      case 'error':
        return <Error color="error" />
      case 'processing':
        return <CircularProgress size={20} />
      default:
        return <HourglassEmpty color="action" />
    }
  }
 
  const getStatusColor = (status: string) => {
    switch (status) {
      case 'completed':
        return 'success'
      case 'error':
        return 'error'
      case 'processing':
        return 'warning'
      default:
        return 'default'
    }
  }
 
  // Bootstrap: charger dynamiquement les fichiers de test du dossier test-files (en dev uniquement)
  useEffect(() => {
    if (bootstrapped || !import.meta.env.DEV) return
    
    const load = async () => {
      console.log('🔄 [BOOTSTRAP] Chargement des fichiers de test...')
      
      try {
        // Récupérer la liste des fichiers disponibles
        const testFiles = await getTestFilesList()
        console.log('📁 [BOOTSTRAP] Fichiers trouvĂ©s:', testFiles.map(f => f.name))
        
        // Filtrer les fichiers supportés
        const supportedFiles = filterSupportedFiles(testFiles)
        console.log('✅ [BOOTSTRAP] Fichiers supportĂ©s:', supportedFiles.map(f => f.name))
        
        if (supportedFiles.length === 0) {
          console.log('⚠ [BOOTSTRAP] Aucun fichier de test supportĂ© trouvĂ©')
          setBootstrapped(true)
          return
        }
        
        const created: Document[] = []
        
        // Charger chaque fichier supporté
        for (const fileInfo of supportedFiles) {
          try {
            console.log(`📄 [BOOTSTRAP] Chargement de ${fileInfo.name}...`)
            const file = await loadTestFile(fileInfo.name)
            
            if (file) {
              // Simuler upload local
              const previewUrl = URL.createObjectURL(file)
              const document: Document = {
                id: `boot-${fileInfo.name}-${Date.now()}`,
                name: fileInfo.name,
                mimeType: fileInfo.type || 'application/octet-stream',
                functionalType: undefined,
                size: fileInfo.size,
                uploadDate: new Date(),
                status: 'completed',
                previewUrl,
              }
              
              created.push(document)
              console.log(`✅ [BOOTSTRAP] ${fileInfo.name} chargĂ© (${(fileInfo.size / 1024).toFixed(1)} KB)`)
            }
          } catch (error) {
            console.warn(`❌ [BOOTSTRAP] Erreur lors du chargement de ${fileInfo.name}:`, error)
          }
        }
        
        if (created.length > 0) {
          console.log(`🎉 [BOOTSTRAP] ${created.length} fichiers chargĂ©s avec succĂšs`)
          
          // Ajouter les documents au store
          dispatch(addDocuments(created))
          
          // Définir le premier document comme document courant
          dispatch(setCurrentDocument(created[0]))
          
          // Déclencher l'extraction pour afficher les barres de progression
          const { extractDocument } = await import('../store/documentSlice')
          created.forEach((doc) => {
            if (!extractionById[doc.id]) {
              console.log(`🔍 [BOOTSTRAP] DĂ©clenchement de l'extraction pour ${doc.name}`)
              dispatch(extractDocument(doc.id))
            }
          })
        } else {
          console.log('⚠ [BOOTSTRAP] Aucun fichier n\'a pu ĂȘtre chargĂ©')
        }
        
        setBootstrapped(true)
      } catch (error) {
        console.error('❌ [BOOTSTRAP] Erreur lors du chargement des fichiers de test:', error)
        setBootstrapped(true)
      }
    }
    
    load()
  }, [dispatch, bootstrapped, extractionById])
 
  return (
    <Layout>
      <Typography variant="h4" gutterBottom>
        Téléversement de documents
      </Typography>
 
      <Paper
        {...getRootProps()}
        sx={{
          p: 4,
          textAlign: 'center',
          cursor: 'pointer',
          border: '2px dashed',
          borderColor: isDragActive ? 'primary.main' : 'grey.300',
          bgcolor: isDragActive ? 'action.hover' : 'background.paper',
          '&:hover': {
            borderColor: 'primary.main',
            bgcolor: 'action.hover',
          },
        }}
      >
        <input {...getInputProps()} />
        <CloudUpload sx={{ fontSize: 48, color: 'primary.main', mb: 2 }} />
        <Typography variant="h6" gutterBottom>
          {isDragActive
            ? 'Déposez les fichiers ici...'
            : 'Glissez-déposez vos documents ou cliquez pour sélectionner'}
        </Typography>
        <Typography variant="body2" color="text.secondary">
          Formats acceptés: PDF, PNG, JPG, JPEG, TIFF, TXT, MD, DOCX
        </Typography>
      </Paper>
 
      {error && (
        <Alert severity="error" sx={{ mt: 2 }}>
          {error}
        </Alert>
      )}
 
      {documents.length > 0 && (
        <Box sx={{ mt: 3 }}>
          <Typography variant="h6" gutterBottom>
            Documents téléversés ({documents.length})
          </Typography>
 
          <Grid container spacing={2}>
            {documents.map((doc, index) => (
              <Grid size={{ xs: 12, md: 6 }} key={`${doc.id}-${index}`}>
                <Paper sx={{ p: 2 }}>
                  <Box display="flex" justifyContent="space-between" alignItems="center" mb={2}>
                    <Box display="flex" alignItems="center" gap={1}>
                      {getStatusIcon(doc.status)}
                      <Typography variant="subtitle1" noWrap>
                        {doc.name}
                      </Typography>
                    </Box>
                    <Box display="flex" gap={1}>
                      <Button
                        size="small"
                        startIcon={<Visibility />}
                        onClick={() => setPreviewDocument(doc)}
                        disabled={doc.status !== 'completed'}
                      >
                        Aperçu
                      </Button>
                      <Button
                        size="small"
                        color="error"
                        onClick={() => dispatch(removeDocument(doc.id))}
                      >
                        Supprimer
                      </Button>
                    </Box>
                  </Box>
 
                  <Box display="flex" gap={1} flexWrap="wrap" alignItems="center">
                    <Chip
                      label={doc.functionalType || doc.mimeType}
                      size="small"
                      variant="outlined"
                    />
                    <Chip
                      label={doc.status}
                      size="small"
                      color={getStatusColor(doc.status) as 'success' | 'error' | 'warning' | 'default'}
                    />
                    <Chip
                      label={`${(doc.size / 1024 / 1024).toFixed(2)} MB`}
                      size="small"
                      variant="outlined"
                    />
                    {progressById[doc.id] && (
                      <Box display="flex" alignItems="center" gap={1} sx={{ ml: 1, minWidth: 160 }}>
                        <Box sx={{ width: 70 }}>
                          <Typography variant="caption">OCR</Typography>
                          <Box sx={{ height: 6, bgcolor: 'grey.300', borderRadius: 1 }}>
                            <Box sx={{ width: `${progressById[doc.id].ocr}%`, height: '100%', bgcolor: 'primary.main', borderRadius: 1 }} />
                          </Box>
                        </Box>
                        <Box sx={{ width: 70 }}>
                          <Typography variant="caption">LLM</Typography>
                          <Box sx={{ height: 6, bgcolor: 'grey.300', borderRadius: 1 }}>
                            <Box sx={{ width: `${progressById[doc.id].llm}%`, height: '100%', bgcolor: 'info.main', borderRadius: 1 }} />
                          </Box>
                        </Box>
                      </Box>
                    )}
                  </Box>
                </Paper>
              </Grid>
            ))}
          </Grid>
        </Box>
      )}
 
      {/* Aperçu du document */}
      {previewDocument && (
        <FilePreview
          document={previewDocument}
          onClose={() => setPreviewDocument(null)}
        />
      )}
    </Layout>
  )
}