photum/frontend/services/apiService.ts
NANDO9322 d84d6ff022 feat(fot): implementa cadastro e listagem de FOT
- Refatora CourseManagement para listar dados de /api/cadastro-fot
- Cria componente FotForm para novo cadastro de turmas
- Adiciona validação de unicidade para número FOT
- Integra dropdowns com endpoints /api/cursos e /api/anos-formaturas
- Corrige duplicidade no registro de profissionais no backend
2025-12-15 16:12:02 -03:00

373 lines
8.5 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,
};
}
}
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
*/
export async function getCadastroFot(token: string): Promise<ApiResponse<any[]>> {
try {
const response = await fetch(`${API_BASE_URL}/api/cadastro-fot`, {
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,
};
}
}
/**
* 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");
}
// ... existing functions ...
/**
* 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,
};
}
}