Se soluciono autenticacion

This commit is contained in:
2025-08-05 13:06:24 -06:00
parent c280afe646
commit c9df4e3ab2
21 changed files with 758 additions and 624 deletions

View File

@@ -1,4 +1,5 @@
// src/api/pedimentoDocuments.ts
import { fetchWithAuth } from '../fetchWithAuth';
export interface PedimentoDocument {
id: string;
@@ -23,8 +24,6 @@ export interface PedimentoDocumentsResponse {
const API_URL = import.meta.env.VITE_EFC_API_URL;
export async function fetchPedimentoDocuments(
token: string,
pedimentoId: string = '',
page: number = 1,
pageSize: number = 10,
filters: {
@@ -32,7 +31,8 @@ export async function fetchPedimentoDocuments(
extension?: string;
document_type?: string | number;
created_at?: string;
} = {}
} = {},
pedimentoId: string = ''
): Promise<PedimentoDocumentsResponse> {
const params = new URLSearchParams();
params.append('page', String(page));
@@ -43,18 +43,10 @@ export async function fetchPedimentoDocuments(
if (filters.document_type) params.append('document_type', String(filters.document_type));
if (filters.created_at) params.append('created_at', filters.created_at);
const res = await fetch(
`${API_URL}/record/documents/?${params.toString()}`,
{
headers: {
'Authorization': `Bearer ${token}`,
'Content-Type': 'application/json',
},
}
const res = await fetchWithAuth(
`${API_URL}/record/documents/?${params.toString()}`
);
if (res.status === 401) {
throw new Error('SESSION_EXPIRED');
}
if (!res.ok) throw new Error('No autorizado o error en la petición');
return res.json();
}

View File

@@ -1,4 +1,5 @@
import { fetchWithAuth } from '../fetchWithAuth';
export interface Document {
id: string;
@@ -19,8 +20,6 @@ export interface DocumentsResponse {
results: Document[];
}
import { refreshToken } from './auth';
const API_URL = import.meta.env.VITE_EFC_API_URL;
// Obtiene la lista de documentos (pedimentos)
export interface PedimentosFilters {
@@ -38,7 +37,6 @@ export interface PedimentosFilters {
}
export async function fetchDocuments(
token: string,
page: number = 1,
pageSize: number = 10,
filters: PedimentosFilters = {}
@@ -51,65 +49,14 @@ export async function fetchDocuments(
params.append(key, String(value));
}
});
let res = await fetch(`${API_URL}/customs/pedimentos/?${params.toString()}`, {
headers: {
'Authorization': `Bearer ${token}`,
'Content-Type': 'application/json',
},
});
if (res.status === 401) {
// Intentar refrescar el token
const refresh = localStorage.getItem('refresh');
if (refresh) {
try {
const data = await refreshToken(refresh);
localStorage.setItem('access', data.access);
// Reintenta la petición con el nuevo access token
res = await fetch(`${API_URL}/customs/pedimentos/?page=${page}&page_size=${pageSize}`, {
headers: {
'Authorization': `Bearer ${data.access}`,
'Content-Type': 'application/json',
},
});
} catch (err) {
throw new Error('SESSION_EXPIRED');
}
} else {
throw new Error('SESSION_EXPIRED');
}
}
const res = await fetchWithAuth(`${API_URL}/customs/pedimentos/?${params.toString()}`);
if (!res.ok) throw new Error('No autorizado o error en la petición');
return res.json();
}
// Obtiene los documentos por id de pedimento
export async function fetchDocumentById(token: string, id: string): Promise<DocumentsResponse> {
let res = await fetch(`${API_URL}/record/documents/?page=1&page_size=10&pedimento=${id}/`, {
headers: {
'Authorization': `Bearer ${token}`,
'Content-Type': 'application/json',
},
});
if (res.status === 401) {
// Intentar refrescar el token
const refresh = localStorage.getItem('refresh');
if (refresh) {
try {
const data = await refreshToken(refresh);
localStorage.setItem('access', data.access);
// Reintenta la petición con el nuevo access token
res = await fetch(`${API_URL}/record/documents/?page=1&page_size=10&pedimento=${id}/`, {
headers: {
'Authorization': `Bearer ${data.access}`,
'Content-Type': 'application/json',
},
});
} catch (err) {
throw new Error('SESSION_EXPIRED');
}
} else {
throw new Error('SESSION_EXPIRED');
}
}
export async function fetchDocumentById(id: string): Promise<DocumentsResponse> {
const res = await fetchWithAuth(`${API_URL}/record/documents/?page=1&page_size=10&pedimento=${id}/`);
if (!res.ok) throw new Error('No autorizado o error en la petición');
return res.json();
}

View File

@@ -1,15 +1,9 @@
import { fetchWithAuth, putWithAuth } from '../fetchWithAuth';
// PUT para marcar una notificación como vista
export async function marcarNotificacionComoVista(id: number): Promise<Notificacion> {
const token = localStorage.getItem('access');
const url = `${API_URL}/notificaciones/notificaciones/${id}/`;
const headers = new Headers();
if (token) headers.append('Authorization', `Bearer ${token}`);
headers.append('Content-Type', 'application/json');
const res = await fetch(url, {
method: 'PUT',
headers,
body: JSON.stringify({ visto: true })
});
const res = await putWithAuth(url, { visto: true });
if (!res.ok) throw new Error('Error al actualizar notificación');
return await res.json();
}
@@ -41,28 +35,16 @@ export interface NotificacionesResponse {
const API_URL = import.meta.env.VITE_EFC_API_URL;
export async function fetchNotificaciones({ page = 1, pageSize = 10, visto = false } = {}): Promise<NotificacionesResponse> {
const token = localStorage.getItem('access');
const url = `${API_URL}/notificaciones/notificaciones/?page=${page}&page_size=${pageSize}&visto=${visto}`;
const headers = new Headers();
if (token) headers.append('Authorization', `Bearer ${token}`);
headers.append('Content-Type', 'application/json');
const res = await fetch(url, {
headers,
});
const res = await fetchWithAuth(url);
if (!res.ok) throw new Error('Error al obtener notificaciones');
return await res.json();
}
export async function fetchAllNotifications({page = 1, page_size=10}): Promise<NotificacionesResponse>{
const token = localStorage.getItem('access');
const url = `${API_URL}/notificaciones/notificaciones/?page=${page}&page_size=${page_size}`;
const headers = new Headers();
if (token) headers.append('Authorization', `Bearer ${token}`);
headers.append('Content-Type', 'application/json');
const res = await fetch(url, {
headers,
});
const res = await fetchWithAuth(url);
if (!res.ok) throw new Error('Error al obtener notificaciones');
return await res.json();
}

View File

@@ -1,5 +1,6 @@
// organization.ts
// Tipos para la respuesta del endpoint de uso de almacenamiento de organización
import { fetchWithAuth } from '../fetchWithAuth';
export interface OrganizationUsage {
organizacion: string;
@@ -16,16 +17,9 @@ export interface OrganizationUsage {
const API_URL = import.meta.env.VITE_EFC_API_URL;
// Ejemplo de función para obtener la información tipada
export async function fetchOrganizationUsage(token: string): Promise<OrganizationUsage> {
const res = await fetch(`${API_URL}/organization/uso-almacenamiento/mi_organizacion/`, {
headers: {
'Authorization': `Bearer ${token}`,
'Content-Type': 'application/json',
},
});
if (res.status === 401) {
throw new Error('SESSION_EXPIRED');
}
export async function fetchOrganizationUsage(): Promise<OrganizationUsage> {
const res = await fetchWithAuth(`${API_URL}/organization/uso-almacenamiento/mi_organizacion/`);
if (!res.ok) {
throw new Error('Error al obtener información de la organización');
}

View File

@@ -1,4 +1,5 @@
// src/api/pedimentoDocuments.ts
import { fetchWithAuth } from '../fetchWithAuth';
export interface PedimentoDocument {
id: string;
@@ -19,26 +20,25 @@ export interface PedimentoDocumentsResponse {
results: PedimentoDocument[];
}
const API_URL = import.meta.env.VITE_EFC_API_URL;
const API_URL = (import.meta as any).env.VITE_EFC_API_URL;
export async function fetchPedimentoDocuments(
token: string,
pedimentoId: string,
page: number = 1,
pageSize: number = 10
): Promise<PedimentoDocumentsResponse> {
const res = await fetch(
`${API_URL}/record/documents/?page=${page}&page_size=${pageSize}&pedimento=${pedimentoId}`,
{
headers: {
'Authorization': `Bearer ${token}`,
'Content-Type': 'application/json',
},
try {
const res = await fetchWithAuth(
`${API_URL}/record/documents/?page=${page}&page_size=${pageSize}&pedimento=${pedimentoId}`
);
if (!res.ok) {
throw new Error('No autorizado o error en la petición');
}
);
if (res.status === 401) {
throw new Error('SESSION_EXPIRED');
return res.json();
} catch (error) {
console.error('Error in fetchPedimentoDocuments:', error);
throw error;
}
if (!res.ok) throw new Error('No autorizado o error en la petición');
return res.json();
}

View File

@@ -1,3 +1,5 @@
import { fetchWithAuth } from '../fetchWithAuth';
// Tipos para la respuesta y registros
export interface ProcesamientoPedimento {
id: number;
@@ -20,14 +22,34 @@ export interface ProcesamientoPedimentosResponse {
// API para customs/procesamientopedimentos/
export async function fetchProcesamientoPedimentos(
token: string | null,
page: number = 1,
pageSize: number = 20
pageSize: number = 20,
filters: Record<string, any> = {}
): Promise<ProcesamientoPedimentosResponse> {
const API_URL = import.meta.env.VITE_EFC_API_URL;
const headers: Record<string, string> = {};
if (token) headers['Authorization'] = `Bearer ${token}`;
const res = await fetch(`${API_URL}/customs/procesamientopedimentos/?page=${page}&page_size=${pageSize}`, { headers });
if (!res.ok) throw new Error('Error al obtener procesamiento de pedimentos');
return await res.json();
try {
const API_URL = (import.meta as any).env.VITE_EFC_API_URL;
// Construir query params
const params = new URLSearchParams();
params.append('page', String(page));
params.append('page_size', String(pageSize));
// Agregar filtros
Object.entries(filters).forEach(([key, value]) => {
if (value !== undefined && value !== null && value !== '') {
params.append(key, String(value));
}
});
const res = await fetchWithAuth(`${API_URL}/customs/procesamientopedimentos/?${params.toString()}`);
if (!res.ok) {
throw new Error('Error al obtener procesamiento de pedimentos');
}
return await res.json();
} catch (error) {
console.error('Error in fetchProcesamientoPedimentos:', error);
throw error;
}
}

View File

@@ -1,4 +1,7 @@
const API_URL = import.meta.env.VITE_EFC_API_URL || 'http://localhost:8000';
import { fetchWithAuth, postWithAuth, putWithAuth, deleteWithAuth } from '../fetchWithAuth';
// Función helper para manejar respuestas
async function handleResponse(response, operation = 'operación') {
if (response.status === 401) {
@@ -15,57 +18,27 @@ async function handleResponse(response, operation = 'operación') {
return response.json();
}
export async function fetchUsers(token) {
export async function fetchUsers() {
const url = `${API_URL}/user/users/`;
const res = await fetch(url, {
headers: {
'Authorization': `Bearer ${token}`,
'Content-Type': 'application/json',
'Accept': 'application/json',
},
});
const res = await fetchWithAuth(url);
return handleResponse(res, 'Fetch Users');
}
export async function createUser(token, userData) {
export async function createUser(userData) {
const url = `${API_URL}/user/users/`;
const res = await fetch(url, {
method: 'POST',
headers: {
'Authorization': `Bearer ${token}`,
'Content-Type': 'application/json',
'Accept': 'application/json',
},
body: JSON.stringify(userData),
});
const res = await postWithAuth(url, userData);
return handleResponse(res, 'Create User');
}
export async function updateUser(token, id, userData) {
export async function updateUser(id, userData) {
const url = `${API_URL}/user/users/${id}/`;
const res = await fetch(url, {
method: 'PUT',
headers: {
'Authorization': `Bearer ${token}`,
'Content-Type': 'application/json',
'Accept': 'application/json',
},
body: JSON.stringify(userData),
});
const res = await putWithAuth(url, userData);
return handleResponse(res, 'Update User');
}
export async function deleteUser(token, id) {
export async function deleteUser(id) {
const url = `${API_URL}/user/users/${id}/`;
const res = await fetch(url, {
method: 'DELETE',
headers: {
'Authorization': `Bearer ${token}`,
'Content-Type': 'application/json',
'Accept': 'application/json',
},
});
if (res.status === 401) throw new Error('SESSION_EXPIRED');
const res = await deleteWithAuth(url);
if (!res.ok) throw new Error(`Error ${res.status}: ${res.statusText}`);
return true;
}

View File

@@ -1,4 +1,5 @@
const API_URL = import.meta.env.VITE_EFC_API_URL || 'http://localhost:8000';
import { fetchWithAuth, postWithAuth, putWithAuth, deleteWithAuth } from '../fetchWithAuth';
// Función helper para manejar respuestas
async function handleResponse(response, operation = 'operación') {
@@ -26,18 +27,12 @@ async function handleResponse(response, operation = 'operación') {
return response.json();
}
export async function fetchUsers(token) {
export async function fetchUsers() {
try {
const url = `${API_URL}/user/users/`;
console.log('👥 Fetching users from:', url);
const res = await fetch(url, {
headers: {
'Authorization': `Bearer ${token}`,
'Content-Type': 'application/json',
'Accept': 'application/json',
},
});
const res = await fetchWithAuth(url);
const data = await handleResponse(res, 'Fetch Users');
console.log('✅ Users data received');
@@ -52,20 +47,12 @@ export async function fetchUsers(token) {
}
}
export async function createUser(token, userData) {
export async function createUser(userData) {
try {
const url = `${API_URL}/user/users/`;
console.log(' Creating user at:', url);
const res = await fetch(url, {
method: 'POST',
headers: {
'Authorization': `Bearer ${token}`,
'Content-Type': 'application/json',
'Accept': 'application/json',
},
body: JSON.stringify(userData),
});
const res = await postWithAuth(url, userData);
const data = await handleResponse(res, 'Create User');
console.log('✅ User created successfully');
@@ -80,20 +67,12 @@ export async function createUser(token, userData) {
}
}
export async function updateUser(token, id, userData) {
export async function updateUser(id, userData) {
try {
const url = `${API_URL}/user/users/${id}/`;
console.log('✏️ Updating user at:', url);
const res = await fetch(url, {
method: 'PUT',
headers: {
'Authorization': `Bearer ${token}`,
'Content-Type': 'application/json',
'Accept': 'application/json',
},
body: JSON.stringify(userData),
});
const res = await putWithAuth(url, userData);
const data = await handleResponse(res, 'Update User');
console.log('✅ User updated successfully');
@@ -108,19 +87,12 @@ export async function updateUser(token, id, userData) {
}
}
export async function deleteUser(token, id) {
export async function deleteUser(id) {
try {
const url = `${API_URL}/user/users/${id}/`;
console.log('🗑️ Deleting user at:', url);
const res = await fetch(url, {
method: 'DELETE',
headers: {
'Authorization': `Bearer ${token}`,
'Content-Type': 'application/json',
'Accept': 'application/json',
},
});
const res = await deleteWithAuth(url);
if (res.status === 401) {
console.error('❌ Unauthorized - session expired');
@@ -145,18 +117,12 @@ export async function deleteUser(token, id) {
}
}
export async function getCurrentUser(token) {
export async function getCurrentUser() {
try {
const url = `${API_URL}/user/users/me/`;
console.log('👤 Fetching current user from:', url);
const res = await fetch(url, {
headers: {
'Authorization': `Bearer ${token}`,
'Content-Type': 'application/json',
'Accept': 'application/json',
},
});
const res = await fetchWithAuth(url);
const data = await handleResponse(res, 'Get Current User');
console.log('✅ Current user data received:', data);