[CONST-D-001] feat: Integrate API frontend with backend
## New Files - .env.example: Environment variables template - .env: Local development config (API URL: localhost:3021) - src/services/auth/auth.api.ts: Authentication API service - src/hooks/useAuth.ts: React Query hooks for auth - src/pages/auth/LoginPage.tsx: Functional login page ## Modified Files - src/App.tsx: Use LoginPage instead of placeholder - src/hooks/index.ts: Export useAuth hook ## Features - Login with email/password - JWT token management - Automatic token refresh - Error handling with toast notifications - Zustand + React Query integration Build: PASSED Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
This commit is contained in:
parent
0d0d52ac29
commit
b93f4c5797
13
web/.env.example
Normal file
13
web/.env.example
Normal file
@ -0,0 +1,13 @@
|
||||
# ===========================================================
|
||||
# ERP CONSTRUCCION - CONFIGURACION FRONTEND
|
||||
# ===========================================================
|
||||
# Copiar este archivo a .env y ajustar valores
|
||||
|
||||
# API Backend URL
|
||||
VITE_API_URL=http://localhost:3021/api/v1
|
||||
|
||||
# Tenant ID para desarrollo
|
||||
VITE_TENANT_ID=default-tenant
|
||||
|
||||
# Ambiente
|
||||
VITE_APP_ENV=development
|
||||
@ -18,6 +18,7 @@ import { ConceptosPage, PresupuestosPage, PresupuestoDetailPage, EstimacionesPag
|
||||
import { OpportunitiesPage, TendersPage, ProposalsPage, VendorsPage } from './pages/admin/bidding';
|
||||
import { IncidentesPage, CapacitacionesPage, InspeccionesPage, InspeccionDetailPage } from './pages/admin/hse';
|
||||
import { AvancesObraPage, BitacoraObraPage, ProgramaObraPage, ControlAvancePage } from './pages/admin/obras';
|
||||
import { LoginPage } from './pages/auth';
|
||||
|
||||
function App() {
|
||||
return (
|
||||
@ -88,8 +89,8 @@ function App() {
|
||||
{/* Portal Obra */}
|
||||
<Route path="/obra/*" element={<div className="p-8">Obra Portal (TODO)</div>} />
|
||||
|
||||
{/* Auth routes placeholder */}
|
||||
<Route path="/auth/login" element={<LoginPlaceholder />} />
|
||||
{/* Auth routes */}
|
||||
<Route path="/auth/login" element={<LoginPage />} />
|
||||
|
||||
{/* 404 */}
|
||||
<Route path="*" element={<Navigate to="/" replace />} />
|
||||
@ -99,23 +100,4 @@ function App() {
|
||||
);
|
||||
}
|
||||
|
||||
function LoginPlaceholder() {
|
||||
return (
|
||||
<div className="min-h-screen flex items-center justify-center bg-gray-100">
|
||||
<div className="bg-white p-8 rounded-lg shadow-sm max-w-md w-full">
|
||||
<h1 className="text-2xl font-bold text-gray-900 mb-4">Login</h1>
|
||||
<p className="text-gray-600 mb-4">
|
||||
Pagina de login placeholder. Por ahora accede directamente a /admin.
|
||||
</p>
|
||||
<a
|
||||
href="/admin"
|
||||
className="block w-full text-center px-4 py-2 bg-blue-600 text-white rounded-lg hover:bg-blue-700"
|
||||
>
|
||||
Ir al Admin
|
||||
</a>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
export default App;
|
||||
|
||||
@ -1,3 +1,4 @@
|
||||
export * from './useAuth';
|
||||
export * from './useConstruccion';
|
||||
export * from './usePresupuestos';
|
||||
export * from './useReports';
|
||||
|
||||
171
web/src/hooks/useAuth.ts
Normal file
171
web/src/hooks/useAuth.ts
Normal file
@ -0,0 +1,171 @@
|
||||
/**
|
||||
* useAuth Hook
|
||||
* Hook para manejo de autenticación con React Query
|
||||
*/
|
||||
|
||||
import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query';
|
||||
import { AxiosError } from 'axios';
|
||||
import toast from 'react-hot-toast';
|
||||
import { useNavigate } from 'react-router-dom';
|
||||
import { useAuthStore } from '../stores/authStore';
|
||||
import {
|
||||
login as loginApi,
|
||||
register as registerApi,
|
||||
logout as logoutApi,
|
||||
getCurrentUser,
|
||||
changePassword as changePasswordApi,
|
||||
requestPasswordReset as requestPasswordResetApi,
|
||||
LoginCredentials,
|
||||
RegisterData,
|
||||
AuthResponse,
|
||||
User,
|
||||
} from '../services/auth';
|
||||
import { ApiError } from '../services/api';
|
||||
|
||||
// Query Keys
|
||||
const AUTH_KEYS = {
|
||||
user: ['auth', 'user'] as const,
|
||||
};
|
||||
|
||||
/**
|
||||
* Hook para login
|
||||
*/
|
||||
export function useLogin() {
|
||||
const queryClient = useQueryClient();
|
||||
const navigate = useNavigate();
|
||||
const { setUser, setTokens } = useAuthStore();
|
||||
|
||||
return useMutation<AuthResponse, AxiosError<ApiError>, LoginCredentials>({
|
||||
mutationFn: loginApi,
|
||||
onSuccess: (data) => {
|
||||
setUser(data.user);
|
||||
setTokens(data.accessToken, data.refreshToken);
|
||||
queryClient.setQueryData(AUTH_KEYS.user, data.user);
|
||||
toast.success('Bienvenido');
|
||||
navigate('/admin/dashboard');
|
||||
},
|
||||
onError: (error) => {
|
||||
const message = error.response?.data?.message || 'Error al iniciar sesión';
|
||||
toast.error(message);
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Hook para registro
|
||||
*/
|
||||
export function useRegister() {
|
||||
const queryClient = useQueryClient();
|
||||
const navigate = useNavigate();
|
||||
const { setUser, setTokens } = useAuthStore();
|
||||
|
||||
return useMutation<AuthResponse, AxiosError<ApiError>, RegisterData>({
|
||||
mutationFn: registerApi,
|
||||
onSuccess: (data) => {
|
||||
setUser(data.user);
|
||||
setTokens(data.accessToken, data.refreshToken);
|
||||
queryClient.setQueryData(AUTH_KEYS.user, data.user);
|
||||
toast.success('Cuenta creada exitosamente');
|
||||
navigate('/admin/dashboard');
|
||||
},
|
||||
onError: (error) => {
|
||||
const message = error.response?.data?.message || 'Error al crear cuenta';
|
||||
toast.error(message);
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Hook para logout
|
||||
*/
|
||||
export function useLogout() {
|
||||
const queryClient = useQueryClient();
|
||||
const navigate = useNavigate();
|
||||
const { logout: clearAuth } = useAuthStore();
|
||||
|
||||
return useMutation({
|
||||
mutationFn: logoutApi,
|
||||
onSuccess: () => {
|
||||
clearAuth();
|
||||
queryClient.clear();
|
||||
navigate('/auth/login');
|
||||
toast.success('Sesión cerrada');
|
||||
},
|
||||
onError: () => {
|
||||
// Aún así limpiar el estado local
|
||||
clearAuth();
|
||||
queryClient.clear();
|
||||
navigate('/auth/login');
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Hook para obtener usuario actual
|
||||
*/
|
||||
export function useCurrentUser() {
|
||||
const { isAuthenticated, user: storedUser } = useAuthStore();
|
||||
|
||||
return useQuery<User, AxiosError<ApiError>>({
|
||||
queryKey: AUTH_KEYS.user,
|
||||
queryFn: getCurrentUser,
|
||||
enabled: isAuthenticated,
|
||||
initialData: storedUser || undefined,
|
||||
staleTime: 5 * 60 * 1000, // 5 minutos
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Hook para cambiar contraseña
|
||||
*/
|
||||
export function useChangePassword() {
|
||||
return useMutation<void, AxiosError<ApiError>, { currentPassword: string; newPassword: string }>({
|
||||
mutationFn: ({ currentPassword, newPassword }) =>
|
||||
changePasswordApi(currentPassword, newPassword),
|
||||
onSuccess: () => {
|
||||
toast.success('Contraseña actualizada');
|
||||
},
|
||||
onError: (error) => {
|
||||
const message = error.response?.data?.message || 'Error al cambiar contraseña';
|
||||
toast.error(message);
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Hook para solicitar reset de contraseña
|
||||
*/
|
||||
export function useRequestPasswordReset() {
|
||||
return useMutation<void, AxiosError<ApiError>, string>({
|
||||
mutationFn: requestPasswordResetApi,
|
||||
onSuccess: () => {
|
||||
toast.success('Se envió un correo con instrucciones');
|
||||
},
|
||||
onError: (error) => {
|
||||
const message = error.response?.data?.message || 'Error al solicitar reset';
|
||||
toast.error(message);
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Hook principal de autenticación
|
||||
* Combina estado de Zustand con queries
|
||||
*/
|
||||
export function useAuth() {
|
||||
const { isAuthenticated, user, accessToken, logout: clearAuth } = useAuthStore();
|
||||
const loginMutation = useLogin();
|
||||
const logoutMutation = useLogout();
|
||||
|
||||
return {
|
||||
isAuthenticated,
|
||||
user,
|
||||
accessToken,
|
||||
login: loginMutation.mutate,
|
||||
loginAsync: loginMutation.mutateAsync,
|
||||
logout: logoutMutation.mutate,
|
||||
isLoggingIn: loginMutation.isPending,
|
||||
isLoggingOut: logoutMutation.isPending,
|
||||
clearAuth,
|
||||
};
|
||||
}
|
||||
158
web/src/pages/auth/LoginPage.tsx
Normal file
158
web/src/pages/auth/LoginPage.tsx
Normal file
@ -0,0 +1,158 @@
|
||||
/**
|
||||
* LoginPage
|
||||
* Página de inicio de sesión para ERP Construcción
|
||||
*/
|
||||
|
||||
import { useState } from 'react';
|
||||
import { Link } from 'react-router-dom';
|
||||
import { useLogin } from '../../hooks/useAuth';
|
||||
import { Building2, Mail, Lock, Eye, EyeOff, Loader2 } from 'lucide-react';
|
||||
|
||||
export function LoginPage() {
|
||||
const [email, setEmail] = useState('');
|
||||
const [password, setPassword] = useState('');
|
||||
const [showPassword, setShowPassword] = useState(false);
|
||||
const loginMutation = useLogin();
|
||||
|
||||
const handleSubmit = (e: React.FormEvent) => {
|
||||
e.preventDefault();
|
||||
if (!email || !password) return;
|
||||
loginMutation.mutate({ email, password });
|
||||
};
|
||||
|
||||
return (
|
||||
<div className="min-h-screen flex items-center justify-center bg-gradient-to-br from-blue-50 to-blue-100 px-4">
|
||||
<div className="w-full max-w-md">
|
||||
{/* Logo y Título */}
|
||||
<div className="text-center mb-8">
|
||||
<div className="inline-flex items-center justify-center w-16 h-16 bg-blue-600 rounded-xl mb-4">
|
||||
<Building2 className="w-8 h-8 text-white" />
|
||||
</div>
|
||||
<h1 className="text-2xl font-bold text-gray-900">ERP Construcción</h1>
|
||||
<p className="text-gray-600 mt-2">Ingresa a tu cuenta</p>
|
||||
</div>
|
||||
|
||||
{/* Formulario */}
|
||||
<div className="bg-white rounded-xl shadow-lg p-8">
|
||||
<form onSubmit={handleSubmit} className="space-y-6">
|
||||
{/* Email */}
|
||||
<div>
|
||||
<label htmlFor="email" className="block text-sm font-medium text-gray-700 mb-2">
|
||||
Correo electrónico
|
||||
</label>
|
||||
<div className="relative">
|
||||
<div className="absolute inset-y-0 left-0 pl-3 flex items-center pointer-events-none">
|
||||
<Mail className="h-5 w-5 text-gray-400" />
|
||||
</div>
|
||||
<input
|
||||
id="email"
|
||||
name="email"
|
||||
type="email"
|
||||
autoComplete="email"
|
||||
required
|
||||
value={email}
|
||||
onChange={(e) => setEmail(e.target.value)}
|
||||
className="block w-full pl-10 pr-4 py-3 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-blue-500 transition-colors"
|
||||
placeholder="usuario@empresa.com"
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Password */}
|
||||
<div>
|
||||
<label htmlFor="password" className="block text-sm font-medium text-gray-700 mb-2">
|
||||
Contraseña
|
||||
</label>
|
||||
<div className="relative">
|
||||
<div className="absolute inset-y-0 left-0 pl-3 flex items-center pointer-events-none">
|
||||
<Lock className="h-5 w-5 text-gray-400" />
|
||||
</div>
|
||||
<input
|
||||
id="password"
|
||||
name="password"
|
||||
type={showPassword ? 'text' : 'password'}
|
||||
autoComplete="current-password"
|
||||
required
|
||||
value={password}
|
||||
onChange={(e) => setPassword(e.target.value)}
|
||||
className="block w-full pl-10 pr-12 py-3 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-blue-500 transition-colors"
|
||||
placeholder="••••••••"
|
||||
/>
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => setShowPassword(!showPassword)}
|
||||
className="absolute inset-y-0 right-0 pr-3 flex items-center"
|
||||
>
|
||||
{showPassword ? (
|
||||
<EyeOff className="h-5 w-5 text-gray-400 hover:text-gray-600" />
|
||||
) : (
|
||||
<Eye className="h-5 w-5 text-gray-400 hover:text-gray-600" />
|
||||
)}
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Opciones */}
|
||||
<div className="flex items-center justify-between">
|
||||
<label className="flex items-center">
|
||||
<input
|
||||
type="checkbox"
|
||||
className="h-4 w-4 text-blue-600 border-gray-300 rounded focus:ring-blue-500"
|
||||
/>
|
||||
<span className="ml-2 text-sm text-gray-600">Recordarme</span>
|
||||
</label>
|
||||
<Link
|
||||
to="/auth/forgot-password"
|
||||
className="text-sm text-blue-600 hover:text-blue-700"
|
||||
>
|
||||
¿Olvidaste tu contraseña?
|
||||
</Link>
|
||||
</div>
|
||||
|
||||
{/* Submit Button */}
|
||||
<button
|
||||
type="submit"
|
||||
disabled={loginMutation.isPending || !email || !password}
|
||||
className="w-full flex items-center justify-center px-4 py-3 bg-blue-600 text-white font-medium rounded-lg hover:bg-blue-700 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-blue-500 disabled:opacity-50 disabled:cursor-not-allowed transition-colors"
|
||||
>
|
||||
{loginMutation.isPending ? (
|
||||
<>
|
||||
<Loader2 className="w-5 h-5 mr-2 animate-spin" />
|
||||
Iniciando sesión...
|
||||
</>
|
||||
) : (
|
||||
'Iniciar sesión'
|
||||
)}
|
||||
</button>
|
||||
</form>
|
||||
|
||||
{/* Divider */}
|
||||
<div className="relative my-6">
|
||||
<div className="absolute inset-0 flex items-center">
|
||||
<div className="w-full border-t border-gray-300" />
|
||||
</div>
|
||||
<div className="relative flex justify-center text-sm">
|
||||
<span className="px-2 bg-white text-gray-500">o</span>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Demo Access */}
|
||||
<div className="text-center">
|
||||
<p className="text-sm text-gray-600 mb-2">¿Quieres ver una demo?</p>
|
||||
<Link
|
||||
to="/admin/dashboard"
|
||||
className="text-sm text-blue-600 hover:text-blue-700 font-medium"
|
||||
>
|
||||
Acceder sin cuenta (modo demo)
|
||||
</Link>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Footer */}
|
||||
<p className="text-center text-sm text-gray-500 mt-6">
|
||||
© 2026 ERP Construcción. Todos los derechos reservados.
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
1
web/src/pages/auth/index.ts
Normal file
1
web/src/pages/auth/index.ts
Normal file
@ -0,0 +1 @@
|
||||
export { LoginPage } from './LoginPage';
|
||||
117
web/src/services/auth/auth.api.ts
Normal file
117
web/src/services/auth/auth.api.ts
Normal file
@ -0,0 +1,117 @@
|
||||
/**
|
||||
* Auth API Service
|
||||
* Endpoints de autenticación para ERP Construcción
|
||||
*/
|
||||
|
||||
import api from '../api';
|
||||
|
||||
// ============================================================
|
||||
// TYPES
|
||||
// ============================================================
|
||||
|
||||
export interface LoginCredentials {
|
||||
email: string;
|
||||
password: string;
|
||||
}
|
||||
|
||||
export interface RegisterData {
|
||||
email: string;
|
||||
password: string;
|
||||
firstName: string;
|
||||
lastName: string;
|
||||
}
|
||||
|
||||
export interface User {
|
||||
id: string;
|
||||
email: string;
|
||||
firstName: string | null;
|
||||
lastName: string | null;
|
||||
tenantId: string;
|
||||
status: string;
|
||||
role?: string;
|
||||
roles?: string[];
|
||||
}
|
||||
|
||||
export interface Tenant {
|
||||
id: string;
|
||||
name: string;
|
||||
slug?: string;
|
||||
}
|
||||
|
||||
export interface AuthResponse {
|
||||
accessToken: string;
|
||||
refreshToken: string;
|
||||
expiresIn?: number;
|
||||
user: User;
|
||||
tenant?: Tenant;
|
||||
}
|
||||
|
||||
export interface RefreshTokenResponse {
|
||||
accessToken: string;
|
||||
refreshToken: string;
|
||||
}
|
||||
|
||||
// ============================================================
|
||||
// API CALLS
|
||||
// ============================================================
|
||||
|
||||
/**
|
||||
* Login con email y password
|
||||
*/
|
||||
export async function login(credentials: LoginCredentials): Promise<AuthResponse> {
|
||||
const response = await api.post<AuthResponse>('/auth/login', credentials);
|
||||
return response.data;
|
||||
}
|
||||
|
||||
/**
|
||||
* Registro de nuevo usuario
|
||||
*/
|
||||
export async function register(data: RegisterData): Promise<AuthResponse> {
|
||||
const response = await api.post<AuthResponse>('/auth/register', data);
|
||||
return response.data;
|
||||
}
|
||||
|
||||
/**
|
||||
* Refresh token
|
||||
*/
|
||||
export async function refreshToken(token: string): Promise<RefreshTokenResponse> {
|
||||
const response = await api.post<RefreshTokenResponse>('/auth/refresh', {
|
||||
refreshToken: token,
|
||||
});
|
||||
return response.data;
|
||||
}
|
||||
|
||||
/**
|
||||
* Logout (invalidar refresh token)
|
||||
*/
|
||||
export async function logout(): Promise<void> {
|
||||
await api.post('/auth/logout');
|
||||
}
|
||||
|
||||
/**
|
||||
* Obtener usuario actual
|
||||
*/
|
||||
export async function getCurrentUser(): Promise<User> {
|
||||
const response = await api.get<User>('/auth/me');
|
||||
return response.data;
|
||||
}
|
||||
|
||||
/**
|
||||
* Cambiar contraseña
|
||||
*/
|
||||
export async function changePassword(
|
||||
currentPassword: string,
|
||||
newPassword: string
|
||||
): Promise<void> {
|
||||
await api.post('/auth/change-password', {
|
||||
currentPassword,
|
||||
newPassword,
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Solicitar reset de contraseña
|
||||
*/
|
||||
export async function requestPasswordReset(email: string): Promise<void> {
|
||||
await api.post('/auth/reset-password', { email });
|
||||
}
|
||||
1
web/src/services/auth/index.ts
Normal file
1
web/src/services/auth/index.ts
Normal file
@ -0,0 +1 @@
|
||||
export * from './auth.api';
|
||||
Loading…
Reference in New Issue
Block a user