photum/frontend/services/apiService.ts
NANDO9322 cd196a0275 feat(auth): adiciona tipo profissional ao schema e corrige avatar
- Adiciona coluna `tipo_profissional` à tabela `usuarios`
- Atualiza handlers e services do Backend Go para persistir o tipo
- Atualiza registro no Frontend para enviar o nome da função (ex: "Cinegrafista")
- Corrige uploads S3 para compatibilidade com Civo (PathStyle)
- Script para definir política pública de leitura no bucket S3
- Adiciona fallback para imagens de avatar na Navbar
2025-12-22 12:37:42 -03:00

703 lines
18 KiB
TypeScript

// Serviço para comunicação com o backend
const API_BASE_URL =
import.meta.env.VITE_API_URL || "http://localhost:3000/api";
interface ApiResponse<T> {
data: T | null;
error: string | null;
isBackendDown: boolean;
}
// Função auxiliar para fazer requisições
async function fetchFromBackend<T>(endpoint: string): Promise<ApiResponse<T>> {
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<ApiResponse<string[]>> {
return fetchFromBackend<string[]>("/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<ApiResponse<any>> {
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,
};
}
}
/**
* Busca a lista de profissionais
*/
export async function getProfessionals(token: string): Promise<ApiResponse<any[]>> {
try {
const response = await fetch(`${API_BASE_URL}/api/profissionais`, {
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 professionals:", 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<EventTypeResponse[]>
> {
return fetchFromBackend<EventTypeResponse[]>("/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<ApiResponse<Array<{ id: string; ano_semestre: string }>>> {
return fetchFromBackend<Array<{ id: string; ano_semestre: string }>>("/api/anos-formaturas");
}
/**
* Busca os cursos disponíveis
*/
export async function getAvailableCourses(): Promise<ApiResponse<Array<{ id: string; nome: string }>>> {
return fetchFromBackend<Array<{ id: string; nome: string }>>("/api/cursos");
}
/**
* Busca a listagem de Cadastro FOT
*/
/**
* Busca a listagem de Cadastro FOT
*/
export async function getCadastroFot(token: string, empresaId?: string): Promise<ApiResponse<any[]>> {
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<ApiResponse<any>> {
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,
};
}
}
/**
* Atualiza um cadastro FOT existente
*/
export async function updateCadastroFot(id: string, data: any, token: string): Promise<ApiResponse<any>> {
try {
const response = await fetch(`${API_BASE_URL}/api/cadastro-fot/${id}`, {
method: "PUT",
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 updating cadastro fot:", error);
return {
data: null,
error: error instanceof Error ? error.message : "Erro desconhecido",
isBackendDown: true,
};
}
}
/**
* Remove um cadastro FOT
*/
export async function deleteCadastroFot(id: string, token: string): Promise<ApiResponse<void>> {
try {
const response = await fetch(`${API_BASE_URL}/api/cadastro-fot/${id}`, {
method: "DELETE",
headers: {
"Content-Type": "application/json",
"Authorization": `Bearer ${token}`
},
});
if (!response.ok) {
const errorData = await response.json().catch(() => ({}));
throw new Error(errorData.error || `HTTP error! status: ${response.status}`);
}
return {
data: null,
error: null,
isBackendDown: false,
};
} catch (error) {
console.error("Error deleting 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<ApiResponse<any[]>> => {
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 };
}
};
export const updateAssignmentStatus = async (token: string, eventId: string, professionalId: string, status: string, reason?: string) => {
try {
const response = await fetch(`${API_BASE_URL}/api/agenda/${eventId}/professionals/${professionalId}/status`, {
method: "PATCH",
headers: {
Authorization: `Bearer ${token}`,
"Content-Type": "application/json",
},
body: JSON.stringify({ status, reason }),
});
if (!response.ok) {
const errorData = await response.json().catch(() => ({}));
return { error: errorData.error || "Failed to update assignment status" };
}
const data = await response.json();
return { data };
} catch (error) {
console.error("API updateAssignmentStatus error:", error);
return { error: "Network error" };
}
};
/**
* Busca usuários pendentes de aprovação
*/
export async function getPendingUsers(token: string): Promise<ApiResponse<any[]>> {
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<ApiResponse<any>> {
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<ApiResponse<any>> {
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,
};
}
}
/**
* Atribui um profissional a um evento
*/
export async function assignProfessional(token: string, eventId: string, professionalId: string): Promise<ApiResponse<void>> {
try {
const response = await fetch(`${API_BASE_URL}/api/agenda/${eventId}/professionals`, {
method: "POST",
headers: {
"Content-Type": "application/json",
"Authorization": `Bearer ${token}`
},
body: JSON.stringify({ professional_id: professionalId })
});
if (!response.ok) {
throw new Error(`HTTP error! status: ${response.status}`);
}
return { data: undefined, error: null, isBackendDown: false };
} catch (error) {
console.error("Error assigning professional:", error);
return { data: null, error: error instanceof Error ? error.message : "Erro desconhecido", isBackendDown: true };
}
}
/**
* Remove um profissional de um evento
*/
export async function removeProfessional(token: string, eventId: string, professionalId: string): Promise<ApiResponse<void>> {
try {
const response = await fetch(`${API_BASE_URL}/api/agenda/${eventId}/professionals/${professionalId}`, {
method: "DELETE",
headers: {
"Content-Type": "application/json",
"Authorization": `Bearer ${token}`
}
});
if (!response.ok) {
throw new Error(`HTTP error! status: ${response.status}`);
}
return { data: undefined, error: null, isBackendDown: false };
} catch (error) {
console.error("Error removing professional:", error);
return { data: null, error: error instanceof Error ? error.message : "Erro desconhecido", isBackendDown: true };
}
}
/**
* Busca profissionais de um evento
*/
export async function getEventProfessionals(token: string, eventId: string): Promise<ApiResponse<any[]>> {
try {
const response = await fetch(`${API_BASE_URL}/api/agenda/${eventId}/professionals`, {
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 event professionals:", error);
return { data: null, error: error instanceof Error ? error.message : "Erro desconhecido", isBackendDown: true };
}
}
/**
* Atualiza o status de um evento
*/
export async function updateEventStatus(token: string, eventId: string, status: string): Promise<ApiResponse<void>> {
try {
const response = await fetch(`${API_BASE_URL}/api/agenda/${eventId}/status`, {
method: "PATCH",
headers: {
"Content-Type": "application/json",
"Authorization": `Bearer ${token}`
},
body: JSON.stringify({ status })
});
if (!response.ok) {
throw new Error(`HTTP error! status: ${response.status}`);
}
return { data: undefined, error: null, isBackendDown: false };
} catch (error) {
console.error("Error updating event status:", error);
return { data: null, error: error instanceof Error ? error.message : "Erro desconhecido", isBackendDown: true };
}
}
/**
* Obtém URL pré-assinada para upload de arquivo
*/
export async function getUploadURL(filename: string, contentType: string): Promise<ApiResponse<{ upload_url: string; public_url: string }>> {
try {
const response = await fetch(`${API_BASE_URL}/auth/upload-url`, {
method: "POST",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify({ filename, content_type: contentType }),
});
if (!response.ok) {
const errorData = await response.json().catch(() => ({}));
throw new Error(errorData.error || `HTTP error! status: ${response.status}`);
}
const data = await response.json();
return {
data,
error: null,
isBackendDown: false,
};
} catch (error) {
console.error("Error fetching upload URL:", error);
return {
data: null,
error: error instanceof Error ? error.message : "Erro desconhecido",
isBackendDown: true,
};
}
}
/**
* Realiza o upload do arquivo para a URL pré-assinada
*/
export async function uploadFileToSignedUrl(uploadUrl: string, file: File): Promise<void> {
const response = await fetch(uploadUrl, {
method: "PUT",
headers: {
"Content-Type": file.type,
},
body: file,
});
if (!response.ok) {
throw new Error(`Failed to upload file to S3. Status: ${response.status}`);
}
}