17 Commits

Author SHA1 Message Date
c95279d96b Merge pull request 'Implementando autenticación usando jwt #28' (#31) from implement_jwt_authentication_#28 into main
Reviewed-on: #31
2026-03-07 17:30:23 -05:00
mono
7f73251c5e #28 style: fix lint issues in auth components 2026-03-07 17:03:30 -05:00
mono
3112c82bb2 #28 fix: update auth state on route change 2026-03-07 16:48:24 -05:00
mono
6088623415 docs: add git commit conventions to AGENTS.md 2026-03-07 16:22:04 -05:00
mono
7731b2fbd6 #28 feat(auth): add login/logout buttons in NavBar 2026-03-07 16:12:17 -05:00
mono
d4421aece4 chore: add .env to gitignore and add .env.example 2026-03-07 16:05:26 -05:00
mono
1c8638b8d4 docs: add AGENTS.md with project conventions for AI agents 2026-03-07 16:03:21 -05:00
mono
72d81bdf47 #28 fix: add component imports in pages and isAuthenticated method 2026-03-07 16:03:17 -05:00
9e78646d20 feat: Add catalog page idea 2026-02-21 17:10:30 -05:00
0ba348cc64 #28 fix(login): handle bad credentials. 2026-02-21 13:38:00 -05:00
4e79ecd56b #28 feat(api): add logout. 2026-02-14 18:55:26 -05:00
4a67f85dcb #28 refactor(api): using axios instead fetch. 2026-02-14 18:20:07 -05:00
173cf3771b #28 dependency: add axios 2026-02-14 17:56:37 -05:00
173ddfd05f feat(Login): add example jwt token 2026-02-14 17:49:49 -05:00
c593dd0273 Merge pull request '#23 Comentado botones para adicionar clientes.' (#25) from delete_add_customer_buttons_#23 into main
Reviewed-on: #25
2025-08-30 16:10:33 -05:00
c8460c8e81 #23 fix: comment add customer button. 2025-08-30 16:08:31 -05:00
Rodia
3fdfc3c883 Merge pull request 'feat: Add page send sales to tryton close #20' (#21) from enviar_ventas_tryton#20 into main
Reviewed-on: #21
2025-08-16 15:15:31 -05:00
18 changed files with 1644 additions and 1577 deletions

2
.env.example Normal file
View File

@@ -0,0 +1,2 @@
VITE_API_IMPLEMENTATION=django
VITE_DJANGO_BASE_URL=http://localhost:7000

1
.gitignore vendored
View File

@@ -5,6 +5,7 @@ node_modules
# local env files # local env files
.env.local .env.local
.env.*.local .env.*.local
.env
# Log files # Log files
npm-debug.log* npm-debug.log*

81
AGENTS.md Normal file
View 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`

2608
package-lock.json generated

File diff suppressed because it is too large Load Diff

View File

@@ -9,6 +9,7 @@
}, },
"dependencies": { "dependencies": {
"@mdi/font": "7.4.47", "@mdi/font": "7.4.47",
"axios": "^1.13.5",
"core-js": "^3.37.1", "core-js": "^3.37.1",
"roboto-fontface": "*", "roboto-fontface": "*",
"vee-validate": "^4.14.6", "vee-validate": "^4.14.6",

View File

@@ -16,7 +16,7 @@
required required
class="mr-4" class="mr-4"
></v-autocomplete> ></v-autocomplete>
<v-btn color="primary" @click="openModal">Agregar Cliente</v-btn> <!-- <v-btn color="primary" @click="openModal">Agregar Cliente</v-btn> -->
<CreateCustomerModal ref="customerModal" @customerCreated="handleNewCustomer"/> <CreateCustomerModal ref="customerModal" @customerCreated="handleNewCustomer"/>
</v-col> </v-col>
<v-col lg="4"> <v-col lg="4">

70
src/components/Login.vue Normal file
View File

@@ -0,0 +1,70 @@
<template>
<h1>Login</h1>
<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>

View 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
View 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>

View File

@@ -3,11 +3,22 @@
<v-app-bar-nav-icon variant="text" @click.stop="drawer = !drawer"></v-app-bar-nav-icon> <v-app-bar-nav-icon variant="text" @click.stop="drawer = !drawer"></v-app-bar-nav-icon>
<v-toolbar-title>Menu</v-toolbar-title> <v-toolbar-title>Menu</v-toolbar-title>
<v-spacer></v-spacer> <v-spacer></v-spacer>
<template v-if="$vuetify.display.mdAndUp"> <v-btn
<v-btn icon="mdi-magnify" variant="text"></v-btn> v-if="!isAuthenticated"
<v-btn icon="mdi-filter" variant="text"></v-btn> prepend-icon="mdi-login"
</template> variant="text"
<v-btn icon="mdi-dots-vertical" variant="text"></v-btn> @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-app-bar>
<v-navigation-drawer v-model="drawer" <v-navigation-drawer v-model="drawer"
:location="$vuetify.display.mobile ? 'bottom' : undefined" :location="$vuetify.display.mobile ? 'bottom' : undefined"
@@ -41,12 +52,14 @@
<script> <script>
import trytonIcon from '../assets/icons/tryton-icon.svg'; import trytonIcon from '../assets/icons/tryton-icon.svg';
import AuthService from '@/services/auth';
export default { export default {
name: 'NavBar', name: 'NavBar',
data: () => ({ data: () => ({
drawer: false, drawer: false,
group: null, group: null,
showAdminMenu: false, showAdminMenu: false,
isAuthenticated: false,
menuItems: [ menuItems: [
{ title: 'Inicio', route: '/', icon: 'mdi-home'}, { title: 'Inicio', route: '/', icon: 'mdi-home'},
{ title: 'Comprar', route:'/comprar', icon: 'mdi-cart'}, { title: 'Comprar', route:'/comprar', icon: 'mdi-cart'},
@@ -61,12 +74,21 @@
{ title: 'Actualizar Ventas Tryton', route: '/sincronizar_ventas_tryton', icon: 'trytonIcon'} { title: 'Actualizar Ventas Tryton', route: '/sincronizar_ventas_tryton', icon: 'trytonIcon'}
], ],
}), }),
mounted() {
this.checkAuth();
},
watch: { watch: {
group () { group () {
this.drawer = false this.drawer = false
}, },
$route() {
this.checkAuth();
},
}, },
methods: { methods: {
checkAuth() {
this.isAuthenticated = AuthService.isAuthenticated();
},
navigate(route) { navigate(route) {
this.$router.push(route); this.$router.push(route);
}, },
@@ -77,6 +99,11 @@
toggleAdminMenu() { toggleAdminMenu() {
this.showAdminMenu = !this.showAdminMenu; this.showAdminMenu = !this.showAdminMenu;
}, },
logout() {
AuthService.logout();
this.isAuthenticated = false;
this.$router.push('/');
},
} }
} }
</script> </script>

View File

@@ -16,7 +16,7 @@
required required
class="mr-4" class="mr-4"
></v-autocomplete> ></v-autocomplete>
<v-btn color="primary" @click="openModal">Agregar Cliente</v-btn> <!--<v-btn color="primary" @click="openModal">Agregar Cliente</v-btn>-->
<CreateCustomerModal ref="customerModal" @customerCreated="handleNewCustomer"/> <CreateCustomerModal ref="customerModal" @customerCreated="handleNewCustomer"/>
</v-col> </v-col>
<v-col lg="4"> <v-col lg="4">

View File

@@ -0,0 +1,7 @@
<template>
<Login />
</template>
<script setup>
//
</script>

130
src/pages/catalog.vue Normal file
View File

@@ -0,0 +1,130 @@
<template>
<v-container>
<v-card>
<v-card-title>
<span class="headline">Catálogo</span>
</v-card-title>
<v-card-text>
<v-list two-line>
<v-list-item v-for="item in items" :key="item.id" class="catalog-item">
<v-row no-gutters align="center" class="w-100">
<v-col cols="12" md="3" class="d-flex">
<v-img :src="item.img" class="product-img" contain></v-img>
</v-col>
<v-col cols="12" md="6">
<v-list-item-title class="title">{{ item.name }}</v-list-item-title>
<v-list-item-subtitle class="subtitle">{{ item.description }}</v-list-item-subtitle>
<div class="prices mt-2">
<div class="price-line">Precio unitario: <strong>{{ currency(item.price) }}</strong></div>
<div class="price-line">Precio total: <strong>{{ currency(item.price * item.quantity) }}</strong></div>
</div>
</v-col>
<v-col cols="12" md="3" class="d-flex align-center justify-end">
<div class="quantity-controls">
<v-btn small text class="qty-btn" @click="decrease(item)"><v-icon small>mdi-minus</v-icon></v-btn>
<v-text-field
v-model.number="item.quantity"
type="number"
min="0"
class="quantity-input"
dense
outlined
hide-details
aria-label="Cantidad"
/>
<v-btn small text class="qty-btn" @click="increase(item)"><v-icon small>mdi-plus</v-icon></v-btn>
</div>
</v-col>
</v-row>
</v-list-item>
</v-list>
</v-card-text>
<v-card-actions>
<v-btn color="primary">Ver más</v-btn>
</v-card-actions>
</v-card>
</v-container>
</template>
<script>
export default {
data() {
return {
items: [
{ id: 1, name: 'Producto 1', description: 'Descripción del producto 1', img: 'https://picsum.photos/300/200?random=1', quantity: 0, price: 1200 },
{ id: 1, name: 'Producto 2', description: 'Descripción del producto 1', img: 'https://picsum.photos/300/200?random=1', quantity: 0, price: 1200 },
{ id: 1, name: 'Producto 3', description: 'Descripción del producto 1', img: 'https://picsum.photos/300/200?random=1', quantity: 0, price: 1200 },
{ id: 1, name: 'Producto 4', description: 'Descripción del producto 1', img: 'https://picsum.photos/300/200?random=1', quantity: 0, price: 1200 },
{ id: 1, name: 'Producto 5', description: 'Descripción del producto 1', img: 'https://picsum.photos/300/200?random=1', quantity: 0, price: 1200 },
{ id: 1, name: 'Producto 6', description: 'Descripción del producto 1', img: 'https://picsum.photos/300/200?random=1', quantity: 0, price: 1200 },
{ id: 1, name: 'Producto 7', description: 'Descripción del producto 1', img: 'https://picsum.photos/300/200?random=1', quantity: 0, price: 1200 },
{ id: 1, name: 'Producto 8', description: 'Descripción del producto 1', img: 'https://picsum.photos/300/200?random=1', quantity: 0, price: 1200 },
{ id: 1, name: 'Producto 9', description: 'Descripción del producto 1', img: 'https://picsum.photos/300/200?random=1', quantity: 0, price: 1200 },
{ id: 1, name: 'Producto 10', description: 'Descripción del producto 1', img: 'https://picsum.photos/300/200?random=1', quantity: 0, price: 1200 },
{ id: 1, name: 'Producto 11', description: 'Descripción del producto 1', img: 'https://picsum.photos/300/200?random=1', quantity: 0, price: 1200 },
{ id: 1, name: 'Producto 12', description: 'Descripción del producto 1', img: 'https://picsum.photos/300/200?random=1', quantity: 0, price: 1200 },
{ id: 1, name: 'Producto 13', description: 'Descripción del producto 1', img: 'https://picsum.photos/300/200?random=1', quantity: 0, price: 1200 },
{ id: 1, name: 'Producto 14', description: 'Descripción del producto 1', img: 'https://picsum.photos/300/200?random=1', quantity: 0, price: 1200 },
{ id: 1, name: 'Producto 15', description: 'Descripción del producto 1', img: 'https://picsum.photos/300/200?random=1', quantity: 0, price: 1200 },
{ id: 1, name: 'Producto 16', description: 'Descripción del producto 1', img: 'https://picsum.photos/300/200?random=1', quantity: 0, price: 1200 },
],
};
},
methods: {
increase(item) {
item.quantity = Number(item.quantity) + 1;
},
decrease(item) {
item.quantity = Math.max(0, Number(item.quantity) - 1);
},
currency(val) {
if (val == null) return '-';
return new Intl.NumberFormat('es-CO', { style: 'currency', currency: 'COP', minimumFractionDigits: 0 }).format(val);
},
},
};
</script>
<style scoped>
.headline {
font-weight: bold;
}
.catalog-item {
padding-top: 12px;
padding-bottom: 12px;
}
.product-img {
width: 150px;
height: 100px;
border-radius: 6px;
object-fit: cover;
}
.quantity-controls {
display: inline-flex;
align-items: center;
justify-content: flex-end;
gap: 8px;
}
.prices .price-line {
margin-bottom: 4px;
}
.quantity-input {
max-width: 90px;
}
.quantity-input input {
text-align: center;
}
.qty-btn {
min-width: 36px !important;
height: 36px !important;
border-radius: 18px !important;
}
@media (max-width: 600px) {
.product-img {
width: 120px;
height: 80px;
}
}
</style>

7
src/pages/salir.vue Normal file
View File

@@ -0,0 +1,7 @@
<template>
<Logout />
</template>
<script setup>
//
</script>

72
src/services/auth.js Normal file
View File

@@ -0,0 +1,72 @@
class AuthService {
static TOKEN_KEY = 'access_token';
static REFRESH_KEY = 'refresh_token';
static async login(credentials) {
const url = `${import.meta.env.VITE_DJANGO_BASE_URL}/api/token/`;
const resp = await fetch(url, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(credentials),
});
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() {
return localStorage.getItem(this.TOKEN_KEY);
}
static getRefreshToken() {
return localStorage.getItem(this.REFRESH_KEY);
}
static async refresh() {
const refresh = this.getRefreshToken();
if (!refresh) throw new Error('No refresh token');
const url = `${import.meta.env.VITE_DJANGO_BASE_URL}/api/token/refresh/`;
const resp = await fetch(url, {
method: 'POST',
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);
}
}
export default AuthService;

View File

@@ -1,8 +1,19 @@
import AuthService from '@/services/auth';
import http from '@/services/http';
class DjangoApi { class DjangoApi {
constructor() { constructor() {
this.base = import.meta.env.VITE_DJANGO_BASE_URL; this.base = import.meta.env.VITE_DJANGO_BASE_URL;
} }
getRequest(url) {
return http.get(url).then(r => r.data);
}
postRequest(url, payload) {
return http.post(url, payload).then(r => r.data);
}
getCustomers() { getCustomers() {
const url = this.base + '/don_confiao/api/customers/'; const url = this.base + '/don_confiao/api/customers/';
return this.getRequest(url); return this.getRequest(url);
@@ -77,45 +88,6 @@ class DjangoApi {
const url = this.base + '/don_confiao/api/enviar_ventas_a_tryton'; const url = this.base + '/don_confiao/api/enviar_ventas_a_tryton';
return this.postRequest(url, {}); return this.postRequest(url, {});
} }
getRequest(url) {
return new Promise ((resolve, reject) => {
fetch(url)
.then(response => response.json())
.then(data => {
resolve(data);
})
.catch(error => {
reject(error);
});
});
}
postRequest(url, content) {
return new Promise((resolve, reject) => {
fetch(url, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify(content)
})
.then(response => {
if (!response.ok) {
reject(new Error(`Error ${response.status}: ${response.statusText}`));
} else {
response.json().then(data => {
if (!data) {
reject(new Error('La respuesta no es un JSON válido'));
} else {
resolve(data);
}
});
}
})
.catch(error => reject(error));
});
}
} }
export default DjangoApi; export default DjangoApi;

44
src/services/http.js Normal file
View 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;

View File

@@ -50,7 +50,7 @@ export default defineConfig({
} }, } },
resolve: { resolve: {
alias: { alias: {
'@': fileURLToPath(new URL('./src', import.meta.url)) '@': fileURLToPath(new URL('./src', import.meta.url)),
}, },
extensions: [ extensions: [
'.js', '.js',