feature/rbac y perfiles implementados

This commit is contained in:
2026-05-21 08:00:43 -06:00
parent 546a411df8
commit dc5f9fd6ce
29 changed files with 2007 additions and 977 deletions

View File

@@ -1,138 +1,39 @@
/// <reference types="vite/client" />
const API_URL = import.meta.env.VITE_EFC_API_URL || 'http://localhost:8000';
import { fetchWithAuth, postWithAuth, putWithAuth, deleteWithAuth } from '../fetchWithAuth';
import { extractApiError } from './apiError';
// Función helper para manejar respuestas
async function handleResponse(response, operation = 'operación') {
console.log(`📡 ${operation} response:`, response.status, response.statusText);
if (response.status === 401) {
console.error('❌ Unauthorized - session expired');
throw new Error('SESSION_EXPIRED');
}
if (!response.ok) {
const errorText = await response.text();
console.error(`${operation} error:`, response.status, errorText);
throw new Error(`Error ${response.status}: ${response.statusText}`);
}
// Verificar que la respuesta es JSON
async function handleResponse(response: Response) {
if (response.status === 401) throw new Error('SESSION_EXPIRED');
if (!response.ok) throw new Error(await extractApiError(response));
const contentType = response.headers.get('content-type');
if (!contentType || !contentType.includes('application/json')) {
const text = await response.text();
console.error('❌ Response is not JSON:', text.substring(0, 200));
throw new Error('El servidor no devolvió JSON válido');
}
if (!contentType?.includes('application/json')) return null;
return response.json();
}
export async function fetchUsers() {
try {
const url = `${API_URL}/user/users/`;
console.log('👥 Fetching users from:', url);
const res = await fetchWithAuth(url);
const data = await handleResponse(res, 'Fetch Users');
console.log('✅ Users data received');
return data;
} catch (error) {
console.error('❌ Error in fetchUsers:', error);
if (error.name === 'TypeError' && error.message.includes('fetch')) {
throw new Error('Error de conexión al servidor');
}
throw error;
}
const res = await fetchWithAuth(`${API_URL}/user/users/`);
return handleResponse(res);
}
export async function createUser(userData) {
try {
const url = `${API_URL}/user/users/`;
console.log(' Creating user at:', url);
const res = await postWithAuth(url, userData);
const data = await handleResponse(res, 'Create User');
console.log('✅ User created successfully');
return data;
} catch (error) {
console.error('❌ Error in createUser:', error);
if (error.name === 'TypeError' && error.message.includes('fetch')) {
throw new Error('Error de conexión al servidor');
}
throw error;
}
export async function createUser(userData: object) {
const res = await postWithAuth(`${API_URL}/user/users/`, userData);
return handleResponse(res);
}
export async function updateUser(id, userData) {
try {
const url = `${API_URL}/user/users/${id}/`;
console.log('✏️ Updating user at:', url);
const res = await putWithAuth(url, userData);
const data = await handleResponse(res, 'Update User');
console.log('✅ User updated successfully');
return data;
} catch (error) {
console.error('❌ Error in updateUser:', error);
if (error.name === 'TypeError' && error.message.includes('fetch')) {
throw new Error('Error de conexión al servidor');
}
throw error;
}
export async function updateUser(id: string | number, userData: object) {
const res = await putWithAuth(`${API_URL}/user/users/${id}/`, userData);
return handleResponse(res);
}
export async function deleteUser(id) {
try {
const url = `${API_URL}/user/users/${id}/`;
console.log('🗑️ Deleting user at:', url);
const res = await deleteWithAuth(url);
if (res.status === 401) {
console.error('❌ Unauthorized - session expired');
throw new Error('SESSION_EXPIRED');
}
if (!res.ok) {
const errorText = await res.text();
console.error('❌ Delete User error:', res.status, errorText);
throw new Error(`Error ${res.status}: ${res.statusText}`);
}
console.log('✅ User deleted successfully');
return true; // DELETE suele no devolver contenido
} catch (error) {
console.error('❌ Error in deleteUser:', error);
if (error.name === 'TypeError' && error.message.includes('fetch')) {
throw new Error('Error de conexión al servidor');
}
throw error;
}
export async function deleteUser(id: string | number) {
const res = await deleteWithAuth(`${API_URL}/user/users/${id}/`);
if (res.status === 401) throw new Error('SESSION_EXPIRED');
if (!res.ok) throw new Error(await extractApiError(res));
return true;
}
export async function getCurrentUser() {
try {
const url = `${API_URL}/user/users/me/`;
console.log('👤 Fetching current user from:', url);
const res = await fetchWithAuth(url);
const data = await handleResponse(res, 'Get Current User');
console.log('✅ Current user data received:', data);
return data;
} catch (error) {
console.error('❌ Error in getCurrentUser:', error);
if (error.name === 'TypeError' && error.message.includes('fetch')) {
throw new Error('Error de conexión al servidor');
}
throw error;
}
const res = await fetchWithAuth(`${API_URL}/user/users/me/`);
return handleResponse(res);
}