All files / apps/web/src/services api.js

70% Statements 70/100
90.19% Branches 46/51
25.71% Functions 9/35
71.27% Lines 67/94

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      2x   2x             2x 12x 12x 1x     12x 12x 50x   12x 12x 12x   12x 12x   12x 12x   12x 2x     12x     2x 1x   3x 2x 3x 2x 1x 1x     3x             2x                   4x 4x 1x     3x 3x   3x 1x 1x             2x 1x           1x       3x   3x 1x 2x 2x 11x   2x 1x   1x       3x       2x                                   2x 2x     2x   2x               2x               2x 3x     3x 3x 1x   3x           3x 1x 1x     2x     2x              
import axios from 'axios'
import { getOrganizationId } from '../utils/organization'
 
const API_URL = import.meta.env.VITE_API_URL || 'http://localhost:8000'
 
const api = axios.create({
  baseURL: `${API_URL}/api/v1`,
  headers: {
    'Content-Type': 'application/json',
  },
})
 
api.interceptors.request.use((config) => {
  const token = localStorage.getItem('accessToken')
  if (token) {
    config.headers.Authorization = `Bearer ${token}`
  }
  
  const orgId = getOrganizationId()
  const noOrgPrefixPatterns = ['/auth/', '/organizations', '/admin/', '/users', '/plans']
  const shouldNotAddOrgPrefix = noOrgPrefixPatterns.some(pattern => config.url.includes(pattern))
  
  const urlSegments = config.url.split('/')
  const firstSegment = urlSegments[1]
  const startsWithOrgId = firstSegment && firstSegment.length >= 20 && /^[a-f0-9]+$/i.test(firstSegment)
  
  const resourceIdPattern = /\/(agents?|crawlers?|workflows?|schedules?|knowledge-bases?|knowledge-routers?|sessions?|jobs?)\/([a-f0-9]{24}|[a-f0-9\-]{36})/i
  const hasResourceId = resourceIdPattern.test(config.url)
  
  const isPostRequest = config.method.toLowerCase() === 'post'
  const isConfigTestRequest = config.url.includes('/config/test/')
  
  if (orgId && !shouldNotAddOrgPrefix && !startsWithOrgId && !hasResourceId && (!isPostRequest || isConfigTestRequest)) {
    config.url = `/${orgId}${config.url}`
  }
  
  return config
})
 
api.interceptors.response.use(
  (response) => response,
  (error) => {
    if (error.response?.status === 401) {
      const publicPatterns = ['/agents/', '/sessions/'];
      const isPublicRoute = publicPatterns.some(p => error.config?.url?.includes(p));
      if (!isPublicRoute) {
        localStorage.removeItem('accessToken')
        window.location.href = '/login'
      }
    }
    return Promise.reject(error)
  }
)
 
export default api
export { API_URL }
 
export const workflowAPI = {
  getStatus: () => api.get('/workflow/status'),
  list: () => api.get('/workflows'),
  listConfigs: () => api.get('/workflows'),
  getConfig: (id) => api.get(`/workflows/${id}`),
  createConfig: (config) => api.post('/workflows', config),
  updateConfig: (id, config) => api.put(`/workflows/${id}`, config),
  deleteConfig: (id) => api.delete(`/workflows/${id}`),
  
  extract: async (source, options = {}) => {
    const workflowId = options.workflowId || options.configId || options.config_id
    if (!workflowId) {
      throw new Error('workflowId est requis dans options')
    }
    
    const orgId = getOrganizationId()
    const { workflowId: _, configId: __, config_id: ___, ...body } = options
    
    if (source && typeof source === 'object') {
      Eif (source.url || source.fileUrl || source.fileId) {
        return api.post(`/${orgId}/workflow/${workflowId}/extract`, {
          ...source,
          ...body
        })
      }
    }
    
    if (typeof source === 'string') {
      return api.post(`/${orgId}/workflow/${workflowId}/extract`, {
        url: source,
        ...body
      })
    }
    
    throw new Error('Source invalide. Fournissez { url }, { fileUrl }, ou { fileId }')
  },
 
  extractGeneric: async (source, config) => {
    const body = { ...config }
    
    if (source && typeof source === 'object' && source.fileId) {
      body.fileId = source.fileId
    } else Eif (typeof source === 'string') {
      const fileExtensions = ['.pdf', '.docx', '.xlsx', '.pptx', '.doc', '.xls', '.ppt', '.png', '.jpg', '.jpeg']
      const isFileUrl = fileExtensions.some(ext => source.toLowerCase().endsWith(ext))
      
      if (isFileUrl) {
        body.fileUrl = source
      } else {
        body.url = source
      }
    }
    
    return api.post('/workflow/extract', body)
  }
}
 
export const jobAPI = {
  getJobStatus: (jobId) => api.get(`/jobs/${jobId}/status`),
  getJobResults: (jobId) => api.get(`/jobs/${jobId}/results`),
  
  createEventSource: (jobId, token) => {
    let url = `${API_URL}/jobs/${jobId}/status`
    return new EventSource(url)
  },
  
  createSSEReadableStream: (jobId, token) => {
    const headers = {
      'Authorization': `Bearer ${token}`,
      'Accept': 'text/event-stream'
    }
    return fetch(`/jobs/${jobId}/status`, { headers })
  }
}
 
export const listKnowledgeBases = () => api.get('/knowledge-bases')
export const searchKnowledgeBase = (id, params) => {
  return api.post(`/knowledge-bases/${id}/search/nooloom`, params);
}
export const createCrawlerJob = (config) => api.post('/jobs', config)
 
export const agentConfigAPI = {
  list: () => api.get('/agents'),
  get: (id) => api.get(`/agents/${id}`),
  create: (config) => api.post('/agents', config),
  update: (id, config) => api.put(`/agents/${id}`, config),
  delete: (id) => api.delete(`/agents/${id}`)
}
 
export const agentExecutionAPI = {
  listSessions: (agentId) => api.get(`/agents/${agentId}/sessions`),
  createSession: (orgId, agentId) => api.post(`/agents/${agentId}/sessions`, {}),
  getSession: (sessionId) => api.get(`/sessions/${sessionId}`),
  getMessages: (sessionId) => api.get(`/sessions/${sessionId}/messages`),
  sendMessage: (sessionId, content) => api.post(`/sessions/${sessionId}/messages`, { content })
}
 
export const sendStreamMessage = async (sessionId, content) => {
  const headers = {
    'Content-Type': 'application/json',
  };
  const token = localStorage.getItem('accessToken');
  if (token) {
    headers['Authorization'] = `Bearer ${token}`;
  }
  const response = await fetch(`${API_URL}/api/v1/sessions/${sessionId}/messages/stream`, {
    method: 'POST',
    headers,
    body: JSON.stringify({ content })
  });
 
  if (!response.ok) {
    const err = await response.json().catch(() => ({}));
    throw new Error(err.message || `HTTP ${response.status}`);
  }
 
  return response.body.getReader();
};
 
export const uploadFile = (file, organizationId) => {
  const formData = new FormData()
  formData.append('file', file)
  return api.post(`/${organizationId}/upload`, formData, {
    headers: { 'Content-Type': 'multipart/form-data' }
  })
}