// Serviço para comunicação com o backend const API_BASE_URL = import.meta.env.VITE_API_URL || "http://localhost:3000/api"; interface ApiResponse { data: T | null; error: string | null; isBackendDown: boolean; } // Função auxiliar para fazer requisições async function fetchFromBackend(endpoint: string): Promise> { try { const response = await fetch(`${API_BASE_URL}${endpoint}`, { method: "GET", headers: { "Content-Type": "application/json", }, }); if (!response.ok) { throw new Error(`HTTP error! status: ${response.status}`); } const data = await response.json(); return { data, error: null, isBackendDown: false, }; } catch (error) { console.error(`Error fetching ${endpoint}:`, error); return { data: null, error: error instanceof Error ? error.message : "Erro desconhecido", isBackendDown: true, }; } } // Funções específicas para cada endpoint /** * Busca as funções profissionais disponíveis */ export async function getProfessionalRoles(): Promise> { return fetchFromBackend("/professional-roles"); } /** * Busca as empresas disponíveis */ export async function getCompanies(): Promise< ApiResponse< Array<{ id: string; nome: string; }> > > { return fetchFromBackend("/api/empresas"); } /** * Busca as funções profissionais disponíveis do backend */ export async function getFunctions(): Promise< ApiResponse< Array<{ id: string; nome: string; }> > > { return fetchFromBackend("/api/funcoes"); } /** * Cria um novo perfil profissional */ export async function createProfessional(data: any, token?: string): Promise> { try { const headers: any = { "Content-Type": "application/json", }; if (token) { headers["Authorization"] = `Bearer ${token}`; } const response = await fetch(`${API_BASE_URL}/api/profissionais`, { method: "POST", headers: headers, body: JSON.stringify(data), }); if (!response.ok) { const errorData = await response.json().catch(() => ({})); throw new Error(errorData.error || `HTTP error! status: ${response.status}`); } const responseData = await response.json(); return { data: responseData, error: null, isBackendDown: false, }; } catch (error) { console.error("Error creating professional:", error); return { data: null, error: error instanceof Error ? error.message : "Erro desconhecido", isBackendDown: true, }; } } export interface EventTypeResponse { id: string; nome: string; precos: any[]; } /** * Busca os tipos de eventos disponíveis */ export async function getEventTypes(): Promise< ApiResponse > { return fetchFromBackend("/api/tipos-eventos"); } /** * Busca os cursos/turmas disponíveis */ export async function getCourses(): Promise< ApiResponse< Array<{ id: string; name: string; institution: string; year: number; }> > > { return fetchFromBackend("/courses"); } /** * Busca as instituições/empresas disponíveis */ export async function getInstitutions(): Promise< ApiResponse< Array<{ id: string; name: string; }> > > { return fetchFromBackend("/institutions"); } /** * Busca os anos de formatura disponíveis */ export async function getGraduationYears(): Promise>> { return fetchFromBackend>("/api/anos-formaturas"); } /** * Busca os cursos disponíveis */ export async function getAvailableCourses(): Promise>> { return fetchFromBackend>("/api/cursos"); } /** * Busca a listagem de Cadastro FOT */ /** * Busca a listagem de Cadastro FOT */ export async function getCadastroFot(token: string, empresaId?: string): Promise> { try { let url = `${API_BASE_URL}/api/cadastro-fot`; if (empresaId) { url += `?empresa_id=${empresaId}`; } const response = await fetch(url, { method: "GET", headers: { "Content-Type": "application/json", "Authorization": `Bearer ${token}` }, }); if (!response.ok) { throw new Error(`HTTP error! status: ${response.status}`); } const data = await response.json(); return { data, error: null, isBackendDown: false, }; } catch (error) { console.error("Error fetching cadastro fot:", error); return { data: null, error: error instanceof Error ? error.message : "Erro desconhecido", isBackendDown: true, }; } } /** * Cria um novo cadastro FOT */ export async function createCadastroFot(data: any, token: string): Promise> { try { const response = await fetch(`${API_BASE_URL}/api/cadastro-fot`, { method: "POST", headers: { "Content-Type": "application/json", "Authorization": `Bearer ${token}` }, body: JSON.stringify(data), }); if (!response.ok) { const errorData = await response.json().catch(() => ({})); throw new Error(errorData.error || `HTTP error! status: ${response.status}`); } const responseData = await response.json(); return { data: responseData, error: null, isBackendDown: false, }; } catch (error) { console.error("Error creating cadastro fot:", error); return { data: null, error: error instanceof Error ? error.message : "Erro desconhecido", isBackendDown: true, }; } } /** * Busca os níveis educacionais disponíveis (EF I / EF II) */ export async function getEducationLevels(): Promise< ApiResponse< Array<{ id: string; nome: string; }> > > { return fetchFromBackend("/api/niveis-educacionais"); } /** * Busca as universidades cadastradas */ export async function getUniversities(): Promise< ApiResponse< Array<{ id: string; nome: string; }> > > { return fetchFromBackend("/api/universidades"); } // Agenda export const createAgenda = async (token: string, data: any) => { try { const response = await fetch(`${API_BASE_URL}/api/agenda`, { method: "POST", headers: { "Content-Type": "application/json", "Authorization": `Bearer ${token}` }, body: JSON.stringify(data), }); if (!response.ok) { const errorData = await response.json().catch(() => ({})); throw new Error(errorData.error || `HTTP error! status: ${response.status}`); } const responseData = await response.json(); return { data: responseData, error: null }; } catch (error: any) { console.error("Erro ao criar agenda:", error); return { data: null, error: error.message || "Erro ao criar agenda" }; } }; // Agenda export const getAgendas = async (token: string): Promise> => { try { const response = await fetch(`${API_BASE_URL}/api/agenda`, { method: "GET", headers: { "Content-Type": "application/json", "Authorization": `Bearer ${token}` }, }); if (!response.ok) { throw new Error(`HTTP error! status: ${response.status}`); } const data = await response.json(); return { data, error: null, isBackendDown: false }; } catch (error: any) { console.error("Erro ao buscar agendas:", error); return { data: null, error: error.message || "Erro ao buscar agendas", isBackendDown: true }; } }; /** * Busca usuários pendentes de aprovação */ export async function getPendingUsers(token: string): Promise> { try { const response = await fetch(`${API_BASE_URL}/api/admin/users/pending`, { method: "GET", headers: { "Content-Type": "application/json", "Authorization": `Bearer ${token}` }, }); if (!response.ok) { throw new Error(`HTTP error! status: ${response.status}`); } const data = await response.json(); return { data, error: null, isBackendDown: false, }; } catch (error) { console.error("Error fetching pending users:", error); return { data: null, error: error instanceof Error ? error.message : "Erro desconhecido", isBackendDown: true, }; } } /** * Aprova um usuário */ export async function approveUser(userId: string, token: string): Promise> { try { const response = await fetch(`${API_BASE_URL}/api/admin/users/${userId}/approve`, { method: "PATCH", headers: { "Content-Type": "application/json", "Authorization": `Bearer ${token}` }, }); if (!response.ok) { throw new Error(`HTTP error! status: ${response.status}`); } const data = await response.json(); return { data, error: null, isBackendDown: false, }; } catch (error) { console.error("Error approving user:", error); return { data: null, error: error instanceof Error ? error.message : "Erro desconhecido", isBackendDown: true, }; } } /** * Rejeita um usuário */ export async function rejectUser(userId: string, token: string): Promise> { try { const response = await fetch(`${API_BASE_URL}/api/admin/users/${userId}/reject`, { method: "PATCH", headers: { "Content-Type": "application/json", "Authorization": `Bearer ${token}` }, // body: JSON.stringify({ reason }) // Future improvement }); if (!response.ok) { throw new Error(`HTTP error! status: ${response.status}`); } const data = await response.json(); return { data, error: null, isBackendDown: false, }; } catch (error) { console.error("Error rejecting user:", error); return { data: null, error: error instanceof Error ? error.message : "Erro desconhecido", isBackendDown: true, }; } }