@innertia-solutions/innertia-nuxt 0.1.85 → 0.1.87

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -16,7 +16,14 @@ const props = defineProps({
16
16
  title: { type: String, default: 'Versiones' },
17
17
  })
18
18
 
19
- const { data, error, pending, refresh } = useFetch(props.endpoint, { server: false, key: `innertia-versions:${props.endpoint}` })
19
+ const { data, error, pending, status, refresh } = useFetch(props.endpoint, { server: false, key: `innertia-versions:${props.endpoint}` })
20
+
21
+ // Con `server: false` el servidor deja el fetch en 'idle' (pending=false) y el cliente
22
+ // lo lanza en onBeforeMount (pending=true) antes de hidratar: si el estado de carga
23
+ // dependiera solo de `pending`, el HTML del servidor (grilla vacía) no coincidiría con
24
+ // el primer render del cliente ("Cargando…") → error de hidratación. 'idle' sin datos
25
+ // también cuenta como cargando, así ambos lados renderizan lo mismo.
26
+ const loading = computed(() => !data.value && !error.value && (pending.value || status.value === 'idle'))
20
27
 
21
28
  function fmtDate(iso) {
22
29
  if (!iso) return '—'
@@ -67,7 +74,7 @@ const sides = computed(() => {
67
74
  </button>
68
75
  </header>
69
76
 
70
- <div v-if="pending && !data" class="p-4 text-sm text-muted-foreground">Cargando…</div>
77
+ <div v-if="loading" class="p-4 text-sm text-muted-foreground">Cargando…</div>
71
78
  <div v-else-if="error" class="p-4 text-sm text-red-600 dark:text-red-400">
72
79
  No se pudieron cargar las versiones ({{ error.statusCode ?? 'error' }}).
73
80
  </div>
@@ -386,7 +386,8 @@ const loadDocx = async () => {
386
386
  }
387
387
  }
388
388
 
389
- watch(() => props.file?.id, () => {
389
+ // También al subir una versión nueva: el id no cambia, pero el contenido sí.
390
+ watch(() => [props.file?.id, props.file?.version], () => {
390
391
  textContent.value = null
391
392
  xlsxWorkbook.value = null
392
393
  xlsxActiveIdx.value = 0
@@ -56,11 +56,19 @@ const props = defineProps({
56
56
  states: { type: Array, required: true },
57
57
  moveMutation: { type: Function, default: null },
58
58
 
59
+ // Bloquea un arrastre ANTES de soltar: (row, fromState, toState) => boolean, síncrona.
60
+ // Si retorna false la columna no se resalta, el cursor indica "no permitido" y el drop
61
+ // no hace nada (no hay optimistic update, ni emit('move'), ni llamada al backend).
62
+ // Solo se consulta al cambiar de columna; reordenar dentro de la misma no pasa por acá.
63
+ canDrop: { type: Function, default: null },
64
+
59
65
  // Endpoint para persistir reorden (POST). Si null → solo cross-column, sin placeholder.
60
66
  reorderEndpoint: { type: String, default: null },
61
67
 
62
68
  // Toolbar visibility
63
69
  showSearch: { type: Boolean, default: true },
70
+ // Término con el que parte el buscador. Solo se lee al montar.
71
+ initialSearch: { type: String, default: '' },
64
72
  searchPlaceholder:{ type: String, default: 'Buscar...' },
65
73
  showColumns: { type: Boolean, default: true },
66
74
  showReloadButton: { type: Boolean, default: true },
@@ -139,7 +147,7 @@ const rows = ref([])
139
147
  const meta = ref(null)
140
148
  const loading = ref(false)
141
149
  const isFetching = ref(false)
142
- const search = ref('')
150
+ const search = ref(props.initialSearch ?? '')
143
151
  const isDataFromCache = ref(false)
144
152
 
145
153
  // Visibilidad de columnas (estados) — { [stateKey]: boolean }
@@ -408,6 +416,8 @@ const loadFromCache = () => {
408
416
  sessionStorage.removeItem(cacheKey.value)
409
417
  return false
410
418
  }
419
+ // Con búsqueda inicial, un caché de otro término no sirve: se pide de nuevo.
420
+ if (props.initialSearch && (cached.search ?? '') !== props.initialSearch) return false
411
421
  rows.value = cached.rows ?? []
412
422
  meta.value = cached.meta ?? null
413
423
  stateVisibility.value = cached.stateVisibility ?? stateVisibility.value
@@ -457,7 +467,24 @@ const onDragStart = (row, state) => {
457
467
  draggedId.value = row.id
458
468
  draggedFrom.value = state
459
469
  }
470
+ // ¿Se puede soltar la tarjeta arrastrada en `state`? Sin prop `canDrop` siempre sí.
471
+ // Sin preventDefault en dragover el navegador rechaza el drop y muestra "no permitido".
472
+ const isDropAllowed = (state) => {
473
+ if (!props.canDrop || !draggedId.value || draggedFrom.value === state) return true
474
+ const row = rows.value.find(r => r.id === draggedId.value)
475
+ if (!row) return true
476
+ try {
477
+ return props.canDrop(row, draggedFrom.value, state) !== false
478
+ } catch (e) {
479
+ console.error('[KanbanStandard] canDrop falló, se bloquea el arrastre:', e)
480
+ return false
481
+ }
482
+ }
460
483
  const onDragOver = (e, state) => {
484
+ if (!isDropAllowed(state)) {
485
+ if (dragOverState.value === state) { dragOverState.value = null; dragOverIndex.value = null }
486
+ return
487
+ }
461
488
  e.preventDefault()
462
489
  if (dragOverState.value !== state) dragOverState.value = state
463
490
  if (!props.reorderEndpoint) return
@@ -483,6 +510,7 @@ const onDragEnd = () => {
483
510
  // Solo escribe el índice si cambió (evita reactividad redundante = menos re-render/parpadeo).
484
511
  const onCardDragOver = (e, state, index) => {
485
512
  if (!props.reorderEndpoint) return
513
+ if (!isDropAllowed(state)) return // burbujea a la columna, que tampoco acepta el drop
486
514
  e.preventDefault()
487
515
  e.stopPropagation()
488
516
  if (dragOverState.value !== state) dragOverState.value = state
@@ -493,6 +521,8 @@ const onCardDragOver = (e, state, index) => {
493
521
  }
494
522
 
495
523
  const onDrop = async (targetState) => {
524
+ // Defensa: el navegador ya no dispara drop si dragover no lo aceptó, pero se revalida.
525
+ const allowed = isDropAllowed(targetState)
496
526
  const id = draggedId.value
497
527
  const fromState = draggedFrom.value
498
528
  const dropIndex = dragOverIndex.value
@@ -500,7 +530,7 @@ const onDrop = async (targetState) => {
500
530
  dragOverIndex.value = null
501
531
  draggedId.value = null
502
532
  draggedFrom.value = null
503
- if (!id) return
533
+ if (!id || !allowed) return
504
534
 
505
535
  // Modo reorden (prop seteada): calcula vecinos y persiste posición.
506
536
  if (props.reorderEndpoint) {
@@ -14,6 +14,9 @@ const props = defineProps({
14
14
  clickRowToOpen: { type: Boolean, default: false },
15
15
  searchPlaceholder: { type: String, default: 'Buscar...' },
16
16
  showSearch: { type: Boolean, default: true },
17
+ // Término con el que parte el buscador (ej. al llegar desde la búsqueda global).
18
+ // Solo se lee al montar; después manda lo que escriba el usuario.
19
+ initialSearch: { type: String, default: '' },
17
20
  showFilters: { type: Boolean, default: true },
18
21
  // Realtime: auto-suscripción a los canales que el backend expone en meta.channels
19
22
  // (`entity.{tabla}.changed` → reload()). realtimeChannel queda como override manual
@@ -151,7 +154,7 @@ const forwardedSlots = computed(() => {
151
154
  return Object.fromEntries(Object.entries(slots).filter(([k]) => !excluded.has(k)))
152
155
  })
153
156
 
154
- const search = ref('')
157
+ const search = ref(props.initialSearch ?? '')
155
158
  const activeFilters = ref({})
156
159
  const tableRef = ref(null)
157
160
  const prefsLoaded = ref(false)
@@ -764,7 +764,8 @@ defineExpose({
764
764
  {{ pagination.pageIndex + 1 }}
765
765
  </span>
766
766
  <span class="text-[10px] font-bold text-muted-foreground uppercase mx-1">de</span>
767
- <span class="text-[10px] font-bold text-muted-foreground">{{ table.getPageCount() }}</span>
767
+ <!-- Sin registros getPageCount() da 0: se muestra "1 de 1", no "1 de 0". -->
768
+ <span class="text-[10px] font-bold text-muted-foreground">{{ Math.max(1, table.getPageCount()) }}</span>
768
769
  </div>
769
770
  <button
770
771
  type="button"
@@ -38,7 +38,11 @@ const formats = [
38
38
  { value: 'json', label: 'JSON' },
39
39
  ]
40
40
 
41
+ // Con columnas para elegir, exportar exige al menos una marcada.
42
+ const noColumnsSelected = computed(() => props.columns.length > 0 && selectedColumns.value.length === 0)
43
+
41
44
  const doExport = () => {
45
+ if (noColumnsSelected.value) return
42
46
  props.tableRef?.exportTable(format.value, true, true, selectedColumns.value)
43
47
  isOpen.value = false
44
48
  }
@@ -158,10 +162,14 @@ defineExpose({ open: () => { isOpen.value = true } })
158
162
  </div>
159
163
 
160
164
  <!-- Export button -->
165
+ <p v-if="noColumnsSelected" class="mb-2 px-1 text-xs text-muted-foreground" role="alert">
166
+ Selecciona al menos una columna para exportar.
167
+ </p>
161
168
  <button
162
169
  type="button"
170
+ :disabled="noColumnsSelected"
163
171
  @click="doExport"
164
- class="w-full py-1.5 px-3 rounded-control bg-primary hover:bg-primary/90 text-white text-sm font-medium transition-colors inline-flex items-center justify-center gap-2"
172
+ class="w-full py-1.5 px-3 rounded-control bg-primary hover:bg-primary/90 text-white text-sm font-medium transition-colors inline-flex items-center justify-center gap-2 disabled:opacity-50 disabled:cursor-not-allowed disabled:hover:bg-primary"
165
173
  >
166
174
  <IconDownload class="size-4" stroke="1.5" />
167
175
  Exportar
@@ -48,6 +48,11 @@ const props = defineProps({
48
48
  // Empty state.
49
49
  emptyMessage: { type: String, default: 'No hay registros.' },
50
50
 
51
+ // Nombre de lo que cuenta el pie ("12 elementos"). El producto puede poner el suyo
52
+ // (ej. item-label="objetivo" item-label-plural="objetivos").
53
+ itemLabel: { type: String, default: 'elemento' },
54
+ itemLabelPlural: { type: String, default: 'elementos' },
55
+
51
56
  // Variante visual:
52
57
  // 'table' — clásico con filas, columnas y bordes (default)
53
58
  // 'list' — compacto tipo file-tree explorer (sin tabla, sin bordes de fila)
@@ -969,7 +974,7 @@ defineExpose({
969
974
 
970
975
  <!-- Total nodes -->
971
976
  <p class="text-sm text-foreground font-medium">
972
- {{ totalRendered }} {{ totalRendered === 1 ? 'nodo' : 'nodos' }}
977
+ {{ totalRendered }} {{ totalRendered === 1 ? itemLabel : itemLabelPlural }}
973
978
  </p>
974
979
 
975
980
  <!-- Cache badge (instant) -->
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@innertia-solutions/innertia-nuxt",
3
- "version": "0.1.85",
3
+ "version": "0.1.87",
4
4
  "description": "Innertia Solutions — Nuxt layer unificada: core, auth, multitenancy, theme y app contexts",
5
5
  "keywords": [
6
6
  "nuxt",
@@ -1,5 +1,5 @@
1
1
  import { describe, it, expect, vi } from 'vitest'
2
- import { decodeJwtPayload, shouldRefreshToken, createTokenRotator } from '../tokenRefresh'
2
+ import { decodeJwtPayload, isPlatformToken, shouldRefreshToken, createTokenRotator } from '../tokenRefresh'
3
3
 
4
4
  function jwt(payload: Record<string, unknown>): string {
5
5
  const b64 = (o: unknown) => Buffer.from(JSON.stringify(o)).toString('base64url')
@@ -30,8 +30,10 @@ describe('shouldRefreshToken', () => {
30
30
  it('no renueva un token ya vencido (Laravel no lo acepta)', () => {
31
31
  expect(shouldRefreshToken(ttl60(), iat + 3601)).toBe(false)
32
32
  })
33
- it('no renueva tokens de plataforma (identidad separada)', () => {
34
- expect(shouldRefreshToken(ttl60({ platform: true }), iat + 3500)).toBe(false)
33
+ it('renueva también tokens de plataforma (contra su propio endpoint)', () => {
34
+ expect(shouldRefreshToken(ttl60({ platform: true }), iat + 3500)).toBe(true)
35
+ expect(isPlatformToken(ttl60({ platform: true }))).toBe(true)
36
+ expect(isPlatformToken(ttl60())).toBe(false)
35
37
  })
36
38
  it('con TTL corto usa 1/3 de la vida como ventana (no renueva en cada request)', () => {
37
39
  const short = jwt({ iat, exp: iat + 300 }) // 5 min
@@ -3,7 +3,7 @@ import type { H3Event } from 'h3'
3
3
  import { readSession, writeSession } from './session'
4
4
  import type { SessionData } from './session'
5
5
  import { buildAuthHeaders, forwardClientHeaders } from './bff'
6
- import { createTokenRotator, shouldRefreshToken } from './tokenRefresh'
6
+ import { createTokenRotator, isPlatformToken, shouldRefreshToken } from './tokenRefresh'
7
7
 
8
8
  // Token de la sesión sellada con renovación deslizante (ver tokenRefresh.ts).
9
9
  // Un rotador por proceso Nitro: deduplica refrescos concurrentes del mismo token.
@@ -15,7 +15,10 @@ function getRotator() {
15
15
  refresh: async (token, ev) => {
16
16
  if (!ev) return null
17
17
  const config = useRuntimeConfig(ev)
18
- const path = String((config as any).authRefresh?.path || 'auth/refresh').replace(/^\/+/, '')
18
+ // La consola de plataforma renueva contra su propio endpoint: un backend sin
19
+ // esa ruta responde 404 y se sigue con el token actual (no cambia de identidad).
20
+ const cfg = (config as any).authRefresh || {}
21
+ const path = String(isPlatformToken(token) ? (cfg.platformPath || 'platform/auth/refresh') : (cfg.path || 'auth/refresh')).replace(/^\/+/, '')
19
22
  const res: any = await $fetch(`${String(config.apiInternalUrl).replace(/\/+$/, '')}/${path}`, {
20
23
  method: 'POST',
21
24
  // Un refresh colgado no debe bloquear el request del usuario: se sigue con el token actual.
@@ -32,20 +32,24 @@ export function decodeJwtPayload(token?: string | null): JwtPayload | null {
32
32
  }
33
33
  }
34
34
 
35
+ /** ¿El token es de la consola de plataforma (identidad separada)? */
36
+ export function isPlatformToken(token: string | null | undefined): boolean {
37
+ return Boolean(decodeJwtPayload(token)?.platform)
38
+ }
39
+
35
40
  /** Ventana máxima (segundos) antes del vencimiento en que se renueva. */
36
41
  export const REFRESH_WINDOW_SECONDS = 10 * 60
37
42
 
38
43
  /**
39
44
  * ¿Conviene renovar ahora? Sí cuando el token sigue vigente y le queda menos de
40
45
  * min(10 min, 1/3 de su vida). El tope por vida evita renovar en cada request si
41
- * el TTL configurado es corto. Los tokens de plataforma (claim `platform`) NO se
42
- * renuevan: auth/refresh de Laravel resuelve el usuario con el modelo de usuarios
43
- * del producto y no conserva el claim, así que emitiría un token de otra identidad.
46
+ * el TTL configurado es corto. Los tokens de plataforma (claim `platform`) también
47
+ * se renuevan, pero contra su propio endpoint (platform/auth/refresh, ver
48
+ * isPlatformToken): el auth/refresh normal de un backend antiguo no conserva el claim.
44
49
  */
45
50
  export function shouldRefreshToken(token: string | null | undefined, nowSeconds: number, windowSeconds = REFRESH_WINDOW_SECONDS): boolean {
46
51
  const payload = decodeJwtPayload(token)
47
52
  if (!payload || typeof payload.exp !== 'number') return false
48
- if (payload.platform) return false
49
53
  const remaining = payload.exp - nowSeconds
50
54
  if (remaining <= 0) return false
51
55
  const issuedAt = typeof payload.iat === 'number' ? payload.iat : (typeof payload.nbf === 'number' ? payload.nbf : null)