All files / src/services api.ts

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

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                                                                                                                                                                                                                                                                                                                                                                           
import axios from 'axios'
import { openaiDocumentApi, openaiExternalApi } from './openai'
import type { Document, ExtractionResult, AnalysisResult, ContextResult, ConseilResult } from '../types'
 
const BASE_URL = import.meta.env.VITE_API_URL || 'http://localhost:8000'
const USE_OPENAI = import.meta.env.VITE_USE_OPENAI === 'true'
 
// Debug non-invasif en dev pour vérifier la lecture du .env
if (import.meta.env.DEV) {
  const maskedKey = (import.meta.env.VITE_OPENAI_API_KEY || '')
    .toString()
    .replace(/.(?=.{4})/g, '*')
  // eslint-disable-next-line no-console
  console.info('[ENV] VITE_API_URL=', BASE_URL, 'VITE_USE_AI=', USE_OPENAI, 'VITE_AI_API_KEY=', maskedKey)
}
 
export const apiClient = axios.create({
  baseURL: BASE_URL,
  timeout: 60000,
})
 
// Intercepteur pour les erreurs
apiClient.interceptors.response.use(
  (response) => response,
  (error) => {
    // Laisser remonter les erreurs au consommateur
    return Promise.reject(error)
  }
)
 
// Services API pour les documents
export const documentApi = {
  // Téléversement de document
  upload: async (file: File): Promise<Document> => {
    if (USE_OPENAI) return openaiDocumentApi.upload(file)
    const formData = new FormData()
    formData.append('file', file)
    const { data } = await apiClient.post('/api/notary/upload', formData)
 
    // L'API retourne {message, document_id, status}
    // On doit mapper vers le format Document attendu
    const fileUrl = URL.createObjectURL(file)
    return {
      id: data.document_id || data.id || 'upload-' + Date.now(),
      name: file.name,
      mimeType: data.mime_type || data.mimeType || file.type || 'application/pdf',
      functionalType: data.functional_type || data.functionalType || undefined,
      size: file.size,
      uploadDate: new Date(),
      status: 'completed',
      previewUrl: fileUrl
    }
  },
 
  // Extraction des données
  extract: async (documentId: string): Promise<ExtractionResult> => {
    if (USE_OPENAI) {
      // En mode OpenAI, nous n’avons pas le fichier original côté service.
      // Le texte a été approximé à l’upload. On tente néanmoins l’extraction textuelle côté OpenAI sans fichier.
      return openaiDocumentApi.extract(documentId)
    }
    const { data } = await apiClient.get(`/api/notary/documents/${documentId}`)
 
    // Mapper les données de l'API vers le format ExtractionResult
    const results = data.results || {}
    return {
      documentId,
      text: results.ocr_text || 'Texte extrait du document...',
      language: 'fr',
      documentType: results.document_type || 'Document',
      identities: results.entities?.persons?.map((name: string, index: number) => ({
        id: `person-${index}`,
        type: 'person' as const,
        firstName: name.split(' ')[0] || name,
        lastName: name.split(' ').slice(1).join(' ') || '',
        birthDate: '',
        nationality: 'Française',
        confidence: 0.9,
      })) || [],
      addresses: results.entities?.addresses?.map((address: string) => ({
        street: address,
        city: 'Paris',
        postalCode: '75001',
        country: 'France',
      })) || [],
      properties: results.entities?.properties?.map((_propertyName: string, index: number) => ({
        id: `prop-${index}`,
        type: 'apartment' as const,
        address: {
          street: '123 Rue de la Paix',
          city: 'Paris',
          postalCode: '75001',
          country: 'France',
        },
        surface: 75,
        cadastralReference: '1234567890AB',
        value: 250000,
      })) || [],
      contracts: [
        {
          id: 'contract-1',
          type: 'sale' as const,
          parties: [],
          amount: 250000,
          date: '2024-01-15',
          clauses: ['Clause de garantie', 'Clause de condition suspensive'],
        },
      ],
      signatures: results.entities?.persons || [],
      confidence: results.verification_score || 0.85,
    }
  },
 
  // Analyse du document
  analyze: async (documentId: string): Promise<AnalysisResult> => {
    if (USE_OPENAI) return openaiDocumentApi.analyze(documentId)
    const { data } = await apiClient.get<AnalysisResult>(`/api/documents/${documentId}/analyze`)
    return data
  },
 
  // Données contextuelles
  getContext: async (documentId: string): Promise<ContextResult> => {
    if (USE_OPENAI) return openaiDocumentApi.getContext(documentId)
    const { data } = await apiClient.get<ContextResult>(`/api/documents/${documentId}/context`)
    return data
  },
 
  // Conseil LLM
  getConseil: async (documentId: string): Promise<ConseilResult> => {
    if (USE_OPENAI) return openaiDocumentApi.getConseil(documentId)
    const { data } = await apiClient.get<ConseilResult>(`/api/documents/${documentId}/conseil`)
    return data
  },
 
  // Détection du type de document
  detectType: async (file: File): Promise<{ type: string; confidence: number }> => {
    if (USE_OPENAI) return openaiDocumentApi.detectType(file)
    const formData = new FormData()
    formData.append('file', file)
    const { data } = await apiClient.post('/api/ocr/detect', formData)
    return data
  },
}
 
// Services API pour les données externes
export const externalApi = {
  // Cadastre via backend
  cadastre: async (address: string) => {
    if (USE_OPENAI) return openaiExternalApi.cadastre(address)
    const { data } = await apiClient.get('/api/context/cadastre', { params: { q: address } })
    return data
  },
 
  // Géorisques via backend
  georisques: async (coordinates: { lat: number; lng: number }) => {
    if (USE_OPENAI) return openaiExternalApi.georisques(coordinates)
    const { data } = await apiClient.get('/api/context/georisques', { params: coordinates })
    return data
  },
 
  // Géofoncier via backend
  geofoncier: async (address: string) => {
    if (USE_OPENAI) return openaiExternalApi.geofoncier(address)
    const { data } = await apiClient.get('/api/context/geofoncier', { params: { address } })
    return data
  },
 
  // BODACC via backend
  bodacc: async (companyName: string) => {
    if (USE_OPENAI) return openaiExternalApi.bodacc(companyName)
    const { data } = await apiClient.get('/api/context/bodacc', { params: { q: companyName } })
    return data
  },
 
  // Infogreffe via backend
  infogreffe: async (siren: string) => {
    if (USE_OPENAI) return openaiExternalApi.infogreffe(siren)
    const { data } = await apiClient.get('/api/context/infogreffe', { params: { siren } })
    return data
  },
}