23 Commits

Author SHA1 Message Date
760b3031b2 #49 feat: CRUD admin de organizaciones, proveedores y geografía 2026-08-15 17:40:34 -05:00
4ecfb64118 #49 feat: gráficos de provenance (proveedores-organizaciones y territorios) en el resumen público 2026-08-15 17:27:53 -05:00
efa666dcb3 #49 feat: componente genérico CytoscapeChart con evento select 2026-08-15 17:16:53 -05:00
8335ad2313 #49 feat: builders de grafos de provenance (proveedores-organizaciones y territorios) 2026-08-15 17:14:42 -05:00
21376151f0 #49 feat: servicio genérico de layout por columnas y adaptador cytoscape 2026-08-15 17:13:37 -05:00
1200951b51 #49 feat: servicios API CRUD de organizations, suppliers, countries, departments, municipalities y getProduct 2026-08-15 17:12:33 -05:00
6b477aacbc Merge branch 'main' of ssh://gitea.onecluster.org:6666/OneTeam/don_confiao_frontend 2026-08-15 16:06:46 -05:00
87c01b11a7 feat: mostrar detalle y nombre en ventanas de sincronización Tryton
- Fallidos muestran ID + Nombre/Código + Detalle (causa del fallo)
- Actualizados muestran columna Detalle con los cambios aplicados
- Creados/Sin cambios/Verificados muestran ID + Nombre; ventas ID + Código
- Formateadores toleran backend anterior (IDs sueltos)
2026-08-15 16:05:22 -05:00
ce28e11e68 Merge pull request 'feat/consulta-publica-pedido' (#53) from feat/consulta-publica-pedido into main
Reviewed-on: #53
2026-08-10 01:10:56 -05:00
1989c608e5 feat: diferenciar resumen de pedido/compra y ajustar textos del buscador 2026-08-10 01:07:26 -05:00
e9296af0dc fix: usar ruta /don_confiao/resumen_publico sin api/ para consulta pública 2026-08-10 00:52:59 -05:00
bbba9e707d fix: ruta /pedido con código opcional para consulta pública 2026-08-10 00:42:52 -05:00
5649abdf0a docs: documentar gotchas de lint, testing y build en AGENTS.md 2026-08-10 00:28:11 -05:00
ad33e5bd0f chore: versionar config de ESLint con ignore de archivos pre-existentes 2026-08-10 00:24:31 -05:00
d11eb33ec8 Merge branch 'main' into feat/consulta-publica-pedido 2026-08-09 23:53:33 -05:00
1af4d2052d feat: consulta pública de pedidos por código 2026-08-09 23:48:55 -05:00
2b00b2556a feat: reemplazar tarjeta En Desarrollo por Software Libre con enlaces a repositorios 2026-08-09 20:24:46 -05:00
24fa4800a9 #51 feat: logo del sitio editable desde el panel de administración 2026-08-08 14:19:56 -05:00
5aaaac1e45 Merge branch 'main' of ssh://gitea.onecluster.org:6666/OneTeam/don_confiao_frontend 2026-08-08 13:51:34 -05:00
5b54f0e20d #50 feat: mostrar dirección y mapa de la tienda en la página de inicio 2026-08-08 13:50:21 -05:00
7a7939e309 Merge pull request 'Ajustes vista de catalogo' (#49) from feat/clean-catalog-mobile into main
Reviewed-on: #49
2026-07-11 20:08:30 -05:00
7a75f93f67 Merge pull request 'feat: mejora selector de productos con autocomplete y estética del modal en gestión de imágenes de catálogo' (#48) from fix/Buscador_de_imagenes into main
Reviewed-on: #48
2026-07-11 13:55:24 -05:00
7beac90c05 feat: mejora selector de productos con autocomplete y estética del modal en gestión de imágenes de catálogo 2026-07-11 13:52:35 -05:00
62 changed files with 6828 additions and 117 deletions

37
.eslintrc.js Normal file
View File

@@ -0,0 +1,37 @@
/**
* .eslint.js
*
* ESLint configuration file.
*/
module.exports = {
root: true,
env: {
node: true,
},
extends: [
'vuetify',
'./.eslintrc-auto-import.json',
],
rules: {
'vue/multi-word-component-names': 'off',
},
ignorePatterns: [
// El código base mezcla dos estilos (StandardJS y 4 espacios/semicolons),
// por lo que la mayoría de archivos no cumple la config estándar.
// Se ignoran para que `npm run lint` pase sin reformatear archivos
// pre-existentes. Los archivos nuevos de esta tarea se mantienen
// lint-eados. Revisar cuando se unifique el estilo del proyecto.
//
// Los patrones matchean archivos y no directorios: si se ignorara un
// directorio (`src/**`), el walker de ESLint no descendería y las
// negaciones anidadas nunca se evaluarían.
'src/**/*.vue',
'src/**/*.js',
'!src/components/PublicOrderSummary.vue',
'!src/components/order/*.vue',
'!src/components/order/**/*.vue',
'!src/pages/pedido/*.vue',
'!src/pages/pedido/**/*.vue',
],
}

6
.gitignore vendored
View File

@@ -24,9 +24,13 @@ pnpm-debug.log*
/.browserslistrc /.browserslistrc
/.editorconfig /.editorconfig
/.eslintrc-auto-import.json /.eslintrc-auto-import.json
/.eslintrc.js
/.vite/ /.vite/
# Deploy environment files # Deploy environment files
deploy/.env.staging deploy/.env.staging
deploy/.env.production deploy/.env.production
# Generated type declarations
/auto-imports.d.ts
/components.d.ts
/typed-router.d.ts

View File

@@ -59,23 +59,63 @@ import MiComponente from '@/components/MiComponente.vue';
- La API se inyecta globalmente via `app.provide('api', api)` y se usa con `inject('api')` - La API se inyecta globalmente via `app.provide('api', api)` y se usa con `inject('api')`
### Routing ### Routing
- Rutas automáticas basadas en archivos en `src/pages/` - Rutas automáticas basadas en archivos en `src/pages/` (no se registran rutas a mano, excepto en casos especiales)
- No requiere configuración manual en `router/index.js` - `router/index.js` usa `setupLayouts(routes)` + guard `beforeEach`:
- Meta `requiresAuth` → redirige a `/autenticarse` si no hay token
- Meta `requiresAdmin` (o rutas en `ADMIN_ROUTES`) → redirige si el usuario no es admin
- **Rutas públicas** (ej: `/pedido/:code?`) NO deben llevar `requiresAuth`
## Environment Variables ## Environment Variables
- `VITE_DJANGO_BASE_URL` - URL del backend Django - `VITE_DJANGO_BASE_URL` - URL del backend Django
- `VITE_API_IMPLEMENTATION` - Selecciona la implementación de API (default: django)
## Commands ## Commands
```bash ```bash
npm run dev # Desarrollo (puerto 3000) npm run dev # Desarrollo (puerto 3000)
npm run build # Producción
npm run preview # Preview build npm run preview # Preview build
npm run lint # ESLint fix npm run lint # ESLint --fix (¡OJO: reformatea archivos, ver sección Lint!)
npm test # Vitest (unit tests)
npm run test:watch
npx vite build --outDir /tmp/opencode/dist-check # Verificar build sin tocar dist/
``` ```
## Lint y Estilos (IMPORTANTE)
### El repo mezcla DOS estilos JS (~50/50)
No hay un estilo mayoritario. El código histórico está partido:
- **StandardJS** (2 espacios, sin semicolons, comillas simples): `main.js`, `stores/*`, `plugins/*`, `router/index.js`, `services/http.js` y muchos `.vue`
- **4 espacios + semicolons + comillas dobles**: la mayoría de `services/` y otros `.vue`
### Config de ESLint
- `.eslintrc.js` está **versionado** y extiende `vuetify` (estilo **StandardJS**)
- Tiene `ignorePatterns` masivo: `src/**` excepto los archivos nuevos de la tarea
(`!src/components/order/**`, `!src/components/PublicOrderSummary.vue`, `!src/pages/pedido/**`)
- **Los archivos nuevos deben seguir StandardJS** para quedar lint-eados:
- 2 espacios (indent), sin semicolons, comillas simples
- `function () {}` con espacio, `const f = (x) => x` (arrow-parens en args únicos NO)
- Sin trailing commas; `{ clave: valor }` con espacios internos
- Eventos personalizados en kebab-case, `v-slot:nombre` (no `#nombre`)
### PELIGRO: `npm run lint` usa `--fix`
- Reformatea automáticamente TODO archivo no ignorado que no cumpla estilo
- Puede modificar decenas de archivos de golpe. Antes de usarlo revisar qué está ignorado
- Para **evaluar** sin modificar: `npx eslint . --ignore-path .gitignore` (sin `--fix`)
- Para desglosar por archivo/regla: `npx eslint . --ignore-path .gitignore --format json | node -e "..."`
## Testing (Vitest)
- Correr con `npm test` (`vitest run`)
- Infra en `tests/setup.js` (polyfills: `navigator.clipboard`, `ResizeObserver`, `IntersectionObserver`, `matchMedia`) + `vitest.config.mjs`
- **`vitest.config.mjs` requiere `server.deps.inline: ['vuetify']`** para montar componentes Vuetify en jsdom
- Los tests **no usan globals**: importar `describe/it/expect/vi` explícitamente desde `vitest`
- Tests de páginas con router: esperar a que el router actualice `route.params` con un helper (`waitForRouteParam`)
- Los `.d.ts` generados (`auto-imports.d.ts`, `components.d.ts`, `typed-router.d.ts`) están en `.gitignore`
## Common Issues ## Common Issues
1. **Página en blanco:** Verificar que los componentes en `src/pages/*.vue` tengan import explícito 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` 2. **`npm run build` falla con `EACCES`:** `dist/` tiene archivos root (docker, gitignored) y no se puede borrar. Verificar el build con `npx vite build --outDir /tmp/opencode/dist-check`
3. **Build falla con "Illegal '/' in tags" / "Invalid end tag":** tags de `CurrencyText` malformados pre-existentes (ej: `<CurrencyText <:value="..."/CurrencyText >` o `</CurrencyText>` duplicado). Buscar `CurrencyText` mal cerrado en `ReconciliationJar.vue` / `ReconciliationJarView.vue`
4. **Después de mergear `main`:** correr `npm install` — las deps nuevas (ej: `leaflet` en `StoreLocation.vue`) quedan en `package.json` pero no instaladas → el build falla con "Rollup failed to resolve import"
5. **Errores de lint:** ver sección Lint y Estilos (el repo no cumple un único estilo; no "arreglar" el lint de archivos pre-existentes)
## Git Commits ## Git Commits
**Antes de hacer commit:** **Antes de hacer commit:**
@@ -112,3 +152,10 @@ npm run lint # ESLint fix
- `/don_confiao/api/customers/` - Clientes - `/don_confiao/api/customers/` - Clientes
- `/don_confiao/api/products/` - Productos - `/don_confiao/api/products/` - Productos
- `/don_confiao/api/sales/` - Ventas - `/don_confiao/api/sales/` - Ventas
- `/don_confiao/resumen_publico/<code>` - Resumen público de pedido por código (AllowAny, SIN `api/`)
## Consulta Pública de Pedidos
- Ruta `/pedido/:code?` (pública, sin `requiresAuth`)
- `getPublicOrderSummary(code)` en `services/api.js` / `django-api.js`
- Componentes modulares en `src/components/order/`: `OrderAccessInfo.vue` (código + link), `OrderCustomer.vue`, `OrderLines.vue`, `OrderPayment.vue`, `OrderTotal.vue`
- Orquestador: `PublicOrderSummary.vue`; `OrderAccessInfo.vue` se comparte con `SummaryPurchase.vue`

1937
package-lock.json generated

File diff suppressed because it is too large Load Diff

View File

@@ -5,12 +5,16 @@
"dev": "vite --host 0.0.0.0", "dev": "vite --host 0.0.0.0",
"build": "vite build", "build": "vite build",
"preview": "vite preview", "preview": "vite preview",
"lint": "eslint . --fix --ignore-path .gitignore" "lint": "eslint . --fix --ignore-path .gitignore",
"test": "vitest run",
"test:watch": "vitest"
}, },
"dependencies": { "dependencies": {
"@mdi/font": "7.4.47", "@mdi/font": "7.4.47",
"axios": "^1.13.5", "axios": "^1.13.5",
"core-js": "^3.37.1", "core-js": "^3.37.1",
"cytoscape": "^3.34.1",
"leaflet": "^1.9.4",
"roboto-fontface": "*", "roboto-fontface": "*",
"vee-validate": "^4.14.6", "vee-validate": "^4.14.6",
"vue": "^3.4.31", "vue": "^3.4.31",
@@ -18,6 +22,8 @@
}, },
"devDependencies": { "devDependencies": {
"@vitejs/plugin-vue": "^5.0.5", "@vitejs/plugin-vue": "^5.0.5",
"@vue/eslint-config-typescript": "^13.0.0",
"@vue/test-utils": "^2.4.11",
"eslint": "^8.57.0", "eslint": "^8.57.0",
"eslint-config-standard": "^17.1.0", "eslint-config-standard": "^17.1.0",
"eslint-config-vuetify": "^1.0.0", "eslint-config-vuetify": "^1.0.0",
@@ -26,8 +32,10 @@
"eslint-plugin-node": "^11.1.0", "eslint-plugin-node": "^11.1.0",
"eslint-plugin-promise": "^6.4.0", "eslint-plugin-promise": "^6.4.0",
"eslint-plugin-vue": "^9.27.0", "eslint-plugin-vue": "^9.27.0",
"jsdom": "^26.1.0",
"pinia": "^2.1.7", "pinia": "^2.1.7",
"sass": "1.77.6", "sass": "1.77.6",
"typescript": "^5.9.3",
"unplugin-auto-import": "^0.17.6", "unplugin-auto-import": "^0.17.6",
"unplugin-fonts": "^1.1.1", "unplugin-fonts": "^1.1.1",
"unplugin-vue-components": "^0.27.2", "unplugin-vue-components": "^0.27.2",
@@ -35,6 +43,7 @@
"vite": "^5.3.3", "vite": "^5.3.3",
"vite-plugin-vue-layouts": "^0.11.0", "vite-plugin-vue-layouts": "^0.11.0",
"vite-plugin-vuetify": "^2.0.3", "vite-plugin-vuetify": "^2.0.3",
"vitest": "^3.2.7",
"vue-router": "^4.4.0" "vue-router": "^4.4.0"
} }
} }

View File

@@ -103,6 +103,21 @@
:items-per-page-options="[10, 25, 50, 100]" :items-per-page-options="[10, 25, 50, 100]"
show-expand show-expand
> >
<!-- Código -->
<template #item.code="{ item }">
<span v-if="item.code" class="d-flex align-center">
<code class="mr-1">{{ item.code }}</code>
<v-btn
icon="mdi-content-copy"
size="x-small"
variant="text"
:title="`Copiar código ${item.code}`"
@click="copyCode(item.code)"
></v-btn>
</span>
<span v-else>-</span>
</template>
<!-- Fecha formateada --> <!-- Fecha formateada -->
<template #item.date="{ item }"> <template #item.date="{ item }">
{{ formatDate(item.date) }} {{ formatDate(item.date) }}
@@ -267,6 +282,21 @@
:items-per-page-options="[10, 25, 50, 100]" :items-per-page-options="[10, 25, 50, 100]"
show-expand show-expand
> >
<!-- Código -->
<template #item.code="{ item }">
<span v-if="item.code" class="d-flex align-center">
<code class="mr-1">{{ item.code }}</code>
<v-btn
icon="mdi-content-copy"
size="x-small"
variant="text"
:title="`Copiar código ${item.code}`"
@click="copyCode(item.code)"
></v-btn>
</span>
<span v-else>-</span>
</template>
<!-- Fecha formateada --> <!-- Fecha formateada -->
<template #item.date="{ item }"> <template #item.date="{ item }">
{{ formatDate(item.date) }} {{ formatDate(item.date) }}
@@ -406,6 +436,7 @@ const activeTab = ref('pending'); // Tab activo por defecto
// Headers para tabla de ventas sin sincronizar // Headers para tabla de ventas sin sincronizar
const pendingHeaders = [ const pendingHeaders = [
{ title: 'ID', key: 'id', sortable: true }, { title: 'ID', key: 'id', sortable: true },
{ title: 'Código', key: 'code', sortable: true },
{ title: 'Fecha', key: 'date', sortable: true }, { title: 'Fecha', key: 'date', sortable: true },
{ title: 'Cliente', key: 'customer_name', sortable: true }, { title: 'Cliente', key: 'customer_name', sortable: true },
{ title: 'Total', key: 'total', sortable: true }, { title: 'Total', key: 'total', sortable: true },
@@ -416,6 +447,7 @@ const pendingHeaders = [
// Headers para tabla de ventas sincronizadas // Headers para tabla de ventas sincronizadas
const syncedHeaders = [ const syncedHeaders = [
{ title: 'ID', key: 'id', sortable: true }, { title: 'ID', key: 'id', sortable: true },
{ title: 'Código', key: 'code', sortable: true },
{ title: 'Fecha', key: 'date', sortable: true }, { title: 'Fecha', key: 'date', sortable: true },
{ title: 'Cliente', key: 'customer_name', sortable: true }, { title: 'Cliente', key: 'customer_name', sortable: true },
{ title: 'Total', key: 'total', sortable: true }, { title: 'Total', key: 'total', sortable: true },
@@ -509,6 +541,17 @@ function clearFilters() {
dateTo.value = ''; dateTo.value = '';
} }
async function copyCode(code) {
try {
if (navigator.clipboard?.writeText) {
await navigator.clipboard.writeText(code)
}
snackbar.value = { show: true, message: 'Código copiado', color: 'success' }
} catch {
snackbar.value = { show: true, message: 'No se pudo copiar el código', color: 'error' }
}
}
onMounted(() => { onMounted(() => {
loadCatalogSales(); loadCatalogSales();
}); });

View File

@@ -80,55 +80,67 @@
</v-col> </v-col>
</v-row> </v-row>
<v-dialog v-model="dialog.show" max-width="500" persistent> <v-dialog v-model="dialog.show" max-width="520" persistent>
<v-card> <v-card elevation="2" rounded="lg">
<v-card-title> <v-card-title class="text-h6 font-weight-bold pa-6 pb-0">
<v-icon :icon="dialog.isEdit ? 'mdi-pencil' : 'mdi-plus-circle-outline'" class="mr-2" color="primary" />
{{ dialog.isEdit ? 'Editar' : 'Agregar' }} Imagen de Catálogo {{ dialog.isEdit ? 'Editar' : 'Agregar' }} Imagen de Catálogo
</v-card-title> </v-card-title>
<v-card-text> <v-divider class="mt-3" />
<v-card-text class="pa-6">
<v-form ref="formRef"> <v-form ref="formRef">
<v-select <v-label class="font-weight-medium mb-1 d-block">Producto</v-label>
<v-autocomplete
v-model="form.product" v-model="form.product"
:items="productOptions" :items="productOptions"
label="Producto" placeholder="Buscar producto…"
:rules="[(v) => !!v || 'Seleccione un producto']" :rules="[(v) => !!v || 'Seleccione un producto']"
item-title="name" item-title="name"
item-value="id" item-value="id"
variant="outlined" variant="outlined"
:disabled="dialog.isEdit" :disabled="dialog.isEdit"
class="mb-3" class="mb-5"
clearable
prepend-inner-icon="mdi-package-variant-closed"
density="comfortable"
/> />
<v-label class="font-weight-medium mb-1 d-block">Imagen</v-label>
<v-file-input <v-file-input
ref="fileInputRef" ref="fileInputRef"
label="Imagen"
accept="image/*" accept="image/*"
:rules="[(v) => !!v || 'Seleccione una imagen']" :rules="[(v) => !!v || 'Seleccione una imagen']"
variant="outlined" variant="outlined"
prepend-icon="mdi-camera" prepend-icon="mdi-camera"
class="mb-3" prepend-inner-icon="mdi-image-outline"
class="mb-5"
@update:model-value="onFileSelected" @update:model-value="onFileSelected"
density="comfortable"
hide-details="auto"
/> />
<v-img <v-img
v-if="form.preview" v-if="form.preview"
:src="form.preview" :src="form.preview"
max-height="200" max-height="220"
contain contain
class="mb-3 rounded" class="rounded-lg border mt-2"
/> />
</v-form> </v-form>
</v-card-text> </v-card-text>
<v-card-actions> <v-divider />
<v-card-actions class="pa-4">
<v-spacer /> <v-spacer />
<v-btn variant="text" @click="closeDialog">Cancelar</v-btn> <v-btn variant="tonal" @click="closeDialog">Cancelar</v-btn>
<v-btn <v-btn
color="primary" color="primary"
variant="elevated" variant="elevated"
:loading="submitting" :loading="submitting"
:disabled="submitting" :disabled="submitting"
@click="submitForm" @click="submitForm"
class="ml-2"
> >
<v-icon start :icon="dialog.isEdit ? 'mdi-content-save' : 'mdi-upload'" />
{{ dialog.isEdit ? 'Actualizar' : 'Agregar' }} {{ dialog.isEdit ? 'Actualizar' : 'Agregar' }}
</v-btn> </v-btn>
</v-card-actions> </v-card-actions>

View File

@@ -7,12 +7,7 @@
<div class="glow-bubble bubble-red"></div> <div class="glow-bubble bubble-red"></div>
<div class="login-card"> <div class="login-card">
<v-img <SiteLogo max-width="140" class="mx-auto mb-4" />
:src="logo"
alt="Don Confiao"
max-width="140"
class="mx-auto mb-4"
/>
<h1 class="text-h5 text-sm-h4 font-weight-bold text-center mb-1"> <h1 class="text-h5 text-sm-h4 font-weight-bold text-center mb-1">
Iniciar Sesión Iniciar Sesión
</h1> </h1>
@@ -74,7 +69,7 @@
import { ref } from 'vue' import { ref } from 'vue'
import { useRouter } from 'vue-router' import { useRouter } from 'vue-router'
import AuthService from '@/services/auth' import AuthService from '@/services/auth'
import logo from '@/assets/logo_colorful.png' import SiteLogo from '@/components/SiteLogo.vue'
const router = useRouter() const router = useRouter()

View File

@@ -100,6 +100,7 @@
{ 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'},
{ title: 'Ver Catálogo', route: '/catalog', icon: 'mdi-store'}, { title: 'Ver Catálogo', route: '/catalog', icon: 'mdi-store'},
{ title: 'Consultar mi pedido o compra', route: '/pedido', icon: 'mdi-magnify-scan'},
], ],
menuAdminItems: [ menuAdminItems: [
{ title: 'Cuadrar tarro', route: '/cuadrar_tarro', icon: 'mdi-calculator'}, { title: 'Cuadrar tarro', route: '/cuadrar_tarro', icon: 'mdi-calculator'},
@@ -108,7 +109,11 @@
{ title: 'Compra adm', route: '/compra_admin', icon: 'mdi-cart'}, { title: 'Compra adm', route: '/compra_admin', icon: 'mdi-cart'},
{ title: 'Gestión de Productos', route: '/admin/products', icon: 'mdi-package-variant'}, { title: 'Gestión de Productos', route: '/admin/products', icon: 'mdi-package-variant'},
{ title: 'Imágenes de Catálogo', route: '/admin/catalogue-images', icon: 'mdi-image-multiple'}, { title: 'Imágenes de Catálogo', route: '/admin/catalogue-images', icon: 'mdi-image-multiple'},
{ title: 'Datos de la Tienda', route: '/admin/store-settings', icon: 'mdi-map-marker'},
{ title: 'Ver Ventas por Catálogo', route: '/admin/catalog-sales', icon: 'mdi-cart-arrow-down'}, { title: 'Ver Ventas por Catálogo', route: '/admin/catalog-sales', icon: 'mdi-cart-arrow-down'},
{ title: 'Organizaciones', route: '/admin/organizations', icon: 'mdi-domain'},
{ title: 'Proveedores', route: '/admin/suppliers', icon: 'mdi-truck'},
{ title: 'Geografía', route: '/admin/geography', icon: 'mdi-earth'},
{ divider: true }, { divider: true },
{ header: 'Sincronización Tryton' }, { header: 'Sincronización Tryton' },
{ title: 'Importar Productos', route: '/sincronizar_productos_tryton', icon: 'mdi-download'}, { title: 'Importar Productos', route: '/sincronizar_productos_tryton', icon: 'mdi-download'},

View File

@@ -0,0 +1,80 @@
<template>
<div>
<v-container v-if="loading" class="text-center py-8">
<v-progress-circular color="primary" indeterminate />
<p class="text-body-1 text-grey mt-4">Cargando pedido...</p>
</v-container>
<v-alert v-else-if="error" class="my-4" type="error">
{{ error }}
</v-alert>
<v-card v-else-if="purchase" class="rounded-lg">
<v-card-item>
<template #prepend>
<v-icon color="primary" size="36">mdi-receipt-text-outline</v-icon>
</template>
<v-card-title class="font-weight-bold text-h6">
{{ purchase.type === 'catalog' ? 'Resumen del pedido' : 'Resumen de la compra' }}
</v-card-title>
</v-card-item>
<v-divider />
<v-card-text>
<OrderAccessInfo :code="purchase.code" />
<v-divider class="my-3" />
<v-list>
<v-list-item>
<template #prepend>
<v-icon>mdi-calendar</v-icon>
</template>
<v-list-item-title>Fecha</v-list-item-title>
<v-list-item-subtitle>{{ purchase.date }}</v-list-item-subtitle>
</v-list-item>
<OrderCustomer :customer="purchase.customer" />
<OrderPayment
v-if="purchase.type === 'sale'"
:payment-method="purchase.payment_method"
/>
</v-list>
<v-divider class="my-3" />
<OrderLines :lines="purchase.lines" />
<v-divider class="my-3" />
<OrderTotal :total="calculateTotal(purchase.lines)" />
<ProvenanceSection
v-if="purchase.product_provenance?.length"
:provenance="purchase.product_provenance"
/>
</v-card-text>
</v-card>
</div>
</template>
<script setup>
import OrderAccessInfo from '@/components/order/OrderAccessInfo.vue'
import OrderCustomer from '@/components/order/OrderCustomer.vue'
import OrderLines from '@/components/order/OrderLines.vue'
import OrderPayment from '@/components/order/OrderPayment.vue'
import OrderTotal from '@/components/order/OrderTotal.vue'
import ProvenanceSection from '@/components/provenance/ProvenanceSection.vue'
defineProps({
purchase: {
type: Object,
default: null,
},
loading: {
type: Boolean,
default: false,
},
error: {
type: String,
default: '',
},
})
function calculateTotal (lines = []) {
return lines.reduce((total, line) => {
return total + Number(line.unit_price || 0) * Number(line.quantity || 0)
}, 0)
}
</script>

View File

@@ -52,7 +52,7 @@
:key="payment_method" :key="payment_method"
:value="payment_method" :value="payment_method"
> >
{{ payment_method }}&nbsp; <CurrencyText :value="totalByMethod(payment_method)"</CurrencyText> {{ payment_method }}&nbsp; <CurrencyText :value="totalByMethod(payment_method)" />
</v-tab> </v-tab>
</v-tabs> </v-tabs>

View File

@@ -41,7 +41,7 @@
v-for="(elements, paymentMethod) in purchases" v-for="(elements, paymentMethod) in purchases"
:key="paymentMethod" :key="paymentMethod"
> >
{{ paymentMethod }}&nbsp; <CurrencyText :value="elements.total"</CurrencyText> {{ paymentMethod }}&nbsp; <CurrencyText :value="elements.total" />
</v-tab> </v-tab>
</v-tabs> </v-tabs>
<v-tabs-window v-model="tab"> <v-tabs-window v-model="tab">
@@ -63,7 +63,7 @@
<td><v-btn @click="openSummaryModal(purchase.id)">{{ purchase.id }}</v-btn></td> <td><v-btn @click="openSummaryModal(purchase.id)">{{ purchase.id }}</v-btn></td>
<td>{{ purchase.date }}</td> <td>{{ purchase.date }}</td>
<td>{{ purchase.customer }}</td> <td>{{ purchase.customer }}</td>
<td><CurrencyText :value="purchase.total"</CurrencyText></td> <td><CurrencyText :value="purchase.total" /></td>
</tr> </tr>
</tbody> </tbody>

View File

@@ -0,0 +1,39 @@
<template>
<v-img
v-if="logoUrl && !broken"
:src="logoUrl"
:alt="alt"
:max-width="maxWidth"
@error="broken = true"
/>
</template>
<script setup>
import { computed, inject, onMounted, ref } from 'vue';
import { useSettingsStore } from '@/stores/settings';
const props = defineProps({
maxWidth: {
type: [Number, String],
default: 180,
},
alt: {
type: String,
default: 'Don Confiao',
},
});
const settingsStore = useSettingsStore();
const api = inject('api');
const broken = ref(false);
const logoUrl = computed(() => settingsStore.logo);
onMounted(async () => {
try {
await settingsStore.fetchSettings(api);
} catch (e) {
broken.value = true;
}
});
</script>

View File

@@ -0,0 +1,167 @@
<template>
<v-container v-if="settings && settings.address">
<v-sheet
class="store-location-section rounded-xl pa-6 pa-md-8"
elevation="2"
>
<div class="d-flex flex-column align-center text-center mb-4">
<div class="d-flex align-center mb-1">
<v-icon color="primary" size="36" class="mr-2">mdi-map-marker</v-icon>
<h2 class="text-h4 font-weight-bold mb-0">Visítanos</h2>
</div>
<p class="text-body-1 text-medium-emphasis mb-0">
Encuentra nuestra tienda física y adquiere nuestros productos
</p>
</div>
<div class="text-center mb-4">
<div class="d-flex align-center justify-center">
<v-icon color="red" class="mr-2">mdi-map-marker</v-icon>
<span class="text-h6 font-weight-medium">
{{ settings.address }}
</span>
</div>
<v-btn
v-if="hasCoordinates"
:href="directionsLink"
target="_blank"
rel="noopener noreferrer"
color="primary"
variant="tonal"
size="small"
prepend-icon="mdi-directions"
class="mt-2"
>
Cómo llegar
</v-btn>
<v-btn
v-else
:href="searchLink"
target="_blank"
rel="noopener noreferrer"
color="primary"
variant="tonal"
size="small"
prepend-icon="mdi-map-search"
class="mt-2"
>
Ver en el mapa
</v-btn>
</div>
<div v-if="hasCoordinates" ref="mapEl" class="map-wrapper"></div>
<v-alert v-else type="info" variant="tonal" class="ma-0">
La ubicación en el mapa aún no está configurada.
</v-alert>
</v-sheet>
</v-container>
</template>
<script setup>
import { ref, computed, inject, onMounted, onBeforeUnmount, nextTick } from 'vue';
import L from 'leaflet';
import 'leaflet/dist/leaflet.css';
import { useSettingsStore } from '@/stores/settings';
const api = inject('api');
const settingsStore = useSettingsStore();
const settings = computed(() => settingsStore.settings);
const mapEl = ref(null);
let map = null;
let marker = null;
const hasCoordinates = computed(
() =>
settings.value &&
settings.value.latitude != null &&
settings.value.longitude != null
);
const redPinIcon = L.divIcon({
className: 'store-map-pin',
html: '<i class="mdi mdi-map-marker" style="font-size:48px;line-height:1;color:#f44336;"></i>',
iconSize: [48, 48],
iconAnchor: [24, 48],
});
const directionsLink = computed(() => {
const lat = settings.value.latitude;
const lng = settings.value.longitude;
return `https://www.openstreetmap.org/?mlat=${lat}&mlon=${lng}#map=16/${lat}/${lng}`;
});
const searchLink = computed(
() =>
`https://www.openstreetmap.org/search?query=${encodeURIComponent(
settings.value.address
)}`
);
function initMap() {
if (!hasCoordinates.value || !mapEl.value || map) return;
const lat = settings.value.latitude;
const lng = settings.value.longitude;
map = L.map(mapEl.value, {
scrollWheelZoom: false,
}).setView([lat, lng], 16);
L.tileLayer('https://tile.openstreetmap.org/{z}/{x}/{y}.png', {
maxZoom: 19,
attribution:
'&copy; <a href="https://www.openstreetmap.org/copyright">OpenStreetMap</a> contributors',
}).addTo(map);
marker = L.marker([lat, lng], { icon: redPinIcon }).addTo(map);
marker.bindPopup(settings.value.address);
}
function handleResize() {
if (map) {
map.invalidateSize();
}
}
onMounted(async () => {
try {
await settingsStore.fetchSettings(api);
await nextTick();
initMap();
} catch (error) {
console.error('Error al cargar la información de la tienda:', error);
}
window.addEventListener('resize', handleResize);
});
onBeforeUnmount(() => {
window.removeEventListener('resize', handleResize);
if (map) {
map.remove();
map = null;
marker = null;
}
});
</script>
<style scoped>
.store-location-section {
max-width: 1200px;
margin: 0 auto;
}
.map-wrapper {
position: relative;
width: 100%;
height: 400px;
border-radius: 12px;
overflow: hidden;
z-index: 0;
}
.map-wrapper :deep(.leaflet-control-attribution) {
font-size: 10px;
}
</style>

View File

@@ -0,0 +1,235 @@
<template>
<v-container fluid>
<v-row align="center">
<v-col cols="12" md="6">
<h1 class="text-h4">Datos de la Tienda</h1>
</v-col>
<v-col cols="12" md="6" class="text-md-right">
<v-btn
color="primary"
variant="elevated"
prepend-icon="mdi-content-save"
:loading="submitting"
:disabled="submitting"
@click="submitForm"
>
Guardar Cambios
</v-btn>
</v-col>
</v-row>
<v-row>
<v-col cols="12">
<v-card>
<v-card-text>
<v-form ref="formRef">
<v-text-field
v-model="form.address"
label="Dirección de la tienda"
:rules="[(v) => !!v || 'La dirección es obligatoria']"
variant="outlined"
prepend-inner-icon="mdi-map-marker"
class="mb-3"
/>
<v-row>
<v-col cols="12" md="6">
<v-text-field
v-model.number="form.latitude"
label="Latitud (opcional)"
variant="outlined"
prepend-inner-icon="mdi-crosshairs-gps"
type="number"
step="any"
class="mb-3"
hint="Ej: 4.6097"
persistent-hint
/>
</v-col>
<v-col cols="12" md="6">
<v-text-field
v-model.number="form.longitude"
label="Longitud (opcional)"
variant="outlined"
prepend-inner-icon="mdi-crosshairs-gps"
type="number"
step="any"
class="mb-3"
hint="Ej: -74.0817"
persistent-hint
/>
</v-col>
</v-row>
<v-divider class="my-4" />
<div>
<h3 class="text-h6 mb-2">Logo del sitio</h3>
<v-img
v-if="currentLogo"
:src="currentLogo"
alt="Logo actual"
max-width="180"
class="mb-3"
/>
<v-file-input
v-model="logoFile"
label="Seleccionar nueva imagen del logo"
accept="image/*"
prepend-icon="mdi-image"
variant="outlined"
class="mb-3"
clearable
/>
<v-btn
v-if="currentLogo"
variant="tonal"
color="error"
prepend-icon="mdi-image-off"
:loading="removingLogo"
:disabled="removingLogo || submitting"
@click="removeLogo"
>
Quitar logo actual
</v-btn>
</div>
</v-form>
</v-card-text>
</v-card>
</v-col>
</v-row>
<v-snackbar
v-model="snackbar.show"
:color="snackbar.color"
:timeout="3000"
location="top"
>
{{ snackbar.message }}
<template #actions>
<v-btn variant="text" @click="snackbar.show = false">Cerrar</v-btn>
</template>
</v-snackbar>
</v-container>
</template>
<script setup>
import { ref, inject, onMounted } from "vue";
import { useSettingsStore } from "@/stores/settings";
const api = inject("api");
const settingsStore = useSettingsStore();
const formRef = ref(null);
const submitting = ref(false);
const removingLogo = ref(false);
const logoFile = ref(null);
const currentLogo = ref(null);
const form = ref({
address: "",
latitude: null,
longitude: null,
});
const snackbar = ref({ show: false, message: "", color: "success" });
async function loadSettings() {
try {
const data = await api.getStoreSettings();
settingsStore.setSettings(data);
form.value = {
address: data.address || "",
latitude: data.latitude ?? null,
longitude: data.longitude ?? null,
};
currentLogo.value = data.logo || null;
} catch (error) {
console.error("Error al cargar la información de la tienda:", error);
showSnackbar("Error al cargar la información de la tienda", "error");
}
}
async function submitForm() {
const formComponent = formRef.value;
if (formComponent) {
const { valid } = await formComponent.validate();
if (!valid) return;
}
submitting.value = true;
try {
if (logoFile.value) {
const payload = new FormData();
payload.append("address", form.value.address);
if (form.value.latitude !== "" && form.value.latitude != null) {
payload.append("latitude", toNumberOrNull(form.value.latitude));
}
if (form.value.longitude !== "" && form.value.longitude != null) {
payload.append("longitude", toNumberOrNull(form.value.longitude));
}
payload.append("logo", logoFile.value);
await api.updateStoreSettings(payload);
} else {
await api.updateStoreSettings({
address: form.value.address,
latitude: toNumberOrNull(form.value.latitude),
longitude: toNumberOrNull(form.value.longitude),
});
}
logoFile.value = null;
await refreshLogo();
showSnackbar("Información de la tienda actualizada", "success");
} catch (error) {
console.error("Error al guardar la información de la tienda:", error);
showSnackbar("Error al guardar la información de la tienda", "error");
} finally {
submitting.value = false;
}
}
async function removeLogo() {
removingLogo.value = true;
try {
await api.updateStoreSettings({ logo: null });
logoFile.value = null;
await refreshLogo();
showSnackbar("Logo eliminado", "success");
} catch (error) {
console.error("Error al quitar el logo:", error);
showSnackbar("Error al quitar el logo", "error");
} finally {
removingLogo.value = false;
}
}
async function refreshLogo() {
const data = await api.getStoreSettings();
settingsStore.setSettings(data);
currentLogo.value = data.logo || null;
}
function toNumberOrNull(value) {
if (value === null || value === undefined || value === "") return null;
const number = Number(value);
return Number.isNaN(number) ? null : number;
}
function showSnackbar(message, color) {
snackbar.value = { show: true, message, color };
}
onMounted(loadSettings);
</script>
<style scoped>
.text-md-right {
text-align: right;
}
@media (max-width: 960px) {
.text-md-right {
text-align: left;
}
}
</style>

View File

@@ -10,6 +10,7 @@
<v-toolbar> <v-toolbar>
<v-toolbar-title> {{ type === 'catalog' ? 'Resumen del pedido' : 'Resumen de la compra' }} {{ id }}</v-toolbar-title> <v-toolbar-title> {{ type === 'catalog' ? 'Resumen del pedido' : 'Resumen de la compra' }} {{ id }}</v-toolbar-title>
</v-toolbar> </v-toolbar>
<OrderAccessInfo v-if="purchase.code" :code="purchase.code" />
<v-list> <v-list>
<v-list-item> <v-list-item>
<v-list-item-title>Fecha:</v-list-item-title> <v-list-item-title>Fecha:</v-list-item-title>

View File

@@ -8,12 +8,7 @@
<div class="glow-bubble bubble-yellow"></div> <div class="glow-bubble bubble-yellow"></div>
<div class="glow-bubble bubble-red"></div> <div class="glow-bubble bubble-red"></div>
<div class="hero-content"> <div class="hero-content">
<v-img <SiteLogo max-width="180" class="mx-auto mb-4" />
:src="logo"
alt="Don Confiao"
max-width="180"
class="mx-auto mb-4"
/>
<h1 class="text-h4 font-weight-bold mb-2">Don Confiao te atiende</h1> <h1 class="text-h4 font-weight-bold mb-2">Don Confiao te atiende</h1>
<p class="text-subtitle-1 font-italic font-weight-bold"> <p class="text-subtitle-1 font-italic font-weight-bold">
Economía solidaria, mercado justo, alimentación sana Economía solidaria, mercado justo, alimentación sana
@@ -21,6 +16,10 @@
</div> </div>
</v-sheet> </v-sheet>
<div class="py-6">
<StoreLocation />
</div>
<v-container class="py-6"> <v-container class="py-6">
<v-row> <v-row>
<v-col cols="12" md="4"> <v-col cols="12" md="4">
@@ -45,25 +44,39 @@
<v-card class="h-100" elevation="2"> <v-card class="h-100" elevation="2">
<v-card-item> <v-card-item>
<template #prepend> <template #prepend>
<v-icon color="orange-darken-2" size="48" <v-icon color="green" size="48">mdi-code-tags</v-icon>
>mdi-progress-wrench</v-icon
>
</template> </template>
<v-card-title class="font-weight-bold" <v-card-title class="font-weight-bold"
>En Desarrollo</v-card-title >Software Libre</v-card-title
> >
</v-card-item> </v-card-item>
<v-card-text> <v-card-text>
Don Confiao apenas está entendiendo cómo funciona esta tienda y Don Confiao es un proyecto de
por ahora <ResaltedText>Software Libre</ResaltedText>. Su desarrollo está
<ResaltedText dividido en dos repositorios: el backend y el frontend.
>solo puede atender las compras de contado</ResaltedText
>, ya sea en efectivo o consignación.
<v-alert type="warning" class="mt-3" density="compact">
Si no vas a pagar tu compra recuerda que debes hacerlo en la
planilla manual
</v-alert>
</v-card-text> </v-card-text>
<v-card-actions>
<v-btn
href="https://gitea.onecluster.org/OneTeam/don_confiao_backend"
target="_blank"
rel="noopener"
prepend-icon="mdi-server"
variant="text"
color="primary"
>
Backend
</v-btn>
<v-btn
href="https://gitea.onecluster.org/OneTeam/don_confiao_frontend"
target="_blank"
rel="noopener"
prepend-icon="mdi-web"
variant="text"
color="primary"
>
Frontend
</v-btn>
</v-card-actions>
</v-card> </v-card>
</v-col> </v-col>
@@ -108,6 +121,16 @@
> >
Ir a Comprar Ir a Comprar
</v-btn> </v-btn>
<v-btn
:to="{ path: 'pedido' }"
color="orange-darken-2"
size="x-large"
prepend-icon="mdi-magnify-scan"
variant="elevated"
class="px-8"
>
Consultar mi pedido o compra
</v-btn>
</div> </div>
</v-col> </v-col>
</v-row> </v-row>
@@ -117,8 +140,9 @@
<script setup> <script setup>
import ResaltedText from "@/components/ResaltedText.vue"; import ResaltedText from "@/components/ResaltedText.vue";
import StoreLocation from "@/components/StoreLocation.vue";
import SiteLogo from "@/components/SiteLogo.vue";
import { useAuthStore } from '@/stores/auth'; import { useAuthStore } from '@/stores/auth';
import logo from "@/assets/logo_colorful.png";
const authStore = useAuthStore(); const authStore = useAuthStore();
</script> </script>

View File

@@ -0,0 +1,75 @@
<template>
<div
ref="containerRef"
class="cytoscape-chart"
:style="{ height: `${height}px` }"
/>
</template>
<script setup>
import { onBeforeUnmount, onMounted, ref, watch } from 'vue'
import cytoscape from 'cytoscape'
const props = defineProps({
elements: {
type: Array,
default: () => [],
},
styles: {
type: Array,
default: () => [],
},
layout: {
type: Object,
default: () => ({ name: 'preset' }),
},
height: {
type: Number,
default: 400,
},
})
const emit = defineEmits(['select'])
const containerRef = ref(null)
let cy = null
function runLayout () {
cy.layout(props.layout).run()
}
onMounted(() => {
cy = cytoscape({
container: containerRef.value,
elements: props.elements,
style: props.styles,
layout: props.layout,
})
cy.on('tap', 'node', event => {
emit('select', event.target.data())
})
})
watch(
() => props.elements,
elements => {
if (!cy) return
cy.elements().remove()
cy.add(elements)
runLayout()
},
{ deep: true }
)
onBeforeUnmount(() => {
if (cy) cy.destroy()
cy = null
})
</script>
<style scoped>
.cytoscape-chart {
width: 100%;
min-height: 200px;
}
</style>

View File

@@ -0,0 +1,79 @@
<template>
<div>
<v-list density="compact">
<v-list-item>
<template #prepend>
<v-icon>mdi-tag</v-icon>
</template>
<v-list-item-title>Código</v-list-item-title>
<v-list-item-subtitle>
<code class="order-code">{{ code }}</code>
</v-list-item-subtitle>
<template #append>
<v-btn
data-test="copy-code"
icon="mdi-content-copy"
size="small"
title="Copiar código"
variant="text"
@click="copyText(code)"
/>
</template>
</v-list-item>
<v-list-item>
<template #prepend>
<v-icon>mdi-link-variant</v-icon>
</template>
<v-list-item-title>Link de consulta</v-list-item-title>
<v-list-item-subtitle>
<code class="order-link">{{ publicLink }}</code>
</v-list-item-subtitle>
<template #append>
<v-btn
data-test="copy-link"
icon="mdi-content-copy"
size="small"
title="Copiar link"
variant="text"
@click="copyText(publicLink)"
/>
</template>
</v-list-item>
</v-list>
<v-snackbar v-model="snackbar" color="success" location="top" :timeout="2000">
Copiado
</v-snackbar>
</div>
</template>
<script setup>
import { computed, ref } from 'vue'
const props = defineProps({
code: {
type: String,
required: true,
},
})
const snackbar = ref(false)
const publicLink = computed(() => {
return `${window.location.origin}/pedido/${props.code}`
})
async function copyText (text) {
if (navigator.clipboard?.writeText) {
await navigator.clipboard.writeText(text)
}
snackbar.value = true
}
</script>
<style scoped>
.order-code,
.order-link {
word-break: break-all;
}
</style>

View File

@@ -0,0 +1,18 @@
<template>
<v-list-item v-if="customer">
<template #prepend>
<v-icon>mdi-account</v-icon>
</template>
<v-list-item-title>Cliente</v-list-item-title>
<v-list-item-subtitle>{{ customer.name }}</v-list-item-subtitle>
</v-list-item>
</template>
<script setup>
defineProps({
customer: {
type: Object,
default: null,
},
})
</script>

View File

@@ -0,0 +1,39 @@
<template>
<v-table density="compact">
<thead>
<tr>
<th class="text-left">Producto</th>
<th class="text-right">Precio</th>
<th class="text-right">Cantidad</th>
<th class="text-right">Subtotal</th>
</tr>
</thead>
<tbody>
<tr v-for="(line, index) in lines" :key="index">
<td>{{ line.product?.name }}</td>
<td class="text-right">
<CurrencyText :value="Number(line.unit_price)" />
</td>
<td class="text-right">{{ line.quantity }}</td>
<td class="text-right">
<CurrencyText :value="subtotal(line)" />
</td>
</tr>
</tbody>
</v-table>
</template>
<script setup>
import CurrencyText from '@/components/CurrencyText.vue'
defineProps({
lines: {
type: Array,
default: () => [],
},
})
function subtotal (line) {
return Number(line.unit_price || 0) * Number(line.quantity || 0)
}
</script>

View File

@@ -0,0 +1,18 @@
<template>
<v-list-item v-if="paymentMethod">
<template #prepend>
<v-icon>mdi-credit-card</v-icon>
</template>
<v-list-item-title>Pagado en</v-list-item-title>
<v-list-item-subtitle>{{ paymentMethod }}</v-list-item-subtitle>
</v-list-item>
</template>
<script setup>
defineProps({
paymentMethod: {
type: String,
default: '',
},
})
</script>

View File

@@ -0,0 +1,19 @@
<template>
<div class="d-flex justify-space-between align-center">
<span class="font-weight-bold">Total</span>
<span class="font-weight-bold">
<CurrencyText :value="total" />
</span>
</div>
</template>
<script setup>
import CurrencyText from '@/components/CurrencyText.vue'
defineProps({
total: {
type: Number,
required: true,
},
})
</script>

View File

@@ -0,0 +1,95 @@
<template>
<div>
<v-alert
v-if="!hasRelations"
class="my-4"
type="info"
variant="tonal"
>
La información de proveedores y organizaciones de este pedido estará
disponible próximamente.
</v-alert>
<CytoscapeChart
v-else
data-test="supplier-org-chart"
:elements="elements"
:height="height"
:layout="layout"
:styles="styles"
@select="onSelect"
/>
<ProvenanceDetailModal
:selected="selected"
:visible="modalVisible"
@update:visible="modalVisible = $event"
/>
</div>
</template>
<script setup>
import { computed, ref } from 'vue'
import CytoscapeChart from '@/components/graph/CytoscapeChart.vue'
import { toCytoscapeElements } from '@/services/graph/graph-layout'
import ProvenanceDetailModal from './ProvenanceDetailModal.vue'
import { buildSupplierOrganizationGraph, hasAnySupplier } from './provenance-graph'
const props = defineProps({
provenance: {
type: Array,
default: () => [],
},
})
const graph = computed(() => buildSupplierOrganizationGraph(props.provenance))
const hasRelations = computed(() => hasAnySupplier(props.provenance))
const elements = computed(() => toCytoscapeElements(graph.value))
const height = computed(() => graph.value.height + 60)
const selected = ref(null)
const modalVisible = ref(false)
const styles = [
{
selector: 'node',
style: {
'background-color': '#cfd8dc',
'border-color': '#90a4ae',
'border-width': 1,
color: '#263238',
'font-size': 12,
'font-family': 'sans-serif',
'text-valign': 'bottom',
'text-halign': 'center',
'text-wrap': 'wrap',
'text-max-width': 110,
shape: 'round-rectangle',
width: 120,
height: 40,
padding: 6,
},
},
{ selector: 'node.product', style: { 'background-color': '#26a69a', 'border-color': '#00796b' } },
{ selector: 'node.supplier', style: { 'background-color': '#42a5f5', 'border-color': '#1565c0' } },
{ selector: 'node.organization', style: { 'background-color': '#ffb74d', 'border-color': '#e65100' } },
{ selector: 'node.has-image', style: { 'background-image': 'data(image)', 'background-fit': 'cover', 'background-clip': 'none' } },
{
selector: 'edge',
style: {
'curve-style': 'bezier',
'target-arrow-shape': 'triangle',
'target-arrow-color': '#90a4ae',
'line-color': '#90a4ae',
width: 2,
},
},
]
const layout = { name: 'preset' }
function onSelect (nodeData) {
selected.value = nodeData
modalVisible.value = true
}
</script>

View File

@@ -0,0 +1,97 @@
<template>
<div>
<v-alert
v-if="!hasRelations"
class="my-4"
type="info"
variant="tonal"
>
La información de municipio, departamento y país de este pedido estará
disponible próximamente.
</v-alert>
<CytoscapeChart
v-else
data-test="territory-chart"
:elements="elements"
:height="height"
:layout="layout"
:styles="styles"
@select="onSelect"
/>
<ProvenanceDetailModal
:selected="selected"
:visible="modalVisible"
@update:visible="modalVisible = $event"
/>
</div>
</template>
<script setup>
import { computed, ref } from 'vue'
import CytoscapeChart from '@/components/graph/CytoscapeChart.vue'
import { toCytoscapeElements } from '@/services/graph/graph-layout'
import ProvenanceDetailModal from './ProvenanceDetailModal.vue'
import { buildTerritoryGraph, hasAnyTerritory } from './provenance-graph'
const props = defineProps({
provenance: {
type: Array,
default: () => [],
},
})
const graph = computed(() => buildTerritoryGraph(props.provenance))
const hasRelations = computed(() => hasAnyTerritory(props.provenance))
const elements = computed(() => toCytoscapeElements(graph.value))
const height = computed(() => graph.value.height + 60)
const selected = ref(null)
const modalVisible = ref(false)
const styles = [
{
selector: 'node',
style: {
'background-color': '#cfd8dc',
'border-color': '#90a4ae',
'border-width': 1,
color: '#263238',
'font-size': 12,
'font-family': 'sans-serif',
'text-valign': 'bottom',
'text-halign': 'center',
'text-wrap': 'wrap',
'text-max-width': 110,
shape: 'round-rectangle',
width: 120,
height: 40,
padding: 6,
},
},
{ selector: 'node.product', style: { 'background-color': '#26a69a', 'border-color': '#00796b' } },
{ selector: 'node.supplier', style: { 'background-color': '#42a5f5', 'border-color': '#1565c0' } },
{ selector: 'node.municipality', style: { 'background-color': '#66bb6a', 'border-color': '#2e7d32' } },
{ selector: 'node.department', style: { 'background-color': '#5c6bc0', 'border-color': '#283593' } },
{ selector: 'node.country', style: { 'background-color': '#ab47bc', 'border-color': '#6a1b9a' } },
{ selector: 'node.has-image', style: { 'background-image': 'data(image)', 'background-fit': 'cover', 'background-clip': 'none' } },
{
selector: 'edge',
style: {
'curve-style': 'bezier',
'target-arrow-shape': 'triangle',
'target-arrow-color': '#90a4ae',
'line-color': '#90a4ae',
width: 2,
},
},
]
const layout = { name: 'preset' }
function onSelect (nodeData) {
selected.value = nodeData
modalVisible.value = true
}
</script>

View File

@@ -0,0 +1,108 @@
<template>
<v-dialog
max-width="520"
:model-value="visible"
@update:model-value="onUpdateVisible"
>
<v-card v-if="selected">
<v-card-title class="d-flex align-center">
<v-icon class="mr-2" :color="kindColor" :icon="kindIcon" />
<span class="font-weight-bold">{{ kindLabel }}</span>
</v-card-title>
<v-divider />
<v-card-text>
<img
v-if="selected.image"
alt="Imagen del producto"
class="provenance-image rounded-lg border mb-3"
:src="selected.image"
>
<div class="text-h6 mb-2">{{ selected.label }}</div>
<v-list v-if="hasDetails" density="compact">
<v-list-item v-if="description">
<v-list-item-title>Descripción</v-list-item-title>
<v-list-item-subtitle>{{ description }}</v-list-item-subtitle>
</v-list-item>
<v-list-item v-if="website">
<v-list-item-title>Sitio web</v-list-item-title>
<v-list-item-subtitle>
<a :href="website" rel="noopener" target="_blank">{{ website }}</a>
</v-list-item-subtitle>
</v-list-item>
<v-list-item v-if="contactEmail">
<v-list-item-title>Correo de contacto</v-list-item-title>
<v-list-item-subtitle>{{ contactEmail }}</v-list-item-subtitle>
</v-list-item>
<v-list-item v-if="contactPhone">
<v-list-item-title>Teléfono de contacto</v-list-item-title>
<v-list-item-subtitle>{{ contactPhone }}</v-list-item-subtitle>
</v-list-item>
</v-list>
</v-card-text>
<v-card-actions>
<v-spacer />
<v-btn variant="text" @click="close">Cerrar</v-btn>
</v-card-actions>
</v-card>
</v-dialog>
</template>
<script setup>
import { computed } from 'vue'
const props = defineProps({
visible: {
type: Boolean,
default: false,
},
selected: {
type: Object,
default: null,
},
})
const emit = defineEmits(['update:visible'])
const KIND_INFO = {
product: { label: 'Producto', icon: 'mdi-package-variant', color: 'teal' },
supplier: { label: 'Proveedor', icon: 'mdi-truck', color: 'blue' },
organization: { label: 'Organización', icon: 'mdi-domain', color: 'orange' },
municipality: { label: 'Municipio', icon: 'mdi-map-marker', color: 'green' },
department: { label: 'Departamento', icon: 'mdi-map', color: 'indigo' },
country: { label: 'País', icon: 'mdi-earth', color: 'purple' },
}
const kindInfo = computed(() => {
return KIND_INFO[props.selected?.kind] || KIND_INFO.product
})
const kindLabel = computed(() => kindInfo.value.label)
const kindIcon = computed(() => kindInfo.value.icon)
const kindColor = computed(() => kindInfo.value.color)
const entity = computed(() => props.selected?.entity || {})
const description = computed(() => entity.value.description || '')
const website = computed(() => entity.value.website || '')
const contactEmail = computed(() => entity.value.contact_email || '')
const contactPhone = computed(() => entity.value.contact_phone || '')
const hasDetails = computed(() => {
return description.value || website.value || contactEmail.value || contactPhone.value
})
function onUpdateVisible (value) {
emit('update:visible', value)
}
function close () {
emit('update:visible', false)
}
</script>
<style scoped>
.provenance-image {
display: block;
max-height: 220px;
max-width: 100%;
object-fit: contain;
}
</style>

View File

@@ -0,0 +1,29 @@
<template>
<div v-if="provenance && provenance.length > 0">
<v-divider class="my-4" />
<h3 class="text-h6 font-weight-bold mb-1">Origen e historia de los productos</h3>
<p class="text-body-2 text-medium-emphasis mb-4">
Conoce quiénes producen los productos que compras y de qué territorios provienen.
</p>
<h4 class="text-subtitle-1 font-weight-medium mb-2">Proveedores y organizaciones</h4>
<ProductSupplierOrganizationChart :provenance="provenance" />
<v-divider class="my-4" />
<h4 class="text-subtitle-1 font-weight-medium mb-2">Departamento y municipio</h4>
<ProductTerritoryChart :provenance="provenance" />
</div>
</template>
<script setup>
import ProductSupplierOrganizationChart from './ProductSupplierOrganizationChart.vue'
import ProductTerritoryChart from './ProductTerritoryChart.vue'
defineProps({
provenance: {
type: Array,
default: null,
},
})
</script>

View File

@@ -0,0 +1,687 @@
<template>
<v-container fluid>
<h1 class="text-h4 mb-4">Gestión de Geografía</h1>
<v-tabs v-model="activeTab" color="primary">
<v-tab
data-testid="geo-tab-countries"
value="countries"
>
Países
</v-tab>
<v-tab
data-testid="geo-tab-departments"
value="departments"
>
Departamentos
</v-tab>
<v-tab
data-testid="geo-tab-municipalities"
value="municipalities"
>
Municipios
</v-tab>
</v-tabs>
<!-- Países -->
<v-row v-if="activeTab === 'countries'" class="mt-2">
<v-col class="text-right" cols="12">
<v-btn
color="primary"
data-testid="geo-country-create"
prepend-icon="mdi-plus"
@click="openCreateCountry"
>
Nuevo país
</v-btn>
</v-col>
<v-col cols="12">
<v-card>
<v-data-table
density="compact"
:headers="countryHeaders"
item-value="id"
:items="countries"
items-per-page="25"
:items-per-page-options="[10, 25, 50, 100]"
:loading="loading"
>
<template #item.actions="{ item }">
<v-btn
:data-testid="'geo-country-edit-' + item.id"
icon="mdi-pencil"
size="small"
variant="text"
@click="openEditCountry(item)"
/>
<v-btn
color="error"
:data-testid="'geo-country-delete-' + item.id"
icon="mdi-delete"
size="small"
variant="text"
@click="openDeleteCountry(item)"
/>
</template>
<template #loading>
<v-skeleton-loader type="table-row@10" />
</template>
<template #no-data>
<v-alert class="my-4" type="info" variant="tonal">
No hay países para mostrar
</v-alert>
</template>
</v-data-table>
</v-card>
</v-col>
</v-row>
<!-- Departamentos -->
<v-row v-if="activeTab === 'departments'" class="mt-2">
<v-col class="text-right" cols="12">
<v-btn
color="primary"
data-testid="geo-department-create"
prepend-icon="mdi-plus"
@click="openCreateDepartment"
>
Nuevo departamento
</v-btn>
</v-col>
<v-col cols="12">
<v-card>
<v-data-table
density="compact"
:headers="departmentHeaders"
item-value="id"
:items="departments"
items-per-page="25"
:items-per-page-options="[10, 25, 50, 100]"
:loading="loading"
>
<template #item.country="{ item }">
{{ item.country_detail?.name }}
</template>
<template #item.actions="{ item }">
<v-btn
:data-testid="'geo-department-edit-' + item.id"
icon="mdi-pencil"
size="small"
variant="text"
@click="openEditDepartment(item)"
/>
<v-btn
color="error"
:data-testid="'geo-department-delete-' + item.id"
icon="mdi-delete"
size="small"
variant="text"
@click="openDeleteDepartment(item)"
/>
</template>
<template #loading>
<v-skeleton-loader type="table-row@10" />
</template>
<template #no-data>
<v-alert class="my-4" type="info" variant="tonal">
No hay departamentos para mostrar
</v-alert>
</template>
</v-data-table>
</v-card>
</v-col>
</v-row>
<!-- Municipios -->
<v-row v-if="activeTab === 'municipalities'" class="mt-2">
<v-col class="text-right" cols="12">
<v-btn
color="primary"
data-testid="geo-municipality-create"
prepend-icon="mdi-plus"
@click="openCreateMunicipality"
>
Nuevo municipio
</v-btn>
</v-col>
<v-col cols="12">
<v-card>
<v-data-table
density="compact"
:headers="municipalityHeaders"
item-value="id"
:items="municipalities"
items-per-page="25"
:items-per-page-options="[10, 25, 50, 100]"
:loading="loading"
>
<template #item.department="{ item }">
{{ item.department_detail?.name }}
</template>
<template #item.country="{ item }">
{{ item.country_detail?.name }}
</template>
<template #item.actions="{ item }">
<v-btn
:data-testid="'geo-municipality-edit-' + item.id"
icon="mdi-pencil"
size="small"
variant="text"
@click="openEditMunicipality(item)"
/>
<v-btn
color="error"
:data-testid="'geo-municipality-delete-' + item.id"
icon="mdi-delete"
size="small"
variant="text"
@click="openDeleteMunicipality(item)"
/>
</template>
<template #loading>
<v-skeleton-loader type="table-row@10" />
</template>
<template #no-data>
<v-alert class="my-4" type="info" variant="tonal">
No hay municipios para mostrar
</v-alert>
</template>
</v-data-table>
</v-card>
</v-col>
</v-row>
<!-- Diálogo país -->
<v-dialog v-model="countryDialog.show" max-width="480">
<v-card>
<v-card-title>
{{ countryDialog.isEdit ? 'Editar país' : 'Nuevo país' }}
</v-card-title>
<v-card-text>
<v-form @submit.prevent="saveCountry">
<v-text-field
v-model="countryForm.name"
data-testid="geo-country-form-name"
label="Nombre"
required
/>
<v-text-field
v-model="countryForm.code"
data-testid="geo-country-form-code"
label="Código (ISO)"
maxlength="3"
required
/>
</v-form>
</v-card-text>
<v-card-actions>
<v-spacer />
<v-btn variant="text" @click="countryDialog.show = false">Cancelar</v-btn>
<v-btn
color="primary"
data-testid="geo-country-save"
:disabled="saving"
variant="elevated"
@click="saveCountry"
>
Guardar
</v-btn>
</v-card-actions>
</v-card>
</v-dialog>
<!-- Diálogo departamento -->
<v-dialog v-model="departmentDialog.show" max-width="480">
<v-card>
<v-card-title>
{{ departmentDialog.isEdit ? 'Editar departamento' : 'Nuevo departamento' }}
</v-card-title>
<v-card-text>
<v-form @submit.prevent="saveDepartment">
<v-text-field
v-model="departmentForm.name"
data-testid="geo-department-form-name"
label="Nombre"
required
/>
<v-select
v-model="departmentForm.country"
data-testid="geo-department-form-country"
item-title="name"
item-value="id"
:items="countries"
label="País"
required
/>
</v-form>
</v-card-text>
<v-card-actions>
<v-spacer />
<v-btn variant="text" @click="departmentDialog.show = false">Cancelar</v-btn>
<v-btn
color="primary"
data-testid="geo-department-save"
:disabled="saving"
variant="elevated"
@click="saveDepartment"
>
Guardar
</v-btn>
</v-card-actions>
</v-card>
</v-dialog>
<!-- Diálogo municipio -->
<v-dialog v-model="municipalityDialog.show" max-width="480">
<v-card>
<v-card-title>
{{ municipalityDialog.isEdit ? 'Editar municipio' : 'Nuevo municipio' }}
</v-card-title>
<v-card-text>
<v-form @submit.prevent="saveMunicipality">
<v-text-field
v-model="municipalityForm.name"
data-testid="geo-municipality-form-name"
label="Nombre"
required
/>
<v-autocomplete
v-model="municipalityForm.department"
data-testid="geo-municipality-form-department"
item-title="name"
item-value="id"
:items="departmentItems"
label="Departamento"
required
:search-input="departmentSearch"
/>
<v-select
v-model="municipalityForm.country"
data-testid="geo-municipality-form-country"
item-title="name"
item-value="id"
:items="countries"
label="País"
required
/>
</v-form>
</v-card-text>
<v-card-actions>
<v-spacer />
<v-btn variant="text" @click="municipalityDialog.show = false">Cancelar</v-btn>
<v-btn
color="primary"
data-testid="geo-municipality-save"
:disabled="saving"
variant="elevated"
@click="saveMunicipality"
>
Guardar
</v-btn>
</v-card-actions>
</v-card>
</v-dialog>
<v-dialog v-model="deleteCountryDialog" max-width="420">
<v-card>
<v-card-title>Eliminar país</v-card-title>
<v-card-text>
¿Está seguro de eliminar "{{ deleteCountryTarget?.name }}"?
</v-card-text>
<v-card-actions>
<v-spacer />
<v-btn variant="text" @click="deleteCountryDialog = false">Cancelar</v-btn>
<v-btn
color="error"
:disabled="saving"
variant="elevated"
@click="confirmDeleteCountry"
>
Eliminar
</v-btn>
</v-card-actions>
</v-card>
</v-dialog>
<v-dialog v-model="deleteDepartmentDialog" max-width="420">
<v-card>
<v-card-title>Eliminar departamento</v-card-title>
<v-card-text>
¿Está seguro de eliminar "{{ deleteDepartmentTarget?.name }}"?
</v-card-text>
<v-card-actions>
<v-spacer />
<v-btn variant="text" @click="deleteDepartmentDialog = false">Cancelar</v-btn>
<v-btn
color="error"
:disabled="saving"
variant="elevated"
@click="confirmDeleteDepartment"
>
Eliminar
</v-btn>
</v-card-actions>
</v-card>
</v-dialog>
<v-dialog v-model="deleteMunicipalityDialog" max-width="420">
<v-card>
<v-card-title>Eliminar municipio</v-card-title>
<v-card-text>
¿Está seguro de eliminar "{{ deleteMunicipalityTarget?.name }}"?
</v-card-text>
<v-card-actions>
<v-spacer />
<v-btn variant="text" @click="deleteMunicipalityDialog = false">Cancelar</v-btn>
<v-btn
color="error"
:disabled="saving"
variant="elevated"
@click="confirmDeleteMunicipality"
>
Eliminar
</v-btn>
</v-card-actions>
</v-card>
</v-dialog>
<v-snackbar
v-model="snackbar.show"
:color="snackbar.color"
location="top"
:timeout="3000"
>
{{ snackbar.message }}
<template #actions>
<v-btn variant="text" @click="snackbar.show = false">Cerrar</v-btn>
</template>
</v-snackbar>
</v-container>
</template>
<script setup>
import { computed, inject, onMounted, ref, watch } from 'vue'
const api = inject('api')
const activeTab = ref('countries')
const countries = ref([])
const departments = ref([])
const municipalities = ref([])
const loading = ref(false)
const saving = ref(false)
const departmentSearch = ref('')
const snackbar = ref({ show: false, message: '', color: 'success' })
const countryHeaders = [
{ title: 'ID', key: 'id' },
{ title: 'Nombre', key: 'name' },
{ title: 'Código', key: 'code' },
{ title: 'Acciones', key: 'actions', sortable: false },
]
const departmentHeaders = [
{ title: 'ID', key: 'id' },
{ title: 'Nombre', key: 'name' },
{ title: 'País', key: 'country' },
{ title: 'Acciones', key: 'actions', sortable: false },
]
const municipalityHeaders = [
{ title: 'ID', key: 'id' },
{ title: 'Nombre', key: 'name' },
{ title: 'Departamento', key: 'department' },
{ title: 'País', key: 'country' },
{ title: 'Acciones', key: 'actions', sortable: false },
]
const countryDialog = ref({ show: false, isEdit: false, item: null })
const countryForm = ref({ name: '', code: '' })
const departmentDialog = ref({ show: false, isEdit: false, item: null })
const departmentForm = ref({ name: '', country: null })
const municipalityDialog = ref({ show: false, isEdit: false, item: null })
const municipalityForm = ref({ name: '', department: null, country: null })
const departmentItems = computed(() => {
const query = departmentSearch.value.trim().toLowerCase()
let filtered = departments.value
if (query) {
filtered = departments.value.filter(department => {
return (department.name || '').toLowerCase().includes(query)
})
}
const selectedId = Number(municipalityForm.value.department)
const hasSelected = filtered.some(department => department.id === selectedId)
if (selectedId && !hasSelected) {
const selected = departments.value.find(department => department.id === selectedId)
if (selected) filtered = [selected, ...filtered]
}
return filtered
})
async function loadCountries () {
loading.value = true
try {
countries.value = await api.getCountries()
} catch (error) {
console.error('Error al cargar países:', error)
showSnackbar('Error al cargar países', 'error')
} finally {
loading.value = false
}
}
async function loadDepartments () {
loading.value = true
try {
departments.value = await api.getDepartments()
} catch (error) {
console.error('Error al cargar departamentos:', error)
showSnackbar('Error al cargar departamentos', 'error')
} finally {
loading.value = false
}
}
async function loadMunicipalities () {
loading.value = true
try {
municipalities.value = await api.getMunicipalities()
} catch (error) {
console.error('Error al cargar municipios:', error)
showSnackbar('Error al cargar municipios', 'error')
} finally {
loading.value = false
}
}
function openCreateCountry () {
countryForm.value = { name: '', code: '' }
countryDialog.value = { show: true, isEdit: false, item: null }
}
function openEditCountry (item) {
countryForm.value = { name: item.name, code: item.code }
countryDialog.value = { show: true, isEdit: true, item }
}
async function saveCountry () {
saving.value = true
try {
if (countryDialog.value.isEdit) {
await api.updateCountry(countryDialog.value.item.id, countryForm.value)
showSnackbar('País actualizado', 'success')
} else {
await api.createCountry(countryForm.value)
showSnackbar('País creado', 'success')
}
countryDialog.value.show = false
await loadCountries()
} catch (error) {
console.error('Error al guardar país:', error)
showSnackbar('Error al guardar país', 'error')
} finally {
saving.value = false
}
}
function openDeleteCountry (item) {
deleteCountryTarget.value = item
deleteCountryDialog.value = true
}
const deleteCountryDialog = ref(false)
const deleteCountryTarget = ref(null)
async function confirmDeleteCountry () {
saving.value = true
try {
await api.deleteCountry(deleteCountryTarget.value.id)
deleteCountryDialog.value = false
showSnackbar('País eliminado', 'success')
await loadCountries()
} catch (error) {
console.error('Error al eliminar país:', error)
showSnackbar('Error al eliminar país', 'error')
} finally {
saving.value = false
}
}
function openCreateDepartment () {
departmentForm.value = { name: '', country: null }
departmentDialog.value = { show: true, isEdit: false, item: null }
}
function openEditDepartment (item) {
departmentForm.value = { name: item.name, country: item.country }
departmentDialog.value = { show: true, isEdit: true, item }
}
async function saveDepartment () {
saving.value = true
try {
if (departmentDialog.value.isEdit) {
await api.updateDepartment(departmentDialog.value.item.id, departmentForm.value)
showSnackbar('Departamento actualizado', 'success')
} else {
await api.createDepartment(departmentForm.value)
showSnackbar('Departamento creado', 'success')
}
departmentDialog.value.show = false
await loadDepartments()
} catch (error) {
console.error('Error al guardar departamento:', error)
showSnackbar('Error al guardar departamento', 'error')
} finally {
saving.value = false
}
}
const deleteDepartmentDialog = ref(false)
const deleteDepartmentTarget = ref(null)
function openDeleteDepartment (item) {
deleteDepartmentTarget.value = item
deleteDepartmentDialog.value = true
}
async function confirmDeleteDepartment () {
saving.value = true
try {
await api.deleteDepartment(deleteDepartmentTarget.value.id)
deleteDepartmentDialog.value = false
showSnackbar('Departamento eliminado', 'success')
await loadDepartments()
} catch (error) {
console.error('Error al eliminar departamento:', error)
showSnackbar('Error al eliminar departamento', 'error')
} finally {
saving.value = false
}
}
function openCreateMunicipality () {
municipalityForm.value = { name: '', department: null, country: null }
municipalityDialog.value = { show: true, isEdit: false, item: null }
}
function openEditMunicipality (item) {
municipalityForm.value = {
name: item.name,
department: item.department,
country: item.country,
}
municipalityDialog.value = { show: true, isEdit: true, item }
}
watch(
() => municipalityForm.value.department,
departmentId => {
if (!departmentId) return
const department = departments.value.find(item => item.id === departmentId)
if (department && department.country) {
municipalityForm.value.country = department.country
}
}
)
async function saveMunicipality () {
saving.value = true
try {
if (municipalityDialog.value.isEdit) {
await api.updateMunicipality(municipalityDialog.value.item.id, municipalityForm.value)
showSnackbar('Municipio actualizado', 'success')
} else {
await api.createMunicipality(municipalityForm.value)
showSnackbar('Municipio creado', 'success')
}
municipalityDialog.value.show = false
await loadMunicipalities()
} catch (error) {
console.error('Error al guardar municipio:', error)
showSnackbar('Error al guardar municipio', 'error')
} finally {
saving.value = false
}
}
const deleteMunicipalityDialog = ref(false)
const deleteMunicipalityTarget = ref(null)
function openDeleteMunicipality (item) {
deleteMunicipalityTarget.value = item
deleteMunicipalityDialog.value = true
}
async function confirmDeleteMunicipality () {
saving.value = true
try {
await api.deleteMunicipality(deleteMunicipalityTarget.value.id)
deleteMunicipalityDialog.value = false
showSnackbar('Municipio eliminado', 'success')
await loadMunicipalities()
} catch (error) {
console.error('Error al eliminar municipio:', error)
showSnackbar('Error al eliminar municipio', 'error')
} finally {
saving.value = false
}
}
function showSnackbar (message, color) {
snackbar.value = { show: true, message, color }
}
watch(activeTab, tab => {
if (tab === 'departments') loadDepartments()
if (tab === 'municipalities') {
loadMunicipalities()
loadDepartments()
}
})
onMounted(loadCountries)
</script>

View File

@@ -0,0 +1,299 @@
<template>
<v-container fluid>
<v-row align="center">
<v-col cols="12" md="6">
<h1 class="text-h4">Gestión de Organizaciones</h1>
</v-col>
<v-col class="text-md-right" cols="12" md="6">
<v-btn
color="primary"
data-testid="org-create"
prepend-icon="mdi-plus"
@click="openCreate"
>
Nueva organización
</v-btn>
</v-col>
</v-row>
<v-row>
<v-col cols="12" md="6">
<v-text-field
v-model="searchQuery"
clearable
data-testid="org-search"
density="compact"
hide-details
label="Buscar por nombre"
prepend-inner-icon="mdi-magnify"
variant="outlined"
/>
</v-col>
</v-row>
<v-row>
<v-col cols="12">
<v-card>
<v-data-table
density="compact"
:headers="headers"
item-value="id"
:items="filteredOrganizations"
items-per-page="25"
:items-per-page-options="[10, 25, 50, 100]"
:loading="loading"
>
<template #item.website="{ item }">
<a
v-if="item.website"
:href="item.website"
rel="noopener"
target="_blank"
>
{{ item.website }}
</a>
</template>
<template #item.actions="{ item }">
<v-btn
:data-testid="'org-edit-' + item.id"
icon="mdi-pencil"
size="small"
variant="text"
@click="openEdit(item)"
/>
<v-btn
color="error"
:data-testid="'org-delete-' + item.id"
icon="mdi-delete"
size="small"
variant="text"
@click="openDelete(item)"
/>
</template>
<template #loading>
<v-skeleton-loader type="table-row@10" />
</template>
<template #no-data>
<v-alert class="my-4" type="info" variant="tonal">
No hay organizaciones para mostrar
</v-alert>
</template>
</v-data-table>
</v-card>
</v-col>
</v-row>
<v-dialog v-model="dialog.show" max-width="520">
<v-card>
<v-card-title>
{{ dialog.isEdit ? 'Editar organización' : 'Nueva organización' }}
</v-card-title>
<v-card-text>
<v-form @submit.prevent="save">
<v-text-field
v-model="formData.name"
data-testid="org-form-name"
label="Nombre"
required
/>
<v-textarea
v-model="formData.description"
data-testid="org-form-description"
label="Descripción"
rows="3"
/>
<v-text-field
v-model="formData.website"
data-testid="org-form-website"
label="Sitio web"
/>
<v-text-field
v-model="formData.contact_email"
data-testid="org-form-email"
label="Correo de contacto"
/>
<v-text-field
v-model="formData.contact_phone"
data-testid="org-form-phone"
label="Teléfono de contacto"
/>
</v-form>
</v-card-text>
<v-card-actions>
<v-spacer />
<v-btn variant="text" @click="dialog.show = false">Cancelar</v-btn>
<v-btn
color="primary"
data-testid="org-save"
:disabled="saving"
variant="elevated"
@click="save"
>
Guardar
</v-btn>
</v-card-actions>
</v-card>
</v-dialog>
<v-dialog v-model="deleteDialog.show" max-width="420">
<v-card>
<v-card-title>Eliminar organización</v-card-title>
<v-card-text>
¿Está seguro de eliminar "{{ deleteDialog.item?.name }}"?
</v-card-text>
<v-card-actions>
<v-spacer />
<v-btn variant="text" @click="deleteDialog.show = false">Cancelar</v-btn>
<v-btn
color="error"
data-testid="org-confirm-delete"
:disabled="saving"
variant="elevated"
@click="confirmDelete"
>
Eliminar
</v-btn>
</v-card-actions>
</v-card>
</v-dialog>
<v-snackbar
v-model="snackbar.show"
:color="snackbar.color"
location="top"
:timeout="3000"
>
{{ snackbar.message }}
<template #actions>
<v-btn variant="text" @click="snackbar.show = false">Cerrar</v-btn>
</template>
</v-snackbar>
</v-container>
</template>
<script setup>
import { computed, inject, onMounted, ref } from 'vue'
const api = inject('api')
const organizations = ref([])
const loading = ref(false)
const saving = ref(false)
const searchQuery = ref('')
const snackbar = ref({ show: false, message: '', color: 'success' })
const dialog = ref({ show: false, isEdit: false, item: null })
const deleteDialog = ref({ show: false, item: null })
const headers = [
{ title: 'ID', key: 'id' },
{ title: 'Nombre', key: 'name' },
{ title: 'Descripción', key: 'description' },
{ title: 'Sitio web', key: 'website' },
{ title: 'Correo', key: 'contact_email' },
{ title: 'Teléfono', key: 'contact_phone' },
{ title: 'Acciones', key: 'actions', sortable: false },
]
const emptyForm = () => ({
name: '',
description: '',
website: '',
contact_email: '',
contact_phone: '',
})
const formData = ref(emptyForm())
const filteredOrganizations = computed(() => {
const query = searchQuery.value.trim().toLowerCase()
if (!query) return organizations.value
return organizations.value.filter(organization => {
return (organization.name || '').toLowerCase().includes(query)
})
})
async function load () {
loading.value = true
try {
organizations.value = await api.getOrganizations()
} catch (error) {
console.error('Error al cargar organizaciones:', error)
showSnackbar('Error al cargar organizaciones', 'error')
} finally {
loading.value = false
}
}
function openCreate () {
formData.value = emptyForm()
dialog.value = { show: true, isEdit: false, item: null }
}
function openEdit (item) {
formData.value = {
name: item.name,
description: item.description,
website: item.website,
contact_email: item.contact_email,
contact_phone: item.contact_phone,
}
dialog.value = { show: true, isEdit: true, item }
}
async function save () {
saving.value = true
try {
if (dialog.value.isEdit) {
await api.updateOrganization(dialog.value.item.id, formData.value)
showSnackbar('Organización actualizada', 'success')
} else {
await api.createOrganization(formData.value)
showSnackbar('Organización creada', 'success')
}
dialog.value.show = false
await load()
} catch (error) {
console.error('Error al guardar organización:', error)
showSnackbar('Error al guardar organización', 'error')
} finally {
saving.value = false
}
}
function openDelete (item) {
deleteDialog.value = { show: true, item }
}
async function confirmDelete () {
saving.value = true
try {
await api.deleteOrganization(deleteDialog.value.item.id)
deleteDialog.value.show = false
showSnackbar('Organización eliminada', 'success')
await load()
} catch (error) {
console.error('Error al eliminar organización:', error)
showSnackbar('Error al eliminar organización', 'error')
} finally {
saving.value = false
}
}
function showSnackbar (message, color) {
snackbar.value = { show: true, message, color }
}
onMounted(load)
</script>
<style scoped>
.text-md-right {
text-align: right;
}
@media (max-width: 960px) {
.text-md-right {
text-align: left;
}
}
</style>

View File

@@ -0,0 +1,338 @@
<template>
<v-container fluid>
<v-row align="center">
<v-col cols="12" md="6">
<h1 class="text-h4">Gestión de Proveedores</h1>
</v-col>
<v-col class="text-md-right" cols="12" md="6">
<v-btn
color="primary"
data-testid="supplier-create"
prepend-icon="mdi-plus"
@click="openCreate"
>
Nuevo proveedor
</v-btn>
</v-col>
</v-row>
<v-row>
<v-col cols="12" md="6">
<v-text-field
v-model="searchQuery"
clearable
data-testid="supplier-search"
density="compact"
hide-details
label="Buscar por nombre"
prepend-inner-icon="mdi-magnify"
variant="outlined"
/>
</v-col>
</v-row>
<v-row>
<v-col cols="12">
<v-card>
<v-data-table
density="compact"
:headers="headers"
item-value="id"
:items="filteredSuppliers"
items-per-page="25"
:items-per-page-options="[10, 25, 50, 100]"
:loading="loading"
>
<template #item.organization="{ item }">
{{ item.organization_detail?.name }}
</template>
<template #item.municipality="{ item }">
{{ item.municipality_detail?.name }}
</template>
<template #item.actions="{ item }">
<v-btn
:data-testid="'supplier-edit-' + item.id"
icon="mdi-pencil"
size="small"
variant="text"
@click="openEdit(item)"
/>
<v-btn
color="error"
:data-testid="'supplier-delete-' + item.id"
icon="mdi-delete"
size="small"
variant="text"
@click="openDelete(item)"
/>
</template>
<template #loading>
<v-skeleton-loader type="table-row@10" />
</template>
<template #no-data>
<v-alert class="my-4" type="info" variant="tonal">
No hay proveedores para mostrar
</v-alert>
</template>
</v-data-table>
</v-card>
</v-col>
</v-row>
<v-dialog v-model="dialog.show" max-width="560">
<v-card>
<v-card-title>
{{ dialog.isEdit ? 'Editar proveedor' : 'Nuevo proveedor' }}
</v-card-title>
<v-card-text>
<v-form @submit.prevent="save">
<v-text-field
v-model="formData.name"
data-testid="supplier-form-name"
label="Nombre"
required
/>
<v-textarea
v-model="formData.description"
data-testid="supplier-form-description"
label="Descripción"
rows="3"
/>
<v-select
v-model="formData.organization"
clearable
data-testid="supplier-form-organization"
item-title="name"
item-value="id"
:items="organizations"
label="Organización"
/>
<v-autocomplete
v-model="formData.municipality"
clearable
data-testid="supplier-form-municipality"
item-title="name"
item-value="id"
:items="municipalityItems"
label="Municipio"
:search-input="municipalitySearch"
/>
<v-text-field
v-model="formData.contact_email"
data-testid="supplier-form-email"
label="Correo de contacto"
/>
<v-text-field
v-model="formData.contact_phone"
data-testid="supplier-form-phone"
label="Teléfono de contacto"
/>
</v-form>
</v-card-text>
<v-card-actions>
<v-spacer />
<v-btn variant="text" @click="dialog.show = false">Cancelar</v-btn>
<v-btn
color="primary"
data-testid="supplier-save"
:disabled="saving"
variant="elevated"
@click="save"
>
Guardar
</v-btn>
</v-card-actions>
</v-card>
</v-dialog>
<v-dialog v-model="deleteDialog.show" max-width="420">
<v-card>
<v-card-title>Eliminar proveedor</v-card-title>
<v-card-text>
¿Está seguro de eliminar "{{ deleteDialog.item?.name }}"?
</v-card-text>
<v-card-actions>
<v-spacer />
<v-btn variant="text" @click="deleteDialog.show = false">Cancelar</v-btn>
<v-btn
color="error"
data-testid="supplier-confirm-delete"
:disabled="saving"
variant="elevated"
@click="confirmDelete"
>
Eliminar
</v-btn>
</v-card-actions>
</v-card>
</v-dialog>
<v-snackbar
v-model="snackbar.show"
:color="snackbar.color"
location="top"
:timeout="3000"
>
{{ snackbar.message }}
<template #actions>
<v-btn variant="text" @click="snackbar.show = false">Cerrar</v-btn>
</template>
</v-snackbar>
</v-container>
</template>
<script setup>
import { computed, inject, onMounted, ref } from 'vue'
const api = inject('api')
const suppliers = ref([])
const organizations = ref([])
const municipalities = ref([])
const loading = ref(false)
const saving = ref(false)
const searchQuery = ref('')
const municipalitySearch = ref('')
const snackbar = ref({ show: false, message: '', color: 'success' })
const dialog = ref({ show: false, isEdit: false, item: null })
const deleteDialog = ref({ show: false, item: null })
const headers = [
{ title: 'ID', key: 'id' },
{ title: 'Nombre', key: 'name' },
{ title: 'Organización', key: 'organization' },
{ title: 'Municipio', key: 'municipality' },
{ title: 'Correo', key: 'contact_email' },
{ title: 'Teléfono', key: 'contact_phone' },
{ title: 'Acciones', key: 'actions', sortable: false },
]
const emptyForm = () => ({
name: '',
description: '',
organization: null,
municipality: null,
contact_email: '',
contact_phone: '',
})
const formData = ref(emptyForm())
const filteredSuppliers = computed(() => {
const query = searchQuery.value.trim().toLowerCase()
if (!query) return suppliers.value
return suppliers.value.filter(supplier => {
return (supplier.name || '').toLowerCase().includes(query)
})
})
const municipalityItems = computed(() => {
const query = municipalitySearch.value.trim().toLowerCase()
let filtered = municipalities.value
if (query) {
filtered = municipalities.value.filter(municipality => {
return (municipality.name || '').toLowerCase().includes(query)
})
}
const selectedId = Number(formData.value.municipality)
const hasSelected = filtered.some(municipality => municipality.id === selectedId)
if (selectedId && !hasSelected) {
const selected = municipalities.value.find(municipality => municipality.id === selectedId)
if (selected) filtered = [selected, ...filtered]
}
return filtered
})
async function load () {
loading.value = true
try {
const [suppliersData, organizationsData, municipalitiesData] = await Promise.all([
api.getSuppliers(),
api.getOrganizations(),
api.getMunicipalities(),
])
suppliers.value = suppliersData
organizations.value = organizationsData
municipalities.value = municipalitiesData
} catch (error) {
console.error('Error al cargar proveedores:', error)
showSnackbar('Error al cargar proveedores', 'error')
} finally {
loading.value = false
}
}
function openCreate () {
formData.value = emptyForm()
dialog.value = { show: true, isEdit: false, item: null }
}
function openEdit (item) {
formData.value = {
name: item.name,
description: item.description,
organization: item.organization,
municipality: item.municipality,
contact_email: item.contact_email,
contact_phone: item.contact_phone,
}
dialog.value = { show: true, isEdit: true, item }
}
async function save () {
saving.value = true
try {
if (dialog.value.isEdit) {
await api.updateSupplier(dialog.value.item.id, formData.value)
showSnackbar('Proveedor actualizado', 'success')
} else {
await api.createSupplier(formData.value)
showSnackbar('Proveedor creado', 'success')
}
dialog.value.show = false
await load()
} catch (error) {
console.error('Error al guardar proveedor:', error)
showSnackbar('Error al guardar proveedor', 'error')
} finally {
saving.value = false
}
}
function openDelete (item) {
deleteDialog.value = { show: true, item }
}
async function confirmDelete () {
saving.value = true
try {
await api.deleteSupplier(deleteDialog.value.item.id)
deleteDialog.value.show = false
showSnackbar('Proveedor eliminado', 'success')
await load()
} catch (error) {
console.error('Error al eliminar proveedor:', error)
showSnackbar('Error al eliminar proveedor', 'error')
} finally {
saving.value = false
}
}
function showSnackbar (message, color) {
snackbar.value = { show: true, message, color }
}
onMounted(load)
</script>
<style scoped>
.text-md-right {
text-align: right;
}
@media (max-width: 960px) {
.text-md-right {
text-align: left;
}
}
</style>

View File

@@ -0,0 +1,104 @@
/**
* Builders de grafos de provenance (específicos del dominio).
*
* Convierten el payload `product_provenance` del resumen de compra/pedido en
* un grafo en capas usando el servicio genérico `services/graph/graph-layout`.
*/
import { computeColumnLayout } from '@/services/graph/graph-layout'
const SUPPLIER_ORG_COLUMNS = { product: 0, supplier: 1, organization: 2 }
const TERRITORY_COLUMNS = { product: 0, supplier: 1, municipality: 2, department: 3, country: 4 }
function makeCollector () {
const nodes = []
const edges = []
const seen = new Map()
return {
nodes,
edges,
addNode (kind, entity) {
const id = `${kind}:${entity.id}`
if (!seen.has(id)) {
const node = {
id,
kind,
label: entity.name,
image: entity.catalogue_images?.[0] || null,
entity: { ...entity, kind },
}
seen.set(id, node)
nodes.push(node)
}
return seen.get(id)
},
addEdge (from, to) {
edges.push({ from, to })
},
}
}
function layout (collector, columns) {
return computeColumnLayout(collector.nodes, collector.edges, {
columnOf: node => columns[node.kind] ?? 0,
columnWidth: 220,
rowHeight: 72,
padding: 24,
})
}
export function buildSupplierOrganizationGraph (provenance) {
const g = makeCollector()
for (const entry of provenance || []) {
if (!entry.product) continue
const product = g.addNode('product', entry.product)
for (const rel of entry.suppliers || []) {
if (!rel.supplier) continue
const supplier = g.addNode('supplier', rel.supplier)
g.addEdge(product.id, supplier.id)
if (rel.organization) {
const organization = g.addNode('organization', rel.organization)
g.addEdge(supplier.id, organization.id)
}
}
}
return layout(g, SUPPLIER_ORG_COLUMNS)
}
export function buildTerritoryGraph (provenance) {
const g = makeCollector()
for (const entry of provenance || []) {
if (!entry.product) continue
const product = g.addNode('product', entry.product)
for (const rel of entry.suppliers || []) {
if (!rel.supplier) continue
const supplier = g.addNode('supplier', rel.supplier)
g.addEdge(product.id, supplier.id)
if (rel.municipality) {
const municipality = g.addNode('municipality', rel.municipality)
g.addEdge(supplier.id, municipality.id)
if (rel.department) {
const department = g.addNode('department', rel.department)
g.addEdge(municipality.id, department.id)
if (rel.country) {
const country = g.addNode('country', rel.country)
g.addEdge(department.id, country.id)
}
}
}
}
}
return layout(g, TERRITORY_COLUMNS)
}
export function hasAnySupplier (provenance) {
return (provenance || []).some(entry => (entry.suppliers || []).length > 0)
}
export function hasAnyTerritory (provenance) {
return (provenance || []).some(entry =>
(entry.suppliers || []).some(rel =>
rel.municipality || rel.department || rel.country
)
)
}

View File

@@ -0,0 +1,10 @@
<template>
<GeographyManagement v-if="authStore.isAdmin" />
</template>
<script setup>
import { useAuthStore } from '@/stores/auth'
import GeographyManagement from '@/components/provenance/admin/GeographyManagement.vue'
const authStore = useAuthStore()
</script>

View File

@@ -0,0 +1,10 @@
<template>
<OrganizationsManagement v-if="authStore.isAdmin" />
</template>
<script setup>
import { useAuthStore } from '@/stores/auth'
import OrganizationsManagement from '@/components/provenance/admin/OrganizationsManagement.vue'
const authStore = useAuthStore()
</script>

View File

@@ -0,0 +1,10 @@
<template>
<StoreSettingsManagement v-if="authStore.isAdmin" />
</template>
<script setup>
import { useAuthStore } from '@/stores/auth';
import StoreSettingsManagement from '@/components/StoreSettingsManagement.vue';
const authStore = useAuthStore();
</script>

View File

@@ -0,0 +1,10 @@
<template>
<SuppliersManagement v-if="authStore.isAdmin" />
</template>
<script setup>
import { useAuthStore } from '@/stores/auth'
import SuppliersManagement from '@/components/provenance/admin/SuppliersManagement.vue'
const authStore = useAuthStore()
</script>

View File

@@ -0,0 +1,79 @@
<template>
<v-container class="pa-4 pa-md-6" fluid>
<v-sheet class="rounded-lg pa-4 pa-md-6 mb-4">
<h1 class="text-h5 font-weight-bold">Consultar mi pedido o compra</h1>
<p class="text-body-2 text-medium-emphasis mb-4">
Ingresa el código de tu pedido o compra, o abre el link que recibiste para revisar su estado.
</p>
<v-form @submit.prevent="onConsult">
<v-row align="center">
<v-col cols="12" md="6" sm="8">
<v-text-field
v-model="inputCode"
clearable
density="comfortable"
hide-details
label="Código"
variant="outlined"
/>
</v-col>
<v-col class="d-flex align-center" cols="12" md="6" sm="4">
<v-btn color="primary" prepend-icon="mdi-magnify-scan" type="submit">
Consultar
</v-btn>
</v-col>
</v-row>
</v-form>
</v-sheet>
<PublicOrderSummary :error="error" :loading="loading" :purchase="purchase" />
</v-container>
</template>
<script setup>
import { inject, ref, watch } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import PublicOrderSummary from '@/components/PublicOrderSummary.vue'
const route = useRoute()
const router = useRouter()
const api = inject('api')
const inputCode = ref(route.params.code || '')
const purchase = ref(null)
const loading = ref(false)
const error = ref('')
async function fetchOrder (code) {
loading.value = true
error.value = ''
purchase.value = null
try {
purchase.value = await api.getPublicOrderSummary(code)
} catch (e) {
error.value =
e?.response?.status === 404
? 'No se encontró un pedido con ese código.'
: 'Ocurrió un error al consultar el pedido. Inténtalo de nuevo.'
} finally {
loading.value = false
}
}
function onConsult () {
const code = inputCode.value.trim()
if (!code) return
router.push(`/pedido/${code}`)
}
watch(
() => route.params.code,
code => {
if (code) {
inputCode.value = code
fetchOrder(code)
}
},
{ immediate: true }
)
</script>

View File

@@ -51,9 +51,13 @@
<v-card-title class="bg-error text-white">❌ Fallidos ({{ result.failed?.length || 0 }})</v-card-title> <v-card-title class="bg-error text-white">❌ Fallidos ({{ result.failed?.length || 0 }})</v-card-title>
<v-card-text> <v-card-text>
<v-data-table <v-data-table
:items="formatItems(result.failed)" :items="formatSalesResults(result.failed)"
density="compact" density="compact"
:headers="[{ title: 'ID', key: 'id' }]" :headers="[
{ title: 'ID', key: 'id' },
{ title: 'Código', key: 'code' },
{ title: 'Detalle', key: 'detail' }
]"
></v-data-table> ></v-data-table>
</v-card-text> </v-card-text>
</v-card> </v-card>
@@ -64,9 +68,12 @@
<v-card-title class="bg-success text-white">✅ Exitosos ({{ result.successful?.length || 0 }})</v-card-title> <v-card-title class="bg-success text-white">✅ Exitosos ({{ result.successful?.length || 0 }})</v-card-title>
<v-card-text> <v-card-text>
<v-data-table <v-data-table
:items="formatItems(result.successful)" :items="formatSalesResults(result.successful)"
density="compact" density="compact"
:headers="[{ title: 'ID', key: 'id' }]" :headers="[
{ title: 'ID', key: 'id' },
{ title: 'Código', key: 'code' }
]"
></v-data-table> ></v-data-table>
</v-card-text> </v-card-text>
</v-card> </v-card>
@@ -99,9 +106,13 @@
} }
}, },
methods: { methods: {
formatItems(ids) { formatSalesResults(items) {
if (!ids || ids.length === 0) return []; if (!items || items.length === 0) return [];
return ids.map(id => ({ id })); return items.map(item =>
typeof item === 'object'
? { id: item.id, code: item.code ?? '', detail: item.error ?? '' }
: { id: item, code: '', detail: '' }
);
}, },
startSync() { startSync() {
this.loading = true; this.loading = true;

View File

@@ -55,9 +55,13 @@
<v-card-title class="bg-error text-white">❌ Fallidos ({{ result.failed_parties?.length || 0 }})</v-card-title> <v-card-title class="bg-error text-white">❌ Fallidos ({{ result.failed_parties?.length || 0 }})</v-card-title>
<v-card-text> <v-card-text>
<v-data-table <v-data-table
:items="formatItems(result.failed_parties)" :items="formatResults(result.failed_parties)"
density="compact" density="compact"
:headers="[{ title: 'ID', key: 'id' }]" :headers="[
{ title: 'ID', key: 'id' },
{ title: 'Nombre', key: 'name' },
{ title: 'Detalle', key: 'detail' }
]"
></v-data-table> ></v-data-table>
</v-card-text> </v-card-text>
</v-card> </v-card>
@@ -68,9 +72,12 @@
<v-card-title class="bg-success text-white">✅ Creados ({{ result.created_customers?.length || 0 }})</v-card-title> <v-card-title class="bg-success text-white">✅ Creados ({{ result.created_customers?.length || 0 }})</v-card-title>
<v-card-text> <v-card-text>
<v-data-table <v-data-table
:items="formatItems(result.created_customers)" :items="formatResults(result.created_customers)"
density="compact" density="compact"
:headers="[{ title: 'ID', key: 'id' }]" :headers="[
{ title: 'ID', key: 'id' },
{ title: 'Nombre', key: 'name' }
]"
></v-data-table> ></v-data-table>
</v-card-text> </v-card-text>
</v-card> </v-card>
@@ -81,9 +88,13 @@
<v-card-title class="bg-warning">🔄 Actualizados ({{ result.updated_customers?.length || 0 }})</v-card-title> <v-card-title class="bg-warning">🔄 Actualizados ({{ result.updated_customers?.length || 0 }})</v-card-title>
<v-card-text> <v-card-text>
<v-data-table <v-data-table
:items="formatItems(result.updated_customers)" :items="formatResults(result.updated_customers)"
density="compact" density="compact"
:headers="[{ title: 'ID', key: 'id' }]" :headers="[
{ title: 'ID', key: 'id' },
{ title: 'Nombre', key: 'name' },
{ title: 'Detalle', key: 'detail' }
]"
></v-data-table> ></v-data-table>
</v-card-text> </v-card-text>
</v-card> </v-card>
@@ -94,9 +105,12 @@
<v-card-title class="bg-grey-lighten-1">⏭️ Sin cambios ({{ result.untouched_customers?.length || 0 }})</v-card-title> <v-card-title class="bg-grey-lighten-1">⏭️ Sin cambios ({{ result.untouched_customers?.length || 0 }})</v-card-title>
<v-card-text> <v-card-text>
<v-data-table <v-data-table
:items="formatItems(result.untouched_customers)" :items="formatResults(result.untouched_customers)"
density="compact" density="compact"
:headers="[{ title: 'ID', key: 'id' }]" :headers="[
{ title: 'ID', key: 'id' },
{ title: 'Nombre', key: 'name' }
]"
></v-data-table> ></v-data-table>
</v-card-text> </v-card-text>
</v-card> </v-card>
@@ -107,9 +121,12 @@
<v-card-title class="bg-info text-white">🔍 Verificados ({{ result.checked_tryton_parties?.length || 0 }})</v-card-title> <v-card-title class="bg-info text-white">🔍 Verificados ({{ result.checked_tryton_parties?.length || 0 }})</v-card-title>
<v-card-text> <v-card-text>
<v-data-table <v-data-table
:items="formatItems(result.checked_tryton_parties)" :items="formatResults(result.checked_tryton_parties)"
density="compact" density="compact"
:headers="[{ title: 'ID', key: 'id' }]" :headers="[
{ title: 'ID', key: 'id' },
{ title: 'Nombre', key: 'name' }
]"
></v-data-table> ></v-data-table>
</v-card-text> </v-card-text>
</v-card> </v-card>
@@ -142,9 +159,13 @@
} }
}, },
methods: { methods: {
formatItems(ids) { formatResults(items) {
if (!ids || ids.length === 0) return []; if (!items || items.length === 0) return [];
return ids.map(id => ({ id })); return items.map(item =>
typeof item === 'object'
? { id: item.id ?? item.external_id, name: item.name ?? '', detail: item.error ?? item.detail ?? '' }
: { id: item, name: '', detail: '' }
);
}, },
startSync() { startSync() {
this.loading = true; this.loading = true;

View File

@@ -55,9 +55,13 @@
<v-card-title class="bg-error text-white">❌ Fallidos ({{ result.failed_products?.length || 0 }})</v-card-title> <v-card-title class="bg-error text-white">❌ Fallidos ({{ result.failed_products?.length || 0 }})</v-card-title>
<v-card-text> <v-card-text>
<v-data-table <v-data-table
:items="formatItems(result.failed_products)" :items="formatResults(result.failed_products)"
density="compact" density="compact"
:headers="[{ title: 'ID', key: 'id' }]" :headers="[
{ title: 'ID', key: 'id' },
{ title: 'Nombre', key: 'name' },
{ title: 'Detalle', key: 'detail' }
]"
></v-data-table> ></v-data-table>
</v-card-text> </v-card-text>
</v-card> </v-card>
@@ -68,9 +72,12 @@
<v-card-title class="bg-success text-white">✅ Creados ({{ result.created_products?.length || 0 }})</v-card-title> <v-card-title class="bg-success text-white">✅ Creados ({{ result.created_products?.length || 0 }})</v-card-title>
<v-card-text> <v-card-text>
<v-data-table <v-data-table
:items="formatItems(result.created_products)" :items="formatResults(result.created_products)"
density="compact" density="compact"
:headers="[{ title: 'ID', key: 'id' }]" :headers="[
{ title: 'ID', key: 'id' },
{ title: 'Nombre', key: 'name' }
]"
></v-data-table> ></v-data-table>
</v-card-text> </v-card-text>
</v-card> </v-card>
@@ -81,9 +88,13 @@
<v-card-title class="bg-info text-white">🔄 Actualizados ({{ result.updated_products?.length || 0 }})</v-card-title> <v-card-title class="bg-info text-white">🔄 Actualizados ({{ result.updated_products?.length || 0 }})</v-card-title>
<v-card-text> <v-card-text>
<v-data-table <v-data-table
:items="formatItems(result.updated_products)" :items="formatResults(result.updated_products)"
density="compact" density="compact"
:headers="[{ title: 'ID', key: 'id' }]" :headers="[
{ title: 'ID', key: 'id' },
{ title: 'Nombre', key: 'name' },
{ title: 'Detalle', key: 'detail' }
]"
></v-data-table> ></v-data-table>
</v-card-text> </v-card-text>
</v-card> </v-card>
@@ -94,9 +105,12 @@
<v-card-title class="bg-grey-lighten-1">⏭️ Sin cambios ({{ result.untouched_products?.length || 0 }})</v-card-title> <v-card-title class="bg-grey-lighten-1">⏭️ Sin cambios ({{ result.untouched_products?.length || 0 }})</v-card-title>
<v-card-text> <v-card-text>
<v-data-table <v-data-table
:items="formatItems(result.untouched_products)" :items="formatResults(result.untouched_products)"
density="compact" density="compact"
:headers="[{ title: 'ID', key: 'id' }]" :headers="[
{ title: 'ID', key: 'id' },
{ title: 'Nombre', key: 'name' }
]"
></v-data-table> ></v-data-table>
</v-card-text> </v-card-text>
</v-card> </v-card>
@@ -129,9 +143,13 @@
} }
}, },
methods: { methods: {
formatItems(ids) { formatResults(items) {
if (!ids || ids.length === 0) return []; if (!items || items.length === 0) return [];
return ids.map(id => ({ id })); return items.map(item =>
typeof item === 'object'
? { id: item.id ?? item.external_id, name: item.name ?? '', detail: item.error ?? item.detail ?? '' }
: { id: item, name: '', detail: '' }
);
}, },
startSync() { startSync() {
this.loading = true; this.loading = true;

View File

@@ -51,9 +51,13 @@
<v-card-title class="bg-error text-white">❌ Fallidos ({{ result.failed?.length || 0 }})</v-card-title> <v-card-title class="bg-error text-white">❌ Fallidos ({{ result.failed?.length || 0 }})</v-card-title>
<v-card-text> <v-card-text>
<v-data-table <v-data-table
:items="formatItems(result.failed)" :items="formatSalesResults(result.failed)"
density="compact" density="compact"
:headers="[{ title: 'ID', key: 'id' }]" :headers="[
{ title: 'ID', key: 'id' },
{ title: 'Código', key: 'code' },
{ title: 'Detalle', key: 'detail' }
]"
></v-data-table> ></v-data-table>
</v-card-text> </v-card-text>
</v-card> </v-card>
@@ -64,9 +68,12 @@
<v-card-title class="bg-success text-white">✅ Exitosos ({{ result.successful?.length || 0 }})</v-card-title> <v-card-title class="bg-success text-white">✅ Exitosos ({{ result.successful?.length || 0 }})</v-card-title>
<v-card-text> <v-card-text>
<v-data-table <v-data-table
:items="formatItems(result.successful)" :items="formatSalesResults(result.successful)"
density="compact" density="compact"
:headers="[{ title: 'ID', key: 'id' }]" :headers="[
{ title: 'ID', key: 'id' },
{ title: 'Código', key: 'code' }
]"
></v-data-table> ></v-data-table>
</v-card-text> </v-card-text>
</v-card> </v-card>
@@ -99,9 +106,13 @@
} }
}, },
methods: { methods: {
formatItems(ids) { formatSalesResults(items) {
if (!ids || ids.length === 0) return []; if (!items || items.length === 0) return [];
return ids.map(id => ({ id })); return items.map(item =>
typeof item === 'object'
? { id: item.id, code: item.code ?? '', detail: item.error ?? '' }
: { id: item, code: '', detail: '' }
);
}, },
startSync() { startSync() {
this.loading = true; this.loading = true;

View File

@@ -24,6 +24,10 @@ const ADMIN_ROUTES = [
'/admin/products', '/admin/products',
'/admin/catalog-sales', '/admin/catalog-sales',
'/admin/catalogue-images', '/admin/catalogue-images',
'/admin/store-settings',
'/admin/organizations',
'/admin/suppliers',
'/admin/geography',
] ]
const router = createRouter({ const router = createRouter({

View File

@@ -15,6 +15,90 @@ class Api {
return this.apiImplementation.updateProduct(productId, data); return this.apiImplementation.updateProduct(productId, data);
} }
getProduct(productId) {
return this.apiImplementation.getProduct(productId);
}
getOrganizations() {
return this.apiImplementation.getOrganizations();
}
createOrganization(data) {
return this.apiImplementation.createOrganization(data);
}
updateOrganization(id, data) {
return this.apiImplementation.updateOrganization(id, data);
}
deleteOrganization(id) {
return this.apiImplementation.deleteOrganization(id);
}
getSuppliers() {
return this.apiImplementation.getSuppliers();
}
createSupplier(data) {
return this.apiImplementation.createSupplier(data);
}
updateSupplier(id, data) {
return this.apiImplementation.updateSupplier(id, data);
}
deleteSupplier(id) {
return this.apiImplementation.deleteSupplier(id);
}
getCountries() {
return this.apiImplementation.getCountries();
}
createCountry(data) {
return this.apiImplementation.createCountry(data);
}
updateCountry(id, data) {
return this.apiImplementation.updateCountry(id, data);
}
deleteCountry(id) {
return this.apiImplementation.deleteCountry(id);
}
getDepartments() {
return this.apiImplementation.getDepartments();
}
createDepartment(data) {
return this.apiImplementation.createDepartment(data);
}
updateDepartment(id, data) {
return this.apiImplementation.updateDepartment(id, data);
}
deleteDepartment(id) {
return this.apiImplementation.deleteDepartment(id);
}
getMunicipalities() {
return this.apiImplementation.getMunicipalities();
}
createMunicipality(data) {
return this.apiImplementation.createMunicipality(data);
}
updateMunicipality(id, data) {
return this.apiImplementation.updateMunicipality(id, data);
}
deleteMunicipality(id) {
return this.apiImplementation.deleteMunicipality(id);
}
getPaymentMethods() { getPaymentMethods() {
return this.apiImplementation.getPaymentMethods(); return this.apiImplementation.getPaymentMethods();
} }
@@ -27,6 +111,10 @@ class Api {
return this.apiImplementation.getSummaryCatalogPurchase(purchaseId); return this.apiImplementation.getSummaryCatalogPurchase(purchaseId);
} }
getPublicOrderSummary(code) {
return this.apiImplementation.getPublicOrderSummary(code);
}
getPurchasesForReconciliation() { getPurchasesForReconciliation() {
return this.apiImplementation.getPurchasesForReconciliation(); return this.apiImplementation.getPurchasesForReconciliation();
} }
@@ -98,6 +186,14 @@ class Api {
deleteCatalogueImage(id) { deleteCatalogueImage(id) {
return this.apiImplementation.deleteCatalogueImage(id); return this.apiImplementation.deleteCatalogueImage(id);
} }
getStoreSettings() {
return this.apiImplementation.getStoreSettings();
}
updateStoreSettings(data) {
return this.apiImplementation.updateStoreSettings(data);
}
} }
export default Api; export default Api;

View File

@@ -18,6 +18,10 @@ class DjangoApi {
return http.patch(url, payload).then((r) => r.data); return http.patch(url, payload).then((r) => r.data);
} }
deleteRequest(url) {
return http.delete(url).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);
@@ -39,6 +43,111 @@ class DjangoApi {
return this.patchRequest(url, data); return this.patchRequest(url, data);
} }
getProduct(productId) {
const url = this.base + `/don_confiao/api/products/${productId}/`;
return this.getRequest(url);
}
getOrganizations() {
const url = this.base + "/don_confiao/api/organizations/";
return this.getRequest(url);
}
createOrganization(data) {
const url = this.base + "/don_confiao/api/organizations/";
return this.postRequest(url, data);
}
updateOrganization(id, data) {
const url = this.base + `/don_confiao/api/organizations/${id}/`;
return this.patchRequest(url, data);
}
deleteOrganization(id) {
const url = this.base + `/don_confiao/api/organizations/${id}/`;
return this.deleteRequest(url);
}
getSuppliers() {
const url = this.base + "/don_confiao/api/suppliers/";
return this.getRequest(url);
}
createSupplier(data) {
const url = this.base + "/don_confiao/api/suppliers/";
return this.postRequest(url, data);
}
updateSupplier(id, data) {
const url = this.base + `/don_confiao/api/suppliers/${id}/`;
return this.patchRequest(url, data);
}
deleteSupplier(id) {
const url = this.base + `/don_confiao/api/suppliers/${id}/`;
return this.deleteRequest(url);
}
getCountries() {
const url = this.base + "/don_confiao/api/countries/";
return this.getRequest(url);
}
createCountry(data) {
const url = this.base + "/don_confiao/api/countries/";
return this.postRequest(url, data);
}
updateCountry(id, data) {
const url = this.base + `/don_confiao/api/countries/${id}/`;
return this.patchRequest(url, data);
}
deleteCountry(id) {
const url = this.base + `/don_confiao/api/countries/${id}/`;
return this.deleteRequest(url);
}
getDepartments() {
const url = this.base + "/don_confiao/api/departments/";
return this.getRequest(url);
}
createDepartment(data) {
const url = this.base + "/don_confiao/api/departments/";
return this.postRequest(url, data);
}
updateDepartment(id, data) {
const url = this.base + `/don_confiao/api/departments/${id}/`;
return this.patchRequest(url, data);
}
deleteDepartment(id) {
const url = this.base + `/don_confiao/api/departments/${id}/`;
return this.deleteRequest(url);
}
getMunicipalities() {
const url = this.base + "/don_confiao/api/municipalities/";
return this.getRequest(url);
}
createMunicipality(data) {
const url = this.base + "/don_confiao/api/municipalities/";
return this.postRequest(url, data);
}
updateMunicipality(id, data) {
const url = this.base + `/don_confiao/api/municipalities/${id}/`;
return this.patchRequest(url, data);
}
deleteMunicipality(id) {
const url = this.base + `/don_confiao/api/municipalities/${id}/`;
return this.deleteRequest(url);
}
getPaymentMethods() { getPaymentMethods() {
const url = const url =
this.base + "/don_confiao/payment_methods/all/select_format"; this.base + "/don_confiao/payment_methods/all/select_format";
@@ -57,6 +166,12 @@ class DjangoApi {
return this.getRequest(url); return this.getRequest(url);
} }
getPublicOrderSummary(code) {
const url =
this.base + `/don_confiao/resumen_publico/${code}`;
return this.getRequest(url);
}
getPurchasesForReconciliation() { getPurchasesForReconciliation() {
const url = this.base + "/don_confiao/purchases/for_reconciliation"; const url = this.base + "/don_confiao/purchases/for_reconciliation";
return this.getRequest(url); return this.getRequest(url);
@@ -154,6 +269,18 @@ class DjangoApi {
const url = this.base + `/don_confiao/api/catalogue_images/${id}/`; const url = this.base + `/don_confiao/api/catalogue_images/${id}/`;
return http.delete(url).then((r) => r.data); return http.delete(url).then((r) => r.data);
} }
getStoreSettings() {
const url = this.base + "/don_confiao/api/store_settings";
return this.getRequest(url);
}
updateStoreSettings(data) {
const url = this.base + "/don_confiao/api/store_settings";
return http.patch(url, data, {
headers: { 'Content-Type': undefined },
}).then((r) => r.data);
}
} }
export default DjangoApi; export default DjangoApi;

View File

@@ -0,0 +1,76 @@
/**
* Servicio genérico de grafos en capas (columnas).
*
* Provee un layout determinista por columnas (un tipo por columna) y un
* adaptador al formato `elements` de cytoscape.js. No conoce el dominio
* (provenance, organigrama, etc.), solo el modelo de grafo:
* node: { id, kind, label, image?, entity? }
* edge: { from, to } (ids de los nodos)
*/
const DEFAULTS = {
columnWidth: 220,
rowHeight: 64,
padding: 24,
}
function groupByColumn (nodes, columnOf) {
const columns = {}
for (const node of nodes) {
const column = columnOf(node) ?? 0
if (!columns[column]) columns[column] = []
columns[column].push(node)
}
return columns
}
export function computeColumnLayout (nodes, edges, options = {}) {
const { columnOf, columnWidth = DEFAULTS.columnWidth, rowHeight = DEFAULTS.rowHeight, padding = DEFAULTS.padding } = options
const columns = groupByColumn(nodes, columnOf)
const columnKeys = Object.keys(columns).map(Number)
const maxColumn = columnKeys.length > 0 ? Math.max(...columnKeys) : 0
const maxRows = columnKeys.length > 0 ? Math.max(...columnKeys.map(c => columns[c].length)) : 0
const positionedNodes = nodes.map(node => {
const column = columnOf(node) ?? 0
const index = columns[column].indexOf(node)
return {
...node,
x: padding + column * columnWidth + columnWidth / 2,
y: padding + index * rowHeight + rowHeight / 2,
}
})
return {
nodes: positionedNodes,
edges,
width: padding * 2 + (maxColumn + 1) * columnWidth,
height: padding * 2 + maxRows * rowHeight,
}
}
export function toCytoscapeElements ({ nodes, edges }) {
return [
...nodes.map(node => {
const classes = node.image ? [node.kind, 'has-image'] : [node.kind]
return {
data: {
id: node.id,
kind: node.kind,
label: node.label,
image: node.image || null,
entity: node.entity || null,
},
classes,
position: { x: node.x, y: node.y },
}
}),
...edges.map(edge => ({
data: {
id: `edge:${edge.from}:${edge.to}`,
source: edge.from,
target: edge.to,
},
})),
]
}

26
src/stores/settings.js Normal file
View File

@@ -0,0 +1,26 @@
import { defineStore } from 'pinia'
export const useSettingsStore = defineStore('settings', {
state: () => ({
settings: null,
loaded: false
}),
getters: {
logo: (state) => state.settings?.logo || null,
address: (state) => state.settings?.address || '',
latitude: (state) => state.settings?.latitude,
longitude: (state) => state.settings?.longitude
},
actions: {
async fetchSettings(api) {
if (this.loaded) return this.settings
this.settings = await api.getStoreSettings()
this.loaded = true
return this.settings
},
setSettings(settings) {
this.settings = settings
this.loaded = true
}
}
})

44
tests/setup.js Normal file
View File

@@ -0,0 +1,44 @@
import { afterEach, vi } from 'vitest'
import { enableAutoUnmount } from '@vue/test-utils'
enableAutoUnmount(afterEach)
if (!navigator.clipboard) {
navigator.clipboard = { writeText: vi.fn().mockResolvedValue(undefined) }
}
if (typeof globalThis.ResizeObserver === 'undefined') {
globalThis.ResizeObserver = class ResizeObserver {
observe () {}
unobserve () {}
disconnect () {}
}
}
if (typeof globalThis.IntersectionObserver === 'undefined') {
globalThis.IntersectionObserver = class IntersectionObserver {
observe () {}
unobserve () {}
disconnect () {}
takeRecords () {
return []
}
}
}
if (typeof window.matchMedia !== 'function') {
window.matchMedia = query => ({
matches: false,
media: query,
onchange: null,
addListener: () => {},
removeListener: () => {},
addEventListener: () => {},
removeEventListener: () => {},
dispatchEvent: () => false,
})
}
afterEach(() => {
vi.restoreAllMocks()
})

View File

@@ -0,0 +1,47 @@
import { beforeEach, describe, expect, it } from 'vitest'
import { mount } from '@vue/test-utils'
import OrderAccessInfo from '@/components/order/OrderAccessInfo.vue'
import vuetify from '@/plugins/vuetify'
function mountAccessInfo (code) {
return mount(OrderAccessInfo, {
props: { code },
global: { plugins: [vuetify] },
})
}
describe('OrderAccessInfo', () => {
beforeEach(() => {
navigator.clipboard.writeText.mockClear()
})
it('muestra el código del pedido', () => {
const wrapper = mountAccessInfo('abc123')
expect(wrapper.text()).toContain('abc123')
})
it('muestra el link público construido con el código', () => {
const wrapper = mountAccessInfo('abc123')
expect(wrapper.text()).toContain(
`${window.location.origin}/pedido/abc123`
)
})
it('copia el link al presionar el botón de copiar link', async () => {
const wrapper = mountAccessInfo('abc123')
await wrapper.find('[data-test="copy-link"]').trigger('click')
expect(navigator.clipboard.writeText).toHaveBeenCalledWith(
`${window.location.origin}/pedido/abc123`
)
})
it('copia el código al presionar el botón de copiar código', async () => {
const wrapper = mountAccessInfo('abc123')
await wrapper.find('[data-test="copy-code"]').trigger('click')
expect(navigator.clipboard.writeText).toHaveBeenCalledWith('abc123')
})
})

View File

@@ -0,0 +1,124 @@
import { describe, expect, it } from 'vitest'
import { mount } from '@vue/test-utils'
import PublicOrderSummary from '@/components/PublicOrderSummary.vue'
import OrderAccessInfo from '@/components/order/OrderAccessInfo.vue'
import OrderCustomer from '@/components/order/OrderCustomer.vue'
import OrderLines from '@/components/order/OrderLines.vue'
import OrderTotal from '@/components/order/OrderTotal.vue'
import OrderPayment from '@/components/order/OrderPayment.vue'
import ProvenanceSection from '@/components/provenance/ProvenanceSection.vue'
import vuetify from '@/plugins/vuetify'
const ProvenanceSectionStub = {
name: 'ProvenanceSection',
props: ['provenance'],
template: '<div data-test="provenance-section" />',
}
const saleData = {
id: 5,
code: 'abc123',
date: '2024-09-02T00:00:00Z',
customer: { id: 1, name: 'Camilo' },
payment_method: 'CASH',
lines: [
{ product: { id: 10, name: 'Panela' }, quantity: 2, unit_price: 3000 },
{ product: { id: 11, name: 'Arroz' }, quantity: 1, unit_price: 5000 },
],
type: 'sale',
}
const catalogData = {
id: 7,
code: 'def456',
date: '2024-09-02T00:00:00Z',
customer: { id: 1, name: 'Camilo' },
lines: [{ product: { id: 10, name: 'Panela' }, quantity: 2, unit_price: 3000 }],
type: 'catalog',
}
function mountSummary (props) {
return mount(PublicOrderSummary, {
props,
global: {
plugins: [vuetify],
stubs: { ProvenanceSection: ProvenanceSectionStub },
},
})
}
describe('PublicOrderSummary', () => {
it('renderiza el resumen de una venta con sus partes', () => {
const wrapper = mountSummary({ purchase: saleData })
expect(wrapper.findComponent(OrderAccessInfo).exists()).toBe(true)
expect(wrapper.findComponent(OrderCustomer).exists()).toBe(true)
expect(wrapper.findComponent(OrderLines).exists()).toBe(true)
expect(wrapper.findComponent(OrderTotal).exists()).toBe(true)
expect(wrapper.findComponent(OrderPayment).exists()).toBe(true)
expect(wrapper.text()).toContain('Resumen de la compra')
expect(wrapper.text()).toContain('Camilo')
expect(wrapper.text()).toContain('Panela')
expect(wrapper.text()).toContain('Arroz')
expect(wrapper.text().replace(/\u00A0/g, ' ')).toContain('11.000')
})
it('renderiza un pedido de catálogo sin bloque de pago', () => {
const wrapper = mountSummary({ purchase: catalogData })
expect(wrapper.findComponent(OrderAccessInfo).exists()).toBe(true)
expect(wrapper.findComponent(OrderCustomer).exists()).toBe(true)
expect(wrapper.findComponent(OrderLines).exists()).toBe(true)
expect(wrapper.findComponent(OrderTotal).exists()).toBe(true)
expect(wrapper.findComponent(OrderPayment).exists()).toBe(false)
expect(wrapper.text()).toContain('Resumen del pedido')
expect(wrapper.text()).toContain('Camilo')
expect(wrapper.text()).toContain('Panela')
})
it('muestra el estado de carga', () => {
const wrapper = mountSummary({ purchase: null, loading: true })
expect(wrapper.text()).toContain('Cargando')
})
it('muestra el mensaje de error cuando lo recibe', () => {
const wrapper = mountSummary({
purchase: null,
error: 'No se encontró un pedido con ese código.',
})
expect(wrapper.text()).toContain('No se encontró un pedido con ese código.')
})
it('no renderiza datos cuando no hay pedido, carga ni error', () => {
const wrapper = mountSummary({ purchase: null })
expect(wrapper.text()).not.toContain('Camilo')
expect(wrapper.findComponent(OrderLines).exists()).toBe(false)
})
it('no renderiza la sección de provenance cuando la respuesta no la incluye', () => {
const wrapper = mountSummary({ purchase: saleData })
expect(wrapper.findComponent(ProvenanceSection).exists()).toBe(false)
})
it('renderiza la sección de provenance cuando el resumen la incluye', () => {
const withProvenance = {
...saleData,
product_provenance: [
{
product: { id: 10, name: 'Panela' },
suppliers: [{ supplier: { id: 5, name: 'La Mesa' }, organization: { id: 3, name: 'Red' }, municipality: { id: 7, name: 'La Mesa' }, department: { id: 2, name: 'Cundinamarca' }, country: { id: 1, name: 'Colombia', code: 'CO' } }],
},
],
}
const wrapper = mountSummary({ purchase: withProvenance })
expect(wrapper.findComponent(ProvenanceSection).exists()).toBe(true)
expect(wrapper.findComponent(ProvenanceSection).props('provenance')).toEqual(
withProvenance.product_provenance
)
})
})

View File

@@ -0,0 +1,93 @@
import cytoscape from 'cytoscape'
import { beforeEach, describe, expect, it, vi } from 'vitest'
import { mount } from '@vue/test-utils'
import CytoscapeChart from '@/components/graph/CytoscapeChart.vue'
const tapHandler = { current: null }
const cy = {
on: vi.fn((event, selector, handler) => {
if (event === 'tap') tapHandler.current = handler
}),
elements: vi.fn(() => ({ remove: vi.fn() })),
add: vi.fn(),
layout: vi.fn(() => ({ run: vi.fn() })),
destroy: vi.fn(),
}
vi.mock('cytoscape', () => ({
default: vi.fn(() => cy),
}))
const elements = [
{ data: { id: 'product:1', kind: 'product', label: 'Panela' }, position: { x: 100, y: 100 } },
{ data: { id: 'supplier:5', kind: 'supplier', label: 'La Mesa' }, position: { x: 320, y: 100 } },
{ data: { id: 'e1', source: 'product:1', target: 'supplier:5' } },
]
const styles = [{ selector: 'node', style: { 'background-color': '#eee' } }]
beforeEach(() => {
vi.clearAllMocks()
tapHandler.current = null
})
function mountChart (props = {}) {
return mount(CytoscapeChart, {
props: { elements, styles, ...props },
})
}
describe('CytoscapeChart', () => {
it('crea la instancia de cytoscape con elements, styles y layout', () => {
mountChart()
expect(cytoscape).toHaveBeenCalledTimes(1)
expect(cytoscape).toHaveBeenCalledWith(
expect.objectContaining({
elements,
style: styles,
layout: { name: 'preset' },
})
)
})
it('permite sobreescribir el layout con el prop layout', () => {
mountChart({ layout: { name: 'breadthfirst' } })
expect(cytoscape).toHaveBeenCalledWith(
expect.objectContaining({ layout: { name: 'breadthfirst' } })
)
})
it('emite select con los datos del nodo al hacer tap', () => {
const wrapper = mountChart()
tapHandler.current({ target: { data: () => elements[0].data } })
expect(wrapper.emitted('select')).toEqual([[elements[0].data]])
})
it('actualiza la instancia cuando cambian los elements', async () => {
const wrapper = mountChart()
const next = [{ data: { id: 'organization:3', kind: 'organization', label: 'Red' } }]
await wrapper.setProps({ elements: next })
expect(cy.elements).toHaveBeenCalled()
expect(cy.add).toHaveBeenCalledWith(next)
expect(cy.layout).toHaveBeenCalled()
})
it('destruye la instancia al desmontarse', () => {
const wrapper = mountChart()
wrapper.unmount()
expect(cy.destroy).toHaveBeenCalledTimes(1)
})
it('no escucha eventos mientras no exista la instancia', () => {
mountChart()
expect(cy.on).toHaveBeenCalledWith('tap', 'node', expect.any(Function))
})
})

View File

@@ -0,0 +1,87 @@
import { beforeEach, describe, expect, it, vi } from 'vitest'
import { mount } from '@vue/test-utils'
import CytoscapeChart from '@/components/graph/CytoscapeChart.vue'
import ProvenanceDetailModal from '@/components/provenance/ProvenanceDetailModal.vue'
import ProductSupplierOrganizationChart from '@/components/provenance/ProductSupplierOrganizationChart.vue'
import vuetify from '@/plugins/vuetify'
const cy = {
on: vi.fn(),
elements: vi.fn(() => ({ remove: vi.fn() })),
add: vi.fn(),
layout: vi.fn(() => ({ run: vi.fn() })),
destroy: vi.fn(),
}
vi.mock('cytoscape', () => ({
default: vi.fn(() => cy),
}))
const provenance = [
{
product: {
id: 1,
name: 'Panela regional por Kg',
catalogue_images: ['http://localhost/media/panela.jpg'],
},
suppliers: [
{
supplier: { id: 5, name: 'Asociación Agropecuaria La Mesa', description: 'Cooperativa' },
organization: { id: 3, name: 'Red de Economía Solidaria', description: 'Red' },
municipality: null,
department: null,
country: null,
},
],
},
]
function mountChart (props = {}) {
return mount(ProductSupplierOrganizationChart, {
props: { provenance, ...props },
global: { plugins: [vuetify] },
})
}
describe('ProductSupplierOrganizationChart', () => {
beforeEach(() => {
vi.clearAllMocks()
})
it('renderiza el gráfico con los elementos de productos, proveedores y organizaciones', () => {
const wrapper = mountChart()
const chart = wrapper.findComponent(CytoscapeChart)
expect(chart.exists()).toBe(true)
const elements = chart.props('elements')
const nodeIds = elements.filter(e => e.data.source === undefined).map(e => e.data.id)
expect(nodeIds).toContain('product:1')
expect(nodeIds).toContain('supplier:5')
expect(nodeIds).toContain('organization:3')
})
it('no muestra mensaje de próximamente cuando existen relaciones', () => {
const wrapper = mountChart()
expect(wrapper.text()).not.toContain('próximamente')
})
it('muestra mensaje de próximamente cuando ningún producto tiene proveedores', () => {
const wrapper = mountChart({
provenance: [{ product: { id: 1, name: 'Panela' }, suppliers: [] }],
})
expect(wrapper.findComponent(CytoscapeChart).exists()).toBe(false)
expect(wrapper.text()).toContain('próximamente')
})
it('abre el modal de detalle al seleccionar un nodo', async () => {
const wrapper = mountChart()
const chart = wrapper.findComponent(CytoscapeChart)
await chart.vm.$emit('select', { kind: 'supplier', label: 'Asociación Agropecuaria La Mesa', entity: { kind: 'supplier' } })
expect(wrapper.findComponent(ProvenanceDetailModal).props('visible')).toBe(true)
expect(document.body.textContent).toContain('Asociación Agropecuaria La Mesa')
})
})

View File

@@ -0,0 +1,84 @@
import { beforeEach, describe, expect, it, vi } from 'vitest'
import { mount } from '@vue/test-utils'
import CytoscapeChart from '@/components/graph/CytoscapeChart.vue'
import ProvenanceDetailModal from '@/components/provenance/ProvenanceDetailModal.vue'
import ProductTerritoryChart from '@/components/provenance/ProductTerritoryChart.vue'
import vuetify from '@/plugins/vuetify'
const cy = {
on: vi.fn(),
elements: vi.fn(() => ({ remove: vi.fn() })),
add: vi.fn(),
layout: vi.fn(() => ({ run: vi.fn() })),
destroy: vi.fn(),
}
vi.mock('cytoscape', () => ({
default: vi.fn(() => cy),
}))
const provenance = [
{
product: { id: 1, name: 'Panela regional por Kg' },
suppliers: [
{
supplier: { id: 5, name: 'Asociación Agropecuaria La Mesa' },
organization: null,
municipality: { id: 7, name: 'La Mesa' },
department: { id: 2, name: 'Cundinamarca' },
country: { id: 1, name: 'Colombia', code: 'CO' },
},
],
},
]
function mountChart (props = {}) {
return mount(ProductTerritoryChart, {
props: { provenance, ...props },
global: { plugins: [vuetify] },
})
}
describe('ProductTerritoryChart', () => {
beforeEach(() => {
vi.clearAllMocks()
})
it('renderiza el gráfico con municipio, departamento y país', () => {
const wrapper = mountChart()
const chart = wrapper.findComponent(CytoscapeChart)
expect(chart.exists()).toBe(true)
const elements = chart.props('elements')
const nodeIds = elements.filter(e => e.data.source === undefined).map(e => e.data.id)
expect(nodeIds).toContain('product:1')
expect(nodeIds).toContain('supplier:5')
expect(nodeIds).toContain('municipality:7')
expect(nodeIds).toContain('department:2')
expect(nodeIds).toContain('country:1')
})
it('muestra mensaje de próximamente cuando ningún proveedor tiene territorio', () => {
const wrapper = mountChart({
provenance: [
{
product: { id: 1, name: 'Panela' },
suppliers: [{ supplier: { id: 5, name: 'La Mesa' }, municipality: null, department: null, country: null }],
},
],
})
expect(wrapper.findComponent(CytoscapeChart).exists()).toBe(false)
expect(wrapper.text()).toContain('próximamente')
})
it('abre el modal de detalle al seleccionar un municipio', async () => {
const wrapper = mountChart()
const chart = wrapper.findComponent(CytoscapeChart)
await chart.vm.$emit('select', { kind: 'municipality', label: 'La Mesa', entity: { kind: 'municipality', name: 'La Mesa' } })
expect(wrapper.findComponent(ProvenanceDetailModal).props('visible')).toBe(true)
expect(document.body.textContent).toContain('La Mesa')
})
})

View File

@@ -0,0 +1,88 @@
import { describe, expect, it } from 'vitest'
import { mount } from '@vue/test-utils'
import ProvenanceDetailModal from '@/components/provenance/ProvenanceDetailModal.vue'
import vuetify from '@/plugins/vuetify'
const supplier = {
id: 'supplier:5',
kind: 'supplier',
label: 'Asociación Agropecuaria La Mesa',
image: null,
entity: {
id: 5,
name: 'Asociación Agropecuaria La Mesa',
description: 'Cooperativa de campesinos',
website: 'https://agro.example.org',
contact_email: 'contacto@agro.example.org',
contact_phone: '300 123 4567',
kind: 'supplier',
},
}
const product = {
id: 'product:1',
kind: 'product',
label: 'Panela regional por Kg',
image: 'http://localhost/media/panela.jpg',
entity: { id: 1, name: 'Panela regional por Kg', kind: 'product' },
}
function mountModal (props) {
return mount(ProvenanceDetailModal, {
props,
global: { plugins: [vuetify] },
})
}
function bodyText () {
return document.body.textContent
}
describe('ProvenanceDetailModal', () => {
it('muestra la información detallada del proveedor seleccionado', () => {
mountModal({ visible: true, selected: supplier })
expect(bodyText()).toContain('Proveedor')
expect(bodyText()).toContain('Asociación Agropecuaria La Mesa')
expect(bodyText()).toContain('Cooperativa de campesinos')
expect(bodyText()).toContain('https://agro.example.org')
expect(bodyText()).toContain('contacto@agro.example.org')
expect(bodyText()).toContain('300 123 4567')
})
it('muestra la imagen del producto cuando existe', () => {
mountModal({ visible: true, selected: product })
expect(document.querySelector('img').getAttribute('src')).toBe(
'http://localhost/media/panela.jpg'
)
})
it('no muestra contenido cuando no hay entidad seleccionada', () => {
mountModal({ visible: true, selected: null })
expect(bodyText()).not.toContain('Proveedor')
expect(bodyText()).not.toContain('Asociación')
})
it('no muestra el diálogo cuando visible es false', () => {
mountModal({ visible: false, selected: supplier })
expect(bodyText()).not.toContain('Asociación Agropecuaria La Mesa')
})
it('omite los campos vacíos', () => {
const minimal = {
id: 'country:1',
kind: 'country',
label: 'Colombia',
image: null,
entity: { id: 1, name: 'Colombia', kind: 'country' },
}
mountModal({ visible: true, selected: minimal })
expect(bodyText()).toContain('Colombia')
expect(bodyText()).not.toContain('Descripción')
expect(bodyText()).not.toContain('Sitio web')
})
})

View File

@@ -0,0 +1,72 @@
import { describe, expect, it, vi } from 'vitest'
import { mount } from '@vue/test-utils'
import ProductSupplierOrganizationChart from '@/components/provenance/ProductSupplierOrganizationChart.vue'
import ProductTerritoryChart from '@/components/provenance/ProductTerritoryChart.vue'
import ProvenanceSection from '@/components/provenance/ProvenanceSection.vue'
import vuetify from '@/plugins/vuetify'
const cy = {
on: vi.fn(),
elements: vi.fn(() => ({ remove: vi.fn() })),
add: vi.fn(),
layout: vi.fn(() => ({ run: vi.fn() })),
destroy: vi.fn(),
}
vi.mock('cytoscape', () => ({
default: vi.fn(() => cy),
}))
const provenance = [
{
product: { id: 1, name: 'Panela regional por Kg' },
suppliers: [
{
supplier: { id: 5, name: 'Asociación La Mesa' },
organization: { id: 3, name: 'Red de Economía Solidaria' },
municipality: { id: 7, name: 'La Mesa' },
department: { id: 2, name: 'Cundinamarca' },
country: { id: 1, name: 'Colombia', code: 'CO' },
},
],
},
]
function mountSection (props = {}) {
return mount(ProvenanceSection, {
props: { provenance, ...props },
global: { plugins: [vuetify] },
})
}
describe('ProvenanceSection', () => {
it('no renderiza nada cuando no hay provenance', () => {
const wrapper = mountSection({ provenance: null })
expect(wrapper.findComponent(ProductSupplierOrganizationChart).exists()).toBe(false)
expect(wrapper.findComponent(ProductTerritoryChart).exists()).toBe(false)
})
it('no renderiza nada cuando provenance es una lista vacía', () => {
const wrapper = mountSection({ provenance: [] })
expect(wrapper.findComponent(ProductSupplierOrganizationChart).exists()).toBe(false)
expect(wrapper.findComponent(ProductTerritoryChart).exists()).toBe(false)
})
it('muestra los dos gráficos con sus títulos cuando hay provenance', () => {
const wrapper = mountSection()
expect(wrapper.findComponent(ProductSupplierOrganizationChart).exists()).toBe(true)
expect(wrapper.findComponent(ProductTerritoryChart).exists()).toBe(true)
expect(wrapper.text()).toContain('Proveedores y organizaciones')
expect(wrapper.text()).toContain('Departamento y municipio')
})
it('pasa el provenance a ambos gráficos', () => {
const wrapper = mountSection()
expect(wrapper.findComponent(ProductSupplierOrganizationChart).props('provenance')).toStrictEqual(provenance)
expect(wrapper.findComponent(ProductTerritoryChart).props('provenance')).toStrictEqual(provenance)
})
})

View File

@@ -0,0 +1,114 @@
import { describe, expect, it, vi } from 'vitest'
import { flushPromises, mount } from '@vue/test-utils'
import GeographyManagement from '@/components/provenance/admin/GeographyManagement.vue'
import vuetify from '@/plugins/vuetify'
import { clickBody, setBodyInput } from './helpers'
const countries = [
{ id: 1, name: 'Colombia', code: 'CO' },
{ id: 2, name: 'Venezuela', code: 'VE' },
]
const departments = [
{ id: 2, name: 'Cundinamarca', country: 1, country_detail: { id: 1, name: 'Colombia', code: 'CO' } },
{ id: 3, name: 'Antioquia', country: 1, country_detail: { id: 1, name: 'Colombia', code: 'CO' } },
]
const municipalities = [
{ id: 7, name: 'La Mesa', department: 2, country: 1, department_detail: { id: 2, name: 'Cundinamarca' } },
{ id: 8, name: 'San Antonio', department: 3, country: 1, department_detail: { id: 3, name: 'Antioquia' } },
]
function mockApi () {
return {
getCountries: vi.fn().mockResolvedValue(countries),
createCountry: vi.fn().mockResolvedValue({}),
updateCountry: vi.fn().mockResolvedValue({}),
deleteCountry: vi.fn().mockResolvedValue({}),
getDepartments: vi.fn().mockResolvedValue(departments),
createDepartment: vi.fn().mockResolvedValue({}),
updateDepartment: vi.fn().mockResolvedValue({}),
deleteDepartment: vi.fn().mockResolvedValue({}),
getMunicipalities: vi.fn().mockResolvedValue(municipalities),
createMunicipality: vi.fn().mockResolvedValue({}),
updateMunicipality: vi.fn().mockResolvedValue({}),
deleteMunicipality: vi.fn().mockResolvedValue({}),
}
}
function mountComponent (api) {
return mount(GeographyManagement, {
global: { plugins: [vuetify], provide: { api } },
})
}
describe('GeographyManagement', () => {
it('muestra los países por defecto y permite crear uno', async () => {
const api = mockApi()
const wrapper = mountComponent(api)
await flushPromises()
expect(api.getCountries).toHaveBeenCalled()
expect(wrapper.text()).toContain('Colombia')
await wrapper.find('[data-testid="geo-country-create"]').trigger('click')
setBodyInput('[data-testid="geo-country-form-name"] input', 'Ecuador')
setBodyInput('[data-testid="geo-country-form-code"] input', 'EC')
clickBody('[data-testid="geo-country-save"]')
await flushPromises()
expect(api.createCountry).toHaveBeenCalledWith({ name: 'Ecuador', code: 'EC' })
expect(api.getCountries).toHaveBeenCalledTimes(2)
})
it('cambia a la pestaña de departamentos y crea uno', async () => {
const api = mockApi()
const wrapper = mountComponent(api)
await flushPromises()
await wrapper.find('[data-testid="geo-tab-departments"]').trigger('click')
await flushPromises()
expect(api.getDepartments).toHaveBeenCalled()
expect(wrapper.text()).toContain('Cundinamarca')
await wrapper.find('[data-testid="geo-department-create"]').trigger('click')
setBodyInput('[data-testid="geo-department-form-name"] input', 'Risaralda')
const countrySelect = wrapper.findAllComponents({ name: 'VSelect' })
.find(select => select.props('items').some(item => item.id === 2))
await countrySelect.vm.$emit('update:modelValue', 2)
clickBody('[data-testid="geo-department-save"]')
await flushPromises()
expect(api.createDepartment).toHaveBeenCalledWith(expect.objectContaining({
name: 'Risaralda',
country: 2,
}))
expect(api.getDepartments).toHaveBeenCalledTimes(2)
})
it('cambia a la pestaña de municipios y crea uno con departamento y país', async () => {
const api = mockApi()
const wrapper = mountComponent(api)
await flushPromises()
await wrapper.find('[data-testid="geo-tab-municipalities"]').trigger('click')
await flushPromises()
expect(api.getMunicipalities).toHaveBeenCalled()
expect(wrapper.text()).toContain('San Antonio')
await wrapper.find('[data-testid="geo-municipality-create"]').trigger('click')
setBodyInput('[data-testid="geo-municipality-form-name"] input', 'Pereira')
await wrapper.findAllComponents({ name: 'VAutocomplete' })[0].vm.$emit('update:modelValue', 3)
clickBody('[data-testid="geo-municipality-save"]')
await flushPromises()
expect(api.createMunicipality).toHaveBeenCalledWith(expect.objectContaining({
name: 'Pereira',
department: 3,
country: 1,
}))
expect(api.getMunicipalities).toHaveBeenCalledTimes(2)
})
})

View File

@@ -0,0 +1,117 @@
import { describe, expect, it, vi } from 'vitest'
import { flushPromises, mount } from '@vue/test-utils'
import OrganizationsManagement from '@/components/provenance/admin/OrganizationsManagement.vue'
import vuetify from '@/plugins/vuetify'
import { clickBody, setBodyInput } from './helpers'
const organizations = [
{
id: 1,
name: 'Red de Economía Solidaria',
description: 'Red de organizaciones',
website: 'https://red.example.org',
contact_email: 'contacto@red.example.org',
contact_phone: '3001112233',
},
{
id: 2,
name: 'Cooperativa El Campo',
description: null,
website: null,
contact_email: null,
contact_phone: null,
},
]
function mockApi () {
return {
getOrganizations: vi.fn().mockResolvedValue(organizations),
createOrganization: vi.fn().mockResolvedValue({}),
updateOrganization: vi.fn().mockResolvedValue({}),
deleteOrganization: vi.fn().mockResolvedValue({}),
}
}
function mountComponent (api) {
return mount(OrganizationsManagement, {
global: { plugins: [vuetify], provide: { api } },
})
}
function fillForm () {
setBodyInput('[data-testid="org-form-name"] input', 'Fundación Montaña')
setBodyInput('[data-testid="org-form-description"] textarea', 'Fundación')
setBodyInput('[data-testid="org-form-website"] input', 'https://montana.example.org')
setBodyInput('[data-testid="org-form-email"] input', 'info@montana.example.org')
setBodyInput('[data-testid="org-form-phone"] input', '3109876543')
}
describe('OrganizationsManagement', () => {
it('carga y muestra las organizaciones', async () => {
const api = mockApi()
const wrapper = mountComponent(api)
await flushPromises()
expect(api.getOrganizations).toHaveBeenCalled()
expect(wrapper.text()).toContain('Red de Economía Solidaria')
expect(wrapper.text()).toContain('Cooperativa El Campo')
})
it('filtra las organizaciones por búsqueda', async () => {
const wrapper = mountComponent(mockApi())
await flushPromises()
await wrapper.find('[data-testid="org-search"] input').setValue('Cooperativa')
expect(wrapper.text()).toContain('Cooperativa El Campo')
expect(wrapper.text()).not.toContain('Red de Economía Solidaria')
})
it('crea una organización', async () => {
const api = mockApi()
const wrapper = mountComponent(api)
await flushPromises()
await wrapper.find('[data-testid="org-create"]').trigger('click')
fillForm()
clickBody('[data-testid="org-save"]')
await flushPromises()
expect(api.createOrganization).toHaveBeenCalledWith({
name: 'Fundación Montaña',
description: 'Fundación',
website: 'https://montana.example.org',
contact_email: 'info@montana.example.org',
contact_phone: '3109876543',
})
expect(api.getOrganizations).toHaveBeenCalledTimes(2)
})
it('edita una organización', async () => {
const api = mockApi()
const wrapper = mountComponent(api)
await flushPromises()
await wrapper.find('[data-testid="org-edit-1"]').trigger('click')
setBodyInput('[data-testid="org-form-name"] input', 'Red de Economía Solidaria Colombia')
clickBody('[data-testid="org-save"]')
await flushPromises()
expect(api.updateOrganization).toHaveBeenCalledWith(1, expect.objectContaining({
name: 'Red de Economía Solidaria Colombia',
}))
})
it('elimina una organización', async () => {
const api = mockApi()
const wrapper = mountComponent(api)
await flushPromises()
await wrapper.find('[data-testid="org-delete-2"]').trigger('click')
clickBody('[data-testid="org-confirm-delete"]')
await flushPromises()
expect(api.deleteOrganization).toHaveBeenCalledWith(2)
expect(api.getOrganizations).toHaveBeenCalledTimes(2)
})
})

View File

@@ -0,0 +1,125 @@
import { describe, expect, it, vi } from 'vitest'
import { flushPromises, mount } from '@vue/test-utils'
import SuppliersManagement from '@/components/provenance/admin/SuppliersManagement.vue'
import vuetify from '@/plugins/vuetify'
import { clickBody, setBodyInput } from './helpers'
const organizations = [
{ id: 3, name: 'Red de Economía Solidaria' },
{ id: 4, name: 'Cooperativa El Campo' },
]
const municipalities = [
{ id: 7, name: 'La Mesa' },
{ id: 8, name: 'San Antonio' },
]
const suppliers = [
{
id: 5,
name: 'Asociación Agropecuaria La Mesa',
description: 'Cooperativa de campesinos',
organization: 3,
organization_detail: { id: 3, name: 'Red de Economía Solidaria' },
municipality: 7,
municipality_detail: { id: 7, name: 'La Mesa' },
contact_email: 'contacto@agro.example.org',
contact_phone: '300 123 4567',
},
{
id: 6,
name: 'Finca El Paraíso',
description: null,
organization: null,
organization_detail: null,
municipality: null,
municipality_detail: null,
contact_email: null,
contact_phone: null,
},
]
function mockApi () {
return {
getSuppliers: vi.fn().mockResolvedValue(suppliers),
getOrganizations: vi.fn().mockResolvedValue(organizations),
getMunicipalities: vi.fn().mockResolvedValue(municipalities),
createSupplier: vi.fn().mockResolvedValue({}),
updateSupplier: vi.fn().mockResolvedValue({}),
deleteSupplier: vi.fn().mockResolvedValue({}),
}
}
function mountComponent (api) {
return mount(SuppliersManagement, {
global: { plugins: [vuetify], provide: { api } },
})
}
describe('SuppliersManagement', () => {
it('carga y muestra los proveedores con su organización y municipio', async () => {
const api = mockApi()
const wrapper = mountComponent(api)
await flushPromises()
expect(api.getSuppliers).toHaveBeenCalled()
expect(wrapper.text()).toContain('Asociación Agropecuaria La Mesa')
expect(wrapper.text()).toContain('Red de Economía Solidaria')
expect(wrapper.text()).toContain('La Mesa')
})
it('crea un proveedor con organización y municipio', async () => {
const api = mockApi()
const wrapper = mountComponent(api)
await flushPromises()
await wrapper.find('[data-testid="supplier-create"]').trigger('click')
setBodyInput('[data-testid="supplier-form-name"] input', 'Asociación El Cedro')
setBodyInput('[data-testid="supplier-form-description"] textarea', 'Caficultores')
const orgSelect = wrapper.findAllComponents({ name: 'VSelect' })
.find(select => select.props('items').some(item => item.id === 4))
await orgSelect.vm.$emit('update:modelValue', 4)
await wrapper.findAllComponents({ name: 'VAutocomplete' })[0].vm.$emit('update:modelValue', 8)
clickBody('[data-testid="supplier-save"]')
await flushPromises()
expect(api.createSupplier).toHaveBeenCalledWith(expect.objectContaining({
name: 'Asociación El Cedro',
description: 'Caficultores',
organization: 4,
municipality: 8,
}))
expect(api.getSuppliers).toHaveBeenCalledTimes(2)
})
it('edita un proveedor conservando la organización seleccionada', async () => {
const api = mockApi()
const wrapper = mountComponent(api)
await flushPromises()
await wrapper.find('[data-testid="supplier-edit-5"]').trigger('click')
setBodyInput('[data-testid="supplier-form-name"] input', 'Asociación Agropecuaria La Mesa Renovada')
clickBody('[data-testid="supplier-save"]')
await flushPromises()
expect(api.updateSupplier).toHaveBeenCalledWith(5, expect.objectContaining({
name: 'Asociación Agropecuaria La Mesa Renovada',
organization: 3,
municipality: 7,
}))
})
it('elimina un proveedor', async () => {
const api = mockApi()
const wrapper = mountComponent(api)
await flushPromises()
await wrapper.find('[data-testid="supplier-delete-6"]').trigger('click')
clickBody('[data-testid="supplier-confirm-delete"]')
await flushPromises()
expect(api.deleteSupplier).toHaveBeenCalledWith(6)
expect(api.getSuppliers).toHaveBeenCalledTimes(2)
})
})

View File

@@ -0,0 +1,23 @@
// Helpers para interactuar con el contenido de diálogos, que Vuetify
// teleporta a document.body fuera del DOM del wrapper.
function setNativeValue (el, value) {
const proto = el.tagName === 'TEXTAREA'
? window.HTMLTextAreaElement.prototype
: window.HTMLInputElement.prototype
const setter = Object.getOwnPropertyDescriptor(proto, 'value').set
setter.call(el, value)
el.dispatchEvent(new Event('input', { bubbles: true }))
}
export function setBodyInput (selector, value) {
const el = document.body.querySelector(selector)
if (!el) throw new Error(`Input no encontrado en body: ${selector}`)
setNativeValue(el, value)
}
export function clickBody (selector) {
const el = document.body.querySelector(selector)
if (!el) throw new Error(`Elemento no encontrado en body: ${selector}`)
el.click()
}

View File

@@ -0,0 +1,159 @@
import { describe, expect, it } from 'vitest'
import {
buildSupplierOrganizationGraph,
buildTerritoryGraph,
hasAnySupplier,
hasAnyTerritory,
} from '@/components/provenance/provenance-graph'
const provenance = [
{
product: {
id: 1,
name: 'Panela regional por Kg',
catalogue_images: ['http://localhost/media/panela.jpg'],
},
suppliers: [
{
supplier: { id: 5, name: 'Asociación Agropecuaria La Mesa', description: 'Cooperativa' },
organization: { id: 3, name: 'Red de Economía Solidaria', description: 'Red' },
municipality: { id: 7, name: 'La Mesa' },
department: { id: 2, name: 'Cundinamarca' },
country: { id: 1, name: 'Colombia', code: 'CO' },
},
],
},
]
describe('hasAnySupplier', () => {
it('es true cuando algún producto tiene proveedores', () => {
expect(hasAnySupplier(provenance)).toBe(true)
})
it('es false cuando todos los productos están sin proveedores', () => {
const empty = [{ product: { id: 1, name: 'Panela' }, suppliers: [] }]
expect(hasAnySupplier(empty)).toBe(false)
})
it('es false cuando no hay provenance', () => {
expect(hasAnySupplier([])).toBe(false)
})
})
describe('hasAnyTerritory', () => {
it('es true cuando algún proveedor tiene territorio', () => {
expect(hasAnyTerritory(provenance)).toBe(true)
})
it('es false cuando todos los territorios vienen en null', () => {
const noTerritory = [
{
product: { id: 1, name: 'Panela' },
suppliers: [{ supplier: { id: 5, name: 'La Mesa' }, organization: null, municipality: null, department: null, country: null }],
},
]
expect(hasAnyTerritory(noTerritory)).toBe(false)
})
it('es false cuando no hay suppliers', () => {
const noSuppliers = [{ product: { id: 1, name: 'Panela' }, suppliers: [] }]
expect(hasAnyTerritory(noSuppliers)).toBe(false)
})
})
describe('buildSupplierOrganizationGraph', () => {
it('crea nodos de producto, proveedor y organización con sus aristas', () => {
const graph = buildSupplierOrganizationGraph(provenance)
const ids = graph.nodes.map(n => n.id)
expect(ids).toContain('product:1')
expect(ids).toContain('supplier:5')
expect(ids).toContain('organization:3')
expect(graph.edges).toContainEqual({ from: 'product:1', to: 'supplier:5' })
expect(graph.edges).toContainEqual({ from: 'supplier:5', to: 'organization:3' })
})
it('incluye la imagen del producto y el detalle de la entidad', () => {
const graph = buildSupplierOrganizationGraph(provenance)
const product = graph.nodes.find(n => n.id === 'product:1')
expect(product.image).toBe('http://localhost/media/panela.jpg')
expect(product.label).toBe('Panela regional por Kg')
expect(product.entity.kind).toBe('product')
expect(product.entity.name).toBe('Panela regional por Kg')
})
it('omite el nodo de organización cuando la relación es null', () => {
const data = [
{
product: { id: 1, name: 'Panela' },
suppliers: [{ supplier: { id: 5, name: 'La Mesa' }, organization: null }],
},
]
const graph = buildSupplierOrganizationGraph(data)
expect(graph.nodes.map(n => n.id)).not.toContain('organization:')
expect(graph.edges).toEqual([{ from: 'product:1', to: 'supplier:5' }])
})
it('no duplica nodos que se repiten entre productos', () => {
const data = [
{ product: { id: 1, name: 'Panela' }, suppliers: [{ supplier: { id: 5, name: 'La Mesa' }, organization: { id: 3, name: 'Red' } }] },
{ product: { id: 2, name: 'Arroz' }, suppliers: [{ supplier: { id: 5, name: 'La Mesa' }, organization: { id: 3, name: 'Red' } }] },
]
const graph = buildSupplierOrganizationGraph(data)
expect(graph.nodes.filter(n => n.id === 'supplier:5')).toHaveLength(1)
expect(graph.nodes.filter(n => n.id === 'organization:3')).toHaveLength(1)
expect(graph.edges).toHaveLength(4)
})
it('ubica producto, proveedor y organización en columnas crecientes', () => {
const graph = buildSupplierOrganizationGraph(provenance)
const product = graph.nodes.find(n => n.id === 'product:1')
const supplier = graph.nodes.find(n => n.id === 'supplier:5')
const organization = graph.nodes.find(n => n.id === 'organization:3')
expect(product.x).toBeLessThan(supplier.x)
expect(supplier.x).toBeLessThan(organization.x)
})
it('devuelve un grafo vacío cuando no hay provenance', () => {
const graph = buildSupplierOrganizationGraph([])
expect(graph.nodes).toEqual([])
expect(graph.edges).toEqual([])
})
})
describe('buildTerritoryGraph', () => {
it('crea la cadena producto → proveedor → municipio → departamento → país', () => {
const graph = buildTerritoryGraph(provenance)
const ids = graph.nodes.map(n => n.id)
expect(ids).toContain('product:1')
expect(ids).toContain('supplier:5')
expect(ids).toContain('municipality:7')
expect(ids).toContain('department:2')
expect(ids).toContain('country:1')
expect(graph.edges).toContainEqual({ from: 'supplier:5', to: 'municipality:7' })
expect(graph.edges).toContainEqual({ from: 'municipality:7', to: 'department:2' })
expect(graph.edges).toContainEqual({ from: 'department:2', to: 'country:1' })
})
it('no crea nodos de territorio cuando el proveedor no tiene municipio', () => {
const data = [
{
product: { id: 1, name: 'Panela' },
suppliers: [{ supplier: { id: 5, name: 'La Mesa' }, municipality: null, department: null, country: null }],
},
]
const graph = buildTerritoryGraph(data)
expect(graph.nodes.map(n => n.id)).toEqual(['product:1', 'supplier:5'])
expect(graph.edges).toEqual([{ from: 'product:1', to: 'supplier:5' }])
})
})

View File

@@ -0,0 +1,92 @@
import { beforeEach, describe, expect, it, vi } from 'vitest'
import { flushPromises, mount } from '@vue/test-utils'
import { createMemoryHistory, createRouter } from 'vue-router'
import PedidoPage from '@/pages/pedido/[[code]].vue'
import PublicOrderSummary from '@/components/PublicOrderSummary.vue'
import vuetify from '@/plugins/vuetify'
const saleData = {
id: 1,
code: 'abc123',
date: '2024-09-02T00:00:00Z',
customer: { id: 1, name: 'Camilo' },
payment_method: 'CASH',
lines: [
{ product: { id: 10, name: 'Panela' }, quantity: 2, unit_price: 3000 },
],
type: 'sale',
}
async function mountPage (api, path) {
const router = createRouter({
history: createMemoryHistory(),
routes: [{ path: '/pedido/:code?', component: PedidoPage }],
})
router.push(path)
await router.isReady()
const wrapper = mount(PedidoPage, {
global: {
plugins: [router, vuetify],
provide: { api },
},
})
return { router, wrapper }
}
async function waitForRouteParam (router, param, value, timeout = 1000) {
const start = Date.now()
while (Date.now() - start < timeout) {
if (router.currentRoute.value.params[param] === value) return
await new Promise(resolve => setTimeout(resolve, 10))
}
throw new Error(`route param ${param} nunca llegó a ser ${value}`)
}
describe('página pública /pedido', () => {
beforeEach(() => {
vi.clearAllMocks()
})
it('sin código no consulta la API y muestra el buscador', async () => {
const api = { getPublicOrderSummary: vi.fn() }
const { wrapper } = await mountPage(api, '/pedido')
await flushPromises()
expect(api.getPublicOrderSummary).not.toHaveBeenCalled()
expect(wrapper.text()).toContain('Código')
})
it('con código por URL consulta y muestra el resumen', async () => {
const api = { getPublicOrderSummary: vi.fn().mockResolvedValue(saleData) }
const { wrapper } = await mountPage(api, '/pedido/abc123')
await flushPromises()
expect(api.getPublicOrderSummary).toHaveBeenCalledWith('abc123')
expect(wrapper.findComponent(PublicOrderSummary).props('purchase')).toEqual(saleData)
expect(wrapper.text()).toContain('Camilo')
})
it('muestra mensaje de no encontrado cuando el código no existe', async () => {
const api = {
getPublicOrderSummary: vi.fn().mockRejectedValue({ response: { status: 404 } }),
}
const { wrapper } = await mountPage(api, '/pedido/zzzzzz')
await flushPromises()
expect(wrapper.findComponent(PublicOrderSummary).props('error')).toContain('No se encontró')
})
it('al consultar un código navega a /pedido/<code> y vuelve a consultar', async () => {
const api = { getPublicOrderSummary: vi.fn().mockResolvedValue(saleData) }
const { router, wrapper } = await mountPage(api, '/pedido/abc123')
await flushPromises()
api.getPublicOrderSummary.mockClear()
await wrapper.find('input').setValue('newcode')
await wrapper.find('form').trigger('submit')
await waitForRouteParam(router, 'code', 'newcode')
expect(router.currentRoute.value.params.code).toBe('newcode')
expect(api.getPublicOrderSummary).toHaveBeenCalledWith('newcode')
})
})

View File

@@ -0,0 +1,217 @@
import { beforeEach, describe, expect, it, vi } from 'vitest'
import http from '@/services/http'
import DjangoApi from '@/services/django-api'
vi.mock('@/services/http', () => ({
default: {
get: vi.fn(),
post: vi.fn(),
patch: vi.fn(),
put: vi.fn(),
delete: vi.fn(),
},
}))
describe('DjangoApi.getPublicOrderSummary', () => {
beforeEach(() => {
vi.stubEnv('VITE_DJANGO_BASE_URL', 'http://backend.test')
http.get.mockReset()
http.get.mockResolvedValue({ data: { code: 'abc123', type: 'sale' } })
})
it('consulta el resumen público por código en la ruta resumen_publico', async () => {
const api = new DjangoApi()
const result = await api.getPublicOrderSummary('abc123')
expect(http.get).toHaveBeenCalledTimes(1)
expect(http.get).toHaveBeenCalledWith(
'http://backend.test/don_confiao/resumen_publico/abc123'
)
expect(result).toEqual({ code: 'abc123', type: 'sale' })
})
})
describe('DjangoApi provenance CRUD', () => {
beforeEach(() => {
vi.stubEnv('VITE_DJANGO_BASE_URL', 'http://backend.test')
http.get.mockReset()
http.post.mockReset()
http.patch.mockReset()
http.delete.mockReset()
http.get.mockResolvedValue({ data: [] })
http.post.mockResolvedValue({ data: { id: 1 } })
http.patch.mockResolvedValue({ data: { id: 1 } })
http.delete.mockResolvedValue({ data: {} })
})
it('getProduct consulta el detalle autenticado del producto', async () => {
const api = new DjangoApi()
await api.getProduct(3)
expect(http.get).toHaveBeenCalledWith(
'http://backend.test/don_confiao/api/products/3/'
)
})
it('getOrganizations consulta la lista de organizaciones', async () => {
const api = new DjangoApi()
await api.getOrganizations()
expect(http.get).toHaveBeenCalledWith(
'http://backend.test/don_confiao/api/organizations/'
)
})
it('createOrganization hace POST con los datos', async () => {
const api = new DjangoApi()
const payload = { name: 'Red de Economía Solidaria' }
await api.createOrganization(payload)
expect(http.post).toHaveBeenCalledWith(
'http://backend.test/don_confiao/api/organizations/',
payload
)
})
it('updateOrganization hace PATCH con los datos', async () => {
const api = new DjangoApi()
const payload = { description: 'Nueva descripción' }
await api.updateOrganization(3, payload)
expect(http.patch).toHaveBeenCalledWith(
'http://backend.test/don_confiao/api/organizations/3/',
payload
)
})
it('deleteOrganization hace DELETE', async () => {
const api = new DjangoApi()
await api.deleteOrganization(3)
expect(http.delete).toHaveBeenCalledWith(
'http://backend.test/don_confiao/api/organizations/3/'
)
})
it('getSuppliers consulta la lista de proveedores', async () => {
const api = new DjangoApi()
await api.getSuppliers()
expect(http.get).toHaveBeenCalledWith(
'http://backend.test/don_confiao/api/suppliers/'
)
})
it('createSupplier hace POST con datos de proveedor', async () => {
const api = new DjangoApi()
const payload = { name: 'Asociación La Mesa', organization: 3, municipality: 7 }
await api.createSupplier(payload)
expect(http.post).toHaveBeenCalledWith(
'http://backend.test/don_confiao/api/suppliers/',
payload
)
})
it('updateSupplier hace PATCH para desvincular organización con null', async () => {
const api = new DjangoApi()
await api.updateSupplier(5, { organization: null })
expect(http.patch).toHaveBeenCalledWith(
'http://backend.test/don_confiao/api/suppliers/5/',
{ organization: null }
)
})
it('deleteSupplier hace DELETE', async () => {
const api = new DjangoApi()
await api.deleteSupplier(5)
expect(http.delete).toHaveBeenCalledWith(
'http://backend.test/don_confiao/api/suppliers/5/'
)
})
it('CRUD de países usa el endpoint countries', async () => {
const api = new DjangoApi()
await api.getCountries()
await api.createCountry({ name: 'Colombia', code: 'CO' })
await api.updateCountry(1, { code: 'CO' })
await api.deleteCountry(1)
expect(http.get).toHaveBeenCalledWith(
'http://backend.test/don_confiao/api/countries/'
)
expect(http.post).toHaveBeenCalledWith(
'http://backend.test/don_confiao/api/countries/',
{ name: 'Colombia', code: 'CO' }
)
expect(http.patch).toHaveBeenCalledWith(
'http://backend.test/don_confiao/api/countries/1/',
{ code: 'CO' }
)
expect(http.delete).toHaveBeenCalledWith(
'http://backend.test/don_confiao/api/countries/1/'
)
})
it('CRUD de departamentos usa el endpoint departments', async () => {
const api = new DjangoApi()
await api.getDepartments()
await api.createDepartment({ name: 'Cundinamarca', country: 1 })
await api.updateDepartment(2, { name: 'Antioquia' })
await api.deleteDepartment(2)
expect(http.get).toHaveBeenCalledWith(
'http://backend.test/don_confiao/api/departments/'
)
expect(http.post).toHaveBeenCalledWith(
'http://backend.test/don_confiao/api/departments/',
{ name: 'Cundinamarca', country: 1 }
)
expect(http.patch).toHaveBeenCalledWith(
'http://backend.test/don_confiao/api/departments/2/',
{ name: 'Antioquia' }
)
expect(http.delete).toHaveBeenCalledWith(
'http://backend.test/don_confiao/api/departments/2/'
)
})
it('CRUD de municipios usa el endpoint municipalities', async () => {
const api = new DjangoApi()
await api.getMunicipalities()
await api.createMunicipality({ name: 'La Mesa', department: 2, country: 1 })
await api.updateMunicipality(7, { name: 'LA MESA' })
await api.deleteMunicipality(7)
expect(http.get).toHaveBeenCalledWith(
'http://backend.test/don_confiao/api/municipalities/'
)
expect(http.post).toHaveBeenCalledWith(
'http://backend.test/don_confiao/api/municipalities/',
{ name: 'La Mesa', department: 2, country: 1 }
)
expect(http.patch).toHaveBeenCalledWith(
'http://backend.test/don_confiao/api/municipalities/7/',
{ name: 'LA MESA' }
)
expect(http.delete).toHaveBeenCalledWith(
'http://backend.test/don_confiao/api/municipalities/7/'
)
})
})

View File

@@ -0,0 +1,100 @@
import { describe, expect, it } from 'vitest'
import { computeColumnLayout, toCytoscapeElements } from '@/services/graph/graph-layout'
const nodes = [
{ id: 'product:1', kind: 'product', label: 'Panela' },
{ id: 'supplier:5', kind: 'supplier', label: 'La Mesa' },
{ id: 'organization:3', kind: 'organization', label: 'Red Solidaria' },
]
const edges = [
{ from: 'product:1', to: 'supplier:5' },
{ from: 'supplier:5', to: 'organization:3' },
]
function columnOf (node) {
return { product: 0, supplier: 1, organization: 2 }[node.kind]
}
describe('computeColumnLayout', () => {
it('ubica cada nodo en su columna según la función columnOf', () => {
const result = computeColumnLayout(nodes, edges, { columnOf, columnWidth: 200, rowHeight: 80, padding: 20 })
const product = result.nodes.find(n => n.id === 'product:1')
const supplier = result.nodes.find(n => n.id === 'supplier:5')
const organization = result.nodes.find(n => n.id === 'organization:3')
expect(product.x).toBeLessThan(supplier.x)
expect(supplier.x).toBeLessThan(organization.x)
expect(product.x).toBeCloseTo(20 + 0 * 200 + 100)
expect(supplier.x).toBeCloseTo(20 + 1 * 200 + 100)
expect(organization.x).toBeCloseTo(20 + 2 * 200 + 100)
})
it('separa verticalmente los nodos que comparten columna y conserva el orden', () => {
const many = [
{ id: 'supplier:1', kind: 'supplier', label: 'A' },
{ id: 'supplier:2', kind: 'supplier', label: 'B' },
]
const result = computeColumnLayout(many, [], { columnOf, columnWidth: 200, rowHeight: 80, padding: 20 })
const a = result.nodes.find(n => n.id === 'supplier:1')
const b = result.nodes.find(n => n.id === 'supplier:2')
expect(a.y).toBeCloseTo(20 + 80 / 2)
expect(b.y).toBeCloseTo(20 + 80 + 80 / 2)
expect(a.y).toBeLessThan(b.y)
})
it('calcula ancho y alto del lienzo según columnas y filas usadas', () => {
const result = computeColumnLayout(nodes, edges, { columnOf, columnWidth: 200, rowHeight: 80, padding: 20 })
expect(result.width).toBeCloseTo(20 * 2 + 3 * 200)
expect(result.height).toBeCloseTo(20 * 2 + 80)
})
it('respeta el orden de aparición de los nodos', () => {
const result = computeColumnLayout(nodes, edges, { columnOf, columnWidth: 200, rowHeight: 80, padding: 20 })
expect(result.nodes.map(n => n.id)).toEqual(['product:1', 'supplier:5', 'organization:3'])
})
})
describe('toCytoscapeElements', () => {
it('convierte nodos y aristas al formato elements de cytoscape', () => {
const layout = computeColumnLayout(nodes, edges, { columnOf, columnWidth: 200, rowHeight: 80, padding: 20 })
const elements = toCytoscapeElements(layout)
const productNode = elements.find(e => e.data.id === 'product:1')
expect(productNode).toMatchObject({
position: { x: productNode.position.x, y: productNode.position.y },
classes: ['product'],
data: { id: 'product:1', kind: 'product', label: 'Panela' },
})
expect(typeof productNode.position.x).toBe('number')
expect(typeof productNode.position.y).toBe('number')
const edge = elements.find(e => e.data.source === 'product:1')
expect(edge).toMatchObject({ data: { source: 'product:1', target: 'supplier:5' } })
})
it('incluye datos extra del nodo en data.entity', () => {
const withEntity = [
{ id: 'product:1', kind: 'product', label: 'Panela', entity: { name: 'Panela', price: 3000 } },
]
const layout = computeColumnLayout(withEntity, [], { columnOf, columnWidth: 200, rowHeight: 80, padding: 20 })
const elements = toCytoscapeElements(layout)
expect(elements[0].data.entity).toEqual({ name: 'Panela', price: 3000 })
})
it('agrega la clase has-image a los nodos con imagen', () => {
const withImage = [
{ id: 'product:1', kind: 'product', label: 'Panela', image: 'http://x/panela.jpg' },
]
const layout = computeColumnLayout(withImage, [], { columnOf, columnWidth: 200, rowHeight: 80, padding: 20 })
const elements = toCytoscapeElements(layout)
expect(elements[0].classes).toContain('has-image')
})
})

34
vitest.config.mjs Normal file
View File

@@ -0,0 +1,34 @@
import { fileURLToPath } from 'node:url'
import { defineConfig } from 'vitest/config'
import Vue from '@vitejs/plugin-vue'
import Vuetify, { transformAssetUrls } from 'vite-plugin-vuetify'
export default defineConfig({
plugins: [
Vue({
template: { transformAssetUrls },
}),
Vuetify({
autoImport: true,
styles: {
configFile: 'src/styles/settings.scss',
},
}),
],
resolve: {
alias: {
'@': fileURLToPath(new URL('./src', import.meta.url)),
},
},
test: {
environment: 'jsdom',
globals: false,
setupFiles: ['./tests/setup.js'],
include: ['tests/**/*.spec.js'],
server: {
deps: {
inline: ['vuetify'],
},
},
},
})