Compare commits
18 Commits
760b3031b2
...
main
| Author | SHA1 | Date | |
|---|---|---|---|
| 02697f09e1 | |||
| e81dbb8154 | |||
| 4641439454 | |||
| e286424919 | |||
| 6966c4180a | |||
| 798a9bba15 | |||
| f24e7ab2ec | |||
| 6a833a1ea4 | |||
| a251ae59eb | |||
| 18026617ce | |||
| 6200fa7432 | |||
| ad0bbb579d | |||
| 5c91e66429 | |||
| 2967ea4f4d | |||
| 58b42d956b | |||
| 79100ef40e | |||
| d16b10d2ee | |||
| 9917d4866f |
@@ -31,6 +31,9 @@ module.exports = {
|
|||||||
'!src/components/PublicOrderSummary.vue',
|
'!src/components/PublicOrderSummary.vue',
|
||||||
'!src/components/order/*.vue',
|
'!src/components/order/*.vue',
|
||||||
'!src/components/order/**/*.vue',
|
'!src/components/order/**/*.vue',
|
||||||
|
'!src/components/provenance/*.vue',
|
||||||
|
'!src/components/provenance/**/*.vue',
|
||||||
|
'!src/components/graph/*.vue',
|
||||||
'!src/pages/pedido/*.vue',
|
'!src/pages/pedido/*.vue',
|
||||||
'!src/pages/pedido/**/*.vue',
|
'!src/pages/pedido/**/*.vue',
|
||||||
],
|
],
|
||||||
|
|||||||
24
AGENTS.md
24
AGENTS.md
@@ -14,8 +14,13 @@
|
|||||||
src/
|
src/
|
||||||
├── assets/ # Imágenes, iconos estáticos
|
├── assets/ # Imágenes, iconos estáticos
|
||||||
├── components/ # Componentes Vue reutilizables
|
├── components/ # Componentes Vue reutilizables
|
||||||
|
│ ├── order/ # Componentes del resumen de pedido público
|
||||||
|
│ ├── provenance/ # Provenance (público + admin): gráficos, sección y CRUD admin
|
||||||
|
│ │ └── admin/ # Organizaciones, Proveedores, Geografía, SupplierLinkDialog
|
||||||
|
│ └── graph/ # VisChart.vue (wrapper genérico de vis-network)
|
||||||
├── layouts/ # Layouts de página
|
├── layouts/ # Layouts de página
|
||||||
├── pages/ # Vistas (auto-routed desde文件名)
|
├── pages/ # Vistas (auto-routed desde文件名)
|
||||||
|
│ └── admin/ # Páginas admin (products, organizations, suppliers, geography, ...)
|
||||||
├── plugins/ # Configuración de Vuetify, etc.
|
├── plugins/ # Configuración de Vuetify, etc.
|
||||||
├── router/ # Configuración de rutas
|
├── router/ # Configuración de rutas
|
||||||
├── services/ # API services (auth.js, etc.)
|
├── services/ # API services (auth.js, etc.)
|
||||||
@@ -89,12 +94,16 @@ No hay un estilo mayoritario. El código histórico está partido:
|
|||||||
### Config de ESLint
|
### Config de ESLint
|
||||||
- `.eslintrc.js` está **versionado** y extiende `vuetify` (estilo **StandardJS**)
|
- `.eslintrc.js` está **versionado** y extiende `vuetify` (estilo **StandardJS**)
|
||||||
- Tiene `ignorePatterns` masivo: `src/**` excepto los archivos nuevos de la tarea
|
- Tiene `ignorePatterns` masivo: `src/**` excepto los archivos nuevos de la tarea
|
||||||
(`!src/components/order/**`, `!src/components/PublicOrderSummary.vue`, `!src/pages/pedido/**`)
|
(`!src/components/order/**`, `!src/components/PublicOrderSummary.vue`,
|
||||||
|
`!src/components/provenance/**`, `!src/components/graph/*.vue`,
|
||||||
|
`!src/pages/pedido/**`)
|
||||||
- **Los archivos nuevos deben seguir StandardJS** para quedar lint-eados:
|
- **Los archivos nuevos deben seguir StandardJS** para quedar lint-eados:
|
||||||
- 2 espacios (indent), sin semicolons, comillas simples
|
- 2 espacios (indent), sin semicolons, comillas simples
|
||||||
- `function () {}` con espacio, `const f = (x) => x` (arrow-parens en args únicos NO)
|
- `function () {}` con espacio, `const f = (x) => x` (arrow-parens en args únicos NO)
|
||||||
- Sin trailing commas; `{ clave: valor }` con espacios internos
|
- Sin trailing commas; `{ clave: valor }` con espacios internos
|
||||||
- Eventos personalizados en kebab-case, `v-slot:nombre` (no `#nombre`)
|
- Eventos personalizados en kebab-case, `v-slot:nombre` (no `#nombre`)
|
||||||
|
- Atributos en orden alfabético dentro de su categoría (`vue/attributes-order`):
|
||||||
|
directivas (`v-if`, `v-model`) primero, luego props/attrs, luego `@eventos`
|
||||||
|
|
||||||
### PELIGRO: `npm run lint` usa `--fix`
|
### PELIGRO: `npm run lint` usa `--fix`
|
||||||
- Reformatea automáticamente TODO archivo no ignorado que no cumpla estilo
|
- Reformatea automáticamente TODO archivo no ignorado que no cumpla estilo
|
||||||
@@ -109,6 +118,9 @@ No hay un estilo mayoritario. El código histórico está partido:
|
|||||||
- Los tests **no usan globals**: importar `describe/it/expect/vi` explícitamente desde `vitest`
|
- 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`)
|
- 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`
|
- Los `.d.ts` generados (`auto-imports.d.ts`, `components.d.ts`, `typed-router.d.ts`) están en `.gitignore`
|
||||||
|
- **Diálogos Vuetify se teleportan a `document.body`**: en tests, el contenido NO está en `wrapper.text()`. Assertar sobre `document.body.textContent` (ver `tests/unit/components/provenance/ProvenanceDetailModal.spec.js`). Helpers para interactuar con inputs/buttons de diálogos en `tests/unit/components/provenance/admin/helpers.js` (`setBodyInput`, `clickBody`)
|
||||||
|
- **Selects/autocompletados en tests**: escribir en su `<input>` NO cambia el `v-model`. Emitir `update:modelValue` sobre el componente (`findAllComponents({ name: 'VSelect' })` / `{ name: 'VAutocomplete' }`). OJO: `VAutocomplete` también matchea como `VSelect`, y `v-data-table` añade un `VSelect` (items-per-page); filtrar por `props('items')` cuando haya varios
|
||||||
|
- **Listas largas** (municipios, proveedores): `v-autocomplete` con búsqueda, pero la selección debe conservarse aunque el filtro no la incluya → `items` computado que devuelve los filtrados + los seleccionados que no estén (patrón en `SuppliersManagement.vue`, `GeographyManagement.vue`, `SupplierLinkDialog.vue`)
|
||||||
|
|
||||||
## 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
|
||||||
@@ -159,3 +171,13 @@ No hay un estilo mayoritario. El código histórico está partido:
|
|||||||
- `getPublicOrderSummary(code)` en `services/api.js` / `django-api.js`
|
- `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`
|
- 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`
|
- Orquestador: `PublicOrderSummary.vue`; `OrderAccessInfo.vue` se comparte con `SummaryPurchase.vue`
|
||||||
|
|
||||||
|
## Provenance (Origen e historia de los productos)
|
||||||
|
- Los gráficos se renderizan en el resumen público (`ProvenanceSection` dentro de `PublicOrderSummary.vue`) a partir de `product_provenance` embebido en el resumen (`GET /don_confiao/resumen_publico/<code>`). El backend NO genera los gráficos.
|
||||||
|
- Payload: `[{ product: {id, name, catalogue_images[]}, suppliers: [{ supplier: {...}, organization|null, municipality|null, department|null, country|null }] }]`.
|
||||||
|
- **Genérico reutilizable:**
|
||||||
|
- `src/components/graph/VisChart.vue`: wrapper de vis-network (props `nodes`, `edges`, `height`, `options`; import `import { DataSet, Network } from 'vis-network/standalone'`; emite `select` con el nodo). **OJO**: nodo con `image: null` → TypeError de vis; omitir la clave `image` si no hay foto
|
||||||
|
- **Específico público** (`src/components/provenance/`): builder puro en `provenance-graph.js` (`buildProvenanceGraph(provenance, kinds)`, `hasAnySupplier`) y el adaptador vis `provenance-vis.js` (`toVisNodes`, `toVisEdges`, `chartOptions`). **Semántica de certeza**: arista con `certain: true` es continua (inequívoca) y `certain: false` es discontinua (dudosa); con varios proveedores por producto se inserta un nodo `junction:<productId>` (disyunción) con arista sólida hasta él y discontinua hacia cada proveedor; la duda se corta donde los proveedores coinciden (misma organización/municipio/departamento). Las aristas se deduplican por par `(from, to)` y si un mismo par repite con distinta certeza gana la duda. `buildProvenanceGraph` acepta los niveles a graficar (`product`, `supplier`, `organization`, `municipality`, `department`, `country`); los niveles omitidos se saltan conectando el nivel previo con el siguiente. `ProvenanceGraph.vue` unifica los charts en uno con checkboxes de filtro (por defecto solo productos y proveedores), leyenda con el color de cada nivel (`KIND_COLORS` en `provenance-vis.js`), columnas por nivel (x fijo por tipo; la física ordena la y) y espaciado vertical mínimo (`minVerticalSpacing` en `VisChart`); muestra "próximamente estará disponible" cuando no hay relaciones. `ProvenanceSection.vue` muestra el título ("Origen de los productos") con un desplegable (clic en el título o botón chevron) que oculta el gráfico por defecto, y un segundo desplegable para el mapa ("Mapa de origen de los productos") — patrón reutilizable para futuros bloques. `ProvenanceMap.vue` muestra un recuadro informativo (lista) con **todos** los productos del payload —incluidos los sin proveedor o cuyo municipio no tiene coordenadas, marcados "Sin geolocalización"— como panel lateral izquierdo junto al mapa (en columna en pantallas < 900px) y, si hay al menos un municipio con coordenadas, el mapa leaflet al lado: un marcador por producto en el municipio de origen (usa `municipality.latitude/longitude` del payload, sin desplazar posiciones aunque coincidan; los productos del mismo punto se agrupan en un único marcador con contador que al hacer clic despliega un popup con la lista de productos internos para abrir cada uno) y un ícono de persona en la posición de la tienda (settings store, endpoint público `getStoreSettings`); `fitBounds` abarca todos los marcadores, al hacer hover sobre un producto dibuja una línea discontinua hasta la tienda y al hacer hover sobre la tienda dibuja las de todos los productos; un botón flotante en el título del panel (`data-test="map-reset-zoom"`) re-ejecuta `fitBounds` para volver al zoom general; clic en un marcador individual abre un **popup de leaflet** anclado al ícono con el detalle (imagen + producto + proveedor + organización + territorio); clic en un producto del popup agrupado reemplaza su contenido por el detalle de ese producto. Clic en un producto del recuadro: si tiene ubicación hace `flyTo` al punto y abre el popup de detalle en el marcador; si no, abre `ProvenanceRelationModal.vue` (único caso donde se usa el modal web, pues no hay ícono en el mapa) que muestra el proveedor/organización disponibles y la nota "Aún sin geolocalización registrada." o "Aún no se ha vinculado un proveedor a este producto.". `ProvenanceDetailModal.vue`
|
||||||
|
- **Admin CRUD** (`src/components/provenance/admin/`): `OrganizationsManagement.vue`, `SuppliersManagement.vue`, `GeographyManagement.vue` (tabs países/departamentos/municipios), `SupplierLinkDialog.vue` (vincula productos↔proveedores, abierto desde `ProductsManagement.vue`). Páginas en `src/pages/admin/{organizations,suppliers,geography}.vue`; rutas en `ADMIN_ROUTES` (`router/index.js`); ítems en `NavBar.vue`
|
||||||
|
- **Endpoints provenance**: `/don_confiao/api/organizations/`, `/suppliers/`, `/countries/`, `/departments/`, `/municipalities/` (CRUD); vincular productos con `PATCH /don_confiao/api/products/<id>/` body `{"suppliers": [ids]}`; detalle de producto (con `suppliers`) via `GET /don_confiao/api/products/<id>/`
|
||||||
|
- Los tests mockean `vis-network/standalone` (`vi.mock('vis-network/standalone', ...)`) o el propio `VisChart.vue`, y la API con `global.provide: { api }`
|
||||||
|
|||||||
1200
package-lock.json
generated
1200
package-lock.json
generated
File diff suppressed because it is too large
Load Diff
@@ -13,10 +13,10 @@
|
|||||||
"@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",
|
"leaflet": "^1.9.4",
|
||||||
"roboto-fontface": "*",
|
"roboto-fontface": "*",
|
||||||
"vee-validate": "^4.14.6",
|
"vee-validate": "^4.14.6",
|
||||||
|
"vis-network": "^10.1.1",
|
||||||
"vue": "^3.4.31",
|
"vue": "^3.4.31",
|
||||||
"vuetify": "^3.6.11"
|
"vuetify": "^3.6.11"
|
||||||
},
|
},
|
||||||
|
|||||||
@@ -122,6 +122,19 @@
|
|||||||
</v-chip>
|
</v-chip>
|
||||||
</template>
|
</template>
|
||||||
|
|
||||||
|
<!-- Slot para columna de proveedores -->
|
||||||
|
<template #item.actions="{ item }">
|
||||||
|
<v-btn
|
||||||
|
@click="openSupplierLink(item)"
|
||||||
|
color="primary"
|
||||||
|
size="small"
|
||||||
|
variant="tonal"
|
||||||
|
prepend-icon="mdi-truck"
|
||||||
|
>
|
||||||
|
Proveedores
|
||||||
|
</v-btn>
|
||||||
|
</template>
|
||||||
|
|
||||||
<!-- Loading state -->
|
<!-- Loading state -->
|
||||||
<template #loading>
|
<template #loading>
|
||||||
<v-skeleton-loader type="table-row@10"></v-skeleton-loader>
|
<v-skeleton-loader type="table-row@10"></v-skeleton-loader>
|
||||||
@@ -138,6 +151,13 @@
|
|||||||
</v-col>
|
</v-col>
|
||||||
</v-row>
|
</v-row>
|
||||||
|
|
||||||
|
<!-- Diálogo de proveedores del producto -->
|
||||||
|
<SupplierLinkDialog
|
||||||
|
:visible="linkDialog"
|
||||||
|
:product="linkProduct"
|
||||||
|
@update:visible="linkDialog = $event"
|
||||||
|
/>
|
||||||
|
|
||||||
<!-- Snackbar de feedback -->
|
<!-- Snackbar de feedback -->
|
||||||
<v-snackbar
|
<v-snackbar
|
||||||
v-model="snackbar.show"
|
v-model="snackbar.show"
|
||||||
@@ -155,6 +175,7 @@
|
|||||||
|
|
||||||
<script setup>
|
<script setup>
|
||||||
import { ref, watch, inject, onMounted, computed } from "vue";
|
import { ref, watch, inject, onMounted, computed } from "vue";
|
||||||
|
import SupplierLinkDialog from "@/components/provenance/admin/SupplierLinkDialog.vue";
|
||||||
|
|
||||||
// Estado
|
// Estado
|
||||||
const api = inject("api");
|
const api = inject("api");
|
||||||
@@ -164,6 +185,8 @@ const selected = ref([]);
|
|||||||
const loading = ref(false);
|
const loading = ref(false);
|
||||||
const snackbar = ref({ show: false, message: "", color: "success" });
|
const snackbar = ref({ show: false, message: "", color: "success" });
|
||||||
const searchQuery = ref("");
|
const searchQuery = ref("");
|
||||||
|
const linkDialog = ref(false);
|
||||||
|
const linkProduct = ref(null);
|
||||||
|
|
||||||
// Headers de la tabla
|
// Headers de la tabla
|
||||||
const headers = [
|
const headers = [
|
||||||
@@ -171,6 +194,7 @@ const headers = [
|
|||||||
{ title: "Nombre", key: "name", sortable: true },
|
{ title: "Nombre", key: "name", sortable: true },
|
||||||
{ title: "Precio", key: "price", sortable: true },
|
{ title: "Precio", key: "price", sortable: true },
|
||||||
{ title: "Estado", key: "active", sortable: true },
|
{ title: "Estado", key: "active", sortable: true },
|
||||||
|
{ title: "Proveedores", key: "actions", sortable: false },
|
||||||
];
|
];
|
||||||
|
|
||||||
// Computed - Productos filtrados por búsqueda
|
// Computed - Productos filtrados por búsqueda
|
||||||
@@ -236,6 +260,11 @@ function showSnackbar(message, color) {
|
|||||||
snackbar.value = { show: true, message, color };
|
snackbar.value = { show: true, message, color };
|
||||||
}
|
}
|
||||||
|
|
||||||
|
function openSupplierLink(product) {
|
||||||
|
linkProduct.value = product;
|
||||||
|
linkDialog.value = true;
|
||||||
|
}
|
||||||
|
|
||||||
// Watchers
|
// Watchers
|
||||||
watch(activeFilter, () => {
|
watch(activeFilter, () => {
|
||||||
selected.value = [];
|
selected.value = [];
|
||||||
|
|||||||
@@ -1,75 +0,0 @@
|
|||||||
<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>
|
|
||||||
155
src/components/graph/VisChart.vue
Normal file
155
src/components/graph/VisChart.vue
Normal file
@@ -0,0 +1,155 @@
|
|||||||
|
<template>
|
||||||
|
<div
|
||||||
|
ref="containerRef"
|
||||||
|
class="vis-chart"
|
||||||
|
:style="{ height: `${height}px` }"
|
||||||
|
/>
|
||||||
|
</template>
|
||||||
|
|
||||||
|
<script setup>
|
||||||
|
import { onBeforeUnmount, onMounted, ref, watch } from 'vue'
|
||||||
|
import { DataSet, Network } from 'vis-network/standalone'
|
||||||
|
|
||||||
|
const props = defineProps({
|
||||||
|
nodes: {
|
||||||
|
type: Array,
|
||||||
|
default: () => [],
|
||||||
|
},
|
||||||
|
edges: {
|
||||||
|
type: Array,
|
||||||
|
default: () => [],
|
||||||
|
},
|
||||||
|
height: {
|
||||||
|
type: Number,
|
||||||
|
default: 400,
|
||||||
|
},
|
||||||
|
options: {
|
||||||
|
type: Object,
|
||||||
|
default: () => ({}),
|
||||||
|
},
|
||||||
|
minVerticalSpacing: {
|
||||||
|
type: Number,
|
||||||
|
default: null,
|
||||||
|
},
|
||||||
|
})
|
||||||
|
|
||||||
|
const emit = defineEmits(['select'])
|
||||||
|
|
||||||
|
const containerRef = ref(null)
|
||||||
|
let network = null
|
||||||
|
let nodesDataSet = null
|
||||||
|
|
||||||
|
const BASE_OPTIONS = {
|
||||||
|
autoResize: true,
|
||||||
|
interaction: {
|
||||||
|
hover: true,
|
||||||
|
tooltipDelay: 150,
|
||||||
|
},
|
||||||
|
physics: {
|
||||||
|
enabled: true,
|
||||||
|
stabilization: { enabled: true, iterations: 800 },
|
||||||
|
barnesHut: {
|
||||||
|
gravitationalConstant: -5000,
|
||||||
|
springLength: 140,
|
||||||
|
springConstant: 0.05,
|
||||||
|
},
|
||||||
|
},
|
||||||
|
nodes: {
|
||||||
|
shape: 'dot',
|
||||||
|
size: 24,
|
||||||
|
borderWidth: 2,
|
||||||
|
font: {
|
||||||
|
face: 'sans-serif',
|
||||||
|
size: 13,
|
||||||
|
color: '#263238',
|
||||||
|
strokeWidth: 4,
|
||||||
|
strokeColor: '#ffffff',
|
||||||
|
},
|
||||||
|
},
|
||||||
|
edges: {
|
||||||
|
smooth: { enabled: true, type: 'dynamic' },
|
||||||
|
arrows: { to: { enabled: true, scaleFactor: 0.6 } },
|
||||||
|
color: { color: '#b0bec5', highlight: '#546e7a', hover: '#90a4ae' },
|
||||||
|
width: 2,
|
||||||
|
},
|
||||||
|
layout: { improvedLayout: true },
|
||||||
|
}
|
||||||
|
|
||||||
|
function mergeOptions () {
|
||||||
|
return {
|
||||||
|
...BASE_OPTIONS,
|
||||||
|
...props.options,
|
||||||
|
nodes: { ...BASE_OPTIONS.nodes, ...(props.options.nodes || {}) },
|
||||||
|
edges: { ...BASE_OPTIONS.edges, ...(props.options.edges || {}) },
|
||||||
|
physics: { ...BASE_OPTIONS.physics, ...(props.options.physics || {}) },
|
||||||
|
interaction: { ...BASE_OPTIONS.interaction, ...(props.options.interaction || {}) },
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function render (nodes, edges) {
|
||||||
|
nodesDataSet = new DataSet(nodes)
|
||||||
|
network.setData({ nodes: nodesDataSet, edges: new DataSet(edges) })
|
||||||
|
}
|
||||||
|
|
||||||
|
function applyMinVerticalSpacing (minSpacing) {
|
||||||
|
if (!minSpacing || minSpacing <= 0) return
|
||||||
|
const columns = new Map()
|
||||||
|
for (const [id, position] of Object.entries(network.getPositions())) {
|
||||||
|
const x = Math.round(position.x)
|
||||||
|
if (!columns.has(x)) columns.set(x, [])
|
||||||
|
columns.get(x).push({ id, x, y: position.y })
|
||||||
|
}
|
||||||
|
for (const column of columns.values()) {
|
||||||
|
column.sort((a, b) => a.y - b.y)
|
||||||
|
let previousY = null
|
||||||
|
for (const item of column) {
|
||||||
|
if (previousY !== null && item.y - previousY < minSpacing) {
|
||||||
|
network.moveNode(item.id, item.x, previousY + minSpacing)
|
||||||
|
}
|
||||||
|
previousY = network.getPositions()[item.id].y
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function setupNetwork () {
|
||||||
|
if (network) network.destroy()
|
||||||
|
network = new Network(containerRef.value, { nodes: [], edges: [] }, mergeOptions())
|
||||||
|
render(props.nodes, props.edges)
|
||||||
|
|
||||||
|
network.on('click', params => {
|
||||||
|
const id = params.nodes?.[0]
|
||||||
|
if (id === undefined) return
|
||||||
|
const node = nodesDataSet.get(id)
|
||||||
|
if (node) emit('select', node)
|
||||||
|
})
|
||||||
|
|
||||||
|
network.once('stabilizationIterationsDone', () => {
|
||||||
|
network.setOptions({ physics: { enabled: false } })
|
||||||
|
applyMinVerticalSpacing(props.minVerticalSpacing)
|
||||||
|
network.fit()
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
onMounted(setupNetwork)
|
||||||
|
|
||||||
|
watch(
|
||||||
|
() => [props.nodes, props.edges],
|
||||||
|
() => {
|
||||||
|
if (!containerRef.value) return
|
||||||
|
setupNetwork()
|
||||||
|
},
|
||||||
|
{ deep: true }
|
||||||
|
)
|
||||||
|
|
||||||
|
onBeforeUnmount(() => {
|
||||||
|
if (network) network.destroy()
|
||||||
|
network = null
|
||||||
|
})
|
||||||
|
</script>
|
||||||
|
|
||||||
|
<style scoped>
|
||||||
|
.vis-chart {
|
||||||
|
width: 100%;
|
||||||
|
min-height: 200px;
|
||||||
|
}
|
||||||
|
</style>
|
||||||
@@ -1,95 +0,0 @@
|
|||||||
<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>
|
|
||||||
@@ -1,97 +0,0 @@
|
|||||||
<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>
|
|
||||||
114
src/components/provenance/ProvenanceGraph.vue
Normal file
114
src/components/provenance/ProvenanceGraph.vue
Normal file
@@ -0,0 +1,114 @@
|
|||||||
|
<template>
|
||||||
|
<div>
|
||||||
|
<v-alert
|
||||||
|
v-if="!hasSuppliers"
|
||||||
|
class="my-4"
|
||||||
|
type="info"
|
||||||
|
variant="tonal"
|
||||||
|
>
|
||||||
|
La información de origen de los productos de este pedido estará disponible
|
||||||
|
próximamente.
|
||||||
|
</v-alert>
|
||||||
|
|
||||||
|
<template v-else>
|
||||||
|
<div class="d-flex flex-wrap align-center ga-4 mb-2">
|
||||||
|
<span class="text-body-2 font-weight-medium">Elementos a graficar:</span>
|
||||||
|
<v-checkbox
|
||||||
|
v-for="option in options"
|
||||||
|
:key="option.value"
|
||||||
|
v-model="selectedKinds"
|
||||||
|
density="compact"
|
||||||
|
:value="option.value"
|
||||||
|
>
|
||||||
|
<template #label>
|
||||||
|
<span class="d-flex align-center">
|
||||||
|
<span
|
||||||
|
class="legend-dot"
|
||||||
|
:style="{ backgroundColor: option.color }"
|
||||||
|
/>
|
||||||
|
{{ option.label }}
|
||||||
|
</span>
|
||||||
|
</template>
|
||||||
|
</v-checkbox>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<v-alert
|
||||||
|
v-if="visNodes.length === 0"
|
||||||
|
class="my-2"
|
||||||
|
type="warning"
|
||||||
|
variant="tonal"
|
||||||
|
>
|
||||||
|
Selecciona al menos un elemento para graficar.
|
||||||
|
</v-alert>
|
||||||
|
|
||||||
|
<VisChart
|
||||||
|
v-if="visNodes.length > 0"
|
||||||
|
data-test="provenance-chart"
|
||||||
|
:edges="visEdges"
|
||||||
|
:height="height"
|
||||||
|
:min-vertical-spacing="minVerticalSpacing"
|
||||||
|
:nodes="visNodes"
|
||||||
|
:options="chartOptions"
|
||||||
|
@select="onSelect"
|
||||||
|
/>
|
||||||
|
</template>
|
||||||
|
|
||||||
|
<ProvenanceDetailModal
|
||||||
|
:selected="selected"
|
||||||
|
:visible="modalVisible"
|
||||||
|
@update:visible="modalVisible = $event"
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
</template>
|
||||||
|
|
||||||
|
<script setup>
|
||||||
|
import { computed, ref } from 'vue'
|
||||||
|
import VisChart from '@/components/graph/VisChart.vue'
|
||||||
|
import ProvenanceDetailModal from './ProvenanceDetailModal.vue'
|
||||||
|
import { buildProvenanceGraph, hasAnySupplier } from './provenance-graph'
|
||||||
|
import { chartOptions, KIND_COLORS, toVisEdges, toVisNodes } from './provenance-vis'
|
||||||
|
|
||||||
|
const props = defineProps({
|
||||||
|
provenance: {
|
||||||
|
type: Array,
|
||||||
|
default: () => [],
|
||||||
|
},
|
||||||
|
})
|
||||||
|
|
||||||
|
const options = [
|
||||||
|
{ value: 'product', label: 'Productos', color: KIND_COLORS.product },
|
||||||
|
{ value: 'supplier', label: 'Proveedores', color: KIND_COLORS.supplier },
|
||||||
|
{ value: 'organization', label: 'Organizaciones', color: KIND_COLORS.organization },
|
||||||
|
{ value: 'municipality', label: 'Municipios', color: KIND_COLORS.municipality },
|
||||||
|
{ value: 'department', label: 'Departamentos', color: KIND_COLORS.department },
|
||||||
|
{ value: 'country', label: 'País', color: KIND_COLORS.country },
|
||||||
|
]
|
||||||
|
|
||||||
|
const selectedKinds = ref(['product', 'supplier'])
|
||||||
|
|
||||||
|
const hasSuppliers = computed(() => hasAnySupplier(props.provenance))
|
||||||
|
const graph = computed(() => buildProvenanceGraph(props.provenance, selectedKinds.value))
|
||||||
|
const visNodes = computed(() => toVisNodes(graph.value.nodes))
|
||||||
|
const visEdges = computed(() => toVisEdges(graph.value.edges))
|
||||||
|
const height = computed(() => Math.max(280, Math.min(700, graph.value.nodes.length * 64)))
|
||||||
|
const minVerticalSpacing = 2 * 24 + 22
|
||||||
|
|
||||||
|
const selected = ref(null)
|
||||||
|
const modalVisible = ref(false)
|
||||||
|
|
||||||
|
function onSelect (node) {
|
||||||
|
if (!node || node.kind === 'junction') return
|
||||||
|
selected.value = node
|
||||||
|
modalVisible.value = true
|
||||||
|
}
|
||||||
|
</script>
|
||||||
|
|
||||||
|
<style scoped>
|
||||||
|
.legend-dot {
|
||||||
|
width: 14px;
|
||||||
|
height: 14px;
|
||||||
|
border-radius: 50%;
|
||||||
|
margin-right: 6px;
|
||||||
|
border: 2px solid rgba(0, 0, 0, 0.15);
|
||||||
|
}
|
||||||
|
</style>
|
||||||
569
src/components/provenance/ProvenanceMap.vue
Normal file
569
src/components/provenance/ProvenanceMap.vue
Normal file
@@ -0,0 +1,569 @@
|
|||||||
|
<template>
|
||||||
|
<div>
|
||||||
|
<template v-if="productRows.length">
|
||||||
|
<div class="map-layout">
|
||||||
|
<v-card class="product-panel" data-test="map-product-box" variant="tonal">
|
||||||
|
<v-card-title class="d-flex align-center justify-space-between py-2">
|
||||||
|
<span class="text-subtitle-1 font-weight-bold">
|
||||||
|
Productos ({{ productRows.length }})
|
||||||
|
</span>
|
||||||
|
<v-btn
|
||||||
|
v-if="hasMarkers"
|
||||||
|
data-test="map-reset-zoom"
|
||||||
|
density="comfortable"
|
||||||
|
icon="mdi-fit-to-page"
|
||||||
|
size="small"
|
||||||
|
variant="flat"
|
||||||
|
@click="resetZoom"
|
||||||
|
/>
|
||||||
|
</v-card-title>
|
||||||
|
<v-divider />
|
||||||
|
<v-list density="compact">
|
||||||
|
<v-list-item
|
||||||
|
v-for="row in productRows"
|
||||||
|
:key="row.product.id"
|
||||||
|
data-test="map-product-row"
|
||||||
|
:prepend-avatar="row.image"
|
||||||
|
role="button"
|
||||||
|
:subtitle="row.locationLabel"
|
||||||
|
:title="row.product.name"
|
||||||
|
@click="onRowClick(row)"
|
||||||
|
>
|
||||||
|
<template #append>
|
||||||
|
<v-icon v-if="row.position" color="primary" size="small">
|
||||||
|
mdi-map-marker
|
||||||
|
</v-icon>
|
||||||
|
<v-icon v-else color="medium-emphasis" size="small">
|
||||||
|
mdi-map-marker-off
|
||||||
|
</v-icon>
|
||||||
|
</template>
|
||||||
|
</v-list-item>
|
||||||
|
</v-list>
|
||||||
|
</v-card>
|
||||||
|
|
||||||
|
<div class="map-area">
|
||||||
|
<template v-if="hasMarkers">
|
||||||
|
<div ref="mapEl" class="map-wrapper" />
|
||||||
|
<v-alert
|
||||||
|
v-if="!storePosition"
|
||||||
|
class="mt-2"
|
||||||
|
type="warning"
|
||||||
|
variant="tonal"
|
||||||
|
>
|
||||||
|
La ubicación de la tienda no está configurada, por lo que no se mostrará su recorrido.
|
||||||
|
</v-alert>
|
||||||
|
<p class="text-caption text-medium-emphasis mt-2 mb-0">
|
||||||
|
Pasa el cursor sobre un producto para ver su recorrido hasta la tienda. Haz clic en un marcador para ver el detalle.
|
||||||
|
</p>
|
||||||
|
</template>
|
||||||
|
<v-alert
|
||||||
|
v-else
|
||||||
|
class="my-2"
|
||||||
|
type="info"
|
||||||
|
variant="tonal"
|
||||||
|
>
|
||||||
|
Las coordenadas geográficas de los municipios de origen aún no están disponibles.
|
||||||
|
</v-alert>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</template>
|
||||||
|
|
||||||
|
<ProvenanceRelationModal
|
||||||
|
:product="selectedProduct"
|
||||||
|
:relation="selectedRelation"
|
||||||
|
:visible="modalVisible"
|
||||||
|
@update:visible="modalVisible = $event"
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
</template>
|
||||||
|
|
||||||
|
<script setup>
|
||||||
|
import { computed, inject, nextTick, onBeforeUnmount, onMounted, ref } from 'vue'
|
||||||
|
import L from 'leaflet'
|
||||||
|
import 'leaflet/dist/leaflet.css'
|
||||||
|
import { useSettingsStore } from '@/stores/settings'
|
||||||
|
import ProvenanceRelationModal from './ProvenanceRelationModal.vue'
|
||||||
|
|
||||||
|
const props = defineProps({
|
||||||
|
provenance: {
|
||||||
|
type: Array,
|
||||||
|
default: () => [],
|
||||||
|
},
|
||||||
|
})
|
||||||
|
|
||||||
|
const api = inject('api')
|
||||||
|
const settingsStore = useSettingsStore()
|
||||||
|
|
||||||
|
const mapEl = ref(null)
|
||||||
|
const selectedProduct = ref(null)
|
||||||
|
const selectedRelation = ref(null)
|
||||||
|
const modalVisible = ref(false)
|
||||||
|
|
||||||
|
let map = null
|
||||||
|
let storeMarker = null
|
||||||
|
let productMarkers = []
|
||||||
|
let activeLines = []
|
||||||
|
|
||||||
|
const settings = computed(() => settingsStore.settings)
|
||||||
|
const storePosition = computed(() => {
|
||||||
|
const current = settings.value
|
||||||
|
if (!current || current.latitude == null || current.longitude == null) return null
|
||||||
|
return [Number(current.latitude), Number(current.longitude)]
|
||||||
|
})
|
||||||
|
|
||||||
|
const markers = computed(() => {
|
||||||
|
const result = []
|
||||||
|
for (const entry of props.provenance || []) {
|
||||||
|
if (!entry.product) continue
|
||||||
|
for (const rel of entry.suppliers || []) {
|
||||||
|
const municipality = rel.municipality
|
||||||
|
if (municipality && municipality.latitude != null && municipality.longitude != null) {
|
||||||
|
result.push({
|
||||||
|
product: entry.product,
|
||||||
|
relation: rel,
|
||||||
|
position: [Number(municipality.latitude), Number(municipality.longitude)],
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return result
|
||||||
|
})
|
||||||
|
|
||||||
|
const productRows = computed(() => {
|
||||||
|
const rows = []
|
||||||
|
for (const entry of props.provenance || []) {
|
||||||
|
if (!entry.product) continue
|
||||||
|
const suppliers = entry.suppliers || []
|
||||||
|
const geoRelations = suppliers.filter(rel =>
|
||||||
|
rel.municipality && rel.municipality.latitude != null && rel.municipality.longitude != null
|
||||||
|
)
|
||||||
|
const municipalities = [...new Map(
|
||||||
|
geoRelations.map(rel => [rel.municipality.id, rel.municipality])
|
||||||
|
).values()]
|
||||||
|
rows.push({
|
||||||
|
product: entry.product,
|
||||||
|
relation: suppliers[0] || null,
|
||||||
|
image: entry.product.catalogue_images?.[0] || null,
|
||||||
|
position: geoRelations.length
|
||||||
|
? [Number(geoRelations[0].municipality.latitude), Number(geoRelations[0].municipality.longitude)]
|
||||||
|
: null,
|
||||||
|
locationLabel: municipalities.length
|
||||||
|
? municipalities.map(m => m.name).join(', ')
|
||||||
|
: 'Sin geolocalización',
|
||||||
|
})
|
||||||
|
}
|
||||||
|
return rows
|
||||||
|
})
|
||||||
|
|
||||||
|
const hasMarkers = computed(() => markers.value.length > 0)
|
||||||
|
|
||||||
|
const markerGroups = computed(() => {
|
||||||
|
const groups = new Map()
|
||||||
|
for (const markerData of markers.value) {
|
||||||
|
const key = markerData.position.join(',')
|
||||||
|
if (!groups.has(key)) groups.set(key, [])
|
||||||
|
groups.get(key).push(markerData)
|
||||||
|
}
|
||||||
|
return [...groups.values()].map(items => ({ position: items[0].position, items }))
|
||||||
|
})
|
||||||
|
|
||||||
|
const personIcon = L.divIcon({
|
||||||
|
className: 'provenance-store-pin',
|
||||||
|
html: '<i class="mdi mdi-account-circle" style="font-size:46px;line-height:1;color:#f44336;"></i>',
|
||||||
|
iconSize: [46, 46],
|
||||||
|
iconAnchor: [23, 46],
|
||||||
|
})
|
||||||
|
|
||||||
|
function productIcon (markerData) {
|
||||||
|
const image = markerData.product.catalogue_images?.[0]
|
||||||
|
const html = image
|
||||||
|
? `<img class="provenance-product-img" src="${image}" alt="${markerData.product.name}">`
|
||||||
|
: '<span class="provenance-product-fallback"><i class="mdi mdi-package-variant"></i></span>'
|
||||||
|
return L.divIcon({
|
||||||
|
className: 'provenance-product-pin',
|
||||||
|
html,
|
||||||
|
iconSize: [38, 38],
|
||||||
|
iconAnchor: [19, 38],
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
function groupIcon (group) {
|
||||||
|
return L.divIcon({
|
||||||
|
className: 'provenance-group-pin',
|
||||||
|
html: `<span class="provenance-group-count">${group.items.length}</span><i class="mdi mdi-package-variant"></i>`,
|
||||||
|
iconSize: [38, 38],
|
||||||
|
iconAnchor: [19, 38],
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
function buildGroupPopup (items, onItemClick) {
|
||||||
|
const container = document.createElement('div')
|
||||||
|
container.className = 'provenance-popup-list'
|
||||||
|
items.forEach((item, index) => {
|
||||||
|
const row = document.createElement('div')
|
||||||
|
row.className = 'provenance-popup-item'
|
||||||
|
row.setAttribute('role', 'button')
|
||||||
|
row.setAttribute('data-test', `map-popup-item-${index}`)
|
||||||
|
const image = item.product.catalogue_images?.[0]
|
||||||
|
if (image) {
|
||||||
|
const img = document.createElement('img')
|
||||||
|
img.src = image
|
||||||
|
img.className = 'provenance-popup-img'
|
||||||
|
row.appendChild(img)
|
||||||
|
}
|
||||||
|
const name = document.createElement('span')
|
||||||
|
name.className = 'provenance-popup-name'
|
||||||
|
name.textContent = item.product.name
|
||||||
|
row.appendChild(name)
|
||||||
|
row.addEventListener('click', event => {
|
||||||
|
event.stopPropagation()
|
||||||
|
onItemClick(item)
|
||||||
|
})
|
||||||
|
container.appendChild(row)
|
||||||
|
})
|
||||||
|
return container
|
||||||
|
}
|
||||||
|
|
||||||
|
function appendEntityRow (container, label, icon, color, entity) {
|
||||||
|
if (!entity) return
|
||||||
|
const row = document.createElement('div')
|
||||||
|
row.className = 'provenance-detail-row'
|
||||||
|
const iconEl = document.createElement('i')
|
||||||
|
iconEl.className = `mdi ${icon}`
|
||||||
|
iconEl.style.color = color
|
||||||
|
row.appendChild(iconEl)
|
||||||
|
const body = document.createElement('div')
|
||||||
|
const labelEl = document.createElement('div')
|
||||||
|
labelEl.className = 'provenance-detail-label'
|
||||||
|
labelEl.textContent = label
|
||||||
|
const nameEl = document.createElement('div')
|
||||||
|
nameEl.className = 'provenance-detail-name'
|
||||||
|
nameEl.textContent = entity.name
|
||||||
|
body.appendChild(labelEl)
|
||||||
|
body.appendChild(nameEl)
|
||||||
|
row.appendChild(body)
|
||||||
|
container.appendChild(row)
|
||||||
|
}
|
||||||
|
|
||||||
|
function buildDetailPopup (markerData) {
|
||||||
|
const container = document.createElement('div')
|
||||||
|
container.className = 'provenance-detail-popup'
|
||||||
|
const header = document.createElement('div')
|
||||||
|
header.className = 'provenance-detail-header'
|
||||||
|
const image = markerData.product.catalogue_images?.[0]
|
||||||
|
if (image) {
|
||||||
|
const img = document.createElement('img')
|
||||||
|
img.src = image
|
||||||
|
img.className = 'provenance-detail-img'
|
||||||
|
header.appendChild(img)
|
||||||
|
}
|
||||||
|
const title = document.createElement('div')
|
||||||
|
title.className = 'provenance-detail-title'
|
||||||
|
title.textContent = markerData.product.name
|
||||||
|
header.appendChild(title)
|
||||||
|
container.appendChild(header)
|
||||||
|
const rel = markerData.relation || {}
|
||||||
|
appendEntityRow(container, 'Proveedor', 'mdi-truck', '#1976d2', rel.supplier)
|
||||||
|
appendEntityRow(container, 'Organización', 'mdi-domain', '#fb8c00', rel.organization)
|
||||||
|
appendEntityRow(container, 'Municipio', 'mdi-map-marker', '#4caf50', rel.municipality)
|
||||||
|
appendEntityRow(container, 'Departamento', 'mdi-map', '#3f51b5', rel.department)
|
||||||
|
appendEntityRow(container, 'País', 'mdi-earth', '#9c27b0', rel.country)
|
||||||
|
return container
|
||||||
|
}
|
||||||
|
|
||||||
|
function openProductDetail (marker, markerData) {
|
||||||
|
marker.setPopupContent(buildDetailPopup(markerData))
|
||||||
|
marker.openPopup()
|
||||||
|
}
|
||||||
|
|
||||||
|
function showLine (from, to) {
|
||||||
|
const line = L.polyline([from, to], {
|
||||||
|
color: '#26a69a',
|
||||||
|
weight: 2,
|
||||||
|
dashArray: '6 6',
|
||||||
|
}).addTo(map)
|
||||||
|
activeLines.push(line)
|
||||||
|
}
|
||||||
|
|
||||||
|
function clearLines () {
|
||||||
|
activeLines.forEach(line => line.remove())
|
||||||
|
activeLines = []
|
||||||
|
}
|
||||||
|
|
||||||
|
function addStoreMarker () {
|
||||||
|
if (!storePosition.value) return
|
||||||
|
storeMarker = L.marker(storePosition.value, { icon: personIcon }).addTo(map)
|
||||||
|
storeMarker.bindTooltip('Tienda')
|
||||||
|
storeMarker.on('mouseover', () => {
|
||||||
|
markers.value.forEach(markerData => showLine(markerData.position, storePosition.value))
|
||||||
|
})
|
||||||
|
storeMarker.on('mouseout', clearLines)
|
||||||
|
}
|
||||||
|
|
||||||
|
function addProductMarkers () {
|
||||||
|
markerGroups.value.forEach(group => {
|
||||||
|
if (group.items.length === 1) {
|
||||||
|
const item = group.items[0]
|
||||||
|
const marker = L.marker(item.position, { icon: productIcon(item) }).addTo(map)
|
||||||
|
marker.bindTooltip(item.product.name)
|
||||||
|
marker.bindPopup(buildDetailPopup(item))
|
||||||
|
marker.on('mouseover', () => {
|
||||||
|
if (storePosition.value) showLine(item.position, storePosition.value)
|
||||||
|
})
|
||||||
|
marker.on('mouseout', clearLines)
|
||||||
|
productMarkers.push({ marker, items: [item] })
|
||||||
|
return
|
||||||
|
}
|
||||||
|
const marker = L.marker(group.position, { icon: groupIcon(group) }).addTo(map)
|
||||||
|
marker.bindTooltip(`${group.items.length} productos en este punto`)
|
||||||
|
marker.bindPopup(buildGroupPopup(group.items, item => openProductDetail(marker, item)))
|
||||||
|
marker.on('popupclose', () => {
|
||||||
|
marker.bindPopup(buildGroupPopup(group.items, item => openProductDetail(marker, item)))
|
||||||
|
})
|
||||||
|
marker.on('mouseover', () => {
|
||||||
|
if (storePosition.value) group.items.forEach(item => showLine(item.position, storePosition.value))
|
||||||
|
})
|
||||||
|
marker.on('mouseout', clearLines)
|
||||||
|
productMarkers.push({ marker, items: group.items })
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
function fitBounds () {
|
||||||
|
const bounds = L.latLngBounds()
|
||||||
|
markers.value.forEach(markerData => bounds.extend(markerData.position))
|
||||||
|
if (storePosition.value) bounds.extend(storePosition.value)
|
||||||
|
if (bounds.isValid()) map.fitBounds(bounds, { padding: [60, 60] })
|
||||||
|
}
|
||||||
|
|
||||||
|
function onRowClick (row) {
|
||||||
|
if (row.position && map) {
|
||||||
|
map.flyTo(row.position, Math.max(map.getZoom(), 12), { duration: 0.6 })
|
||||||
|
const entry = productMarkers.find(entry =>
|
||||||
|
entry.items.some(item => item.product.id === row.product.id && item.relation === row.relation)
|
||||||
|
)
|
||||||
|
if (entry) {
|
||||||
|
const item = entry.items.find(i => i.relation === row.relation) || entry.items[0]
|
||||||
|
openProductDetail(entry.marker, item)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
}
|
||||||
|
selectedProduct.value = row.product
|
||||||
|
selectedRelation.value = row.relation
|
||||||
|
modalVisible.value = true
|
||||||
|
}
|
||||||
|
|
||||||
|
function resetZoom () {
|
||||||
|
if (map) fitBounds()
|
||||||
|
}
|
||||||
|
|
||||||
|
function initMap () {
|
||||||
|
if (!mapEl.value || map) return
|
||||||
|
const center = storePosition.value || markers.value[0].position
|
||||||
|
map = L.map(mapEl.value, { scrollWheelZoom: false }).setView(center, 6)
|
||||||
|
L.tileLayer('https://tile.openstreetmap.org/{z}/{x}/{y}.png', {
|
||||||
|
maxZoom: 19,
|
||||||
|
attribution: '© <a href="https://www.openstreetmap.org/copyright">OpenStreetMap</a> contributors',
|
||||||
|
}).addTo(map)
|
||||||
|
addStoreMarker()
|
||||||
|
addProductMarkers()
|
||||||
|
fitBounds()
|
||||||
|
}
|
||||||
|
|
||||||
|
function handleResize () {
|
||||||
|
if (map) map.invalidateSize()
|
||||||
|
}
|
||||||
|
|
||||||
|
onMounted(async () => {
|
||||||
|
window.addEventListener('resize', handleResize)
|
||||||
|
try {
|
||||||
|
await settingsStore.fetchSettings(api)
|
||||||
|
await nextTick()
|
||||||
|
if (mapEl.value) initMap()
|
||||||
|
} catch (error) {
|
||||||
|
console.error('Error al cargar la configuración de la tienda:', error)
|
||||||
|
}
|
||||||
|
})
|
||||||
|
|
||||||
|
onBeforeUnmount(() => {
|
||||||
|
window.removeEventListener('resize', handleResize)
|
||||||
|
if (map) {
|
||||||
|
map.remove()
|
||||||
|
map = null
|
||||||
|
storeMarker = null
|
||||||
|
productMarkers = []
|
||||||
|
}
|
||||||
|
})
|
||||||
|
</script>
|
||||||
|
|
||||||
|
<style scoped>
|
||||||
|
.map-layout {
|
||||||
|
display: flex;
|
||||||
|
gap: 12px;
|
||||||
|
align-items: stretch;
|
||||||
|
}
|
||||||
|
|
||||||
|
.product-panel {
|
||||||
|
flex: 0 0 300px;
|
||||||
|
max-height: 480px;
|
||||||
|
overflow-y: auto;
|
||||||
|
}
|
||||||
|
|
||||||
|
.map-area {
|
||||||
|
flex: 1;
|
||||||
|
min-width: 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
.map-wrapper {
|
||||||
|
position: relative;
|
||||||
|
width: 100%;
|
||||||
|
height: 420px;
|
||||||
|
border-radius: 12px;
|
||||||
|
overflow: hidden;
|
||||||
|
z-index: 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
@media (max-width: 900px) {
|
||||||
|
.map-layout {
|
||||||
|
flex-direction: column;
|
||||||
|
}
|
||||||
|
|
||||||
|
.product-panel {
|
||||||
|
flex-basis: auto;
|
||||||
|
max-height: none;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
.map-wrapper :deep(.provenance-product-pin) {
|
||||||
|
display: flex;
|
||||||
|
align-items: center;
|
||||||
|
justify-content: center;
|
||||||
|
border: none;
|
||||||
|
background: transparent;
|
||||||
|
}
|
||||||
|
|
||||||
|
.map-wrapper :deep(.provenance-product-img) {
|
||||||
|
width: 38px;
|
||||||
|
height: 38px;
|
||||||
|
border-radius: 50%;
|
||||||
|
object-fit: cover;
|
||||||
|
border: 2px solid #ffffff;
|
||||||
|
box-shadow: 0 1px 4px rgba(0, 0, 0, 0.35);
|
||||||
|
}
|
||||||
|
|
||||||
|
.map-wrapper :deep(.provenance-product-fallback) {
|
||||||
|
display: flex;
|
||||||
|
align-items: center;
|
||||||
|
justify-content: center;
|
||||||
|
width: 38px;
|
||||||
|
height: 38px;
|
||||||
|
border-radius: 50%;
|
||||||
|
background: #26a69a;
|
||||||
|
color: #ffffff;
|
||||||
|
border: 2px solid #ffffff;
|
||||||
|
box-shadow: 0 1px 4px rgba(0, 0, 0, 0.35);
|
||||||
|
font-size: 24px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.map-wrapper :deep(.provenance-store-pin) {
|
||||||
|
border: none;
|
||||||
|
background: transparent;
|
||||||
|
}
|
||||||
|
|
||||||
|
.map-wrapper :deep(.provenance-group-pin) {
|
||||||
|
display: flex;
|
||||||
|
flex-direction: column;
|
||||||
|
align-items: center;
|
||||||
|
justify-content: center;
|
||||||
|
background: #26a69a;
|
||||||
|
border: 2px solid #ffffff;
|
||||||
|
border-radius: 50%;
|
||||||
|
color: #ffffff;
|
||||||
|
box-shadow: 0 1px 4px rgba(0, 0, 0, 0.35);
|
||||||
|
cursor: pointer;
|
||||||
|
}
|
||||||
|
|
||||||
|
.map-wrapper :deep(.provenance-group-pin .provenance-group-count) {
|
||||||
|
font-weight: 700;
|
||||||
|
font-size: 14px;
|
||||||
|
line-height: 1;
|
||||||
|
}
|
||||||
|
|
||||||
|
.map-wrapper :deep(.provenance-group-pin .mdi) {
|
||||||
|
font-size: 12px;
|
||||||
|
line-height: 1;
|
||||||
|
margin-top: 2px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.map-wrapper :deep(.provenance-popup-item) {
|
||||||
|
display: flex;
|
||||||
|
align-items: center;
|
||||||
|
gap: 8px;
|
||||||
|
padding: 4px 0;
|
||||||
|
cursor: pointer;
|
||||||
|
}
|
||||||
|
|
||||||
|
.map-wrapper :deep(.provenance-popup-item:hover) {
|
||||||
|
text-decoration: underline;
|
||||||
|
}
|
||||||
|
|
||||||
|
.map-wrapper :deep(.provenance-popup-img) {
|
||||||
|
width: 28px;
|
||||||
|
height: 28px;
|
||||||
|
border-radius: 4px;
|
||||||
|
object-fit: cover;
|
||||||
|
}
|
||||||
|
|
||||||
|
.map-wrapper :deep(.provenance-popup-name) {
|
||||||
|
font-weight: 500;
|
||||||
|
}
|
||||||
|
|
||||||
|
.map-wrapper :deep(.provenance-detail-popup) {
|
||||||
|
min-width: 200px;
|
||||||
|
max-width: 260px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.map-wrapper :deep(.provenance-detail-header) {
|
||||||
|
display: flex;
|
||||||
|
align-items: center;
|
||||||
|
gap: 8px;
|
||||||
|
margin-bottom: 6px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.map-wrapper :deep(.provenance-detail-img) {
|
||||||
|
width: 40px;
|
||||||
|
height: 40px;
|
||||||
|
border-radius: 50%;
|
||||||
|
object-fit: cover;
|
||||||
|
}
|
||||||
|
|
||||||
|
.map-wrapper :deep(.provenance-detail-title) {
|
||||||
|
font-weight: 700;
|
||||||
|
}
|
||||||
|
|
||||||
|
.map-wrapper :deep(.provenance-detail-row) {
|
||||||
|
display: flex;
|
||||||
|
align-items: flex-start;
|
||||||
|
gap: 8px;
|
||||||
|
padding: 4px 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
.map-wrapper :deep(.provenance-detail-row .mdi) {
|
||||||
|
font-size: 18px;
|
||||||
|
margin-top: 2px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.map-wrapper :deep(.provenance-detail-label) {
|
||||||
|
font-size: 11px;
|
||||||
|
font-weight: 700;
|
||||||
|
text-transform: uppercase;
|
||||||
|
opacity: 0.7;
|
||||||
|
}
|
||||||
|
|
||||||
|
.map-wrapper :deep(.provenance-detail-name) {
|
||||||
|
font-weight: 500;
|
||||||
|
}
|
||||||
|
|
||||||
|
.map-wrapper :deep(.leaflet-control-attribution) {
|
||||||
|
font-size: 10px;
|
||||||
|
}
|
||||||
|
</style>
|
||||||
145
src/components/provenance/ProvenanceRelationModal.vue
Normal file
145
src/components/provenance/ProvenanceRelationModal.vue
Normal file
@@ -0,0 +1,145 @@
|
|||||||
|
<template>
|
||||||
|
<v-dialog
|
||||||
|
max-width="560"
|
||||||
|
:model-value="visible"
|
||||||
|
@update:model-value="onUpdateVisible"
|
||||||
|
>
|
||||||
|
<v-card v-if="relation || product">
|
||||||
|
<v-card-title class="d-flex align-center">
|
||||||
|
<v-icon class="mr-2" color="teal" icon="mdi-package-variant" />
|
||||||
|
<span class="font-weight-bold">{{ productName }}</span>
|
||||||
|
</v-card-title>
|
||||||
|
<v-divider />
|
||||||
|
<v-card-text>
|
||||||
|
<img
|
||||||
|
v-if="productImage"
|
||||||
|
alt="Imagen del producto"
|
||||||
|
class="provenance-image rounded-lg border mb-3"
|
||||||
|
:src="productImage"
|
||||||
|
>
|
||||||
|
<div
|
||||||
|
v-if="!hasLocation"
|
||||||
|
class="d-flex align-start mb-3"
|
||||||
|
>
|
||||||
|
<v-icon class="mr-3" color="grey" icon="mdi-map-marker-off" />
|
||||||
|
<div>
|
||||||
|
<div class="text-subtitle-2 font-weight-bold">
|
||||||
|
Geolocalización
|
||||||
|
</div>
|
||||||
|
<div class="text-body-1">
|
||||||
|
{{ locationNote }}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
<div
|
||||||
|
v-for="row in rows"
|
||||||
|
:key="row.kind"
|
||||||
|
class="d-flex align-start mb-3"
|
||||||
|
>
|
||||||
|
<v-icon class="mr-3" :color="row.color" :icon="row.icon" />
|
||||||
|
<div>
|
||||||
|
<div class="text-subtitle-2 font-weight-bold">
|
||||||
|
{{ row.label }}
|
||||||
|
</div>
|
||||||
|
<div class="text-body-1">
|
||||||
|
{{ row.name }}
|
||||||
|
</div>
|
||||||
|
<div
|
||||||
|
v-for="detail in row.details"
|
||||||
|
:key="detail.label"
|
||||||
|
class="text-body-2 text-medium-emphasis"
|
||||||
|
>
|
||||||
|
{{ detail.label }}: {{ detail.value }}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</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,
|
||||||
|
},
|
||||||
|
relation: {
|
||||||
|
type: Object,
|
||||||
|
default: null,
|
||||||
|
},
|
||||||
|
product: {
|
||||||
|
type: Object,
|
||||||
|
default: null,
|
||||||
|
},
|
||||||
|
})
|
||||||
|
|
||||||
|
const emit = defineEmits(['update:visible'])
|
||||||
|
|
||||||
|
const ENTITY_INFO = {
|
||||||
|
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 productName = computed(() => props.product?.name || 'Producto')
|
||||||
|
const productImage = computed(() => props.product?.catalogue_images?.[0] || null)
|
||||||
|
const hasLocation = computed(() => !!(props.relation?.municipality || props.relation?.department))
|
||||||
|
const locationNote = computed(() => {
|
||||||
|
if (props.relation) return 'Aún sin geolocalización registrada.'
|
||||||
|
return 'Aún no se ha vinculado un proveedor a este producto.'
|
||||||
|
})
|
||||||
|
|
||||||
|
function entityDetails (kind, entity) {
|
||||||
|
const details = []
|
||||||
|
if (kind === 'supplier' || kind === 'organization') {
|
||||||
|
if (entity.description) details.push({ label: 'Descripción', value: entity.description })
|
||||||
|
if (entity.website) details.push({ label: 'Sitio web', value: entity.website })
|
||||||
|
if (entity.contact_email) details.push({ label: 'Correo', value: entity.contact_email })
|
||||||
|
if (entity.contact_phone) details.push({ label: 'Teléfono', value: entity.contact_phone })
|
||||||
|
}
|
||||||
|
return details
|
||||||
|
}
|
||||||
|
|
||||||
|
const rows = computed(() => {
|
||||||
|
const rel = props.relation || {}
|
||||||
|
return ['supplier', 'organization', 'municipality', 'department', 'country']
|
||||||
|
.filter(kind => rel[kind])
|
||||||
|
.map(kind => {
|
||||||
|
const info = ENTITY_INFO[kind]
|
||||||
|
return {
|
||||||
|
kind,
|
||||||
|
label: info.label,
|
||||||
|
icon: info.icon,
|
||||||
|
color: info.color,
|
||||||
|
name: rel[kind].name,
|
||||||
|
details: entityDetails(kind, rel[kind]),
|
||||||
|
}
|
||||||
|
})
|
||||||
|
})
|
||||||
|
|
||||||
|
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>
|
||||||
@@ -1,24 +1,69 @@
|
|||||||
<template>
|
<template>
|
||||||
<div v-if="provenance && provenance.length > 0">
|
<div v-if="provenance && provenance.length > 0">
|
||||||
<v-divider class="my-4" />
|
<v-divider class="my-4" />
|
||||||
<h3 class="text-h6 font-weight-bold mb-1">Origen e historia de los productos</h3>
|
<div
|
||||||
<p class="text-body-2 text-medium-emphasis mb-4">
|
class="d-flex align-center justify-space-between cursor-pointer"
|
||||||
Conoce quiénes producen los productos que compras y de qué territorios provienen.
|
data-test="provenance-toggle"
|
||||||
</p>
|
role="button"
|
||||||
|
@click="expanded = !expanded"
|
||||||
|
>
|
||||||
|
<h3 class="text-h6 font-weight-bold">
|
||||||
|
Origen de los productos
|
||||||
|
</h3>
|
||||||
|
<v-btn
|
||||||
|
data-test="provenance-toggle-button"
|
||||||
|
density="comfortable"
|
||||||
|
:icon="expanded ? 'mdi-chevron-up' : 'mdi-chevron-down'"
|
||||||
|
variant="text"
|
||||||
|
@click.stop="expanded = !expanded"
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
|
||||||
<h4 class="text-subtitle-1 font-weight-medium mb-2">Proveedores y organizaciones</h4>
|
<v-expand-transition>
|
||||||
<ProductSupplierOrganizationChart :provenance="provenance" />
|
<div v-if="expanded">
|
||||||
|
<p class="text-body-2 text-medium-emphasis mb-4">
|
||||||
|
Conoce quiénes producen los productos que compras y de qué territorios provienen.
|
||||||
|
</p>
|
||||||
|
|
||||||
|
<ProvenanceGraph :provenance="provenance" />
|
||||||
|
</div>
|
||||||
|
</v-expand-transition>
|
||||||
|
|
||||||
<v-divider class="my-4" />
|
<v-divider class="my-4" />
|
||||||
|
<div
|
||||||
|
class="d-flex align-center justify-space-between cursor-pointer"
|
||||||
|
data-test="map-toggle"
|
||||||
|
role="button"
|
||||||
|
@click="mapExpanded = !mapExpanded"
|
||||||
|
>
|
||||||
|
<h3 class="text-h6 font-weight-bold">
|
||||||
|
Mapa de origen de los productos
|
||||||
|
</h3>
|
||||||
|
<v-btn
|
||||||
|
data-test="map-toggle-button"
|
||||||
|
density="comfortable"
|
||||||
|
:icon="mapExpanded ? 'mdi-chevron-up' : 'mdi-chevron-down'"
|
||||||
|
variant="text"
|
||||||
|
@click.stop="mapExpanded = !mapExpanded"
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
|
||||||
<h4 class="text-subtitle-1 font-weight-medium mb-2">Departamento y municipio</h4>
|
<v-expand-transition>
|
||||||
<ProductTerritoryChart :provenance="provenance" />
|
<div v-if="mapExpanded">
|
||||||
|
<p class="text-body-2 text-medium-emphasis mb-4">
|
||||||
|
Recorrido de cada producto desde el municipio donde se produce hasta nuestra tienda.
|
||||||
|
</p>
|
||||||
|
|
||||||
|
<ProvenanceMap :provenance="provenance" />
|
||||||
|
</div>
|
||||||
|
</v-expand-transition>
|
||||||
</div>
|
</div>
|
||||||
</template>
|
</template>
|
||||||
|
|
||||||
<script setup>
|
<script setup>
|
||||||
import ProductSupplierOrganizationChart from './ProductSupplierOrganizationChart.vue'
|
import { ref } from 'vue'
|
||||||
import ProductTerritoryChart from './ProductTerritoryChart.vue'
|
import ProvenanceGraph from './ProvenanceGraph.vue'
|
||||||
|
import ProvenanceMap from './ProvenanceMap.vue'
|
||||||
|
|
||||||
defineProps({
|
defineProps({
|
||||||
provenance: {
|
provenance: {
|
||||||
@@ -26,4 +71,7 @@
|
|||||||
default: null,
|
default: null,
|
||||||
},
|
},
|
||||||
})
|
})
|
||||||
|
|
||||||
|
const expanded = ref(false)
|
||||||
|
const mapExpanded = ref(false)
|
||||||
</script>
|
</script>
|
||||||
|
|||||||
126
src/components/provenance/admin/SupplierLinkDialog.vue
Normal file
126
src/components/provenance/admin/SupplierLinkDialog.vue
Normal file
@@ -0,0 +1,126 @@
|
|||||||
|
<template>
|
||||||
|
<v-dialog
|
||||||
|
max-width="560"
|
||||||
|
:model-value="visible"
|
||||||
|
@update:model-value="onUpdateVisible"
|
||||||
|
>
|
||||||
|
<v-card>
|
||||||
|
<v-card-title>Proveedores del producto</v-card-title>
|
||||||
|
<v-card-text>
|
||||||
|
<p v-if="product" class="text-subtitle-1 mb-3">
|
||||||
|
{{ product.name }}
|
||||||
|
</p>
|
||||||
|
<v-autocomplete
|
||||||
|
v-model="selectedIds"
|
||||||
|
chips
|
||||||
|
closable-chips
|
||||||
|
item-title="name"
|
||||||
|
item-value="id"
|
||||||
|
:items="supplierItems"
|
||||||
|
label="Proveedores"
|
||||||
|
multiple
|
||||||
|
:search-input="searchQuery"
|
||||||
|
/>
|
||||||
|
<v-chip
|
||||||
|
v-if="selectedIds.length > 0"
|
||||||
|
class="mt-3"
|
||||||
|
color="primary"
|
||||||
|
variant="tonal"
|
||||||
|
>
|
||||||
|
Seleccionados ({{ selectedIds.length }})
|
||||||
|
</v-chip>
|
||||||
|
</v-card-text>
|
||||||
|
<v-card-actions>
|
||||||
|
<v-spacer />
|
||||||
|
<v-btn variant="text" @click="close">Cancelar</v-btn>
|
||||||
|
<v-btn
|
||||||
|
color="primary"
|
||||||
|
data-testid="supplier-link-save"
|
||||||
|
:disabled="saving"
|
||||||
|
variant="elevated"
|
||||||
|
@click="save"
|
||||||
|
>
|
||||||
|
Guardar
|
||||||
|
</v-btn>
|
||||||
|
</v-card-actions>
|
||||||
|
</v-card>
|
||||||
|
</v-dialog>
|
||||||
|
</template>
|
||||||
|
|
||||||
|
<script setup>
|
||||||
|
import { computed, inject, ref, watch } from 'vue'
|
||||||
|
|
||||||
|
const props = defineProps({
|
||||||
|
visible: {
|
||||||
|
type: Boolean,
|
||||||
|
default: false,
|
||||||
|
},
|
||||||
|
product: {
|
||||||
|
type: Object,
|
||||||
|
default: null,
|
||||||
|
},
|
||||||
|
})
|
||||||
|
|
||||||
|
const emit = defineEmits(['update:visible'])
|
||||||
|
|
||||||
|
const api = inject('api')
|
||||||
|
const suppliers = ref([])
|
||||||
|
const selectedIds = ref([])
|
||||||
|
const searchQuery = ref('')
|
||||||
|
const saving = ref(false)
|
||||||
|
|
||||||
|
const supplierItems = computed(() => {
|
||||||
|
const query = searchQuery.value.trim().toLowerCase()
|
||||||
|
let filtered = suppliers.value
|
||||||
|
if (query) {
|
||||||
|
filtered = suppliers.value.filter(supplier => {
|
||||||
|
return (supplier.name || '').toLowerCase().includes(query)
|
||||||
|
})
|
||||||
|
}
|
||||||
|
const selected = selectedIds.value.map(Number)
|
||||||
|
for (const supplier of suppliers.value) {
|
||||||
|
const isSelected = selected.includes(supplier.id)
|
||||||
|
const alreadyIncluded = filtered.some(item => item.id === supplier.id)
|
||||||
|
if (isSelected && !alreadyIncluded) filtered = [supplier, ...filtered]
|
||||||
|
}
|
||||||
|
return filtered
|
||||||
|
})
|
||||||
|
|
||||||
|
async function load () {
|
||||||
|
suppliers.value = await api.getSuppliers()
|
||||||
|
if (props.product) {
|
||||||
|
const detail = await api.getProduct(props.product.id)
|
||||||
|
selectedIds.value = detail.suppliers || []
|
||||||
|
} else {
|
||||||
|
selectedIds.value = []
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
watch(
|
||||||
|
() => props.visible,
|
||||||
|
async isVisible => {
|
||||||
|
if (isVisible) await load()
|
||||||
|
},
|
||||||
|
{ immediate: true }
|
||||||
|
)
|
||||||
|
|
||||||
|
async function save () {
|
||||||
|
saving.value = true
|
||||||
|
try {
|
||||||
|
await api.updateProduct(props.product.id, { suppliers: selectedIds.value })
|
||||||
|
close()
|
||||||
|
} catch (error) {
|
||||||
|
console.error('Error al guardar proveedores del producto:', error)
|
||||||
|
} finally {
|
||||||
|
saving.value = false
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function onUpdateVisible (value) {
|
||||||
|
emit('update:visible', value)
|
||||||
|
}
|
||||||
|
|
||||||
|
function close () {
|
||||||
|
emit('update:visible', false)
|
||||||
|
}
|
||||||
|
</script>
|
||||||
@@ -111,7 +111,7 @@
|
|||||||
v-model="formData.municipality"
|
v-model="formData.municipality"
|
||||||
clearable
|
clearable
|
||||||
data-testid="supplier-form-municipality"
|
data-testid="supplier-form-municipality"
|
||||||
item-title="name"
|
:item-title="municipalityItemTitle"
|
||||||
item-value="id"
|
item-value="id"
|
||||||
:items="municipalityItems"
|
:items="municipalityItems"
|
||||||
label="Municipio"
|
label="Municipio"
|
||||||
@@ -189,6 +189,7 @@
|
|||||||
const suppliers = ref([])
|
const suppliers = ref([])
|
||||||
const organizations = ref([])
|
const organizations = ref([])
|
||||||
const municipalities = ref([])
|
const municipalities = ref([])
|
||||||
|
const departments = ref([])
|
||||||
const loading = ref(false)
|
const loading = ref(false)
|
||||||
const saving = ref(false)
|
const saving = ref(false)
|
||||||
const searchQuery = ref('')
|
const searchQuery = ref('')
|
||||||
@@ -226,12 +227,18 @@
|
|||||||
})
|
})
|
||||||
})
|
})
|
||||||
|
|
||||||
|
function municipalityItemTitle (item) {
|
||||||
|
const department = departments.value.find(department => department.id === item.department)
|
||||||
|
if (!department) return item.name || ''
|
||||||
|
return `${item.name} (${department.name})`
|
||||||
|
}
|
||||||
|
|
||||||
const municipalityItems = computed(() => {
|
const municipalityItems = computed(() => {
|
||||||
const query = municipalitySearch.value.trim().toLowerCase()
|
const query = municipalitySearch.value.trim().toLowerCase()
|
||||||
let filtered = municipalities.value
|
let filtered = municipalities.value
|
||||||
if (query) {
|
if (query) {
|
||||||
filtered = municipalities.value.filter(municipality => {
|
filtered = municipalities.value.filter(municipality => {
|
||||||
return (municipality.name || '').toLowerCase().includes(query)
|
return municipalityItemTitle(municipality).toLowerCase().includes(query)
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
const selectedId = Number(formData.value.municipality)
|
const selectedId = Number(formData.value.municipality)
|
||||||
@@ -246,14 +253,16 @@
|
|||||||
async function load () {
|
async function load () {
|
||||||
loading.value = true
|
loading.value = true
|
||||||
try {
|
try {
|
||||||
const [suppliersData, organizationsData, municipalitiesData] = await Promise.all([
|
const [suppliersData, organizationsData, municipalitiesData, departmentsData] = await Promise.all([
|
||||||
api.getSuppliers(),
|
api.getSuppliers(),
|
||||||
api.getOrganizations(),
|
api.getOrganizations(),
|
||||||
api.getMunicipalities(),
|
api.getMunicipalities(),
|
||||||
|
api.getDepartments(),
|
||||||
])
|
])
|
||||||
suppliers.value = suppliersData
|
suppliers.value = suppliersData
|
||||||
organizations.value = organizationsData
|
organizations.value = organizationsData
|
||||||
municipalities.value = municipalitiesData
|
municipalities.value = municipalitiesData
|
||||||
|
departments.value = departmentsData
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
console.error('Error al cargar proveedores:', error)
|
console.error('Error al cargar proveedores:', error)
|
||||||
showSnackbar('Error al cargar proveedores', 'error')
|
showSnackbar('Error al cargar proveedores', 'error')
|
||||||
|
|||||||
@@ -2,18 +2,30 @@
|
|||||||
* Builders de grafos de provenance (específicos del dominio).
|
* Builders de grafos de provenance (específicos del dominio).
|
||||||
*
|
*
|
||||||
* Convierten el payload `product_provenance` del resumen de compra/pedido en
|
* Convierten el payload `product_provenance` del resumen de compra/pedido en
|
||||||
* un grafo en capas usando el servicio genérico `services/graph/graph-layout`.
|
* un grafo con la semántica de certeza:
|
||||||
|
* - Arista cierta (continua): el destino es inequívoco.
|
||||||
|
* - Arista dudosa (discontinua): el destino es una posibilidad entre varias.
|
||||||
|
* - Con varios proveedores para un producto se inserta un nodo de disyunción
|
||||||
|
* (junction): sólida hasta él y discontinua hacia cada proveedor.
|
||||||
|
*
|
||||||
|
* `buildProvenanceGraph` permite elegir los niveles a graficar
|
||||||
|
* (product, supplier, organization, municipality, department, country);
|
||||||
|
* los niveles no solicitados se omiten conectando el nivel previo con el
|
||||||
|
* siguiente.
|
||||||
|
*
|
||||||
|
* El modelo devuelto es agnóstico de la herramienta de renderizado:
|
||||||
|
* node: { id, kind, label, image, entity }
|
||||||
|
* edge: { from, to, certain }
|
||||||
*/
|
*/
|
||||||
|
|
||||||
import { computeColumnLayout } from '@/services/graph/graph-layout'
|
const DEFAULT_KINDS = ['product', 'supplier']
|
||||||
|
const TERRITORY_ORDER = ['municipality', 'department', 'country']
|
||||||
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 () {
|
function makeCollector () {
|
||||||
const nodes = []
|
const nodes = []
|
||||||
const edges = []
|
const edges = []
|
||||||
const seen = new Map()
|
const seen = new Map()
|
||||||
|
const edgeSeen = new Map()
|
||||||
return {
|
return {
|
||||||
nodes,
|
nodes,
|
||||||
edges,
|
edges,
|
||||||
@@ -23,7 +35,7 @@ function makeCollector () {
|
|||||||
const node = {
|
const node = {
|
||||||
id,
|
id,
|
||||||
kind,
|
kind,
|
||||||
label: entity.name,
|
label: entity.name || '',
|
||||||
image: entity.catalogue_images?.[0] || null,
|
image: entity.catalogue_images?.[0] || null,
|
||||||
entity: { ...entity, kind },
|
entity: { ...entity, kind },
|
||||||
}
|
}
|
||||||
@@ -32,73 +44,102 @@ function makeCollector () {
|
|||||||
}
|
}
|
||||||
return seen.get(id)
|
return seen.get(id)
|
||||||
},
|
},
|
||||||
addEdge (from, to) {
|
addEdge (from, to, certain) {
|
||||||
edges.push({ from, to })
|
const key = `${from}\u0000${to}`
|
||||||
|
if (edgeSeen.has(key)) {
|
||||||
|
edgeSeen.get(key).certain = edgeSeen.get(key).certain && Boolean(certain)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
const edge = { from, to, certain: Boolean(certain) }
|
||||||
|
edgeSeen.set(key, edge)
|
||||||
|
edges.push(edge)
|
||||||
},
|
},
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
function layout (collector, columns) {
|
function distinctValues (items) {
|
||||||
return computeColumnLayout(collector.nodes, collector.edges, {
|
const seen = new Map()
|
||||||
columnOf: node => columns[node.kind] ?? 0,
|
for (const item of items) {
|
||||||
columnWidth: 220,
|
if (item && !seen.has(item.id)) seen.set(item.id, item)
|
||||||
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)
|
return [...seen.values()]
|
||||||
}
|
}
|
||||||
|
|
||||||
export function buildTerritoryGraph (provenance) {
|
function isCertain (values) {
|
||||||
const g = makeCollector()
|
return values.length <= 1
|
||||||
|
}
|
||||||
|
|
||||||
|
function wirePath (collector, path, certainties) {
|
||||||
|
for (let index = 0; index < path.length - 1; index++) {
|
||||||
|
const to = path[index + 1]
|
||||||
|
const kind = to.split(':')[0]
|
||||||
|
collector.addEdge(path[index], to, certainties[kind])
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
export function buildProvenanceGraph (provenance, kinds = DEFAULT_KINDS) {
|
||||||
|
const active = new Set(kinds)
|
||||||
|
const collector = makeCollector()
|
||||||
|
|
||||||
for (const entry of provenance || []) {
|
for (const entry of provenance || []) {
|
||||||
if (!entry.product) continue
|
if (!entry.product) continue
|
||||||
const product = g.addNode('product', entry.product)
|
const relations = (entry.suppliers || []).filter(rel => rel.supplier)
|
||||||
for (const rel of entry.suppliers || []) {
|
if (relations.length === 0) continue
|
||||||
if (!rel.supplier) continue
|
|
||||||
const supplier = g.addNode('supplier', rel.supplier)
|
const product = active.has('product') ? collector.addNode('product', entry.product) : null
|
||||||
g.addEdge(product.id, supplier.id)
|
const suppliersActive = active.has('supplier')
|
||||||
if (rel.municipality) {
|
|
||||||
const municipality = g.addNode('municipality', rel.municipality)
|
const certainties = {
|
||||||
g.addEdge(supplier.id, municipality.id)
|
municipality: isCertain(distinctValues(relations.map(rel => rel.municipality))),
|
||||||
if (rel.department) {
|
department: isCertain(distinctValues(relations.map(rel => rel.department))),
|
||||||
const department = g.addNode('department', rel.department)
|
country: isCertain(distinctValues(relations.map(rel => rel.country))),
|
||||||
g.addEdge(municipality.id, department.id)
|
organization: isCertain(distinctValues(relations.map(rel => rel.organization))),
|
||||||
if (rel.country) {
|
}
|
||||||
const country = g.addNode('country', rel.country)
|
|
||||||
g.addEdge(department.id, country.id)
|
for (const rel of relations) {
|
||||||
}
|
if (suppliersActive) collector.addNode('supplier', rel.supplier)
|
||||||
|
if (active.has('municipality') && rel.municipality) collector.addNode('municipality', rel.municipality)
|
||||||
|
if (active.has('department') && rel.department) collector.addNode('department', rel.department)
|
||||||
|
if (active.has('country') && rel.country) collector.addNode('country', rel.country)
|
||||||
|
if (active.has('organization') && rel.organization) collector.addNode('organization', rel.organization)
|
||||||
|
}
|
||||||
|
|
||||||
|
if (suppliersActive && product) {
|
||||||
|
if (relations.length === 1) {
|
||||||
|
collector.addEdge(product.id, `supplier:${relations[0].supplier.id}`, true)
|
||||||
|
} else {
|
||||||
|
const junction = collector.addNode('junction', { id: entry.product.id, name: '' })
|
||||||
|
collector.addEdge(product.id, junction.id, true)
|
||||||
|
for (const rel of relations) {
|
||||||
|
collector.addEdge(junction.id, `supplier:${rel.supplier.id}`, false)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
for (const rel of relations) {
|
||||||
|
const path = []
|
||||||
|
if (suppliersActive) {
|
||||||
|
path.push(`supplier:${rel.supplier.id}`)
|
||||||
|
} else if (product) {
|
||||||
|
path.push(product.id)
|
||||||
|
}
|
||||||
|
for (const level of TERRITORY_ORDER) {
|
||||||
|
if (active.has(level) && rel[level]) path.push(`${level}:${rel[level].id}`)
|
||||||
|
}
|
||||||
|
wirePath(collector, path, certainties)
|
||||||
|
}
|
||||||
|
|
||||||
|
if (active.has('organization')) {
|
||||||
|
for (const rel of relations) {
|
||||||
|
if (!rel.organization) continue
|
||||||
|
const source = suppliersActive ? `supplier:${rel.supplier.id}` : (product ? product.id : null)
|
||||||
|
if (source) collector.addEdge(source, `organization:${rel.organization.id}`, certainties.organization)
|
||||||
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
return layout(g, TERRITORY_COLUMNS)
|
return { nodes: collector.nodes, edges: collector.edges }
|
||||||
}
|
}
|
||||||
|
|
||||||
export function hasAnySupplier (provenance) {
|
export function hasAnySupplier (provenance) {
|
||||||
return (provenance || []).some(entry => (entry.suppliers || []).length > 0)
|
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
|
|
||||||
)
|
|
||||||
)
|
|
||||||
}
|
|
||||||
|
|||||||
80
src/components/provenance/provenance-vis.js
Normal file
80
src/components/provenance/provenance-vis.js
Normal file
@@ -0,0 +1,80 @@
|
|||||||
|
/**
|
||||||
|
* Adapta el modelo de grafo de provenance ({ id, kind, label, image, entity }
|
||||||
|
* y { from, to, certain }) al formato de vis-network, incluyendo la semántica
|
||||||
|
* de certeza: arista cierta = sólida, arista dudosa = discontinua.
|
||||||
|
*/
|
||||||
|
|
||||||
|
const COLORS = {
|
||||||
|
product: '#26a69a',
|
||||||
|
supplier: '#42a5f5',
|
||||||
|
organization: '#ffb74d',
|
||||||
|
municipality: '#66bb6a',
|
||||||
|
department: '#5c6bc0',
|
||||||
|
country: '#ab47bc',
|
||||||
|
junction: '#78909c',
|
||||||
|
}
|
||||||
|
|
||||||
|
const PRODUCT_SPACING = 110
|
||||||
|
const COLUMN_X = {
|
||||||
|
product: -240,
|
||||||
|
junction: -160,
|
||||||
|
supplier: -80,
|
||||||
|
organization: 80,
|
||||||
|
municipality: 240,
|
||||||
|
department: 400,
|
||||||
|
country: 560,
|
||||||
|
}
|
||||||
|
|
||||||
|
export const KIND_COLORS = COLORS
|
||||||
|
|
||||||
|
export function toVisNodes (nodes) {
|
||||||
|
const products = nodes.filter(node => node.kind === 'product')
|
||||||
|
const productY = new Map()
|
||||||
|
products.forEach((node, index) => {
|
||||||
|
productY.set(node.entity.id, (index - (products.length - 1) / 2) * PRODUCT_SPACING)
|
||||||
|
})
|
||||||
|
return nodes.map(node => {
|
||||||
|
const color = COLORS[node.kind] || '#cfd8dc'
|
||||||
|
const { image, ...rest } = node
|
||||||
|
if (node.kind === 'junction') {
|
||||||
|
return {
|
||||||
|
...rest,
|
||||||
|
shape: 'dot',
|
||||||
|
color,
|
||||||
|
size: 10,
|
||||||
|
label: '',
|
||||||
|
x: COLUMN_X.junction,
|
||||||
|
y: productY.get(node.entity.id),
|
||||||
|
fixed: { x: true, y: true },
|
||||||
|
}
|
||||||
|
}
|
||||||
|
const base = image
|
||||||
|
? { ...rest, image, shape: 'circularImage', borderWidth: 2 }
|
||||||
|
: { ...rest, shape: 'dot', color, borderWidth: 2 }
|
||||||
|
if (node.kind === 'product') {
|
||||||
|
return {
|
||||||
|
...base,
|
||||||
|
x: COLUMN_X.product,
|
||||||
|
y: productY.get(node.entity.id),
|
||||||
|
fixed: { x: true, y: true },
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return { ...base, x: COLUMN_X[node.kind], fixed: { x: true, y: false } }
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
export function toVisEdges (edges) {
|
||||||
|
return edges.map(edge => ({
|
||||||
|
from: edge.from,
|
||||||
|
to: edge.to,
|
||||||
|
dashes: !edge.certain,
|
||||||
|
}))
|
||||||
|
}
|
||||||
|
|
||||||
|
export const chartOptions = {
|
||||||
|
nodes: { font: { size: 13, color: '#263238' } },
|
||||||
|
edges: { color: { color: '#546e7a' } },
|
||||||
|
physics: {
|
||||||
|
barnesHut: { gravitationalConstant: -4000, springLength: 120, springConstant: 0.02 },
|
||||||
|
},
|
||||||
|
}
|
||||||
@@ -116,6 +116,39 @@
|
|||||||
</v-card>
|
</v-card>
|
||||||
</v-col>
|
</v-col>
|
||||||
|
|
||||||
|
<v-col cols="12" md="6">
|
||||||
|
<v-card elevation="2">
|
||||||
|
<v-card-title class="bg-indigo text-white">🏷️ Categorías creadas ({{ result.created_categories?.length || 0 }})</v-card-title>
|
||||||
|
<v-card-text>
|
||||||
|
<v-data-table
|
||||||
|
:items="formatResults(result.created_categories)"
|
||||||
|
density="compact"
|
||||||
|
:headers="[
|
||||||
|
{ title: 'ID', key: 'id' },
|
||||||
|
{ title: 'Nombre', key: 'name' }
|
||||||
|
]"
|
||||||
|
></v-data-table>
|
||||||
|
</v-card-text>
|
||||||
|
</v-card>
|
||||||
|
</v-col>
|
||||||
|
|
||||||
|
<v-col cols="12" md="6">
|
||||||
|
<v-card elevation="2">
|
||||||
|
<v-card-title class="bg-deep-purple text-white">♻️ Categorías actualizadas ({{ result.updated_categories?.length || 0 }})</v-card-title>
|
||||||
|
<v-card-text>
|
||||||
|
<v-data-table
|
||||||
|
:items="formatResults(result.updated_categories)"
|
||||||
|
density="compact"
|
||||||
|
:headers="[
|
||||||
|
{ title: 'ID', key: 'id' },
|
||||||
|
{ title: 'Nombre', key: 'name' },
|
||||||
|
{ title: 'Detalle', key: 'detail' }
|
||||||
|
]"
|
||||||
|
></v-data-table>
|
||||||
|
</v-card-text>
|
||||||
|
</v-card>
|
||||||
|
</v-col>
|
||||||
|
|
||||||
<v-col cols="12" class="text-center mt-4">
|
<v-col cols="12" class="text-center mt-4">
|
||||||
<v-btn color="primary" @click="$router.push('/')">
|
<v-btn color="primary" @click="$router.push('/')">
|
||||||
Volver al inicio
|
Volver al inicio
|
||||||
|
|||||||
@@ -1,76 +0,0 @@
|
|||||||
/**
|
|
||||||
* 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,
|
|
||||||
},
|
|
||||||
})),
|
|
||||||
]
|
|
||||||
}
|
|
||||||
80
tests/unit/components/NavBar.spec.js
Normal file
80
tests/unit/components/NavBar.spec.js
Normal file
@@ -0,0 +1,80 @@
|
|||||||
|
import { beforeEach, describe, expect, it, vi } from 'vitest'
|
||||||
|
import { flushPromises, mount } from '@vue/test-utils'
|
||||||
|
import { createPinia, setActivePinia } from 'pinia'
|
||||||
|
import NavBar from '@/components/NavBar.vue'
|
||||||
|
import vuetify from '@/plugins/vuetify'
|
||||||
|
|
||||||
|
import AuthService from '@/services/auth'
|
||||||
|
|
||||||
|
vi.mock('@/services/auth', () => ({
|
||||||
|
default: {
|
||||||
|
isAuthenticated: vi.fn(),
|
||||||
|
logout: vi.fn(),
|
||||||
|
},
|
||||||
|
}))
|
||||||
|
|
||||||
|
function mountNavBar (api) {
|
||||||
|
const pinia = createPinia()
|
||||||
|
setActivePinia(pinia)
|
||||||
|
const wrapper = mount(NavBar, {
|
||||||
|
global: {
|
||||||
|
plugins: [pinia, vuetify],
|
||||||
|
provide: { api },
|
||||||
|
mocks: { $router: { push: vi.fn() } },
|
||||||
|
stubs: {
|
||||||
|
VAppBar: { template: '<div><slot /></div>' },
|
||||||
|
VNavigationDrawer: { template: '<div><slot /></div>' },
|
||||||
|
},
|
||||||
|
},
|
||||||
|
})
|
||||||
|
return { wrapper }
|
||||||
|
}
|
||||||
|
|
||||||
|
describe('NavBar', () => {
|
||||||
|
beforeEach(() => {
|
||||||
|
vi.clearAllMocks()
|
||||||
|
localStorage.clear()
|
||||||
|
})
|
||||||
|
|
||||||
|
it('sin sesión muestra el botón de login y no el menú de administración', async () => {
|
||||||
|
AuthService.isAuthenticated.mockReturnValue(false)
|
||||||
|
const { wrapper } = mountNavBar({ getCurrentUser: vi.fn() })
|
||||||
|
await flushPromises()
|
||||||
|
|
||||||
|
expect(wrapper.text()).toContain('Login')
|
||||||
|
expect(wrapper.text()).not.toContain('Administracion')
|
||||||
|
})
|
||||||
|
|
||||||
|
it('el administrador ve los ítems de administración de provenance', async () => {
|
||||||
|
AuthService.isAuthenticated.mockReturnValue(true)
|
||||||
|
const api = {
|
||||||
|
getCurrentUser: vi.fn().mockResolvedValue({ username: 'admin', role: 'administrator' }),
|
||||||
|
}
|
||||||
|
const { wrapper } = mountNavBar(api)
|
||||||
|
await flushPromises()
|
||||||
|
|
||||||
|
expect(api.getCurrentUser).toHaveBeenCalled()
|
||||||
|
expect(wrapper.text()).toContain('Administracion')
|
||||||
|
|
||||||
|
const adminItem = wrapper.findAll('.v-list-item')
|
||||||
|
.find(item => item.text().includes('Administracion'))
|
||||||
|
await adminItem.trigger('click')
|
||||||
|
|
||||||
|
expect(wrapper.text()).toContain('Organizaciones')
|
||||||
|
expect(wrapper.text()).toContain('Proveedores')
|
||||||
|
expect(wrapper.text()).toContain('Geografía')
|
||||||
|
})
|
||||||
|
|
||||||
|
it('el usuario público no ve el menú de administración y no ve "Comprar"', async () => {
|
||||||
|
AuthService.isAuthenticated.mockReturnValue(true)
|
||||||
|
const api = {
|
||||||
|
getCurrentUser: vi.fn().mockResolvedValue({ username: 'cliente', role: 'publico' }),
|
||||||
|
}
|
||||||
|
const { wrapper } = mountNavBar(api)
|
||||||
|
await flushPromises()
|
||||||
|
|
||||||
|
expect(wrapper.text()).not.toContain('Administracion')
|
||||||
|
expect(wrapper.text()).not.toContain('Comprar')
|
||||||
|
expect(wrapper.text()).toContain('Ver Catálogo')
|
||||||
|
})
|
||||||
|
})
|
||||||
@@ -1,93 +0,0 @@
|
|||||||
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))
|
|
||||||
})
|
|
||||||
})
|
|
||||||
157
tests/unit/components/graph/VisChart.spec.js
Normal file
157
tests/unit/components/graph/VisChart.spec.js
Normal file
@@ -0,0 +1,157 @@
|
|||||||
|
import { beforeEach, describe, expect, it, vi } from 'vitest'
|
||||||
|
import { mount } from '@vue/test-utils'
|
||||||
|
import VisChart from '@/components/graph/VisChart.vue'
|
||||||
|
|
||||||
|
const vis = vi.hoisted(() => {
|
||||||
|
const networkInstance = {
|
||||||
|
on: vi.fn(),
|
||||||
|
once: vi.fn(),
|
||||||
|
setData: vi.fn(),
|
||||||
|
setOptions: vi.fn(),
|
||||||
|
fit: vi.fn(),
|
||||||
|
destroy: vi.fn(),
|
||||||
|
getPositions: vi.fn(() => ({})),
|
||||||
|
moveNode: vi.fn(),
|
||||||
|
}
|
||||||
|
const dataSetInstance = {
|
||||||
|
get: vi.fn(),
|
||||||
|
}
|
||||||
|
return {
|
||||||
|
networkInstance,
|
||||||
|
dataSetInstance,
|
||||||
|
Network: vi.fn(() => networkInstance),
|
||||||
|
DataSet: vi.fn(() => dataSetInstance),
|
||||||
|
}
|
||||||
|
})
|
||||||
|
|
||||||
|
vi.mock('vis-network/standalone', () => ({
|
||||||
|
Network: vis.Network,
|
||||||
|
DataSet: vis.DataSet,
|
||||||
|
}))
|
||||||
|
|
||||||
|
function handlerFor (mock, eventName) {
|
||||||
|
const call = mock.mock.calls.find(args => args[0] === eventName)
|
||||||
|
return call ? call[1] : null
|
||||||
|
}
|
||||||
|
|
||||||
|
describe('VisChart', () => {
|
||||||
|
beforeEach(() => {
|
||||||
|
vi.clearAllMocks()
|
||||||
|
})
|
||||||
|
|
||||||
|
it('crea la red con los nodos y aristas recibidos', () => {
|
||||||
|
const nodes = [{ id: 'product:1', label: 'Panela' }]
|
||||||
|
const edges = [{ from: 'product:1', to: 'supplier:5', dashes: true }]
|
||||||
|
mount(VisChart, { props: { nodes, edges } })
|
||||||
|
|
||||||
|
expect(vis.Network).toHaveBeenCalledTimes(1)
|
||||||
|
const [container, , options] = vis.Network.mock.calls[0]
|
||||||
|
expect(container).toBeInstanceOf(HTMLElement)
|
||||||
|
expect(options.physics.stabilization.enabled).toBe(true)
|
||||||
|
expect(vis.dataSetInstance.get).toBeDefined()
|
||||||
|
const data = vis.networkInstance.setData.mock.calls[0][0]
|
||||||
|
expect(data.nodes).toBe(vis.dataSetInstance)
|
||||||
|
expect(data.edges).toBe(vis.dataSetInstance)
|
||||||
|
})
|
||||||
|
|
||||||
|
it('mezcla las opciones base con las recibidas', () => {
|
||||||
|
mount(VisChart, {
|
||||||
|
props: {
|
||||||
|
nodes: [],
|
||||||
|
edges: [],
|
||||||
|
options: { nodes: { font: { size: 16 } }, physics: { stabilization: { iterations: 100 } } },
|
||||||
|
},
|
||||||
|
})
|
||||||
|
|
||||||
|
const options = vis.Network.mock.calls[0][2]
|
||||||
|
expect(options.nodes.font.size).toBe(16)
|
||||||
|
expect(options.nodes.shape).toBe('dot')
|
||||||
|
expect(options.physics.stabilization.iterations).toBe(100)
|
||||||
|
expect(options.physics.barnesHut.springLength).toBe(140)
|
||||||
|
})
|
||||||
|
|
||||||
|
it('emite select con el nodo al hacer click', () => {
|
||||||
|
const wrapper = mount(VisChart, { props: { nodes: [{ id: 'supplier:5', kind: 'supplier' }], edges: [] } })
|
||||||
|
|
||||||
|
vis.dataSetInstance.get.mockReturnValue({ id: 'supplier:5', kind: 'supplier', label: 'La Mesa' })
|
||||||
|
handlerFor(vis.networkInstance.on, 'click')({ nodes: ['supplier:5'] })
|
||||||
|
|
||||||
|
expect(wrapper.emitted('select')[0][0]).toEqual({ id: 'supplier:5', kind: 'supplier', label: 'La Mesa' })
|
||||||
|
})
|
||||||
|
|
||||||
|
it('no emite select cuando el click no cae sobre un nodo', () => {
|
||||||
|
const wrapper = mount(VisChart, { props: { nodes: [], edges: [] } })
|
||||||
|
|
||||||
|
handlerFor(vis.networkInstance.on, 'click')({ nodes: [] })
|
||||||
|
|
||||||
|
expect(wrapper.emitted('select')).toBeUndefined()
|
||||||
|
})
|
||||||
|
|
||||||
|
it('desactiva la física y ajusta la vista cuando la estabilización termina', () => {
|
||||||
|
mount(VisChart, { props: { nodes: [], edges: [] } })
|
||||||
|
|
||||||
|
const onStabilized = handlerFor(vis.networkInstance.once, 'stabilizationIterationsDone')
|
||||||
|
expect(onStabilized).toBeDefined()
|
||||||
|
onStabilized()
|
||||||
|
|
||||||
|
expect(vis.networkInstance.setOptions).toHaveBeenCalledWith({ physics: { enabled: false } })
|
||||||
|
expect(vis.networkInstance.fit).toHaveBeenCalled()
|
||||||
|
})
|
||||||
|
|
||||||
|
it('separa verticalmente los nodos de una misma columna tras estabilizar', () => {
|
||||||
|
vis.networkInstance.getPositions.mockReturnValue({
|
||||||
|
'supplier:5': { x: 0, y: 100 },
|
||||||
|
'supplier:6': { x: 0, y: 112 },
|
||||||
|
'municipality:7': { x: 240, y: 100 },
|
||||||
|
'product:1': { x: -240, y: 60 },
|
||||||
|
})
|
||||||
|
mount(VisChart, { props: { nodes: [], edges: [], minVerticalSpacing: 70 } })
|
||||||
|
|
||||||
|
const onStabilized = handlerFor(vis.networkInstance.once, 'stabilizationIterationsDone')
|
||||||
|
onStabilized()
|
||||||
|
|
||||||
|
expect(vis.networkInstance.moveNode).toHaveBeenCalledWith('supplier:6', 0, 170)
|
||||||
|
expect(vis.networkInstance.moveNode).not.toHaveBeenCalledWith('supplier:5', 0, expect.anything())
|
||||||
|
expect(vis.networkInstance.moveNode).not.toHaveBeenCalledWith('municipality:7', 240, expect.anything())
|
||||||
|
expect(vis.networkInstance.moveNode).not.toHaveBeenCalledWith('product:1', -240, expect.anything())
|
||||||
|
})
|
||||||
|
|
||||||
|
it('no separa nodos cuando no se indica espaciado vertical mínimo', () => {
|
||||||
|
vis.networkInstance.getPositions.mockReturnValue({
|
||||||
|
'supplier:5': { x: 0, y: 100 },
|
||||||
|
'supplier:6': { x: 0, y: 112 },
|
||||||
|
})
|
||||||
|
mount(VisChart, { props: { nodes: [], edges: [] } })
|
||||||
|
|
||||||
|
const onStabilized = handlerFor(vis.networkInstance.once, 'stabilizationIterationsDone')
|
||||||
|
onStabilized()
|
||||||
|
|
||||||
|
expect(vis.networkInstance.moveNode).not.toHaveBeenCalled()
|
||||||
|
})
|
||||||
|
|
||||||
|
it('vuelve a estabilizar el grafo cuando cambian los nodos o aristas', async () => {
|
||||||
|
const wrapper = mount(VisChart, { props: { nodes: [{ id: 'product:1' }], edges: [] } })
|
||||||
|
expect(vis.Network).toHaveBeenCalledTimes(1)
|
||||||
|
expect(vis.networkInstance.destroy).not.toHaveBeenCalled()
|
||||||
|
|
||||||
|
await wrapper.setProps({ nodes: [{ id: 'product:2' }], edges: [{ from: 'product:2', to: 'supplier:5' }] })
|
||||||
|
|
||||||
|
expect(vis.networkInstance.destroy).toHaveBeenCalled()
|
||||||
|
expect(vis.Network).toHaveBeenCalledTimes(2)
|
||||||
|
expect(vis.networkInstance.setData).toHaveBeenCalledTimes(2)
|
||||||
|
})
|
||||||
|
|
||||||
|
it('aplica la altura recibida al contenedor', () => {
|
||||||
|
const wrapper = mount(VisChart, { props: { height: 340 } })
|
||||||
|
|
||||||
|
expect(wrapper.element.style.height).toBe('340px')
|
||||||
|
})
|
||||||
|
|
||||||
|
it('destruye la red al desmontar', () => {
|
||||||
|
const wrapper = mount(VisChart, { props: { nodes: [], edges: [] } })
|
||||||
|
|
||||||
|
wrapper.unmount()
|
||||||
|
|
||||||
|
expect(vis.networkInstance.destroy).toHaveBeenCalled()
|
||||||
|
})
|
||||||
|
})
|
||||||
@@ -1,87 +0,0 @@
|
|||||||
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')
|
|
||||||
})
|
|
||||||
})
|
|
||||||
@@ -1,84 +0,0 @@
|
|||||||
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')
|
|
||||||
})
|
|
||||||
})
|
|
||||||
164
tests/unit/components/provenance/ProvenanceGraph.spec.js
Normal file
164
tests/unit/components/provenance/ProvenanceGraph.spec.js
Normal file
@@ -0,0 +1,164 @@
|
|||||||
|
import { beforeEach, describe, expect, it, vi } from 'vitest'
|
||||||
|
import { mount } from '@vue/test-utils'
|
||||||
|
import { nextTick } from 'vue'
|
||||||
|
import ProvenanceDetailModal from '@/components/provenance/ProvenanceDetailModal.vue'
|
||||||
|
import ProvenanceGraph from '@/components/provenance/ProvenanceGraph.vue'
|
||||||
|
import vuetify from '@/plugins/vuetify'
|
||||||
|
|
||||||
|
vi.mock('@/components/graph/VisChart.vue', () => ({
|
||||||
|
default: {
|
||||||
|
name: 'VisChart',
|
||||||
|
template: '<div class="vis-chart-stub" />',
|
||||||
|
props: ['nodes', 'edges', 'height', 'options', 'minVerticalSpacing'],
|
||||||
|
},
|
||||||
|
}))
|
||||||
|
|
||||||
|
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' },
|
||||||
|
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' },
|
||||||
|
},
|
||||||
|
],
|
||||||
|
},
|
||||||
|
]
|
||||||
|
|
||||||
|
function mountGraph (props = {}) {
|
||||||
|
return mount(ProvenanceGraph, {
|
||||||
|
props: { provenance, ...props },
|
||||||
|
global: { plugins: [vuetify] },
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
function visChart (wrapper) {
|
||||||
|
return wrapper.findComponent({ name: 'VisChart' })
|
||||||
|
}
|
||||||
|
|
||||||
|
function checkbox (wrapper, label) {
|
||||||
|
return wrapper.findAllComponents({ name: 'VCheckbox' }).find(cb => cb.text().trim() === label)
|
||||||
|
}
|
||||||
|
|
||||||
|
async function setKinds (wrapper, kinds) {
|
||||||
|
checkbox(wrapper, 'Productos').vm.$emit('update:modelValue', kinds)
|
||||||
|
await nextTick()
|
||||||
|
}
|
||||||
|
|
||||||
|
describe('ProvenanceGraph', () => {
|
||||||
|
beforeEach(() => {
|
||||||
|
vi.clearAllMocks()
|
||||||
|
})
|
||||||
|
|
||||||
|
it('por defecto grafica solo productos y proveedores', () => {
|
||||||
|
const wrapper = mountGraph()
|
||||||
|
|
||||||
|
const nodeKinds = visChart(wrapper).props('nodes').map(node => node.kind)
|
||||||
|
expect(nodeKinds).toEqual(['product', 'supplier'])
|
||||||
|
const edges = visChart(wrapper).props('edges')
|
||||||
|
expect(edges.find(edge => edge.from === 'product:1' && edge.to === 'supplier:5').dashes).toBe(false)
|
||||||
|
})
|
||||||
|
|
||||||
|
it('pide separación vertical mínima equivalente al círculo más una línea de label', () => {
|
||||||
|
const wrapper = mountGraph()
|
||||||
|
|
||||||
|
expect(visChart(wrapper).props('minVerticalSpacing')).toBe(70)
|
||||||
|
})
|
||||||
|
|
||||||
|
it('muestra un checkbox por cada nivel con productos y proveedores activos', () => {
|
||||||
|
const wrapper = mountGraph()
|
||||||
|
|
||||||
|
const labels = wrapper.findAllComponents({ name: 'VCheckbox' }).map(cb => cb.text().trim())
|
||||||
|
expect(labels).toEqual(['Productos', 'Proveedores', 'Organizaciones', 'Municipios', 'Departamentos', 'País'])
|
||||||
|
})
|
||||||
|
|
||||||
|
it('dibuja un círculo de color junto a cada checkbox como leyenda', () => {
|
||||||
|
const wrapper = mountGraph()
|
||||||
|
|
||||||
|
const dots = wrapper.findAll('.legend-dot')
|
||||||
|
expect(dots).toHaveLength(6)
|
||||||
|
expect(dots[0].element.style.backgroundColor).toBe('rgb(38, 166, 154)')
|
||||||
|
expect(dots[1].element.style.backgroundColor).toBe('rgb(66, 165, 245)')
|
||||||
|
expect(dots[2].element.style.backgroundColor).toBe('rgb(255, 183, 77)')
|
||||||
|
})
|
||||||
|
|
||||||
|
it('al activar municipios agrega nodos de municipio y la arista proveedor→municipio', async () => {
|
||||||
|
const wrapper = mountGraph()
|
||||||
|
|
||||||
|
await setKinds(wrapper, ['product', 'supplier', 'municipality'])
|
||||||
|
|
||||||
|
const nodeIds = visChart(wrapper).props('nodes').map(node => node.id)
|
||||||
|
expect(nodeIds).toContain('municipality:7')
|
||||||
|
const edges = visChart(wrapper).props('edges')
|
||||||
|
expect(edges.find(edge => edge.from === 'supplier:5' && edge.to === 'municipality:7').dashes).toBe(false)
|
||||||
|
})
|
||||||
|
|
||||||
|
it('con país activo crea el nodo país', async () => {
|
||||||
|
const wrapper = mountGraph()
|
||||||
|
|
||||||
|
await setKinds(wrapper, ['product', 'supplier', 'country'])
|
||||||
|
|
||||||
|
expect(visChart(wrapper).props('nodes').map(node => node.id)).toContain('country:1')
|
||||||
|
})
|
||||||
|
|
||||||
|
it('al desactivar productos no se crean nodos de producto', async () => {
|
||||||
|
const wrapper = mountGraph()
|
||||||
|
|
||||||
|
await setKinds(wrapper, ['supplier', 'municipality', 'department'])
|
||||||
|
|
||||||
|
const nodeKinds = visChart(wrapper).props('nodes').map(node => node.kind)
|
||||||
|
expect(nodeKinds).not.toContain('product')
|
||||||
|
expect(nodeKinds).not.toContain('junction')
|
||||||
|
})
|
||||||
|
|
||||||
|
it('avisa cuando no queda ningún nivel seleccionado', async () => {
|
||||||
|
const wrapper = mountGraph()
|
||||||
|
|
||||||
|
await setKinds(wrapper, [])
|
||||||
|
|
||||||
|
expect(visChart(wrapper).exists()).toBe(false)
|
||||||
|
expect(wrapper.text()).toContain('Selecciona al menos un elemento')
|
||||||
|
})
|
||||||
|
|
||||||
|
it('muestra mensaje de próximamente cuando ningún producto tiene proveedores', () => {
|
||||||
|
const wrapper = mountGraph({
|
||||||
|
provenance: [{ product: { id: 1, name: 'Panela' }, suppliers: [] }],
|
||||||
|
})
|
||||||
|
|
||||||
|
expect(visChart(wrapper).exists()).toBe(false)
|
||||||
|
expect(wrapper.text()).toContain('próximamente')
|
||||||
|
})
|
||||||
|
|
||||||
|
it('abre el modal de detalle al seleccionar un proveedor', async () => {
|
||||||
|
const wrapper = mountGraph()
|
||||||
|
|
||||||
|
await visChart(wrapper).vm.$emit('select', { id: 'supplier:5', 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')
|
||||||
|
})
|
||||||
|
|
||||||
|
it('ignora la selección del punto de disyunción', async () => {
|
||||||
|
const provenanceWithTwoSuppliers = [
|
||||||
|
{
|
||||||
|
product: { id: 1, name: 'Panela' },
|
||||||
|
suppliers: [
|
||||||
|
{ supplier: { id: 5, name: 'A' }, municipality: { id: 7, name: 'La Mesa' } },
|
||||||
|
{ supplier: { id: 6, name: 'B' }, municipality: { id: 8, name: 'San Antonio' } },
|
||||||
|
],
|
||||||
|
},
|
||||||
|
]
|
||||||
|
const wrapper = mountGraph({ provenance: provenanceWithTwoSuppliers })
|
||||||
|
|
||||||
|
await visChart(wrapper).vm.$emit('select', { id: 'junction:1', kind: 'junction', label: '' })
|
||||||
|
|
||||||
|
expect(wrapper.findComponent(ProvenanceDetailModal).props('visible')).toBe(false)
|
||||||
|
})
|
||||||
|
})
|
||||||
402
tests/unit/components/provenance/ProvenanceMap.spec.js
Normal file
402
tests/unit/components/provenance/ProvenanceMap.spec.js
Normal file
@@ -0,0 +1,402 @@
|
|||||||
|
import { beforeEach, describe, expect, it, vi } from 'vitest'
|
||||||
|
import { flushPromises, mount } from '@vue/test-utils'
|
||||||
|
import { nextTick } from 'vue'
|
||||||
|
import { createPinia, setActivePinia } from 'pinia'
|
||||||
|
import ProvenanceMap from '@/components/provenance/ProvenanceMap.vue'
|
||||||
|
import vuetify from '@/plugins/vuetify'
|
||||||
|
|
||||||
|
const leaflet = vi.hoisted(() => {
|
||||||
|
const markers = []
|
||||||
|
const polylines = []
|
||||||
|
const layers = []
|
||||||
|
function makeLayer (type) {
|
||||||
|
const layer = {
|
||||||
|
type,
|
||||||
|
addTo: vi.fn(function () { return this }),
|
||||||
|
on: vi.fn(),
|
||||||
|
bindTooltip: vi.fn(function () { return this }),
|
||||||
|
bindPopup: vi.fn(function () { return this }),
|
||||||
|
setPopupContent: vi.fn(),
|
||||||
|
openPopup: vi.fn(),
|
||||||
|
closePopup: vi.fn(),
|
||||||
|
remove: vi.fn(),
|
||||||
|
getLatLng: vi.fn(function () { return this.pos }),
|
||||||
|
setLatLng: vi.fn(),
|
||||||
|
}
|
||||||
|
layers.push(layer)
|
||||||
|
return layer
|
||||||
|
}
|
||||||
|
const map = {
|
||||||
|
setView: vi.fn(function () { return this }),
|
||||||
|
fitBounds: vi.fn(),
|
||||||
|
flyTo: vi.fn(),
|
||||||
|
remove: vi.fn(),
|
||||||
|
invalidateSize: vi.fn(),
|
||||||
|
on: vi.fn(),
|
||||||
|
getZoom: vi.fn(() => 8),
|
||||||
|
}
|
||||||
|
const bounds = { extend: vi.fn(), isValid: vi.fn(() => true) }
|
||||||
|
return {
|
||||||
|
markers,
|
||||||
|
polylines,
|
||||||
|
layers,
|
||||||
|
map,
|
||||||
|
bounds,
|
||||||
|
L: {
|
||||||
|
map: vi.fn(() => map),
|
||||||
|
tileLayer: vi.fn(() => makeLayer('tileLayer')),
|
||||||
|
marker: vi.fn((pos, opts) => {
|
||||||
|
const marker = makeLayer('marker')
|
||||||
|
marker.pos = pos
|
||||||
|
marker.opts = opts
|
||||||
|
markers.push(marker)
|
||||||
|
return marker
|
||||||
|
}),
|
||||||
|
divIcon: vi.fn(opts => opts),
|
||||||
|
polyline: vi.fn((points, opts) => {
|
||||||
|
const polyline = makeLayer('polyline')
|
||||||
|
polyline.points = points
|
||||||
|
polyline.opts = opts
|
||||||
|
polylines.push(polyline)
|
||||||
|
return polyline
|
||||||
|
}),
|
||||||
|
latLngBounds: vi.fn(() => bounds),
|
||||||
|
},
|
||||||
|
}
|
||||||
|
})
|
||||||
|
|
||||||
|
vi.mock('leaflet', () => ({ default: leaflet.L }))
|
||||||
|
|
||||||
|
const settings = { latitude: 4.6, longitude: -74.08, address: 'Cra 1 #2-3' }
|
||||||
|
|
||||||
|
const provenance = [
|
||||||
|
{
|
||||||
|
product: { id: 1, name: 'Panela regional', catalogue_images: ['http://localhost/media/panela.jpg'] },
|
||||||
|
suppliers: [
|
||||||
|
{
|
||||||
|
supplier: { id: 5, name: 'Asociación La Mesa' },
|
||||||
|
organization: { id: 3, name: 'Red de Economía Solidaria' },
|
||||||
|
municipality: { id: 7, name: 'Santa Bárbara', latitude: 6.23, longitude: -75.56 },
|
||||||
|
},
|
||||||
|
],
|
||||||
|
},
|
||||||
|
{
|
||||||
|
product: { id: 2, name: 'Arroz blanco', catalogue_images: [] },
|
||||||
|
suppliers: [
|
||||||
|
{ supplier: { id: 6, name: 'Campesinos del Oriente' }, municipality: { id: 8, name: 'La Mesa', latitude: 4.86, longitude: -74.63 } },
|
||||||
|
{ supplier: { id: 7, name: 'Finca El Paraíso' }, municipality: { id: 9, name: 'San Antonio', latitude: 6.22, longitude: -75.57 } },
|
||||||
|
],
|
||||||
|
},
|
||||||
|
]
|
||||||
|
|
||||||
|
const sameMuni = [
|
||||||
|
{
|
||||||
|
product: { id: 1, name: 'Panela', catalogue_images: [] },
|
||||||
|
suppliers: [{ supplier: { id: 5, name: 'A' }, municipality: { id: 7, name: 'LA MESA', latitude: '4.6310280', longitude: '-74.4615880' } }],
|
||||||
|
},
|
||||||
|
{
|
||||||
|
product: { id: 2, name: 'Arroz', catalogue_images: [] },
|
||||||
|
suppliers: [{ supplier: { id: 6, name: 'B' }, municipality: { id: 7, name: 'LA MESA', latitude: '4.6310280', longitude: '-74.4615880' } }],
|
||||||
|
},
|
||||||
|
]
|
||||||
|
|
||||||
|
function mountMap (props = {}) {
|
||||||
|
const api = { getStoreSettings: vi.fn().mockResolvedValue(settings) }
|
||||||
|
const pinia = createPinia()
|
||||||
|
setActivePinia(pinia)
|
||||||
|
const wrapper = mount(ProvenanceMap, {
|
||||||
|
props: { provenance, ...props },
|
||||||
|
global: {
|
||||||
|
plugins: [pinia, vuetify],
|
||||||
|
provide: { api },
|
||||||
|
},
|
||||||
|
})
|
||||||
|
return { api, wrapper }
|
||||||
|
}
|
||||||
|
|
||||||
|
function handlerOf (marker, event) {
|
||||||
|
return marker.on.mock.calls.find(args => args[0] === event)[1]
|
||||||
|
}
|
||||||
|
|
||||||
|
beforeEach(() => {
|
||||||
|
vi.clearAllMocks()
|
||||||
|
leaflet.markers.length = 0
|
||||||
|
leaflet.polylines.length = 0
|
||||||
|
leaflet.layers.length = 0
|
||||||
|
document.body.innerHTML = ''
|
||||||
|
})
|
||||||
|
|
||||||
|
describe('ProvenanceMap', () => {
|
||||||
|
it('carga la configuración de la tienda al montarse', async () => {
|
||||||
|
const { api } = mountMap()
|
||||||
|
await flushPromises()
|
||||||
|
|
||||||
|
expect(api.getStoreSettings).toHaveBeenCalled()
|
||||||
|
})
|
||||||
|
|
||||||
|
it('crea el mapa con la tienda y un marcador por municipio de origen', async () => {
|
||||||
|
mountMap()
|
||||||
|
await flushPromises()
|
||||||
|
|
||||||
|
expect(leaflet.L.map).toHaveBeenCalledTimes(1)
|
||||||
|
expect(leaflet.L.tileLayer).toHaveBeenCalledTimes(1)
|
||||||
|
expect(leaflet.markers).toHaveLength(4)
|
||||||
|
expect(leaflet.map.fitBounds).toHaveBeenCalled()
|
||||||
|
expect(leaflet.markers[0].bindTooltip).toHaveBeenCalled()
|
||||||
|
})
|
||||||
|
|
||||||
|
it('al pasar sobre un producto dibuja una línea hasta la tienda', async () => {
|
||||||
|
mountMap()
|
||||||
|
await flushPromises()
|
||||||
|
|
||||||
|
handlerOf(leaflet.markers[1], 'mouseover')()
|
||||||
|
|
||||||
|
expect(leaflet.L.polyline).toHaveBeenCalledTimes(1)
|
||||||
|
expect(leaflet.L.polyline.mock.calls[0][0]).toEqual([[6.23, -75.56], [4.6, -74.08]])
|
||||||
|
expect(leaflet.polylines[0].addTo).toHaveBeenCalled()
|
||||||
|
})
|
||||||
|
|
||||||
|
it('al pasar sobre la tienda dibuja las líneas de todos los productos', async () => {
|
||||||
|
mountMap()
|
||||||
|
await flushPromises()
|
||||||
|
|
||||||
|
handlerOf(leaflet.markers[0], 'mouseover')()
|
||||||
|
|
||||||
|
expect(leaflet.L.polyline).toHaveBeenCalledTimes(3)
|
||||||
|
})
|
||||||
|
|
||||||
|
it('al salir del marcador se limpian las líneas', async () => {
|
||||||
|
mountMap()
|
||||||
|
await flushPromises()
|
||||||
|
|
||||||
|
handlerOf(leaflet.markers[1], 'mouseover')()
|
||||||
|
expect(leaflet.polylines).toHaveLength(1)
|
||||||
|
handlerOf(leaflet.markers[1], 'mouseout')()
|
||||||
|
|
||||||
|
expect(leaflet.polylines[0].remove).toHaveBeenCalled()
|
||||||
|
})
|
||||||
|
|
||||||
|
it('muestra el detalle del producto en un popup sobre el marcador', async () => {
|
||||||
|
mountMap()
|
||||||
|
await flushPromises()
|
||||||
|
|
||||||
|
const marker = leaflet.markers[1]
|
||||||
|
expect(marker.bindPopup).toHaveBeenCalledTimes(1)
|
||||||
|
const popupEl = marker.bindPopup.mock.calls[0][0]
|
||||||
|
expect(popupEl.textContent).toContain('Panela regional')
|
||||||
|
expect(popupEl.textContent).toContain('Asociación La Mesa')
|
||||||
|
expect(popupEl.textContent).toContain('Santa Bárbara')
|
||||||
|
})
|
||||||
|
|
||||||
|
it('no abre el modal web para productos con ubicación', async () => {
|
||||||
|
mountMap()
|
||||||
|
await flushPromises()
|
||||||
|
|
||||||
|
expect(document.body.textContent).not.toContain('Proveedor')
|
||||||
|
})
|
||||||
|
|
||||||
|
it('no dibuja la línea de la tienda cuando la tienda no tiene coordenadas', async () => {
|
||||||
|
const api = { getStoreSettings: vi.fn().mockResolvedValue({ address: 'Cra 1' }) }
|
||||||
|
const pinia = createPinia()
|
||||||
|
setActivePinia(pinia)
|
||||||
|
mount(ProvenanceMap, {
|
||||||
|
props: { provenance },
|
||||||
|
global: {
|
||||||
|
plugins: [pinia, vuetify],
|
||||||
|
provide: { api },
|
||||||
|
},
|
||||||
|
})
|
||||||
|
await flushPromises()
|
||||||
|
|
||||||
|
expect(leaflet.markers).toHaveLength(3)
|
||||||
|
handlerOf(leaflet.markers[0], 'mouseover')()
|
||||||
|
expect(leaflet.L.polyline).not.toHaveBeenCalled()
|
||||||
|
})
|
||||||
|
|
||||||
|
it('muestra un aviso cuando ningún municipio tiene coordenadas', async () => {
|
||||||
|
const noCoords = [
|
||||||
|
{ product: { id: 1, name: 'Panela' }, suppliers: [{ supplier: { id: 5, name: 'A' }, municipality: { id: 7, name: 'M' } }] },
|
||||||
|
]
|
||||||
|
const { wrapper } = mountMap({ provenance: noCoords })
|
||||||
|
await flushPromises()
|
||||||
|
|
||||||
|
expect(leaflet.L.map).not.toHaveBeenCalled()
|
||||||
|
expect(wrapper.text()).toContain('coordenadas')
|
||||||
|
})
|
||||||
|
|
||||||
|
it('mantiene la posición exacta del municipio aunque varios productos coincidan', async () => {
|
||||||
|
mountMap({ provenance: sameMuni })
|
||||||
|
await flushPromises()
|
||||||
|
|
||||||
|
expect(leaflet.markers).toHaveLength(2)
|
||||||
|
expect(leaflet.markers[1].pos).toEqual([4.631028, -74.461588])
|
||||||
|
expect(leaflet.map.on).not.toHaveBeenCalledWith('zoomend', expect.anything())
|
||||||
|
})
|
||||||
|
|
||||||
|
it('agrupa los productos del mismo punto en un marcador con contador', async () => {
|
||||||
|
mountMap({ provenance: sameMuni })
|
||||||
|
await flushPromises()
|
||||||
|
|
||||||
|
const groupIcon = leaflet.L.divIcon.mock.calls.find(args => args[0].className === 'provenance-group-pin')
|
||||||
|
expect(groupIcon).toBeDefined()
|
||||||
|
expect(groupIcon[0].html).toContain('2')
|
||||||
|
expect(groupIcon[0].html).toContain('mdi-package-variant')
|
||||||
|
const groupMarker = leaflet.markers[1]
|
||||||
|
expect(groupMarker.bindPopup).toHaveBeenCalled()
|
||||||
|
expect(groupMarker.bindTooltip.mock.calls[0][0]).toContain('2 productos')
|
||||||
|
})
|
||||||
|
|
||||||
|
it('al hacer clic en el marcador agrupado despliega los productos internos', async () => {
|
||||||
|
mountMap({ provenance: sameMuni })
|
||||||
|
await flushPromises()
|
||||||
|
|
||||||
|
const popupEl = leaflet.markers[1].bindPopup.mock.calls[0][0]
|
||||||
|
expect(popupEl.textContent).toContain('Panela')
|
||||||
|
expect(popupEl.textContent).toContain('Arroz')
|
||||||
|
})
|
||||||
|
|
||||||
|
it('al hacer clic en un producto del popup agrupado muestra su detalle sin cerrar el popup ni propagar el clic al mapa', async () => {
|
||||||
|
mountMap({ provenance: sameMuni })
|
||||||
|
await flushPromises()
|
||||||
|
|
||||||
|
const groupMarker = leaflet.markers[1]
|
||||||
|
const popupEl = groupMarker.bindPopup.mock.calls[0][0]
|
||||||
|
let bubbled = false
|
||||||
|
popupEl.addEventListener('click', () => { bubbled = true })
|
||||||
|
const item = popupEl.querySelector('[data-test="map-popup-item-1"]')
|
||||||
|
item.dispatchEvent(new MouseEvent('click', { bubbles: true }))
|
||||||
|
|
||||||
|
expect(bubbled).toBe(false)
|
||||||
|
expect(groupMarker.closePopup).not.toHaveBeenCalled()
|
||||||
|
expect(groupMarker.setPopupContent).toHaveBeenCalledTimes(1)
|
||||||
|
const detailEl = groupMarker.setPopupContent.mock.calls[0][0]
|
||||||
|
expect(detailEl.textContent).toContain('Arroz')
|
||||||
|
expect(detailEl.textContent).toContain('B')
|
||||||
|
expect(groupMarker.openPopup).toHaveBeenCalled()
|
||||||
|
})
|
||||||
|
|
||||||
|
it('al pasar sobre la tienda dibuja una línea por cada producto agrupado', async () => {
|
||||||
|
mountMap({ provenance: sameMuni })
|
||||||
|
await flushPromises()
|
||||||
|
|
||||||
|
handlerOf(leaflet.markers[0], 'mouseover')()
|
||||||
|
|
||||||
|
expect(leaflet.L.polyline).toHaveBeenCalledTimes(2)
|
||||||
|
})
|
||||||
|
|
||||||
|
it('al pasar sobre el marcador agrupado dibuja las líneas de sus productos', async () => {
|
||||||
|
mountMap({ provenance: sameMuni })
|
||||||
|
await flushPromises()
|
||||||
|
|
||||||
|
handlerOf(leaflet.markers[1], 'mouseover')()
|
||||||
|
|
||||||
|
expect(leaflet.L.polyline).toHaveBeenCalledTimes(2)
|
||||||
|
expect(leaflet.polylines[0].points[0]).toEqual([4.631028, -74.461588])
|
||||||
|
})
|
||||||
|
|
||||||
|
it('muestra un recuadro con todos los productos, incluidos los sin geolocalización', async () => {
|
||||||
|
const withNoGeo = [
|
||||||
|
{
|
||||||
|
product: { id: 1, name: 'Panela regional', catalogue_images: ['http://localhost/media/panela.jpg'] },
|
||||||
|
suppliers: [{ supplier: { id: 5, name: 'Asociación La Mesa' }, municipality: { id: 7, name: 'Santa Bárbara', latitude: 6.23, longitude: -75.56 } }],
|
||||||
|
},
|
||||||
|
{
|
||||||
|
product: { id: 2, name: 'Café de montaña', catalogue_images: [] },
|
||||||
|
suppliers: [{ supplier: { id: 8, name: 'Caficultores del Valle' }, municipality: null }],
|
||||||
|
},
|
||||||
|
{
|
||||||
|
product: { id: 3, name: 'Miel pura', catalogue_images: [] },
|
||||||
|
suppliers: [],
|
||||||
|
},
|
||||||
|
]
|
||||||
|
const { wrapper } = mountMap({ provenance: withNoGeo })
|
||||||
|
await flushPromises()
|
||||||
|
|
||||||
|
const rows = wrapper.findAll('[data-test="map-product-row"]')
|
||||||
|
expect(rows).toHaveLength(3)
|
||||||
|
expect(rows.map(row => row.text().replace(/\s+/g, ' ').trim())).toEqual([
|
||||||
|
expect.stringContaining('Panela regional'),
|
||||||
|
expect.stringContaining('Café de montaña'),
|
||||||
|
expect.stringContaining('Miel pura'),
|
||||||
|
])
|
||||||
|
expect(rows[1].text()).toContain('Sin geolocalización')
|
||||||
|
expect(rows[2].text()).toContain('Sin geolocalización')
|
||||||
|
expect(rows[0].text()).toContain('Santa Bárbara')
|
||||||
|
})
|
||||||
|
|
||||||
|
it('al hacer clic en un producto con ubicación centra el mapa y abre su detalle en el marcador', async () => {
|
||||||
|
const { wrapper } = mountMap()
|
||||||
|
await flushPromises()
|
||||||
|
|
||||||
|
await wrapper.find('[data-test="map-product-row"]').trigger('click')
|
||||||
|
await nextTick()
|
||||||
|
|
||||||
|
expect(leaflet.map.flyTo).toHaveBeenCalledTimes(1)
|
||||||
|
expect(leaflet.map.flyTo.mock.calls[0][0]).toEqual([6.23, -75.56])
|
||||||
|
const marker = leaflet.markers[1]
|
||||||
|
expect(marker.setPopupContent).toHaveBeenCalled()
|
||||||
|
expect(marker.setPopupContent.mock.calls[0][0].textContent).toContain('Panela regional')
|
||||||
|
expect(marker.setPopupContent.mock.calls[0][0].textContent).toContain('Asociación La Mesa')
|
||||||
|
expect(marker.openPopup).toHaveBeenCalled()
|
||||||
|
expect(document.body.textContent).not.toContain('Proveedor')
|
||||||
|
})
|
||||||
|
|
||||||
|
it('al hacer clic en un producto sin geolocalización abre el diálogo con la información disponible sin centrar el mapa', async () => {
|
||||||
|
const withNoGeo = [
|
||||||
|
{
|
||||||
|
product: { id: 1, name: 'Panela regional', catalogue_images: [] },
|
||||||
|
suppliers: [{ supplier: { id: 5, name: 'Asociación La Mesa' }, municipality: { id: 7, name: 'Santa Bárbara', latitude: 6.23, longitude: -75.56 } }],
|
||||||
|
},
|
||||||
|
{
|
||||||
|
product: { id: 2, name: 'Café de montaña', catalogue_images: [] },
|
||||||
|
suppliers: [{ supplier: { id: 8, name: 'Caficultores del Valle' }, municipality: null }],
|
||||||
|
},
|
||||||
|
]
|
||||||
|
const { wrapper } = mountMap({ provenance: withNoGeo })
|
||||||
|
await flushPromises()
|
||||||
|
|
||||||
|
const noGeoRow = wrapper.findAll('[data-test="map-product-row"]').find(row => row.text().includes('Café de montaña'))
|
||||||
|
await noGeoRow.trigger('click')
|
||||||
|
await nextTick()
|
||||||
|
|
||||||
|
expect(leaflet.map.flyTo).not.toHaveBeenCalled()
|
||||||
|
expect(document.body.textContent).toContain('Café de montaña')
|
||||||
|
expect(document.body.textContent).toContain('Caficultores del Valle')
|
||||||
|
expect(document.body.textContent).toContain('sin geolocalización')
|
||||||
|
})
|
||||||
|
|
||||||
|
it('al hacer clic en el botón de zoom general vuelve a encuadrar todos los marcadores', async () => {
|
||||||
|
const { wrapper } = mountMap()
|
||||||
|
await flushPromises()
|
||||||
|
leaflet.map.fitBounds.mockClear()
|
||||||
|
|
||||||
|
await wrapper.find('[data-test="map-reset-zoom"]').trigger('click')
|
||||||
|
|
||||||
|
expect(leaflet.map.fitBounds).toHaveBeenCalledTimes(1)
|
||||||
|
})
|
||||||
|
|
||||||
|
it('lee las coordenadas string del backend y da fondo visible al producto sin imagen', async () => {
|
||||||
|
const backendProvenance = [
|
||||||
|
{
|
||||||
|
product: { id: 110, name: 'Panela condimentada 150 grs', catalogue_images: [] },
|
||||||
|
suppliers: [
|
||||||
|
{
|
||||||
|
supplier: { id: 4, name: 'Asociación Agropecuaria La Mesa' },
|
||||||
|
organization: null,
|
||||||
|
municipality: { id: 2653, name: 'LA MESA', latitude: '4.6310280', longitude: '-74.4615880' },
|
||||||
|
department: { id: 91, name: 'Cundinamarca' },
|
||||||
|
country: { id: 3, name: 'Colombia', code: 'CO' },
|
||||||
|
},
|
||||||
|
],
|
||||||
|
},
|
||||||
|
]
|
||||||
|
mountMap({ provenance: backendProvenance })
|
||||||
|
await flushPromises()
|
||||||
|
|
||||||
|
expect(leaflet.L.map).toHaveBeenCalledTimes(1)
|
||||||
|
expect(leaflet.markers).toHaveLength(2)
|
||||||
|
expect(leaflet.markers[1].pos).toEqual([4.631028, -74.461588])
|
||||||
|
const productIcon = leaflet.L.divIcon.mock.calls.find(args => args[0].html.includes('provenance-product-fallback'))
|
||||||
|
expect(productIcon).toBeDefined()
|
||||||
|
})
|
||||||
|
})
|
||||||
@@ -0,0 +1,96 @@
|
|||||||
|
import { describe, expect, it } from 'vitest'
|
||||||
|
import { mount } from '@vue/test-utils'
|
||||||
|
import ProvenanceRelationModal from '@/components/provenance/ProvenanceRelationModal.vue'
|
||||||
|
import vuetify from '@/plugins/vuetify'
|
||||||
|
|
||||||
|
const relation = {
|
||||||
|
supplier: { id: 5, name: 'Asociación La Mesa', contact_email: 'info@mesa.co' },
|
||||||
|
organization: { id: 3, name: 'Red de Economía Solidaria' },
|
||||||
|
municipality: { id: 7, name: 'Santa Bárbara' },
|
||||||
|
department: { id: 2, name: 'Antioquia' },
|
||||||
|
country: { id: 1, name: 'Colombia', code: 'CO' },
|
||||||
|
}
|
||||||
|
const product = {
|
||||||
|
id: 1,
|
||||||
|
name: 'Panela regional',
|
||||||
|
catalogue_images: ['http://localhost/media/panela.jpg'],
|
||||||
|
}
|
||||||
|
|
||||||
|
function mountModal (props = {}) {
|
||||||
|
return mount(ProvenanceRelationModal, {
|
||||||
|
props: { product, relation, visible: true, ...props },
|
||||||
|
global: { plugins: [vuetify] },
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
function bodyText () {
|
||||||
|
return document.body.textContent
|
||||||
|
}
|
||||||
|
|
||||||
|
describe('ProvenanceRelationModal', () => {
|
||||||
|
it('muestra el producto y todas las entidades de la relación', () => {
|
||||||
|
mountModal()
|
||||||
|
|
||||||
|
expect(bodyText()).toContain('Panela regional')
|
||||||
|
expect(bodyText()).toContain('Proveedor')
|
||||||
|
expect(bodyText()).toContain('Asociación La Mesa')
|
||||||
|
expect(bodyText()).toContain('Organización')
|
||||||
|
expect(bodyText()).toContain('Red de Economía Solidaria')
|
||||||
|
expect(bodyText()).toContain('Municipio')
|
||||||
|
expect(bodyText()).toContain('Santa Bárbara')
|
||||||
|
expect(bodyText()).toContain('Departamento')
|
||||||
|
expect(bodyText()).toContain('Antioquia')
|
||||||
|
expect(bodyText()).toContain('País')
|
||||||
|
expect(bodyText()).toContain('Colombia')
|
||||||
|
})
|
||||||
|
|
||||||
|
it('incluye los detalles de contacto del proveedor', () => {
|
||||||
|
mountModal()
|
||||||
|
|
||||||
|
expect(bodyText()).toContain('info@mesa.co')
|
||||||
|
})
|
||||||
|
|
||||||
|
it('muestra la imagen del producto cuando existe', () => {
|
||||||
|
mountModal()
|
||||||
|
|
||||||
|
expect(document.querySelector('img').getAttribute('src')).toBe(
|
||||||
|
'http://localhost/media/panela.jpg'
|
||||||
|
)
|
||||||
|
})
|
||||||
|
|
||||||
|
it('no muestra las entidades ausentes', () => {
|
||||||
|
mountModal({ relation: { supplier: { id: 5, name: 'Asociación La Mesa' } } })
|
||||||
|
|
||||||
|
expect(bodyText()).not.toContain('Organización')
|
||||||
|
expect(bodyText()).not.toContain('Municipio')
|
||||||
|
expect(bodyText()).not.toContain('Departamento')
|
||||||
|
expect(bodyText()).not.toContain('País')
|
||||||
|
})
|
||||||
|
|
||||||
|
it('muestra el producto y un aviso cuando no hay proveedor vinculado', () => {
|
||||||
|
mountModal({ relation: null })
|
||||||
|
|
||||||
|
expect(bodyText()).toContain('Panela regional')
|
||||||
|
expect(bodyText()).toContain('no se ha vinculado un proveedor')
|
||||||
|
})
|
||||||
|
|
||||||
|
it('no muestra contenido cuando no hay producto ni relación', () => {
|
||||||
|
mountModal({ relation: null, product: null })
|
||||||
|
|
||||||
|
expect(bodyText()).not.toContain('Proveedor')
|
||||||
|
expect(bodyText()).not.toContain('Producto')
|
||||||
|
})
|
||||||
|
|
||||||
|
it('indica que aún no tiene geolocalización cuando la relación no tiene municipio', () => {
|
||||||
|
mountModal({ relation: { supplier: { id: 5, name: 'Asociación La Mesa' } } })
|
||||||
|
|
||||||
|
expect(bodyText()).toContain('Asociación La Mesa')
|
||||||
|
expect(bodyText()).toContain('sin geolocalización')
|
||||||
|
})
|
||||||
|
|
||||||
|
it('no muestra el diálogo cuando visible es false', () => {
|
||||||
|
mountModal({ visible: false })
|
||||||
|
|
||||||
|
expect(bodyText()).not.toContain('Asociación La Mesa')
|
||||||
|
})
|
||||||
|
})
|
||||||
@@ -1,20 +1,15 @@
|
|||||||
import { describe, expect, it, vi } from 'vitest'
|
import { describe, expect, it, vi } from 'vitest'
|
||||||
import { mount } from '@vue/test-utils'
|
import { mount } from '@vue/test-utils'
|
||||||
import ProductSupplierOrganizationChart from '@/components/provenance/ProductSupplierOrganizationChart.vue'
|
import ProvenanceGraph from '@/components/provenance/ProvenanceGraph.vue'
|
||||||
import ProductTerritoryChart from '@/components/provenance/ProductTerritoryChart.vue'
|
|
||||||
import ProvenanceSection from '@/components/provenance/ProvenanceSection.vue'
|
import ProvenanceSection from '@/components/provenance/ProvenanceSection.vue'
|
||||||
import vuetify from '@/plugins/vuetify'
|
import vuetify from '@/plugins/vuetify'
|
||||||
|
|
||||||
const cy = {
|
vi.mock('@/components/graph/VisChart.vue', () => ({
|
||||||
on: vi.fn(),
|
default: {
|
||||||
elements: vi.fn(() => ({ remove: vi.fn() })),
|
name: 'VisChart',
|
||||||
add: vi.fn(),
|
template: '<div class="vis-chart-stub" />',
|
||||||
layout: vi.fn(() => ({ run: vi.fn() })),
|
props: ['nodes', 'edges', 'height', 'options', 'minVerticalSpacing'],
|
||||||
destroy: vi.fn(),
|
},
|
||||||
}
|
|
||||||
|
|
||||||
vi.mock('cytoscape', () => ({
|
|
||||||
default: vi.fn(() => cy),
|
|
||||||
}))
|
}))
|
||||||
|
|
||||||
const provenance = [
|
const provenance = [
|
||||||
@@ -35,38 +30,98 @@ const provenance = [
|
|||||||
function mountSection (props = {}) {
|
function mountSection (props = {}) {
|
||||||
return mount(ProvenanceSection, {
|
return mount(ProvenanceSection, {
|
||||||
props: { provenance, ...props },
|
props: { provenance, ...props },
|
||||||
global: { plugins: [vuetify] },
|
global: { plugins: [vuetify], stubs: { ProvenanceMap: true } },
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
|
function mapWrapper (wrapper) {
|
||||||
|
return wrapper.findComponent({ name: 'ProvenanceMap' })
|
||||||
|
}
|
||||||
|
|
||||||
describe('ProvenanceSection', () => {
|
describe('ProvenanceSection', () => {
|
||||||
it('no renderiza nada cuando no hay provenance', () => {
|
it('no renderiza nada cuando no hay provenance', () => {
|
||||||
const wrapper = mountSection({ provenance: null })
|
const wrapper = mountSection({ provenance: null })
|
||||||
|
|
||||||
expect(wrapper.findComponent(ProductSupplierOrganizationChart).exists()).toBe(false)
|
expect(wrapper.findComponent(ProvenanceGraph).exists()).toBe(false)
|
||||||
expect(wrapper.findComponent(ProductTerritoryChart).exists()).toBe(false)
|
|
||||||
})
|
})
|
||||||
|
|
||||||
it('no renderiza nada cuando provenance es una lista vacía', () => {
|
it('no renderiza nada cuando provenance es una lista vacía', () => {
|
||||||
const wrapper = mountSection({ provenance: [] })
|
const wrapper = mountSection({ provenance: [] })
|
||||||
|
|
||||||
expect(wrapper.findComponent(ProductSupplierOrganizationChart).exists()).toBe(false)
|
expect(wrapper.findComponent(ProvenanceGraph).exists()).toBe(false)
|
||||||
expect(wrapper.findComponent(ProductTerritoryChart).exists()).toBe(false)
|
|
||||||
})
|
})
|
||||||
|
|
||||||
it('muestra los dos gráficos con sus títulos cuando hay provenance', () => {
|
it('muestra el título y oculta el gráfico por defecto', () => {
|
||||||
const wrapper = mountSection()
|
const wrapper = mountSection()
|
||||||
|
|
||||||
expect(wrapper.findComponent(ProductSupplierOrganizationChart).exists()).toBe(true)
|
expect(wrapper.text()).toContain('Origen de los productos')
|
||||||
expect(wrapper.findComponent(ProductTerritoryChart).exists()).toBe(true)
|
expect(wrapper.text()).not.toContain('historia')
|
||||||
expect(wrapper.text()).toContain('Proveedores y organizaciones')
|
expect(wrapper.findComponent(ProvenanceGraph).exists()).toBe(false)
|
||||||
expect(wrapper.text()).toContain('Departamento y municipio')
|
|
||||||
})
|
})
|
||||||
|
|
||||||
it('pasa el provenance a ambos gráficos', () => {
|
it('muestra el gráfico al hacer clic en el título y lo oculta al volver a hacer clic', async () => {
|
||||||
const wrapper = mountSection()
|
const wrapper = mountSection()
|
||||||
|
|
||||||
expect(wrapper.findComponent(ProductSupplierOrganizationChart).props('provenance')).toStrictEqual(provenance)
|
await wrapper.find('[data-test="provenance-toggle"]').trigger('click')
|
||||||
expect(wrapper.findComponent(ProductTerritoryChart).props('provenance')).toStrictEqual(provenance)
|
expect(wrapper.findComponent(ProvenanceGraph).exists()).toBe(true)
|
||||||
|
|
||||||
|
await wrapper.find('[data-test="provenance-toggle"]').trigger('click')
|
||||||
|
expect(wrapper.findComponent(ProvenanceGraph).exists()).toBe(false)
|
||||||
|
})
|
||||||
|
|
||||||
|
it('también despliega y repliega con el botón de chevron', async () => {
|
||||||
|
const wrapper = mountSection()
|
||||||
|
|
||||||
|
const button = wrapper.find('[data-test="provenance-toggle-button"]')
|
||||||
|
expect(button.exists()).toBe(true)
|
||||||
|
await button.trigger('click')
|
||||||
|
expect(wrapper.findComponent(ProvenanceGraph).exists()).toBe(true)
|
||||||
|
|
||||||
|
await button.trigger('click')
|
||||||
|
expect(wrapper.findComponent(ProvenanceGraph).exists()).toBe(false)
|
||||||
|
})
|
||||||
|
|
||||||
|
it('pasa el provenance al gráfico al desplegarlo', async () => {
|
||||||
|
const wrapper = mountSection()
|
||||||
|
|
||||||
|
await wrapper.find('[data-test="provenance-toggle"]').trigger('click')
|
||||||
|
|
||||||
|
expect(wrapper.findComponent(ProvenanceGraph).props('provenance')).toStrictEqual(provenance)
|
||||||
|
})
|
||||||
|
|
||||||
|
it('oculta el mapa por defecto', () => {
|
||||||
|
const wrapper = mountSection()
|
||||||
|
|
||||||
|
expect(mapWrapper(wrapper).exists()).toBe(false)
|
||||||
|
})
|
||||||
|
|
||||||
|
it('muestra el mapa al hacer clic en su título y lo oculta al volver a hacer clic', async () => {
|
||||||
|
const wrapper = mountSection()
|
||||||
|
|
||||||
|
await wrapper.find('[data-test="map-toggle"]').trigger('click')
|
||||||
|
expect(mapWrapper(wrapper).exists()).toBe(true)
|
||||||
|
|
||||||
|
await wrapper.find('[data-test="map-toggle"]').trigger('click')
|
||||||
|
expect(mapWrapper(wrapper).exists()).toBe(false)
|
||||||
|
})
|
||||||
|
|
||||||
|
it('también despliega y repliega el mapa con el botón de chevron', async () => {
|
||||||
|
const wrapper = mountSection()
|
||||||
|
|
||||||
|
const button = wrapper.find('[data-test="map-toggle-button"]')
|
||||||
|
expect(button.exists()).toBe(true)
|
||||||
|
await button.trigger('click')
|
||||||
|
expect(mapWrapper(wrapper).exists()).toBe(true)
|
||||||
|
|
||||||
|
await button.trigger('click')
|
||||||
|
expect(mapWrapper(wrapper).exists()).toBe(false)
|
||||||
|
})
|
||||||
|
|
||||||
|
it('pasa el provenance al mapa al desplegarlo', async () => {
|
||||||
|
const wrapper = mountSection()
|
||||||
|
|
||||||
|
await wrapper.find('[data-test="map-toggle"]').trigger('click')
|
||||||
|
|
||||||
|
expect(mapWrapper(wrapper).props('provenance')).toStrictEqual(provenance)
|
||||||
})
|
})
|
||||||
})
|
})
|
||||||
|
|||||||
@@ -0,0 +1,72 @@
|
|||||||
|
import { describe, expect, it, vi } from 'vitest'
|
||||||
|
import { flushPromises, mount } from '@vue/test-utils'
|
||||||
|
import SupplierLinkDialog from '@/components/provenance/admin/SupplierLinkDialog.vue'
|
||||||
|
import vuetify from '@/plugins/vuetify'
|
||||||
|
import { clickBody } from './helpers'
|
||||||
|
|
||||||
|
const suppliers = [
|
||||||
|
{ id: 5, name: 'Asociación Agropecuaria La Mesa' },
|
||||||
|
{ id: 9, name: 'Finca El Paraíso' },
|
||||||
|
{ id: 12, name: 'Cooperativa del Valle' },
|
||||||
|
]
|
||||||
|
|
||||||
|
function mockApi () {
|
||||||
|
return {
|
||||||
|
getSuppliers: vi.fn().mockResolvedValue(suppliers),
|
||||||
|
getProduct: vi.fn().mockResolvedValue({ id: 1, name: 'Panela regional por Kg', suppliers: [5] }),
|
||||||
|
updateProduct: vi.fn().mockResolvedValue({}),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function mountDialog (api, props = {}) {
|
||||||
|
return mount(SupplierLinkDialog, {
|
||||||
|
props: { visible: true, product: { id: 1, name: 'Panela regional por Kg' }, ...props },
|
||||||
|
global: { plugins: [vuetify], provide: { api } },
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
describe('SupplierLinkDialog', () => {
|
||||||
|
it('carga los proveedores y los suppliers actuales del producto al abrir', async () => {
|
||||||
|
const api = mockApi()
|
||||||
|
mountDialog(api)
|
||||||
|
await flushPromises()
|
||||||
|
|
||||||
|
expect(api.getSuppliers).toHaveBeenCalled()
|
||||||
|
expect(api.getProduct).toHaveBeenCalledWith(1)
|
||||||
|
expect(document.body.textContent).toContain('Panela regional por Kg')
|
||||||
|
})
|
||||||
|
|
||||||
|
it('permite cambiar la selección y guarda los proveedores', async () => {
|
||||||
|
const api = mockApi()
|
||||||
|
const wrapper = mountDialog(api)
|
||||||
|
await flushPromises()
|
||||||
|
|
||||||
|
const autocomplete = wrapper.findAllComponents({ name: 'VAutocomplete' })
|
||||||
|
.find(component => component.props('items').some(item => item.id === 5))
|
||||||
|
await autocomplete.vm.$emit('update:modelValue', [5, 9])
|
||||||
|
|
||||||
|
expect(document.body.textContent).toContain('Seleccionados (2)')
|
||||||
|
|
||||||
|
clickBody('[data-testid="supplier-link-save"]')
|
||||||
|
await flushPromises()
|
||||||
|
|
||||||
|
expect(api.updateProduct).toHaveBeenCalledWith(1, { suppliers: [5, 9] })
|
||||||
|
})
|
||||||
|
|
||||||
|
it('mantiene los proveedores seleccionados aunque el filtro no los incluya', async () => {
|
||||||
|
const api = mockApi()
|
||||||
|
const wrapper = mountDialog(api)
|
||||||
|
await flushPromises()
|
||||||
|
|
||||||
|
const autocomplete = wrapper.findAllComponents({ name: 'VAutocomplete' })
|
||||||
|
.find(component => component.props('items').some(item => item.id === 5))
|
||||||
|
await autocomplete.vm.$emit('update:modelValue', [5, 12])
|
||||||
|
await autocomplete.vm.$emit('update:search', 'Finca')
|
||||||
|
|
||||||
|
const items = autocomplete.props('items')
|
||||||
|
expect(items.some(item => item.id === 5)).toBe(true)
|
||||||
|
expect(items.some(item => item.id === 12)).toBe(true)
|
||||||
|
expect(items.some(item => item.id === 9)).toBe(true)
|
||||||
|
expect(items.some(item => item.id === 7)).toBe(false)
|
||||||
|
})
|
||||||
|
})
|
||||||
@@ -10,8 +10,13 @@ const organizations = [
|
|||||||
]
|
]
|
||||||
|
|
||||||
const municipalities = [
|
const municipalities = [
|
||||||
{ id: 7, name: 'La Mesa' },
|
{ id: 7, name: 'La Mesa', department: 2 },
|
||||||
{ id: 8, name: 'San Antonio' },
|
{ id: 8, name: 'San Antonio', department: 3 },
|
||||||
|
]
|
||||||
|
|
||||||
|
const departments = [
|
||||||
|
{ id: 2, name: 'Cundinamarca' },
|
||||||
|
{ id: 3, name: 'Antioquia' },
|
||||||
]
|
]
|
||||||
|
|
||||||
const suppliers = [
|
const suppliers = [
|
||||||
@@ -44,6 +49,7 @@ function mockApi () {
|
|||||||
getSuppliers: vi.fn().mockResolvedValue(suppliers),
|
getSuppliers: vi.fn().mockResolvedValue(suppliers),
|
||||||
getOrganizations: vi.fn().mockResolvedValue(organizations),
|
getOrganizations: vi.fn().mockResolvedValue(organizations),
|
||||||
getMunicipalities: vi.fn().mockResolvedValue(municipalities),
|
getMunicipalities: vi.fn().mockResolvedValue(municipalities),
|
||||||
|
getDepartments: vi.fn().mockResolvedValue(departments),
|
||||||
createSupplier: vi.fn().mockResolvedValue({}),
|
createSupplier: vi.fn().mockResolvedValue({}),
|
||||||
updateSupplier: vi.fn().mockResolvedValue({}),
|
updateSupplier: vi.fn().mockResolvedValue({}),
|
||||||
deleteSupplier: vi.fn().mockResolvedValue({}),
|
deleteSupplier: vi.fn().mockResolvedValue({}),
|
||||||
@@ -68,6 +74,18 @@ describe('SuppliersManagement', () => {
|
|||||||
expect(wrapper.text()).toContain('La Mesa')
|
expect(wrapper.text()).toContain('La Mesa')
|
||||||
})
|
})
|
||||||
|
|
||||||
|
it('muestra el departamento en el título del municipio', async () => {
|
||||||
|
const api = mockApi()
|
||||||
|
const wrapper = mountComponent(api)
|
||||||
|
await flushPromises()
|
||||||
|
|
||||||
|
await wrapper.find('[data-testid="supplier-create"]').trigger('click')
|
||||||
|
const autocomplete = wrapper.findAllComponents({ name: 'VAutocomplete' })[0]
|
||||||
|
const itemTitle = autocomplete.props('itemTitle')
|
||||||
|
|
||||||
|
expect(itemTitle({ id: 7, name: 'La Mesa', department: 2 })).toBe('La Mesa (Cundinamarca)')
|
||||||
|
})
|
||||||
|
|
||||||
it('crea un proveedor con organización y municipio', async () => {
|
it('crea un proveedor con organización y municipio', async () => {
|
||||||
const api = mockApi()
|
const api = mockApi()
|
||||||
const wrapper = mountComponent(api)
|
const wrapper = mountComponent(api)
|
||||||
|
|||||||
@@ -1,12 +1,12 @@
|
|||||||
import { describe, expect, it } from 'vitest'
|
import { describe, expect, it } from 'vitest'
|
||||||
import {
|
import {
|
||||||
buildSupplierOrganizationGraph,
|
buildProvenanceGraph,
|
||||||
buildTerritoryGraph,
|
|
||||||
hasAnySupplier,
|
hasAnySupplier,
|
||||||
hasAnyTerritory,
|
|
||||||
} from '@/components/provenance/provenance-graph'
|
} from '@/components/provenance/provenance-graph'
|
||||||
|
|
||||||
const provenance = [
|
const ALL_KINDS = ['product', 'supplier', 'organization', 'municipality', 'department', 'country']
|
||||||
|
|
||||||
|
const singleRelation = [
|
||||||
{
|
{
|
||||||
product: {
|
product: {
|
||||||
id: 1,
|
id: 1,
|
||||||
@@ -15,19 +15,49 @@ const provenance = [
|
|||||||
},
|
},
|
||||||
suppliers: [
|
suppliers: [
|
||||||
{
|
{
|
||||||
supplier: { id: 5, name: 'Asociación Agropecuaria La Mesa', description: 'Cooperativa' },
|
supplier: { id: 5, name: 'Asociación Agropecuaria La Mesa' },
|
||||||
organization: { id: 3, name: 'Red de Economía Solidaria', description: 'Red' },
|
organization: { id: 3, name: 'Red de Economía Solidaria' },
|
||||||
municipality: { id: 7, name: 'La Mesa' },
|
municipality: { id: 7, name: 'La Mesa' },
|
||||||
department: { id: 2, name: 'Cundinamarca' },
|
department: { id: 2, name: 'Cundinamarca' },
|
||||||
country: { id: 1, name: 'Colombia', code: 'CO' },
|
country: { id: 1, name: 'Colombia' },
|
||||||
},
|
},
|
||||||
],
|
],
|
||||||
},
|
},
|
||||||
]
|
]
|
||||||
|
|
||||||
|
function twoSuppliers (overrides = {}) {
|
||||||
|
return [
|
||||||
|
{
|
||||||
|
product: { id: 1, name: 'Panela' },
|
||||||
|
suppliers: [
|
||||||
|
{
|
||||||
|
supplier: { id: 5, name: 'Asociación A' },
|
||||||
|
organization: { id: 3, name: 'Red' },
|
||||||
|
municipality: { id: 7, name: 'La Mesa' },
|
||||||
|
department: { id: 2, name: 'Cundinamarca' },
|
||||||
|
country: { id: 1, name: 'Colombia' },
|
||||||
|
...(overrides.first || {}),
|
||||||
|
},
|
||||||
|
{
|
||||||
|
supplier: { id: 6, name: 'Asociación B' },
|
||||||
|
organization: { id: 3, name: 'Red' },
|
||||||
|
municipality: { id: 8, name: 'San Antonio' },
|
||||||
|
department: { id: 3, name: 'Antioquia' },
|
||||||
|
country: { id: 1, name: 'Colombia' },
|
||||||
|
...(overrides.second || {}),
|
||||||
|
},
|
||||||
|
],
|
||||||
|
},
|
||||||
|
]
|
||||||
|
}
|
||||||
|
|
||||||
|
function edgeOf (graph, from, to) {
|
||||||
|
return graph.edges.find(edge => edge.from === from && edge.to === to)
|
||||||
|
}
|
||||||
|
|
||||||
describe('hasAnySupplier', () => {
|
describe('hasAnySupplier', () => {
|
||||||
it('es true cuando algún producto tiene proveedores', () => {
|
it('es true cuando algún producto tiene proveedores', () => {
|
||||||
expect(hasAnySupplier(provenance)).toBe(true)
|
expect(hasAnySupplier(singleRelation)).toBe(true)
|
||||||
})
|
})
|
||||||
|
|
||||||
it('es false cuando todos los productos están sin proveedores', () => {
|
it('es false cuando todos los productos están sin proveedores', () => {
|
||||||
@@ -40,120 +70,107 @@ describe('hasAnySupplier', () => {
|
|||||||
})
|
})
|
||||||
})
|
})
|
||||||
|
|
||||||
describe('hasAnyTerritory', () => {
|
describe('buildProvenanceGraph', () => {
|
||||||
it('es true cuando algún proveedor tiene territorio', () => {
|
it('por defecto solo grafica productos y proveedores', () => {
|
||||||
expect(hasAnyTerritory(provenance)).toBe(true)
|
const graph = buildProvenanceGraph(singleRelation)
|
||||||
|
|
||||||
|
expect(graph.nodes.map(n => n.kind)).toEqual(['product', 'supplier'])
|
||||||
|
expect(graph.edges).toEqual([{ from: 'product:1', to: 'supplier:5', certain: true }])
|
||||||
})
|
})
|
||||||
|
|
||||||
it('es false cuando todos los territorios vienen en null', () => {
|
it('con todos los niveles grafica la cadena completa y la organización', () => {
|
||||||
const noTerritory = [
|
const graph = buildProvenanceGraph(singleRelation, ALL_KINDS)
|
||||||
{
|
|
||||||
product: { id: 1, name: 'Panela' },
|
expect(edgeOf(graph, 'product:1', 'supplier:5')).toEqual({ from: 'product:1', to: 'supplier:5', certain: true })
|
||||||
suppliers: [{ supplier: { id: 5, name: 'La Mesa' }, organization: null, municipality: null, department: null, country: null }],
|
expect(edgeOf(graph, 'supplier:5', 'organization:3').certain).toBe(true)
|
||||||
},
|
expect(edgeOf(graph, 'supplier:5', 'municipality:7')).toEqual({ from: 'supplier:5', to: 'municipality:7', certain: true })
|
||||||
|
expect(edgeOf(graph, 'municipality:7', 'department:2').certain).toBe(true)
|
||||||
|
expect(edgeOf(graph, 'department:2', 'country:1').certain).toBe(true)
|
||||||
|
})
|
||||||
|
|
||||||
|
it('con varios proveedores crea el punto de disyunción y la duda se propaga', () => {
|
||||||
|
const graph = buildProvenanceGraph(twoSuppliers(), ALL_KINDS)
|
||||||
|
|
||||||
|
expect(graph.nodes.map(n => n.id)).toContain('junction:1')
|
||||||
|
expect(edgeOf(graph, 'product:1', 'junction:1')).toEqual({ from: 'product:1', to: 'junction:1', certain: true })
|
||||||
|
expect(edgeOf(graph, 'junction:1', 'supplier:5').certain).toBe(false)
|
||||||
|
expect(edgeOf(graph, 'junction:1', 'supplier:6').certain).toBe(false)
|
||||||
|
expect(edgeOf(graph, 'supplier:5', 'municipality:7').certain).toBe(false)
|
||||||
|
expect(edgeOf(graph, 'municipality:7', 'department:2').certain).toBe(false)
|
||||||
|
expect(edgeOf(graph, 'department:2', 'country:1').certain).toBe(true)
|
||||||
|
expect(edgeOf(graph, 'supplier:5', 'organization:3').certain).toBe(true)
|
||||||
|
})
|
||||||
|
|
||||||
|
it('omite los niveles no solicitados conectando el nivel previo con el siguiente', () => {
|
||||||
|
const graph = buildProvenanceGraph(singleRelation, ['product', 'supplier', 'department'])
|
||||||
|
|
||||||
|
expect(graph.nodes.map(n => n.kind)).toEqual(['product', 'supplier', 'department'])
|
||||||
|
expect(edgeOf(graph, 'supplier:5', 'department:2')).toEqual({ from: 'supplier:5', to: 'department:2', certain: true })
|
||||||
|
expect(edgeOf(graph, 'supplier:5', 'municipality:7')).toBeUndefined()
|
||||||
|
})
|
||||||
|
|
||||||
|
it('sin proveedores activos conecta el producto con el siguiente nivel', () => {
|
||||||
|
const graph = buildProvenanceGraph(singleRelation, ['product', 'municipality', 'department'])
|
||||||
|
|
||||||
|
expect(edgeOf(graph, 'product:1', 'municipality:7')).toEqual({ from: 'product:1', to: 'municipality:7', certain: true })
|
||||||
|
expect(edgeOf(graph, 'municipality:7', 'department:2').certain).toBe(true)
|
||||||
|
})
|
||||||
|
|
||||||
|
it('sin productos activos los proveedores quedan como raíces sin junction', () => {
|
||||||
|
const graph = buildProvenanceGraph(twoSuppliers(), ['supplier', 'municipality'])
|
||||||
|
|
||||||
|
expect(graph.nodes.some(n => n.kind === 'product')).toBe(false)
|
||||||
|
expect(graph.nodes.some(n => n.kind === 'junction')).toBe(false)
|
||||||
|
expect(edgeOf(graph, 'supplier:5', 'municipality:7').certain).toBe(false)
|
||||||
|
})
|
||||||
|
|
||||||
|
it('con país activo crea el nodo país aunque se omitan niveles intermedios', () => {
|
||||||
|
const graph = buildProvenanceGraph(singleRelation, ['product', 'supplier', 'country'])
|
||||||
|
|
||||||
|
expect(graph.nodes.map(n => n.id)).toContain('country:1')
|
||||||
|
expect(edgeOf(graph, 'supplier:5', 'country:1').certain).toBe(true)
|
||||||
|
})
|
||||||
|
|
||||||
|
it('no crea nodos de país si no se solicita', () => {
|
||||||
|
const graph = buildProvenanceGraph(singleRelation, ['product', 'supplier', 'municipality'])
|
||||||
|
|
||||||
|
expect(graph.nodes.some(n => n.kind === 'country')).toBe(false)
|
||||||
|
})
|
||||||
|
|
||||||
|
it('no duplica aristas cuando varios productos comparten proveedor y municipio', () => {
|
||||||
|
const data = [
|
||||||
|
{ product: { id: 1, name: 'Panela' }, suppliers: [{ supplier: { id: 5, name: 'A' }, municipality: { id: 7, name: 'La Mesa' }, department: { id: 2, name: 'Cundinamarca' } }] },
|
||||||
|
{ product: { id: 2, name: 'Arroz' }, suppliers: [{ supplier: { id: 5, name: 'A' }, municipality: { id: 7, name: 'La Mesa' }, department: { id: 2, name: 'Cundinamarca' } }] },
|
||||||
]
|
]
|
||||||
expect(hasAnyTerritory(noTerritory)).toBe(false)
|
const graph = buildProvenanceGraph(data, ['product', 'supplier', 'municipality'])
|
||||||
|
|
||||||
|
expect(graph.nodes.filter(n => n.id === 'municipality:7')).toHaveLength(1)
|
||||||
|
expect(graph.edges.filter(e => e.from === 'supplier:5' && e.to === 'municipality:7')).toHaveLength(1)
|
||||||
})
|
})
|
||||||
|
|
||||||
it('es false cuando no hay suppliers', () => {
|
it('si el mismo par de nodos repite con distinta certeza, gana la duda', () => {
|
||||||
const noSuppliers = [{ product: { id: 1, name: 'Panela' }, suppliers: [] }]
|
const data = [
|
||||||
expect(hasAnyTerritory(noSuppliers)).toBe(false)
|
{ product: { id: 1, name: 'Panela' }, suppliers: [{ supplier: { id: 5, name: 'A' }, organization: { id: 3, name: 'Red' } }] },
|
||||||
})
|
{ product: { id: 2, name: 'Arroz' }, suppliers: [{ supplier: { id: 5, name: 'A' }, organization: { id: 3, name: 'Red' } }, { supplier: { id: 6, name: 'B' }, organization: { id: 4, name: 'Coop' } }] },
|
||||||
})
|
]
|
||||||
|
const graph = buildProvenanceGraph(data, ['product', 'supplier', 'organization'])
|
||||||
|
|
||||||
describe('buildSupplierOrganizationGraph', () => {
|
expect(graph.edges.filter(e => e.from === 'supplier:5' && e.to === 'organization:3')).toHaveLength(1)
|
||||||
it('crea nodos de producto, proveedor y organización con sus aristas', () => {
|
expect(edgeOf(graph, 'supplier:5', 'organization:3').certain).toBe(false)
|
||||||
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', () => {
|
it('incluye la imagen y el detalle de la entidad del producto', () => {
|
||||||
const graph = buildSupplierOrganizationGraph(provenance)
|
const graph = buildProvenanceGraph(singleRelation)
|
||||||
const product = graph.nodes.find(n => n.id === 'product:1')
|
const product = graph.nodes.find(n => n.id === 'product:1')
|
||||||
|
|
||||||
expect(product.image).toBe('http://localhost/media/panela.jpg')
|
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.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', () => {
|
it('devuelve un grafo vacío cuando no hay provenance', () => {
|
||||||
const graph = buildSupplierOrganizationGraph([])
|
const graph = buildProvenanceGraph([])
|
||||||
|
|
||||||
expect(graph.nodes).toEqual([])
|
expect(graph.nodes).toEqual([])
|
||||||
expect(graph.edges).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' }])
|
|
||||||
})
|
|
||||||
})
|
|
||||||
|
|||||||
83
tests/unit/pages/admin/admin-pages.spec.js
Normal file
83
tests/unit/pages/admin/admin-pages.spec.js
Normal file
@@ -0,0 +1,83 @@
|
|||||||
|
import { describe, expect, it, vi } from 'vitest'
|
||||||
|
import { flushPromises, mount } from '@vue/test-utils'
|
||||||
|
import { createPinia, setActivePinia } from 'pinia'
|
||||||
|
import { useAuthStore } from '@/stores/auth'
|
||||||
|
import OrganizationsManagement from '@/components/provenance/admin/OrganizationsManagement.vue'
|
||||||
|
import SuppliersManagement from '@/components/provenance/admin/SuppliersManagement.vue'
|
||||||
|
import GeographyManagement from '@/components/provenance/admin/GeographyManagement.vue'
|
||||||
|
import OrganizationsPage from '@/pages/admin/organizations.vue'
|
||||||
|
import SuppliersPage from '@/pages/admin/suppliers.vue'
|
||||||
|
import GeographyPage from '@/pages/admin/geography.vue'
|
||||||
|
import vuetify from '@/plugins/vuetify'
|
||||||
|
|
||||||
|
function mockApi () {
|
||||||
|
return {
|
||||||
|
getOrganizations: vi.fn().mockResolvedValue([]),
|
||||||
|
getSuppliers: vi.fn().mockResolvedValue([]),
|
||||||
|
getMunicipalities: vi.fn().mockResolvedValue([]),
|
||||||
|
getCountries: vi.fn().mockResolvedValue([]),
|
||||||
|
getDepartments: vi.fn().mockResolvedValue([]),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function mountAdmin (page, api, role) {
|
||||||
|
const pinia = createPinia()
|
||||||
|
setActivePinia(pinia)
|
||||||
|
const authStore = useAuthStore()
|
||||||
|
authStore.setUser({ role, username: 'admin' })
|
||||||
|
const wrapper = mount(page, {
|
||||||
|
global: { plugins: [pinia, vuetify], provide: { api } },
|
||||||
|
})
|
||||||
|
return { wrapper }
|
||||||
|
}
|
||||||
|
|
||||||
|
async function flushAll (wrapper) {
|
||||||
|
await flushPromises()
|
||||||
|
await wrapper.vm.$nextTick()
|
||||||
|
}
|
||||||
|
|
||||||
|
describe('página admin/organizations', () => {
|
||||||
|
it('renderiza OrganizationsManagement cuando el usuario es administrador', async () => {
|
||||||
|
const { wrapper } = mountAdmin(OrganizationsPage, mockApi(), 'administrator')
|
||||||
|
await flushAll(wrapper)
|
||||||
|
|
||||||
|
expect(wrapper.findComponent(OrganizationsManagement).exists()).toBe(true)
|
||||||
|
})
|
||||||
|
|
||||||
|
it('no renderiza el componente cuando el usuario no es administrador', async () => {
|
||||||
|
const { wrapper } = mountAdmin(OrganizationsPage, mockApi(), 'publico')
|
||||||
|
|
||||||
|
expect(wrapper.findComponent(OrganizationsManagement).exists()).toBe(false)
|
||||||
|
expect(wrapper.text()).toBe('')
|
||||||
|
})
|
||||||
|
})
|
||||||
|
|
||||||
|
describe('página admin/suppliers', () => {
|
||||||
|
it('renderiza SuppliersManagement cuando el usuario es administrador', async () => {
|
||||||
|
const { wrapper } = mountAdmin(SuppliersPage, mockApi(), 'administrator')
|
||||||
|
await flushAll(wrapper)
|
||||||
|
|
||||||
|
expect(wrapper.findComponent(SuppliersManagement).exists()).toBe(true)
|
||||||
|
})
|
||||||
|
|
||||||
|
it('no renderiza el componente cuando el usuario no es administrador', async () => {
|
||||||
|
const { wrapper } = mountAdmin(SuppliersPage, mockApi(), 'publico')
|
||||||
|
|
||||||
|
expect(wrapper.findComponent(SuppliersManagement).exists()).toBe(false)
|
||||||
|
})
|
||||||
|
})
|
||||||
|
|
||||||
|
describe('página admin/geography', () => {
|
||||||
|
it('renderiza GeographyManagement cuando el usuario es administrador', async () => {
|
||||||
|
const { wrapper } = mountAdmin(GeographyPage, mockApi(), 'administrator')
|
||||||
|
await flushAll(wrapper)
|
||||||
|
|
||||||
|
expect(wrapper.findComponent(GeographyManagement).exists()).toBe(true)
|
||||||
|
})
|
||||||
|
|
||||||
|
it('no renderiza el componente cuando el usuario no es administrador', async () => {
|
||||||
|
const { wrapper } = mountAdmin(GeographyPage, mockApi(), 'publico')
|
||||||
|
|
||||||
|
expect(wrapper.findComponent(GeographyManagement).exists()).toBe(false)
|
||||||
|
})
|
||||||
|
})
|
||||||
82
tests/unit/pages/sincronizar_productos_tryton.spec.js
Normal file
82
tests/unit/pages/sincronizar_productos_tryton.spec.js
Normal file
@@ -0,0 +1,82 @@
|
|||||||
|
import { describe, expect, it, vi } from 'vitest'
|
||||||
|
import { flushPromises, mount } from '@vue/test-utils'
|
||||||
|
import { createPinia, setActivePinia } from 'pinia'
|
||||||
|
import { useAuthStore } from '@/stores/auth'
|
||||||
|
import ProductsFromTrytonPage from '@/pages/sincronizar_productos_tryton.vue'
|
||||||
|
import vuetify from '@/plugins/vuetify'
|
||||||
|
|
||||||
|
const syncResult = {
|
||||||
|
checked_tryton_products: [{ id: 190, name: 'Producto 1' }],
|
||||||
|
created_products: [{ id: 3, name: 'Producto 1' }],
|
||||||
|
updated_products: [],
|
||||||
|
failed_products: [],
|
||||||
|
untouched_products: [],
|
||||||
|
created_categories: [
|
||||||
|
{ id: 9, name: 'Abarrotes', external_id: '5' },
|
||||||
|
],
|
||||||
|
updated_categories: [
|
||||||
|
{
|
||||||
|
id: 7,
|
||||||
|
name: 'Cereales',
|
||||||
|
external_id: '7',
|
||||||
|
detail: 'Nombre: Granos → Cereales',
|
||||||
|
},
|
||||||
|
],
|
||||||
|
}
|
||||||
|
|
||||||
|
function mockApi () {
|
||||||
|
return {
|
||||||
|
getProductsFromTryton: vi.fn().mockResolvedValue(syncResult),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async function mountPageAsAdmin (api) {
|
||||||
|
const pinia = createPinia()
|
||||||
|
setActivePinia(pinia)
|
||||||
|
const authStore = useAuthStore()
|
||||||
|
authStore.setUser({ role: 'administrator', username: 'admin' })
|
||||||
|
const wrapper = mount(ProductsFromTrytonPage, {
|
||||||
|
global: { plugins: [pinia, vuetify], provide: { api } },
|
||||||
|
})
|
||||||
|
await flushPromises()
|
||||||
|
await wrapper.vm.$nextTick()
|
||||||
|
return wrapper
|
||||||
|
}
|
||||||
|
|
||||||
|
async function startSync (wrapper) {
|
||||||
|
const button = wrapper
|
||||||
|
.findAll('button')
|
||||||
|
.find(b => b.text().includes('Iniciar Sincronización'))
|
||||||
|
await button.trigger('click')
|
||||||
|
await flushPromises()
|
||||||
|
await wrapper.vm.$nextTick()
|
||||||
|
}
|
||||||
|
|
||||||
|
describe('página sincronizar_productos_tryton', () => {
|
||||||
|
it('muestra las categorías creadas al sincronizar productos', async () => {
|
||||||
|
const wrapper = await mountPageAsAdmin(mockApi())
|
||||||
|
await startSync(wrapper)
|
||||||
|
|
||||||
|
expect(wrapper.text()).toContain('Categorías creadas (1)')
|
||||||
|
expect(wrapper.text()).toContain('Abarrotes')
|
||||||
|
})
|
||||||
|
|
||||||
|
it('muestra las categorías actualizadas con su detalle', async () => {
|
||||||
|
const wrapper = await mountPageAsAdmin(mockApi())
|
||||||
|
await startSync(wrapper)
|
||||||
|
|
||||||
|
expect(wrapper.text()).toContain('Categorías actualizadas (1)')
|
||||||
|
expect(wrapper.text()).toContain('Cereales')
|
||||||
|
expect(wrapper.text()).toContain('Nombre: Granos → Cereales')
|
||||||
|
})
|
||||||
|
|
||||||
|
it('mantiene el resumen de productos al sincronizar', async () => {
|
||||||
|
const api = mockApi()
|
||||||
|
const wrapper = await mountPageAsAdmin(api)
|
||||||
|
await startSync(wrapper)
|
||||||
|
|
||||||
|
expect(api.getProductsFromTryton).toHaveBeenCalled()
|
||||||
|
expect(wrapper.text()).toContain('✅ Creados (1)')
|
||||||
|
expect(wrapper.text()).toContain('Producto 1')
|
||||||
|
})
|
||||||
|
})
|
||||||
@@ -1,100 +0,0 @@
|
|||||||
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')
|
|
||||||
})
|
|
||||||
})
|
|
||||||
Reference in New Issue
Block a user