Compare commits
10 Commits
173cf3771b
...
7f73251c5e
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
7f73251c5e | ||
|
|
3112c82bb2 | ||
|
|
6088623415 | ||
|
|
7731b2fbd6 | ||
|
|
d4421aece4 | ||
|
|
1c8638b8d4 | ||
|
|
72d81bdf47 | ||
| 0ba348cc64 | |||
| 4e79ecd56b | |||
| 4a67f85dcb |
2
.env.example
Normal file
2
.env.example
Normal file
@@ -0,0 +1,2 @@
|
||||
VITE_API_IMPLEMENTATION=django
|
||||
VITE_DJANGO_BASE_URL=http://localhost:7000
|
||||
1
.gitignore
vendored
1
.gitignore
vendored
@@ -5,6 +5,7 @@ node_modules
|
||||
# local env files
|
||||
.env.local
|
||||
.env.*.local
|
||||
.env
|
||||
|
||||
# Log files
|
||||
npm-debug.log*
|
||||
|
||||
81
AGENTS.md
Normal file
81
AGENTS.md
Normal file
@@ -0,0 +1,81 @@
|
||||
# Don Confiao - Frontend
|
||||
|
||||
## Tech Stack
|
||||
- **Framework:** Vue 3 (Composition API)
|
||||
- **UI Library:** Vuetify 3
|
||||
- **Routing:** Vue Router 4 (auto-routes con `unplugin-vue-router`)
|
||||
- **State:** Pinia
|
||||
- **HTTP:** Axios
|
||||
- **Build:** Vite
|
||||
- **Linting:** ESLint
|
||||
|
||||
## Project Structure
|
||||
```
|
||||
src/
|
||||
├── assets/ # Imágenes, iconos estáticos
|
||||
├── components/ # Componentes Vue reutilizables
|
||||
├── layouts/ # Layouts de página
|
||||
├── pages/ # Vistas (auto-routed desde文件名)
|
||||
├── plugins/ # Configuración de Vuetify, etc.
|
||||
├── router/ # Configuración de rutas
|
||||
├── services/ # API services (auth.js, etc.)
|
||||
├── stores/ # Pinia stores
|
||||
└── styles/ # SCSS settings
|
||||
```
|
||||
|
||||
## Important Conventions
|
||||
|
||||
### Auto-imports
|
||||
- Componentes en `src/components/` se auto-importan por nombre
|
||||
- Los archivos en `src/pages/*.vue` se routing automáticamente via `unplugin-vue-router`
|
||||
- Alias `@` = `src/`
|
||||
|
||||
### Pages (CRITICAL)
|
||||
**Siempre importar componentes en los archivos de página:**
|
||||
```vue
|
||||
<template>
|
||||
<MiComponente />
|
||||
</template>
|
||||
|
||||
<script setup>
|
||||
import MiComponente from '@/components/MiComponente.vue';
|
||||
</script>
|
||||
```
|
||||
|
||||
### Componentes
|
||||
- Usar Composition API (`<script setup>` o `export default { }`)
|
||||
- Naming: PascalCase (ej: `LoginDialog.vue`, `CartGrid.vue`)
|
||||
- Componentes de página van en `pages/`, componentes reutilizables en `components/`
|
||||
|
||||
### Servicios API
|
||||
- Ubicación: `src/services/`
|
||||
- Usar Axios para HTTP requests
|
||||
- JWT tokens en localStorage (`access_token`, `refresh_token`)
|
||||
|
||||
### Routing
|
||||
- Rutas automáticas basadas en archivos en `src/pages/`
|
||||
- No requiere configuración manual en `router/index.js`
|
||||
|
||||
## Environment Variables
|
||||
- `VITE_DJANGO_BASE_URL` - URL del backend Django
|
||||
|
||||
## Commands
|
||||
```bash
|
||||
npm run dev # Desarrollo (puerto 3000)
|
||||
npm run build # Producción
|
||||
npm run preview # Preview build
|
||||
npm run lint # ESLint fix
|
||||
```
|
||||
|
||||
## Common Issues
|
||||
1. **Página en blanco:** Verificar que los componentes en `src/pages/*.vue` tengan import explícito
|
||||
2. **Errores de lint:** Ejecutar `npm run lint`
|
||||
|
||||
## Git Commits
|
||||
**Antes de hacer commit:**
|
||||
1. Pedir permiso al usuario
|
||||
2. Mostrar resumen de los cambios que se incluirán
|
||||
|
||||
**Formato de mensajes:**
|
||||
- Usar prefijo `#<numero>` para referenciar el issue (ej: `#28 feat: add login` donde #28 es el número del issue en GitHub/GitLab)
|
||||
- Prefijos válidos: `feat`, `fix`, `chore`, `docs`, `refactor`, `style`
|
||||
@@ -1,42 +1,70 @@
|
||||
<script setup>
|
||||
import { ref } from 'vue';
|
||||
import AuthService from '@/services/auth';
|
||||
import { inject } from 'vue';
|
||||
|
||||
const username = ref('');
|
||||
const password = ref('');
|
||||
const error = ref('');
|
||||
|
||||
async function login() {
|
||||
try {
|
||||
await AuthService.login({ username: username.value, password: password.value });
|
||||
// opcional: redirigir al dashboard
|
||||
} catch (e) {
|
||||
error.value = e.message;
|
||||
}
|
||||
}
|
||||
|
||||
// ejemplo de llamada a clientes (requiere token)
|
||||
const api = inject('api');
|
||||
|
||||
async function loadCustomers() {
|
||||
try {
|
||||
const data = await api.getCustomers();
|
||||
console.log(data);
|
||||
} catch (e) {
|
||||
console.error(e);
|
||||
}
|
||||
}
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<h1>Login</h1>
|
||||
<v-form @submit.prevent="login">
|
||||
<v-text-field v-model="username" label="Usuario" required />
|
||||
<v-text-field v-model="password" label="Contraseña" type="password" required />
|
||||
<v-btn type="submit">Entrar</v-btn>
|
||||
<v-alert v-if="error" type="error">{{ error }}</v-alert>
|
||||
</v-form>
|
||||
|
||||
<v-btn @click="loadCustomers">Cargar clientes</v-btn>
|
||||
<v-form ref="loginForm" @submit.prevent="onSubmit">
|
||||
<v-text-field
|
||||
v-model="username"
|
||||
label="Usuario"
|
||||
:rules="[requiredRule]"
|
||||
required
|
||||
/>
|
||||
<v-text-field
|
||||
v-model="password"
|
||||
label="Contraseña"
|
||||
type="password"
|
||||
:rules="[requiredRule]"
|
||||
required
|
||||
/>
|
||||
|
||||
<v-btn type="submit" color="primary">Entrar</v-btn>
|
||||
|
||||
<v-alert v-if="error" type="error" class="mt-2">{{ error }}</v-alert>
|
||||
</v-form>
|
||||
</template>
|
||||
|
||||
<script>
|
||||
import AuthService from '@/services/auth';
|
||||
|
||||
export default {
|
||||
name: 'DonConfiao',
|
||||
|
||||
data() {
|
||||
return {
|
||||
username: '',
|
||||
password: '',
|
||||
error: '',
|
||||
};
|
||||
},
|
||||
|
||||
methods: {
|
||||
requiredRule(value) {
|
||||
return !!value || 'Este campo es obligatorio';
|
||||
},
|
||||
|
||||
async onSubmit() {
|
||||
this.error = '';
|
||||
|
||||
const form = this.$refs.loginForm;
|
||||
const isValid = await form.validate();
|
||||
|
||||
if (!isValid) return;
|
||||
|
||||
if (!this.username || !this.password) {
|
||||
this.error = 'Usuario y contraseña son obligatorios';
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
await AuthService.login({
|
||||
username: this.username,
|
||||
password: this.password,
|
||||
});
|
||||
this.$router.push({ path: '/' });
|
||||
} catch (e) {
|
||||
const msg = e?.response?.data?.message ?? e.message;
|
||||
this.error = msg ?? 'Error al iniciar sesión';
|
||||
}
|
||||
},
|
||||
},
|
||||
};
|
||||
</script>
|
||||
|
||||
69
src/components/LoginDialog.vue
Normal file
69
src/components/LoginDialog.vue
Normal file
@@ -0,0 +1,69 @@
|
||||
<template>
|
||||
<v-dialog v-model="show" max-width="400">
|
||||
<v-card>
|
||||
<v-card-title class="headline">Iniciar sesión</v-card-title>
|
||||
<v-card-text>
|
||||
<v-form ref="form" @submit.prevent="onSubmit">
|
||||
<v-text-field
|
||||
v-model="username"
|
||||
label="Usuario"
|
||||
:rules="[required]"
|
||||
required
|
||||
/>
|
||||
<v-text-field
|
||||
v-model="password"
|
||||
label="Contraseña"
|
||||
type="password"
|
||||
:rules="[required]"
|
||||
required
|
||||
/>
|
||||
<v-alert v-if="error" type="error" class="mt-2">{{ error }}</v-alert>
|
||||
</v-form>
|
||||
</v-card-text>
|
||||
|
||||
<v-card-actions>
|
||||
<v-spacer />
|
||||
<v-btn text @click="show = false">Cancelar</v-btn>
|
||||
<v-btn color="primary" @click="onSubmit">Entrar</v-btn>
|
||||
</v-card-actions>
|
||||
</v-card>
|
||||
</v-dialog>
|
||||
</template>
|
||||
|
||||
<script>
|
||||
import AuthService from '@/services/auth';
|
||||
|
||||
export default {
|
||||
name: 'LoginDialog',
|
||||
data: () => ({
|
||||
show: false,
|
||||
username: '',
|
||||
password: '',
|
||||
error: '',
|
||||
}),
|
||||
methods: {
|
||||
required(v) {
|
||||
return !!v || 'Campo obligatorio';
|
||||
},
|
||||
async onSubmit() {
|
||||
this.error = '';
|
||||
const form = this.$refs.form;
|
||||
if (!(await form.validate())) return;
|
||||
|
||||
try {
|
||||
await AuthService.login({
|
||||
username: this.username,
|
||||
password: this.password,
|
||||
});
|
||||
this.show = false;
|
||||
this.$emit('login-success');
|
||||
} catch (e) {
|
||||
this.error = e.message ?? 'Error al iniciar sesión';
|
||||
}
|
||||
},
|
||||
open() {
|
||||
this.show = true;
|
||||
},
|
||||
},
|
||||
};
|
||||
</script>
|
||||
32
src/components/Logout.vue
Normal file
32
src/components/Logout.vue
Normal file
@@ -0,0 +1,32 @@
|
||||
<template>
|
||||
<v-container class="d-flex flex-column align-center justify-center" style="height: 100vh;">
|
||||
<v-progress-circular indeterminate color="primary" />
|
||||
<p class="mt-4">Cerrando sesión…</p>
|
||||
</v-container>
|
||||
</template>
|
||||
|
||||
<script>
|
||||
import AuthService from '@/services/auth';
|
||||
|
||||
export default {
|
||||
name: 'DonConfiao',
|
||||
mounted() {
|
||||
this.logout();
|
||||
},
|
||||
methods: {
|
||||
logout() {
|
||||
AuthService.logout();
|
||||
this.$router.push({
|
||||
path: '/autenticarse'
|
||||
});
|
||||
},
|
||||
},
|
||||
};
|
||||
</script>
|
||||
|
||||
<style scoped>
|
||||
p {
|
||||
font-size: 1.1rem;
|
||||
color: #555;
|
||||
}
|
||||
</style>
|
||||
@@ -3,11 +3,22 @@
|
||||
<v-app-bar-nav-icon variant="text" @click.stop="drawer = !drawer"></v-app-bar-nav-icon>
|
||||
<v-toolbar-title>Menu</v-toolbar-title>
|
||||
<v-spacer></v-spacer>
|
||||
<template v-if="$vuetify.display.mdAndUp">
|
||||
<v-btn icon="mdi-magnify" variant="text"></v-btn>
|
||||
<v-btn icon="mdi-filter" variant="text"></v-btn>
|
||||
</template>
|
||||
<v-btn icon="mdi-dots-vertical" variant="text"></v-btn>
|
||||
<v-btn
|
||||
v-if="!isAuthenticated"
|
||||
prepend-icon="mdi-login"
|
||||
variant="text"
|
||||
@click="navigate('/autenticarse')"
|
||||
>
|
||||
Login
|
||||
</v-btn>
|
||||
<v-btn
|
||||
v-else
|
||||
prepend-icon="mdi-logout"
|
||||
variant="text"
|
||||
@click="logout"
|
||||
>
|
||||
Logout
|
||||
</v-btn>
|
||||
</v-app-bar>
|
||||
<v-navigation-drawer v-model="drawer"
|
||||
:location="$vuetify.display.mobile ? 'bottom' : undefined"
|
||||
@@ -41,12 +52,14 @@
|
||||
|
||||
<script>
|
||||
import trytonIcon from '../assets/icons/tryton-icon.svg';
|
||||
import AuthService from '@/services/auth';
|
||||
export default {
|
||||
name: 'NavBar',
|
||||
data: () => ({
|
||||
drawer: false,
|
||||
group: null,
|
||||
showAdminMenu: false,
|
||||
isAuthenticated: false,
|
||||
menuItems: [
|
||||
{ title: 'Inicio', route: '/', icon: 'mdi-home'},
|
||||
{ title: 'Comprar', route:'/comprar', icon: 'mdi-cart'},
|
||||
@@ -61,12 +74,21 @@
|
||||
{ title: 'Actualizar Ventas Tryton', route: '/sincronizar_ventas_tryton', icon: 'trytonIcon'}
|
||||
],
|
||||
}),
|
||||
mounted() {
|
||||
this.checkAuth();
|
||||
},
|
||||
watch: {
|
||||
group () {
|
||||
this.drawer = false
|
||||
},
|
||||
$route() {
|
||||
this.checkAuth();
|
||||
},
|
||||
},
|
||||
methods: {
|
||||
checkAuth() {
|
||||
this.isAuthenticated = AuthService.isAuthenticated();
|
||||
},
|
||||
navigate(route) {
|
||||
this.$router.push(route);
|
||||
},
|
||||
@@ -77,6 +99,11 @@
|
||||
toggleAdminMenu() {
|
||||
this.showAdminMenu = !this.showAdminMenu;
|
||||
},
|
||||
logout() {
|
||||
AuthService.logout();
|
||||
this.isAuthenticated = false;
|
||||
this.$router.push('/');
|
||||
},
|
||||
}
|
||||
}
|
||||
</script>
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
<template>
|
||||
<Login />
|
||||
<Logout />
|
||||
</template>
|
||||
|
||||
<script setup>
|
||||
@@ -2,19 +2,32 @@ class AuthService {
|
||||
static TOKEN_KEY = 'access_token';
|
||||
static REFRESH_KEY = 'refresh_token';
|
||||
|
||||
static login(credentials) {
|
||||
static async login(credentials) {
|
||||
const url = `${import.meta.env.VITE_DJANGO_BASE_URL}/api/token/`;
|
||||
return fetch(url, {
|
||||
|
||||
const resp = await fetch(url, {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify(credentials),
|
||||
})
|
||||
.then(r => r.json())
|
||||
.then(data => {
|
||||
});
|
||||
|
||||
if (!resp.ok) {
|
||||
let errMsg = resp.statusText;
|
||||
try {
|
||||
const errData = await resp.json();
|
||||
errMsg = errData?.detail ?? errData?.message ?? errMsg;
|
||||
} catch (_) { /* ignore */ }
|
||||
throw new Error(errMsg);
|
||||
}
|
||||
|
||||
const data = await resp.json();
|
||||
|
||||
if (data.access && data.refresh) {
|
||||
localStorage.setItem(this.TOKEN_KEY, data.access);
|
||||
localStorage.setItem(this.REFRESH_KEY, data.refresh);
|
||||
}
|
||||
|
||||
return data;
|
||||
});
|
||||
}
|
||||
|
||||
static getAccessToken() {
|
||||
@@ -35,11 +48,21 @@ class AuthService {
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ refresh }),
|
||||
});
|
||||
|
||||
if (!resp.ok) {
|
||||
const errData = await resp.json().catch(() => ({}));
|
||||
throw new Error(errData?.detail ?? resp.statusText);
|
||||
}
|
||||
|
||||
const data = await resp.json();
|
||||
localStorage.setItem(this.TOKEN_KEY, data.access);
|
||||
return data.access;
|
||||
}
|
||||
|
||||
static isAuthenticated() {
|
||||
return !!this.getAccessToken();
|
||||
}
|
||||
|
||||
static logout() {
|
||||
localStorage.removeItem(this.TOKEN_KEY);
|
||||
localStorage.removeItem(this.REFRESH_KEY);
|
||||
|
||||
@@ -1,36 +1,17 @@
|
||||
import AuthService from '@/services/auth';
|
||||
import http from '@/services/http';
|
||||
|
||||
class DjangoApi {
|
||||
constructor() {
|
||||
this.base = import.meta.env.VITE_DJANGO_BASE_URL;
|
||||
}
|
||||
|
||||
_authHeaders() {
|
||||
const token = AuthService.getAccessToken();
|
||||
return token ? { Authorization: `Bearer ${token}` } : {};
|
||||
getRequest(url) {
|
||||
return http.get(url).then(r => r.data);
|
||||
}
|
||||
|
||||
_handleResponse(response) {
|
||||
if (!response.ok) {
|
||||
// Si el token ha expirado (401) intentamos refrescar y re‑intentar
|
||||
if (response.status === 401) {
|
||||
return AuthService.refresh().then(newToken => {
|
||||
// volver a ejecutar la petición original con el nuevo token
|
||||
const retryHeaders = {
|
||||
...response.headers,
|
||||
Authorization: `Bearer ${newToken}`,
|
||||
};
|
||||
// aquí usamos fetch de nuevo con los mismos parámetros
|
||||
// (para simplificar, delegamos a getRequest/postRequest)
|
||||
// En la práctica, extrae la lógica a una función reutilizable.
|
||||
throw new Error('Retry logic should be implemented here');
|
||||
});
|
||||
}
|
||||
return response.json().then(err => {
|
||||
throw new Error(`Error ${response.status}: ${err.detail || response.statusText}`);
|
||||
});
|
||||
}
|
||||
return response.json();
|
||||
postRequest(url, payload) {
|
||||
return http.post(url, payload).then(r => r.data);
|
||||
}
|
||||
|
||||
getCustomers() {
|
||||
@@ -107,26 +88,6 @@ class DjangoApi {
|
||||
const url = this.base + '/don_confiao/api/enviar_ventas_a_tryton';
|
||||
return this.postRequest(url, {});
|
||||
}
|
||||
|
||||
getRequest(url) {
|
||||
return fetch(url, {
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
...this._authHeaders(),
|
||||
},
|
||||
}).then(this._handleResponse);
|
||||
}
|
||||
|
||||
postRequest(url, content) {
|
||||
return fetch(url, {
|
||||
method: 'POST',
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
...this._authHeaders(),
|
||||
},
|
||||
body: JSON.stringify(content),
|
||||
}).then(this._handleResponse);
|
||||
}
|
||||
}
|
||||
|
||||
export default DjangoApi;
|
||||
|
||||
44
src/services/http.js
Normal file
44
src/services/http.js
Normal file
@@ -0,0 +1,44 @@
|
||||
import axios from 'axios';
|
||||
import AuthService from '@/services/auth';
|
||||
|
||||
const http = axios.create({
|
||||
baseURL: import.meta.env.VITE_DJANGO_BASE_URL,
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
},
|
||||
});
|
||||
|
||||
http.interceptors.request.use(
|
||||
config => {
|
||||
const token = AuthService.getAccessToken();
|
||||
if (token) {
|
||||
config.headers.Authorization = `Bearer ${token}`;
|
||||
}
|
||||
return config;
|
||||
},
|
||||
error => Promise.reject(error)
|
||||
);
|
||||
|
||||
http.interceptors.response.use(
|
||||
response => response,
|
||||
async error => {
|
||||
const originalRequest = error.config;
|
||||
|
||||
if (error.response?.status === 401 && !originalRequest._retry) {
|
||||
originalRequest._retry = true;
|
||||
try {
|
||||
const newAccess = await AuthService.refresh();
|
||||
originalRequest.headers.Authorization = `Bearer ${newAccess}`;
|
||||
return http.request(originalRequest);
|
||||
} catch (refreshError) {
|
||||
AuthService.logout();
|
||||
window.location.href = '/autenticarse';
|
||||
return Promise.reject(refreshError);
|
||||
}
|
||||
}
|
||||
|
||||
return Promise.reject(error);
|
||||
}
|
||||
);
|
||||
|
||||
export default http;
|
||||
@@ -11,16 +11,6 @@ import Vuetify, { transformAssetUrls } from 'vite-plugin-vuetify'
|
||||
import { defineConfig } from 'vite'
|
||||
import { fileURLToPath, URL } from 'node:url'
|
||||
|
||||
const aliasMap = {
|
||||
'@': fileURLToPath(new URL('./src', import.meta.url)),
|
||||
};
|
||||
|
||||
console.log('🔧 Alias configurado:');
|
||||
console.log(aliasMap); // <-- se muestra en la terminal al iniciar Vite
|
||||
console.log('Resolución real de "@":', aliasMap['@']);
|
||||
|
||||
|
||||
|
||||
// https://vitejs.dev/config/
|
||||
export default defineConfig({
|
||||
plugins: [
|
||||
|
||||
Reference in New Issue
Block a user