All files / src/store documentSlice.ts

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

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                                                                                                                                                                                                                                                                                                                                                                                                                       
import { createSlice, createAsyncThunk } from '@reduxjs/toolkit'
import type { PayloadAction } from '@reduxjs/toolkit'
import type { Document, ExtractionResult, AnalysisResult, ContextResult, ConseilResult } from '../types'
import { documentApi } from '../services/api'
import { openaiDocumentApi } from '../services/openai'
 
interface DocumentState {
  documents: Document[]
  currentDocument: Document | null
  extractionResult: ExtractionResult | null
  extractionById: Record<string, ExtractionResult>
  fileById: Record<string, File>
  analysisResult: AnalysisResult | null
  contextResult: ContextResult | null
  conseilResult: ConseilResult | null
  loading: boolean
  error: string | null
  progressById: Record<string, { ocr: number; llm: number }>
}
 
const initialState: DocumentState = {
  documents: [],
  currentDocument: null,
  extractionResult: null,
  extractionById: {},
  fileById: {},
  analysisResult: null,
  contextResult: null,
  conseilResult: null,
  loading: false,
  error: null,
  progressById: {},
}
 
export const uploadDocument = createAsyncThunk(
  'document/upload',
  async (file: File) => {
    return await documentApi.upload(file)
  }
)
 
export const extractDocument = createAsyncThunk(
  'document/extract',
  async (documentId: string, thunkAPI) => {
    const useOpenAI = import.meta.env.VITE_USE_OPENAI === 'true'
    if (useOpenAI) {
      const state = thunkAPI.getState() as { document: DocumentState }
      const doc = state.document.documents.find((d) => d.id === documentId)
 
      // Hooks de progression simplifiés pour éviter les boucles
      const progressHooks = {
        onOcrProgress: (p: number) => {
          console.log(`📊 [PROGRESS] OCR ${documentId}: ${Math.round(p * 100)}%`)
          // Dispatch seulement si changement significatif
          const currentProgress = (state.document.progressById[documentId]?.ocr || 0)
          if (Math.abs(p - currentProgress) > 0.1) {
            (thunkAPI.dispatch as any)(setOcrProgress({ id: documentId, progress: p }))
          }
        },
        onLlmProgress: (p: number) => {
          console.log(`📊 [PROGRESS] LLM ${documentId}: ${Math.round(p * 100)}%`)
          // Dispatch seulement si changement significatif
          const currentProgress = (state.document.progressById[documentId]?.llm || 0)
          if (Math.abs(p - currentProgress) > 0.1) {
            (thunkAPI.dispatch as any)(setLlmProgress({ id: documentId, progress: p }))
          }
        }
      }
 
      if (doc?.previewUrl) {
        try {
          const res = await fetch(doc.previewUrl)
          const blob = await res.blob()
          const file = new File([blob], doc.name, { type: doc.mimeType })
          return await openaiDocumentApi.extract(documentId, file, progressHooks)
        } catch {
          // fallback sans fichier
          return await openaiDocumentApi.extract(documentId, undefined, progressHooks)
        }
      }
      return await openaiDocumentApi.extract(documentId, undefined, progressHooks)
    }
    return await documentApi.extract(documentId)
  }
)
 
export const analyzeDocument = createAsyncThunk(
  'document/analyze',
  async (documentId: string) => {
    return await documentApi.analyze(documentId)
  }
)
 
export const getContextData = createAsyncThunk(
  'document/context',
  async (documentId: string) => {
    return await documentApi.getContext(documentId)
  }
)
 
export const getConseil = createAsyncThunk(
  'document/conseil',
  async (documentId: string) => {
    return await documentApi.getConseil(documentId)
  }
)
 
const documentSlice = createSlice({
  name: 'document',
  initialState,
  reducers: {
    setCurrentDocument: (state, action: PayloadAction<Document | null>) => {
      state.currentDocument = action.payload
    },
    clearResults: (state) => {
      state.extractionResult = null
      // Ne pas effacer extractionById pour conserver les résultats par document
      state.analysisResult = null
      state.contextResult = null
      state.conseilResult = null
    },
    addDocuments: (state, action: PayloadAction<Document[]>) => {
      const incoming = action.payload
      // Évite les doublons par (name,size) pour les bootstraps répétés en dev
      const seenKey = new Set(state.documents.map((d) => `${d.name}::${d.size}`))
      const merged = [...state.documents]
      incoming.forEach((d) => {
        const key = `${d.name}::${d.size}`
        if (!seenKey.has(key)) {
          seenKey.add(key)
          merged.push(d)
        }
      })
      state.documents = merged
    },
    removeDocument: (state, action: PayloadAction<string>) => {
      const idToRemove = action.payload
      state.documents = state.documents.filter((d) => d.id !== idToRemove)
      if (state.currentDocument && state.currentDocument.id === idToRemove) {
        state.currentDocument = null
        state.extractionResult = null
        state.analysisResult = null
        state.contextResult = null
        state.conseilResult = null
      }
      delete state.progressById[idToRemove]
    },
    setOcrProgress: (state, action: PayloadAction<{ id: string; progress: number }>) => {
      const { id, progress } = action.payload
      state.progressById[id] = { ocr: Math.max(0, Math.min(100, Math.round(progress * 100))), llm: state.progressById[id]?.llm || 0 }
    },
    setLlmProgress: (state, action: PayloadAction<{ id: string; progress: number }>) => {
      const { id, progress } = action.payload
      state.progressById[id] = { ocr: state.progressById[id]?.ocr || 0, llm: Math.max(0, Math.min(100, Math.round(progress * 100))) }
    },
  },
  extraReducers: (builder) => {
    builder
      .addCase(uploadDocument.pending, (state) => {
        state.loading = true
        state.error = null
      })
      .addCase(uploadDocument.fulfilled, (state, action) => {
        state.loading = false
        state.documents.push(action.payload)
        state.currentDocument = action.payload
        // Capture le File depuis l'URL blob si disponible
        if (action.payload.previewUrl?.startsWith('blob:')) {
          // On ne peut pas récupérer l'objet File initial ici sans passer par onDrop;
          // il est reconstruit lors de l'extraction via fetch blob.
        }
      })
      .addCase(uploadDocument.rejected, (state, action) => {
        state.loading = false
        state.error = action.error.message || 'Erreur lors du téléversement'
      })
      .addCase(extractDocument.pending, (state) => {
        state.loading = true
        state.error = null
      })
      .addCase(extractDocument.fulfilled, (state, action) => {
        state.loading = false
        state.extractionResult = action.payload
        state.extractionById[action.payload.documentId] = action.payload
      })
      .addCase(extractDocument.rejected, (state, action) => {
        state.loading = false
        state.error = action.error.message || 'Erreur lors de l\'extraction'
      })
      .addCase(analyzeDocument.fulfilled, (state, action) => {
        state.analysisResult = action.payload
      })
      .addCase(getContextData.fulfilled, (state, action) => {
        state.contextResult = action.payload
      })
      .addCase(getConseil.fulfilled, (state, action) => {
        state.conseilResult = action.payload
      })
  },
})
 
export const { setCurrentDocument, clearResults, addDocuments, removeDocument, setOcrProgress, setLlmProgress } = documentSlice.actions
export const documentReducer = documentSlice.reducer