Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
0052dfa1da | ||
|
|
3b2f99c7a0 | ||
|
|
00d7f58c9a | ||
|
|
6f24109d91 | ||
|
|
edd14ca790 | ||
|
|
b6e3bddbc6 | ||
|
|
3c0ce03e09 | ||
|
|
e7699befc5 | ||
|
|
44d6e10ea2 | ||
|
|
f5de074ea1 | ||
|
|
8e74d0b516 | ||
|
|
e95ac086f0 | ||
|
|
6a78257d71 | ||
|
|
7a67ba0743 | ||
|
|
bc566b1fc0 | ||
|
|
8fc9df3b50 | ||
|
|
707a05cc6e | ||
|
|
e20f3e1ddf | ||
|
|
5b03066ed2 | ||
|
|
78cc5ef93b | ||
|
|
9a8e12fa8b | ||
|
|
e36525e0d8 | ||
|
|
b00dd14f76 | ||
|
|
97f6fb91d8 | ||
|
|
40f8628e5d | ||
|
|
e7533b402d | ||
|
|
206571627b | ||
|
|
d64218f45f | ||
|
|
7695ca0dea | ||
|
|
bd956328db | ||
|
|
20bc559a6c |
No files matched your search
@@ -0,0 +1,191 @@
|
|||||||
|
# Agente de diagnóstico/corrección (lab-agent)
|
||||||
|
|
||||||
|
Wrapper headless (`scripts/lab-agent/lab-agent.sh`) que corre `claude -p`
|
||||||
|
periódicamente para diagnosticar el estado del lab y, solo para un
|
||||||
|
conjunto explícito y aprobado de recursos, ejecutar una acción
|
||||||
|
correctiva de bajo riesgo. Este documento es tanto referencia técnica
|
||||||
|
como decisión de gobernanza — la lista blanca de abajo es lo que
|
||||||
|
autoriza al agente a actuar sin intervención humana, y debe poder
|
||||||
|
auditarse.
|
||||||
|
|
||||||
|
Estado: **script y prueba end-to-end validados en vivo (2026-08-26)**.
|
||||||
|
El timer de systemd (automatización continua) **todavía no está
|
||||||
|
activo** — pendiente de decisión explícita para habilitarlo.
|
||||||
|
|
||||||
|
## Lista blanca de acciones correctivas automáticas
|
||||||
|
|
||||||
|
Aprobada 2026-08-25, antes de escribir una sola línea de código.
|
||||||
|
|
||||||
|
### 1. `kubectl rollout restart deployment/<nombre>`
|
||||||
|
|
||||||
|
| Condición | Valor |
|
||||||
|
|---|---|
|
||||||
|
| Trigger | Deployment con `readyReplicas < replicas` o condición `Available=False` durante **≥10 minutos consecutivos** |
|
||||||
|
| Namespace elegible | `ecommerce` (todos los deployments detectados ahí en el momento de la corrida) |
|
||||||
|
| Excepción | `medusa-deploy` — el deployment real de "commerce-backend" en la terminología de `CLAUDE.md` (confirmado en vivo 2026-08-25: no existe un deployment llamado literalmente `commerce-backend`) — solo elegible si además la hora **local** del host está entre **00:00–06:00** |
|
||||||
|
| Namespaces excluidos siempre | `argocd`, `kube-system`, cualquier otro namespace de plataforma |
|
||||||
|
|
||||||
|
### 2. `docker restart <contenedor>`
|
||||||
|
|
||||||
|
| Condición | Valor |
|
||||||
|
|---|---|
|
||||||
|
| Contenedores elegibles | **Únicamente `gitea-runner`** |
|
||||||
|
| Trigger | Contenedor no está en estado `running` durante ≥10 min, **o** la API de Gitea Actions reporta un run en estado `running` atascado por más de 10 min sin terminar (señal del incidente de runner zombie del 2026-08-16) |
|
||||||
|
| Degradación segura | Si no hay `GITEA_TOKEN_FILE` configurado o la API falla, esa señal se omite — nunca dispara una acción sobre una lectura no verificada, solo queda la señal de "contenedor caído" |
|
||||||
|
| Excluidos siempre | `gitea`, `nginxproxymanager`, `cloudflared` |
|
||||||
|
|
||||||
|
### 3. Fuera de alcance automático — SIEMPRE (solo diagnóstico + notificación)
|
||||||
|
|
||||||
|
- Borrar cualquier recurso, escalar réplicas, tocar `ConfigMap`/`Secret`/configuración.
|
||||||
|
- Reiniciar `gitea`, `nginxproxymanager`, `cloudflared`.
|
||||||
|
- Cualquier acción sobre `medusa-deploy` fuera de la ventana 00:00–06:00.
|
||||||
|
- Cualquier namespace/deployment no detectado explícitamente en `ecommerce`.
|
||||||
|
|
||||||
|
### 4. Límites obligatorios
|
||||||
|
|
||||||
|
- **Rate limit:** máx. 1 acción correctiva por recurso cada 30 min.
|
||||||
|
- **Sin reintento silencioso:** tras un primer intento cuyo problema no
|
||||||
|
se resuelve, el recurso queda `blocked` — solo notificación, hasta
|
||||||
|
que un humano limpie la entrada en `state.json` o el recurso se
|
||||||
|
recupere solo.
|
||||||
|
- **Logging completo:** cada decisión (actúe o no) se registra en
|
||||||
|
`actions.jsonl` con timestamp, recurso, decisión, resultado y motivo.
|
||||||
|
- **Notificación siempre:** toda acción correctiva o anomalía dispara
|
||||||
|
notificación — nunca es silenciosa.
|
||||||
|
|
||||||
|
## Diseño de seguridad: por qué Claude nunca ejecuta comandos
|
||||||
|
|
||||||
|
`claude -p` se invoca con `--allowedTools ""` (cero herramientas) y
|
||||||
|
`--json-schema`, así que el modelo **nunca** ejecuta un comando —
|
||||||
|
solo devuelve una decisión estructurada
|
||||||
|
(`{"actions":[{"resource","decision","reason"}], "summary"}`). El
|
||||||
|
script bash es el único que ejecuta `kubectl`/`docker`, y solo después
|
||||||
|
de revalidar la decisión contra su propio cálculo de elegibilidad —
|
||||||
|
nunca confía en el JSON de Claude por sí solo.
|
||||||
|
|
||||||
|
Se descartó dar a Claude un `Bash` tool con un patrón tipo
|
||||||
|
`Bash(kubectl rollout restart deployment/medusa-deploy -n ecommerce)`
|
||||||
|
porque se comprobó en vivo (2026-08-25) que `--allowedTools` hace
|
||||||
|
**coincidencia por prefijo, no exacta**: un patrón `Bash(echo pintest)`
|
||||||
|
también permite ejecutar `echo pintest && echo INJECTED` o
|
||||||
|
`echo pintest; rm -rf /`. Para un comando root-capaz eso no es un
|
||||||
|
límite seguro. Con `--allowedTools ""`, el peor caso posible es que
|
||||||
|
Claude proponga una decisión incorrecta en el JSON — y el wrapper la
|
||||||
|
rechaza si el recurso no está en su propia lista de elegibles.
|
||||||
|
|
||||||
|
El prompt también advierte contra prompt injection: los datos de
|
||||||
|
diagnóstico (estado de pods, logs) podrían contener texto arbitrario
|
||||||
|
si algo en el cluster está comprometido, e instruye a Claude a ignorar
|
||||||
|
cualquier instrucción incrustada ahí.
|
||||||
|
|
||||||
|
## Autenticación: login de suscripción, no API key
|
||||||
|
|
||||||
|
`ANTHROPIC_API_KEY_FILE` queda vacío por defecto — `claude -p` usa el
|
||||||
|
login de suscripción ya activo del usuario que corre el script
|
||||||
|
(`~/.claude/.credentials.json`), el mismo que usa una sesión
|
||||||
|
interactiva normal. Esta decisión se tomó en vivo (2026-08-26) al
|
||||||
|
confirmar que no había una API key real disponible; el diseño original
|
||||||
|
pedía un secreto root-only para la API key, pero se simplificó porque:
|
||||||
|
|
||||||
|
1. No hacía falta una API key aparte — la suscripción ya cubre esto.
|
||||||
|
2. Elimina la necesidad de crear secretos root-only vía `sudo` (que
|
||||||
|
además está bloqueado para una sesión de Claude Code interactiva
|
||||||
|
por diseño — ver `feedback_scoped_root_access_pattern` en memoria
|
||||||
|
del proyecto).
|
||||||
|
|
||||||
|
**Consecuencia directa:** el servicio systemd (cuando se active) debe
|
||||||
|
correr como usuario `devops`, no como `root` — root no tiene acceso a
|
||||||
|
ese login. `CLAUDE_BIN`/`KUBECTL_BIN` apuntan por ruta absoluta a
|
||||||
|
`/DATA/AppData/home-devops/.local/bin/` porque ese directorio no está
|
||||||
|
en el `PATH` de root ni de systemd (confirmado en vivo: `sudo which
|
||||||
|
claude` no lo encuentra).
|
||||||
|
|
||||||
|
El único secreto que queda es `GITEA_TOKEN_FILE` (token de Gitea
|
||||||
|
Actions, opcional, scope lectura), dueño `devops`, `600` — sin sudo.
|
||||||
|
|
||||||
|
## Prueba end-to-end (2026-08-26)
|
||||||
|
|
||||||
|
Ejecutada contra el cluster real, rama `fix/lab-agent-diagnostico-headless`.
|
||||||
|
Umbral bajado a 2 minutos solo para esta prueba (`UNHEALTHY_THRESHOLD_MIN`,
|
||||||
|
valor real en producción: 10). Canario desechable: `deployment/test-agent-canary`
|
||||||
|
en `ecommerce`, imagen `busybox:stable` con `command: ["sh","-c","exit 1"]`
|
||||||
|
— garantiza `CrashLoopBackOff` predecible, sin relación con
|
||||||
|
`catalog-api-deploy`/`frontend-deploy`/`medusa-deploy`.
|
||||||
|
|
||||||
|
### Bugs encontrados y corregidos durante la prueba
|
||||||
|
|
||||||
|
1. **Subshell perdía el resultado de la acción.** `execute_corrective_action`
|
||||||
|
se invocaba como `result="$(execute_corrective_action "$resource")"` —
|
||||||
|
al correr en un subshell, las variables `LAST_ACTION_CMD`/`STDOUT`/`STDERR`
|
||||||
|
nunca volvían al script principal → crash con `unbound variable`.
|
||||||
|
Corregido: la función ahora devuelve éxito/fallo por exit status, invocada
|
||||||
|
directamente (sin `$(...)`) para que sus variables globales persistan.
|
||||||
|
2. **DRY_RUN contaminaba el estado real.** El wrapper marcaba `blocked=true`
|
||||||
|
en `state.json` incluso en modo simulación, lo que habría bloqueado
|
||||||
|
incorrectamente una corrida real posterior sobre el mismo recurso.
|
||||||
|
Corregido: la actualización de `state.json` (bloqueo/rate-limit) solo
|
||||||
|
ocurre fuera de `DRY_RUN`.
|
||||||
|
3. **`claude`/`kubectl` fuera del PATH de root/systemd** — ver sección de
|
||||||
|
autenticación arriba. Corregido con `CLAUDE_BIN`/`KUBECTL_BIN` por ruta
|
||||||
|
absoluta.
|
||||||
|
|
||||||
|
### Evidencia por paso
|
||||||
|
|
||||||
|
**DRY_RUN (elegibilidad + decisión, sin tocar el cluster):**
|
||||||
|
|
||||||
|
- 1ª corrida (recién detectado): `elegibilidad=not_eligible:bajo_umbral(0m<2m)`
|
||||||
|
→ Claude devolvió `notify_only` para los 5 recursos.
|
||||||
|
- 2ª corrida (>2 min después): `elegibilidad=eligible` para
|
||||||
|
`test-agent-canary` → Claude devolvió `decision:"restart"` solo para
|
||||||
|
ese recurso, `notify_only` para los otros 4 (sanos).
|
||||||
|
- Log: `ACCIÓN EJECUTADA: kubectl -n ecommerce rollout restart
|
||||||
|
deployment/test-agent-canary -> OK`, pero verificado en el cluster real
|
||||||
|
que **no hubo restart** (sin anotación `restartedAt`, mismo pod, misma
|
||||||
|
edad). `actions.jsonl` registra `"dry_run": true`.
|
||||||
|
|
||||||
|
**Ejecución real (`--live`):**
|
||||||
|
|
||||||
|
- Misma decisión de Claude (`restart` para el canario, `notify_only` para
|
||||||
|
el resto).
|
||||||
|
- Verificado en el cluster: nueva anotación
|
||||||
|
`kubectl.kubernetes.io/restartedAt` en el deployment, evento
|
||||||
|
`ScalingReplicaSet` de un ReplicaSet **nuevo**, pod nuevo en otro nodo.
|
||||||
|
- `actions.jsonl`: `"result": "success", "dry_run": false`.
|
||||||
|
- `state.json`: `last_action_at` seteado, `blocked: true`.
|
||||||
|
|
||||||
|
**Rate limit / sin reintento silencioso:**
|
||||||
|
|
||||||
|
- El canario (siempre crashea por diseño) volvió a estar unhealthy sin
|
||||||
|
intervención extra.
|
||||||
|
- Corrida siguiente: `elegibilidad=not_eligible:blocked_tras_intento_previo_sin_recuperacion`.
|
||||||
|
- Claude devolvió `notify_only` para **todos** los recursos, incluido el
|
||||||
|
canario — ningún segundo restart propuesto ni ejecutado.
|
||||||
|
- `state.json` sin cambios (mismo `last_action_at` que la corrida real
|
||||||
|
anterior) — confirma que no hubo reintento.
|
||||||
|
- Notificación real entregada vía ntfy.sh, confirmada leyendo el propio
|
||||||
|
historial del topic (no solo el log del script).
|
||||||
|
|
||||||
|
**Limpieza:** `deployment/test-agent-canary` eliminado, entrada
|
||||||
|
correspondiente en `state.json` borrada. Los logs de la prueba
|
||||||
|
(`actions.jsonl`, `run-*.log`) se conservan como evidencia auditable —
|
||||||
|
no se purgaron.
|
||||||
|
|
||||||
|
## Notificaciones
|
||||||
|
|
||||||
|
Canal: [ntfy](https://ntfy.sh) — sin sistema de notificación previo en
|
||||||
|
el lab, se eligió la opción sin infraestructura nueva (tópico público
|
||||||
|
de ntfy.sh, nombre privado difícil de adivinar) para validar la prueba
|
||||||
|
end-to-end sin bloquear en instalar y exponer un contenedor propio.
|
||||||
|
Migrar a un ntfy self-hosted (mismo patrón que gitea/nginxproxymanager/
|
||||||
|
cloudflared) es un cambio de una sola variable (`NTFY_URL`) cuando se
|
||||||
|
decida.
|
||||||
|
|
||||||
|
## Pendiente antes de activar el timer en continuo
|
||||||
|
|
||||||
|
- **Confirmación explícita del propietario del lab** para habilitar el
|
||||||
|
timer de systemd (Paso 4 original) — no se activa automáticamente
|
||||||
|
solo por haber pasado la prueba end-to-end.
|
||||||
|
- Unidad systemd corriendo como `devops` (no root), con límites de
|
||||||
|
CPU/memoria.
|
||||||
|
- Opcional: `GITEA_TOKEN_FILE` para activar la señal de "runner
|
||||||
|
atascado" vía API de Gitea Actions (hoy se omite, degradación segura).
|
||||||
@@ -1,13 +1,14 @@
|
|||||||
# ADR 0005 — Rediseño del storefront para catálogo multi-categoría
|
# ADR 0005 — Rediseño del storefront para catálogo multi-categoría
|
||||||
|
|
||||||
**Estado:** propuesta — pendiente de aprobación antes de Etapa 2
|
**Estado:** aceptada — Etapa 2 implementada y en producción
|
||||||
**Fecha:** 2026-08-23
|
**Fecha:** 2026-08-23 (Etapa 1) — actualizado 2026-08-25 (Etapa 2 completa)
|
||||||
|
|
||||||
> Este documento es la propuesta de Etapa 1 del rediseño de ARI
|
> Este documento arrancó como la propuesta de Etapa 1 del rediseño de
|
||||||
> Shopping. No incluye código de producción — solo auditoría,
|
> ARI Shopping (auditoría, decisión — ver también [ADR 0004](0004-evaluacion-stack-multi-categoria.md) —
|
||||||
> decisión (ver también [ADR 0004](0004-evaluacion-stack-multi-categoria.md)),
|
> patrones de UX y datos demo). Etapa 2 fue aprobada y se implementó
|
||||||
> patrones de UX y datos demo ya creados y visibles en producción
|
> completa en tres sub-fases (datos/categorías, navegación,
|
||||||
> como línea base.
|
> componentes visuales) — ver la sección 6 para el detalle de cada
|
||||||
|
> sub-fase y sus PRs.
|
||||||
|
|
||||||
## 1. Resumen de la auditoría
|
## 1. Resumen de la auditoría
|
||||||
|
|
||||||
@@ -255,12 +256,33 @@ objetivo es validar la tubería Admin → MinIO → NPM → frontend, no el
|
|||||||
contenido visual final.
|
contenido visual final.
|
||||||
|
|
||||||
Usuario admin temporal `[email protected]` usado para esta
|
Usuario admin temporal `[email protected]` usado para esta
|
||||||
auditoría — pendiente de borrar una vez aprobada esta propuesta.
|
auditoría — pendiente de borrar (ver sección 6).
|
||||||
|
|
||||||
## 6. Próximos pasos
|
## 6. Etapa 2 — implementada (2026-08-23 a 2026-08-25)
|
||||||
|
|
||||||
Pendiente de tu aprobación explícita antes de iniciar Etapa 2. Cuando
|
Aprobada y ejecutada en tres sub-fases, cada una validada en vivo
|
||||||
apruebes, Etapa 2 se dividirá en sub-fases (datos/categorías primero,
|
contra estos 9 productos demo:
|
||||||
luego navegación, luego componentes visuales), validando en cada paso
|
|
||||||
contra estos 9 productos demo que precio/descripción/imágenes siguen
|
1. **Datos/categorías** (2026-08-23/24): fix del bug de Store API que
|
||||||
actualizándose correctamente desde Admin.
|
impedía ver la categoría real de un producto (causa raíz del ADR
|
||||||
|
0004); 21 categorías/9 productos demo creados; `legacyProductMeta`
|
||||||
|
eliminado (PR #29) — 17 productos legacy con categoría/colección/
|
||||||
|
marca/rango de edad reales.
|
||||||
|
2. **Navegación** (2026-08-25): navbar y tiles del home pasaron de
|
||||||
|
arrays hardcodeados a data-driven contra el árbol real de
|
||||||
|
categorías (`getCategories()`, PR #32); guard de CI actualizado
|
||||||
|
(PR #33); fix de tipos (PR #34); home/layout forzados a render
|
||||||
|
dinámico para evitar que quedaran cacheados con datos mock (PR #35).
|
||||||
|
3. **Componentes visuales** (2026-08-25), los 4 patrones de la
|
||||||
|
sección 3 más el breadcrumb/facetas de Amazon: mega-menú
|
||||||
|
"Departamentos" multi-columna (PR #36), badges antes/ahora
|
||||||
|
(PR #37), swatches de variante inline (PR #38), mensaje de
|
||||||
|
urgencia por inventario real (PR #39), breadcrumb real + conteos
|
||||||
|
por filtro en el catálogo (PR #40), tiles promocionales
|
||||||
|
intercalados en la grilla (PR #41, con fix-forward de tipos en
|
||||||
|
PR #42).
|
||||||
|
|
||||||
|
**Pendiente:** borrar el usuario admin temporal `[email protected]`
|
||||||
|
de Medusa Admin (creado para la auditoría de la sección 5, ya no
|
||||||
|
necesario). Sin próxima etapa definida todavía — este ADR no
|
||||||
|
especifica una Etapa 3.
|
||||||
@@ -84,6 +84,7 @@ nav:
|
|||||||
- Visión general: arquitectura/vision-general.md
|
- Visión general: arquitectura/vision-general.md
|
||||||
- Red y exposición: arquitectura/red-y-exposicion.md
|
- Red y exposición: arquitectura/red-y-exposicion.md
|
||||||
- Flujo GitOps: arquitectura/gitops-flujo.md
|
- Flujo GitOps: arquitectura/gitops-flujo.md
|
||||||
|
- Agente de monitoreo: arquitectura/agente-monitoreo.md
|
||||||
- Glosario: arquitectura/glosario.md
|
- Glosario: arquitectura/glosario.md
|
||||||
- Decisiones (ADRs):
|
- Decisiones (ADRs):
|
||||||
- "0001 · Por qué k3d": decisiones/0001-por-que-k3d.md
|
- "0001 · Por qué k3d": decisiones/0001-por-que-k3d.md
|
||||||
|
|||||||
@@ -25,7 +25,7 @@ spec:
|
|||||||
runAsNonRoot: false
|
runAsNonRoot: false
|
||||||
containers:
|
containers:
|
||||||
- name: app
|
- name: app
|
||||||
image: gitea.cruzcloud.net/devops/docs-portal:v1.0.125
|
image: gitea.cruzcloud.net/devops/docs-portal:v1.0.159
|
||||||
# El base saca TODAS las capabilities. Probado en vivo y
|
# El base saca TODAS las capabilities. Probado en vivo y
|
||||||
# revertido: con drop: ALL (aunque se agregue NET_BIND_SERVICE
|
# revertido: con drop: ALL (aunque se agregue NET_BIND_SERVICE
|
||||||
# de vuelta) el propio entrypoint de nginx:1.27-alpine falla al
|
# de vuelta) el propio entrypoint de nginx:1.27-alpine falla al
|
||||||
|
|||||||
@@ -41,6 +41,7 @@ export default async function CatalogPage({ searchParams }: CatalogPageProps) {
|
|||||||
<CatalogClient
|
<CatalogClient
|
||||||
key={`${category}:${collection}:${query}`}
|
key={`${category}:${collection}:${query}`}
|
||||||
products={products}
|
products={products}
|
||||||
|
categories={categories}
|
||||||
categoryGroups={categoryGroups}
|
categoryGroups={categoryGroups}
|
||||||
initialCategory={category}
|
initialCategory={category}
|
||||||
initialCollection={collection}
|
initialCollection={collection}
|
||||||
|
|||||||
@@ -6,6 +6,13 @@ import { Navbar } from "@/components/layout/navbar";
|
|||||||
import { WishlistDrawer } from "@/components/wishlist/wishlist-drawer";
|
import { WishlistDrawer } from "@/components/wishlist/wishlist-drawer";
|
||||||
import { getCategories, getProducts } from "@/lib/headless/client";
|
import { getCategories, getProducts } from "@/lib/headless/client";
|
||||||
|
|
||||||
|
// El Navbar (categorias/colecciones/predictive search) vive en este layout
|
||||||
|
// compartido -- si alguna pagina futura queda estatica, este fetch se
|
||||||
|
// congelaria con datos de build time (mock) igual que le paso al home
|
||||||
|
// (ver app/page.tsx). Forzarlo aca protege el nav en cualquier ruta, no
|
||||||
|
// solo en las que hoy ya son dinamicas por otro motivo (searchParams, etc.).
|
||||||
|
export const dynamic = "force-dynamic";
|
||||||
|
|
||||||
export const metadata: Metadata = {
|
export const metadata: Metadata = {
|
||||||
metadataBase: new URL(process.env.NEXT_PUBLIC_SITE_URL ?? "https://shop.cruzcloud.net"),
|
metadataBase: new URL(process.env.NEXT_PUBLIC_SITE_URL ?? "https://shop.cruzcloud.net"),
|
||||||
title: { default: "ARI Shopping | Juguetes, regalos y variedades", template: "%s | ARI Shopping" },
|
title: { default: "ARI Shopping | Juguetes, regalos y variedades", template: "%s | ARI Shopping" },
|
||||||
|
|||||||
@@ -7,6 +7,13 @@ import { ProductCarousel } from "@/components/product/product-carousel";
|
|||||||
import { Button } from "@/components/ui/button";
|
import { Button } from "@/components/ui/button";
|
||||||
import { getCategories, getProducts } from "@/lib/headless/client";
|
import { getCategories, getProducts } from "@/lib/headless/client";
|
||||||
|
|
||||||
|
// Sin esto, Next.js prerenderiza "/" en build time dentro del Dockerfile,
|
||||||
|
// donde HEADLESS_PROVIDER/MEDUSA_* todavia no existen (solo se inyectan en
|
||||||
|
// runtime via el Deployment) -- cae al provider mock y ese HTML queda
|
||||||
|
// cacheado 1 año (visto en vivo: x-nextjs-prerender:1, s-maxage=31536000),
|
||||||
|
// violando el flujo Admin -> revalidate del ADR 0005 justo en el home.
|
||||||
|
export const dynamic = "force-dynamic";
|
||||||
|
|
||||||
export default async function HomePage() {
|
export default async function HomePage() {
|
||||||
const [products, categories] = await Promise.all([getProducts(), getCategories()]);
|
const [products, categories] = await Promise.all([getProducts(), getCategories()]);
|
||||||
const treasures = products.filter((product) => product.isNew || product.featured).slice(0, 8);
|
const treasures = products.filter((product) => product.isNew || product.featured).slice(0, 8);
|
||||||
|
|||||||
@@ -1,22 +1,70 @@
|
|||||||
"use client";
|
"use client";
|
||||||
|
|
||||||
import { SlidersHorizontal, X } from "lucide-react";
|
import Link from "next/link";
|
||||||
|
import { ChevronRight, SlidersHorizontal, X } from "lucide-react";
|
||||||
import { useEffect, useMemo, useState } from "react";
|
import { useEffect, useMemo, useState } from "react";
|
||||||
|
import { PromoTile } from "@/components/home/category-tiles";
|
||||||
import { ProductCard } from "@/components/product/product-card";
|
import { ProductCard } from "@/components/product/product-card";
|
||||||
import { Button } from "@/components/ui/button";
|
import { Button } from "@/components/ui/button";
|
||||||
import { Input } from "@/components/ui/input";
|
import { Input } from "@/components/ui/input";
|
||||||
import type { Product } from "@/lib/headless/types";
|
import type { Category, Product } from "@/lib/headless/types";
|
||||||
|
|
||||||
|
// Cada cuantas tarjetas de producto se intercala un tile promocional en
|
||||||
|
// la grilla (patron Walmart, ADR 0005 seccion 3): grid con tiles
|
||||||
|
// promocionales intercalados, no solo tarjetas homogeneas.
|
||||||
|
const PROMO_TILE_INTERVAL = 8;
|
||||||
|
|
||||||
|
type GridItem = { type: "product"; product: Product } | { type: "promo"; category: Category };
|
||||||
|
|
||||||
type CatalogClientProps = {
|
type CatalogClientProps = {
|
||||||
products: Product[];
|
products: Product[];
|
||||||
|
categories?: Category[];
|
||||||
categoryGroups?: Record<string, string[]>;
|
categoryGroups?: Record<string, string[]>;
|
||||||
initialCategory?: string;
|
initialCategory?: string;
|
||||||
initialCollection?: string;
|
initialCollection?: string;
|
||||||
initialQuery?: string;
|
initialQuery?: string;
|
||||||
};
|
};
|
||||||
|
|
||||||
|
function matchesQuery(product: Product, query: string): boolean {
|
||||||
|
if (!query) return true;
|
||||||
|
const search = [product.name, product.category, product.collection, product.brand].join(" ").toLowerCase();
|
||||||
|
return search.includes(query.toLowerCase());
|
||||||
|
}
|
||||||
|
function matchesCategory(product: Product, allowedCategories: string[]): boolean {
|
||||||
|
return allowedCategories.includes(product.category);
|
||||||
|
}
|
||||||
|
function matchesCollection(product: Product, collection: string): boolean {
|
||||||
|
return !collection || product.collection === collection;
|
||||||
|
}
|
||||||
|
function matchesBrand(product: Product, brand: string): boolean {
|
||||||
|
return brand === "Todas" || product.brand === brand;
|
||||||
|
}
|
||||||
|
function matchesAge(product: Product, age: string): boolean {
|
||||||
|
return age === "Todas" || product.ageRange === age;
|
||||||
|
}
|
||||||
|
function matchesPrice(product: Product, maxPrice: number): boolean {
|
||||||
|
return product.price === null || maxPrice === 0 || product.price <= maxPrice;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Camina parentId hacia arriba desde la categoria seleccionada para armar
|
||||||
|
// el breadcrumb real (Inicio > raiz > hija), igual que en Amazon.
|
||||||
|
function buildBreadcrumb(categories: Category[], name: string): Category[] {
|
||||||
|
const node = categories.find((category) => category.name === name);
|
||||||
|
if (!node) return [];
|
||||||
|
const trail = [node];
|
||||||
|
let current = node;
|
||||||
|
while (current.parentId) {
|
||||||
|
const parent = categories.find((category) => category.id === current.parentId);
|
||||||
|
if (!parent) break;
|
||||||
|
trail.unshift(parent);
|
||||||
|
current = parent;
|
||||||
|
}
|
||||||
|
return trail;
|
||||||
|
}
|
||||||
|
|
||||||
export function CatalogClient({
|
export function CatalogClient({
|
||||||
products,
|
products,
|
||||||
|
categories: categoryNodes = [],
|
||||||
categoryGroups = {},
|
categoryGroups = {},
|
||||||
initialCategory = "Todos",
|
initialCategory = "Todos",
|
||||||
initialCollection = "",
|
initialCollection = "",
|
||||||
@@ -55,29 +103,25 @@ export function CatalogClient({
|
|||||||
// tiene la raiz asignada directamente. Si no es una raiz conocida, se
|
// tiene la raiz asignada directamente. Si no es una raiz conocida, se
|
||||||
// trata como el nombre de categoria exacto de siempre.
|
// trata como el nombre de categoria exacto de siempre.
|
||||||
const allowedCategories = categoryGroups[category] ?? [category];
|
const allowedCategories = categoryGroups[category] ?? [category];
|
||||||
|
const breadcrumb = useMemo(() => (category === "Todos" ? [] : buildBreadcrumb(categoryNodes, category)), [categoryNodes, category]);
|
||||||
|
// No promociona la misma categoria raiz que el usuario ya esta viendo.
|
||||||
|
const promoRoots = useMemo(() => {
|
||||||
|
const excludeRootId = breadcrumb[0]?.id;
|
||||||
|
return categoryNodes.filter((node) => !node.parentId && node.id !== excludeRootId);
|
||||||
|
}, [categoryNodes, breadcrumb]);
|
||||||
|
|
||||||
const filtered = useMemo(
|
const filtered = useMemo(
|
||||||
() =>
|
() =>
|
||||||
products
|
products
|
||||||
.filter((product) => {
|
.filter(
|
||||||
const search = [
|
(product) =>
|
||||||
product.name,
|
matchesQuery(product, query) &&
|
||||||
product.category,
|
(category === "Todos" || matchesCategory(product, allowedCategories)) &&
|
||||||
product.collection,
|
matchesCollection(product, collection) &&
|
||||||
product.brand,
|
matchesBrand(product, brand) &&
|
||||||
]
|
matchesAge(product, age) &&
|
||||||
.join(" ")
|
matchesPrice(product, maxPrice),
|
||||||
.toLowerCase();
|
)
|
||||||
|
|
||||||
return (
|
|
||||||
(!query || search.includes(query.toLowerCase())) &&
|
|
||||||
(category === "Todos" || allowedCategories.includes(product.category)) &&
|
|
||||||
(!collection || product.collection === collection) &&
|
|
||||||
(brand === "Todas" || product.brand === brand) &&
|
|
||||||
(age === "Todas" || product.ageRange === age) &&
|
|
||||||
(product.price === null || maxPrice === 0 || product.price <= maxPrice)
|
|
||||||
);
|
|
||||||
})
|
|
||||||
.sort((a, b) =>
|
.sort((a, b) =>
|
||||||
sort === "name"
|
sort === "name"
|
||||||
? a.name.localeCompare(b.name, "es")
|
? a.name.localeCompare(b.name, "es")
|
||||||
@@ -88,6 +132,78 @@ export function CatalogClient({
|
|||||||
[age, allowedCategories, brand, category, collection, maxPrice, products, query, sort],
|
[age, allowedCategories, brand, category, collection, maxPrice, products, query, sort],
|
||||||
);
|
);
|
||||||
|
|
||||||
|
// Intercala un tile promocional cada PROMO_TILE_INTERVAL productos,
|
||||||
|
// ciclando por las categorias raiz -- si no hay jerarquia de
|
||||||
|
// categorias disponible, la grilla queda igual que antes (solo
|
||||||
|
// productos).
|
||||||
|
const gridItems = useMemo<GridItem[]>(() => {
|
||||||
|
if (promoRoots.length === 0) return filtered.map((product) => ({ type: "product", product }));
|
||||||
|
|
||||||
|
const items: GridItem[] = [];
|
||||||
|
let promoIndex = 0;
|
||||||
|
filtered.forEach((product, index) => {
|
||||||
|
items.push({ type: "product", product });
|
||||||
|
const isLast = index === filtered.length - 1;
|
||||||
|
const promoCategory = promoRoots[promoIndex % promoRoots.length];
|
||||||
|
if (!isLast && (index + 1) % PROMO_TILE_INTERVAL === 0 && promoCategory) {
|
||||||
|
items.push({ type: "promo", category: promoCategory });
|
||||||
|
promoIndex += 1;
|
||||||
|
}
|
||||||
|
});
|
||||||
|
return items;
|
||||||
|
}, [filtered, promoRoots]);
|
||||||
|
|
||||||
|
// Conteos por valor de filtro (patron Amazon: "Marca (12)"), calculados
|
||||||
|
// sobre los productos que ya pasan el resto de filtros activos -- cada
|
||||||
|
// dimension se cuenta excluyendose a si misma para reflejar cuantos
|
||||||
|
// resultados habria si se eligiera ese valor.
|
||||||
|
const categoryCounts = useMemo(() => {
|
||||||
|
const base = products.filter(
|
||||||
|
(product) => matchesQuery(product, query) && matchesCollection(product, collection) && matchesBrand(product, brand) && matchesAge(product, age) && matchesPrice(product, maxPrice),
|
||||||
|
);
|
||||||
|
const counts: Record<string, number> = { Todos: base.length };
|
||||||
|
for (const name of categories) {
|
||||||
|
if (name === "Todos") continue;
|
||||||
|
const allowed = categoryGroups[name] ?? [name];
|
||||||
|
counts[name] = base.filter((product) => matchesCategory(product, allowed)).length;
|
||||||
|
}
|
||||||
|
return counts;
|
||||||
|
}, [age, brand, categories, categoryGroups, collection, maxPrice, products, query]);
|
||||||
|
|
||||||
|
const brandCounts = useMemo(() => {
|
||||||
|
const base = products.filter(
|
||||||
|
(product) =>
|
||||||
|
matchesQuery(product, query) &&
|
||||||
|
(category === "Todos" || matchesCategory(product, allowedCategories)) &&
|
||||||
|
matchesCollection(product, collection) &&
|
||||||
|
matchesAge(product, age) &&
|
||||||
|
matchesPrice(product, maxPrice),
|
||||||
|
);
|
||||||
|
const counts: Record<string, number> = { Todas: base.length };
|
||||||
|
for (const value of brands) {
|
||||||
|
if (value === "Todas") continue;
|
||||||
|
counts[value] = base.filter((product) => product.brand === value).length;
|
||||||
|
}
|
||||||
|
return counts;
|
||||||
|
}, [age, allowedCategories, brands, category, collection, maxPrice, products, query]);
|
||||||
|
|
||||||
|
const ageCounts = useMemo(() => {
|
||||||
|
const base = products.filter(
|
||||||
|
(product) =>
|
||||||
|
matchesQuery(product, query) &&
|
||||||
|
(category === "Todos" || matchesCategory(product, allowedCategories)) &&
|
||||||
|
matchesCollection(product, collection) &&
|
||||||
|
matchesBrand(product, brand) &&
|
||||||
|
matchesPrice(product, maxPrice),
|
||||||
|
);
|
||||||
|
const counts: Record<string, number> = { Todas: base.length };
|
||||||
|
for (const value of ages) {
|
||||||
|
if (value === "Todas") continue;
|
||||||
|
counts[value] = base.filter((product) => product.ageRange === value).length;
|
||||||
|
}
|
||||||
|
return counts;
|
||||||
|
}, [ages, allowedCategories, brand, category, collection, maxPrice, products, query]);
|
||||||
|
|
||||||
const reset = () => {
|
const reset = () => {
|
||||||
setQuery("");
|
setQuery("");
|
||||||
setCategory("Todos");
|
setCategory("Todos");
|
||||||
@@ -101,6 +217,27 @@ export function CatalogClient({
|
|||||||
return (
|
return (
|
||||||
<div className="mx-auto max-w-7xl px-4 py-10">
|
<div className="mx-auto max-w-7xl px-4 py-10">
|
||||||
<div className="mb-8">
|
<div className="mb-8">
|
||||||
|
{breadcrumb.length > 0 && (
|
||||||
|
<nav aria-label="Breadcrumb" className="mb-4 flex flex-wrap items-center gap-1.5 text-xs font-bold text-slate-500">
|
||||||
|
<Link href="/catalog" prefetch={false} className="hover:text-fuchsia-600">
|
||||||
|
Inicio
|
||||||
|
</Link>
|
||||||
|
{breadcrumb.map((node, index) => (
|
||||||
|
<span key={node.id} className="flex items-center gap-1.5">
|
||||||
|
<ChevronRight className="size-3" />
|
||||||
|
{index === breadcrumb.length - 1 ? (
|
||||||
|
<span aria-current="page" className="text-slate-900">
|
||||||
|
{node.name}
|
||||||
|
</span>
|
||||||
|
) : (
|
||||||
|
<Link href={`/catalog?category=${encodeURIComponent(node.name)}`} prefetch={false} className="hover:text-fuchsia-600">
|
||||||
|
{node.name}
|
||||||
|
</Link>
|
||||||
|
)}
|
||||||
|
</span>
|
||||||
|
))}
|
||||||
|
</nav>
|
||||||
|
)}
|
||||||
<span className="text-xs font-black uppercase tracking-[.18em] text-fuchsia-600">
|
<span className="text-xs font-black uppercase tracking-[.18em] text-fuchsia-600">
|
||||||
Catálogo completo
|
Catálogo completo
|
||||||
</span>
|
</span>
|
||||||
@@ -134,9 +271,10 @@ export function CatalogClient({
|
|||||||
values={categories}
|
values={categories}
|
||||||
selected={category}
|
selected={category}
|
||||||
onChange={setCategory}
|
onChange={setCategory}
|
||||||
|
counts={categoryCounts}
|
||||||
/>
|
/>
|
||||||
<Filter title="Marca" values={brands} selected={brand} onChange={setBrand} />
|
<Filter title="Marca" values={brands} selected={brand} onChange={setBrand} counts={brandCounts} />
|
||||||
<Filter title="Edad" values={ages} selected={age} onChange={setAge} />
|
<Filter title="Edad" values={ages} selected={age} onChange={setAge} counts={ageCounts} />
|
||||||
|
|
||||||
<fieldset>
|
<fieldset>
|
||||||
<legend className="mb-3 text-sm font-black">Precio máximo</legend>
|
<legend className="mb-3 text-sm font-black">Precio máximo</legend>
|
||||||
@@ -180,9 +318,13 @@ export function CatalogClient({
|
|||||||
|
|
||||||
{filtered.length ? (
|
{filtered.length ? (
|
||||||
<div className="grid gap-5 sm:grid-cols-2 xl:grid-cols-3">
|
<div className="grid gap-5 sm:grid-cols-2 xl:grid-cols-3">
|
||||||
{filtered.map((product) => (
|
{gridItems.map((item, index) =>
|
||||||
<ProductCard key={product.id} product={product} />
|
item.type === "product" ? (
|
||||||
))}
|
<ProductCard key={item.product.id} product={item.product} />
|
||||||
|
) : (
|
||||||
|
<PromoTile key={`promo-${index}`} category={item.category} className="min-h-[22rem]" />
|
||||||
|
),
|
||||||
|
)}
|
||||||
</div>
|
</div>
|
||||||
) : (
|
) : (
|
||||||
<div className="grid min-h-80 place-items-center rounded-3xl border border-dashed border-slate-300 text-center">
|
<div className="grid min-h-80 place-items-center rounded-3xl border border-dashed border-slate-300 text-center">
|
||||||
@@ -205,11 +347,13 @@ function Filter({
|
|||||||
values,
|
values,
|
||||||
selected,
|
selected,
|
||||||
onChange,
|
onChange,
|
||||||
|
counts,
|
||||||
}: {
|
}: {
|
||||||
title: string;
|
title: string;
|
||||||
values: string[];
|
values: string[];
|
||||||
selected: string;
|
selected: string;
|
||||||
onChange: (value: string) => void;
|
onChange: (value: string) => void;
|
||||||
|
counts?: Record<string, number>;
|
||||||
}) {
|
}) {
|
||||||
return (
|
return (
|
||||||
<fieldset>
|
<fieldset>
|
||||||
@@ -227,6 +371,7 @@ function Filter({
|
|||||||
}`}
|
}`}
|
||||||
>
|
>
|
||||||
{value}
|
{value}
|
||||||
|
{counts && <span className="ml-1 opacity-60">({counts[value] ?? 0})</span>}
|
||||||
</button>
|
</button>
|
||||||
))}
|
))}
|
||||||
</div>
|
</div>
|
||||||
|
|||||||
@@ -2,12 +2,15 @@ import Image from "next/image";
|
|||||||
import Link from "next/link";
|
import Link from "next/link";
|
||||||
import { ArrowUpRight } from "lucide-react";
|
import { ArrowUpRight } from "lucide-react";
|
||||||
import type { Category } from "@/lib/headless/types";
|
import type { Category } from "@/lib/headless/types";
|
||||||
|
import { cn } from "@/lib/utils";
|
||||||
|
|
||||||
|
type TileContent = { subtitle: string; image?: string; color: string };
|
||||||
|
|
||||||
// No hay fotografia real todavia para las 6 categorias raiz de la taxonomia
|
// No hay fotografia real todavia para las 6 categorias raiz de la taxonomia
|
||||||
// (ver ADR 0005) -- solo se mapean imagen/subtitulo para las que ya tienen
|
// (ver ADR 0005) -- solo se mapean imagen/subtitulo para las que ya tienen
|
||||||
// un asset en public/images/categories/. Las demas caen al tile de solo
|
// un asset en public/images/categories/. Las demas caen al tile de solo
|
||||||
// gradiente en vez de mostrar una imagen que no les corresponde.
|
// gradiente en vez de mostrar una imagen que no les corresponde.
|
||||||
const tileContent: Record<string, { subtitle: string; image?: string; color: string }> = {
|
const tileContent: Record<string, TileContent> = {
|
||||||
juguetes: { subtitle: "Personajes que inspiran", image: "/images/categories/figuras.webp", color: "from-yellow-300 to-orange-400" },
|
juguetes: { subtitle: "Personajes que inspiran", image: "/images/categories/figuras.webp", color: "from-yellow-300 to-orange-400" },
|
||||||
"mochilas-y-morrales": { subtitle: "Estilo para cada aventura", image: "/images/categories/mochilas.webp", color: "from-cyan-400 to-blue-500" },
|
"mochilas-y-morrales": { subtitle: "Estilo para cada aventura", image: "/images/categories/mochilas.webp", color: "from-cyan-400 to-blue-500" },
|
||||||
"bebes-y-primera-infancia": { subtitle: "Primeros descubrimientos", color: "from-pink-300 to-fuchsia-400" },
|
"bebes-y-primera-infancia": { subtitle: "Primeros descubrimientos", color: "from-pink-300 to-fuchsia-400" },
|
||||||
@@ -16,7 +19,38 @@ const tileContent: Record<string, { subtitle: string; image?: string; color: str
|
|||||||
variedades: { subtitle: "Un poco de todo", color: "from-violet-400 to-purple-600" },
|
variedades: { subtitle: "Un poco de todo", color: "from-violet-400 to-purple-600" },
|
||||||
};
|
};
|
||||||
|
|
||||||
const defaultTile = { subtitle: "Explora esta categoría", color: "from-slate-400 to-slate-600" };
|
const defaultTile: TileContent = { subtitle: "Explora esta categoría", color: "from-slate-400 to-slate-600" };
|
||||||
|
|
||||||
|
// Tile individual reutilizado tanto por la seccion de mundos del home
|
||||||
|
// como por el grid del catalogo (tiles promocionales intercalados,
|
||||||
|
// ADR 0005 seccion 3, patron Walmart) -- mismo primitivo visual, no un
|
||||||
|
// componente nuevo.
|
||||||
|
export function PromoTile({ category, className = "" }: { category: Category; className?: string }) {
|
||||||
|
const content = tileContent[category.handle] ?? defaultTile;
|
||||||
|
|
||||||
|
return (
|
||||||
|
<Link
|
||||||
|
href={`/catalog?category=${encodeURIComponent(category.name)}`}
|
||||||
|
className={cn(`group relative min-h-64 overflow-hidden rounded-[2rem] bg-gradient-to-br ${content.color} shadow-xl`, className)}
|
||||||
|
>
|
||||||
|
{content.image && (
|
||||||
|
<>
|
||||||
|
<Image src={content.image} alt={category.name} fill sizes="(max-width: 640px) 100vw, (max-width: 1024px) 33vw, 16vw" className="object-cover transition duration-500 group-hover:scale-105" />
|
||||||
|
<div className="absolute inset-0 bg-gradient-to-t from-slate-950/80 via-transparent to-white/5" />
|
||||||
|
</>
|
||||||
|
)}
|
||||||
|
<div className="absolute inset-x-0 bottom-0 flex items-end justify-between p-6 text-white">
|
||||||
|
<div>
|
||||||
|
<h3 className="text-xl font-black">{category.name}</h3>
|
||||||
|
<p className="mt-1 text-sm font-semibold text-white/80">{content.subtitle}</p>
|
||||||
|
</div>
|
||||||
|
<span className="grid size-11 shrink-0 place-items-center rounded-full bg-white text-slate-950 transition group-hover:rotate-45">
|
||||||
|
<ArrowUpRight />
|
||||||
|
</span>
|
||||||
|
</div>
|
||||||
|
</Link>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
export function CategoryTiles({ categories }: { categories: Category[] }) {
|
export function CategoryTiles({ categories }: { categories: Category[] }) {
|
||||||
const roots = categories.filter((category) => !category.parentId);
|
const roots = categories.filter((category) => !category.parentId);
|
||||||
@@ -33,33 +67,9 @@ export function CategoryTiles({ categories }: { categories: Category[] }) {
|
|||||||
<Link href="/catalog" className="hidden font-black text-cyan-700 sm:block">Ver todo →</Link>
|
<Link href="/catalog" className="hidden font-black text-cyan-700 sm:block">Ver todo →</Link>
|
||||||
</div>
|
</div>
|
||||||
<div className="grid gap-5 sm:grid-cols-2 lg:grid-cols-3 xl:grid-cols-6">
|
<div className="grid gap-5 sm:grid-cols-2 lg:grid-cols-3 xl:grid-cols-6">
|
||||||
{roots.map((category) => {
|
{roots.map((category) => (
|
||||||
const content = tileContent[category.handle] ?? defaultTile;
|
<PromoTile key={category.id} category={category} />
|
||||||
|
))}
|
||||||
return (
|
|
||||||
<Link
|
|
||||||
key={category.id}
|
|
||||||
href={`/catalog?category=${encodeURIComponent(category.name)}`}
|
|
||||||
className={`group relative min-h-64 overflow-hidden rounded-[2rem] bg-gradient-to-br ${content.color} shadow-xl`}
|
|
||||||
>
|
|
||||||
{content.image && (
|
|
||||||
<>
|
|
||||||
<Image src={content.image} alt={category.name} fill sizes="(max-width: 640px) 100vw, (max-width: 1024px) 33vw, 16vw" className="object-cover transition duration-500 group-hover:scale-105" />
|
|
||||||
<div className="absolute inset-0 bg-gradient-to-t from-slate-950/80 via-transparent to-white/5" />
|
|
||||||
</>
|
|
||||||
)}
|
|
||||||
<div className="absolute inset-x-0 bottom-0 flex items-end justify-between p-6 text-white">
|
|
||||||
<div>
|
|
||||||
<h3 className="text-xl font-black">{category.name}</h3>
|
|
||||||
<p className="mt-1 text-sm font-semibold text-white/80">{content.subtitle}</p>
|
|
||||||
</div>
|
|
||||||
<span className="grid size-11 shrink-0 place-items-center rounded-full bg-white text-slate-950 transition group-hover:rotate-45">
|
|
||||||
<ArrowUpRight />
|
|
||||||
</span>
|
|
||||||
</div>
|
|
||||||
</Link>
|
|
||||||
);
|
|
||||||
})}
|
|
||||||
</div>
|
</div>
|
||||||
</section>
|
</section>
|
||||||
);
|
);
|
||||||
|
|||||||
@@ -3,8 +3,8 @@
|
|||||||
import Image from "next/image";
|
import Image from "next/image";
|
||||||
import Link from "next/link";
|
import Link from "next/link";
|
||||||
import { usePathname, useSearchParams } from "next/navigation";
|
import { usePathname, useSearchParams } from "next/navigation";
|
||||||
import { ChevronDown, Heart, Menu, MessageCircle, PackageCheck, ShoppingCart, UserRound } from "lucide-react";
|
import { ChevronDown, Heart, LayoutGrid, Menu, MessageCircle, PackageCheck, ShoppingCart, UserRound } from "lucide-react";
|
||||||
import { Suspense, useMemo, useState } from "react";
|
import { Suspense, useEffect, useMemo, useRef, useState } from "react";
|
||||||
import { PredictiveSearch } from "@/components/search/predictive-search";
|
import { PredictiveSearch } from "@/components/search/predictive-search";
|
||||||
import { Button } from "@/components/ui/button";
|
import { Button } from "@/components/ui/button";
|
||||||
import { Dialog, DialogContent } from "@/components/ui/dialog";
|
import { Dialog, DialogContent } from "@/components/ui/dialog";
|
||||||
@@ -151,94 +151,120 @@ function mobileLinkClass(active: boolean): string {
|
|||||||
|
|
||||||
function DesktopCategoryNavigation({ tree, onOpenMenu }: { tree: CategoryNode[]; onOpenMenu: () => void }) {
|
function DesktopCategoryNavigation({ tree, onOpenMenu }: { tree: CategoryNode[]; onOpenMenu: () => void }) {
|
||||||
const { isActive, isAllActive } = useCategoryNavigationState();
|
const { isActive, isAllActive } = useCategoryNavigationState();
|
||||||
|
return <CategoryNavBar tree={tree} onOpenMenu={onOpenMenu} isActive={isActive} isAllActive={isAllActive} />;
|
||||||
|
}
|
||||||
|
|
||||||
|
function DesktopCategoryNavigationFallback({ tree, onOpenMenu }: { tree: CategoryNode[]; onOpenMenu: () => void }) {
|
||||||
|
return <CategoryNavBar tree={tree} onOpenMenu={onOpenMenu} isActive={() => false} isAllActive={false} />;
|
||||||
|
}
|
||||||
|
|
||||||
|
function CategoryNavBar({
|
||||||
|
tree,
|
||||||
|
onOpenMenu,
|
||||||
|
isActive,
|
||||||
|
isAllActive,
|
||||||
|
}: {
|
||||||
|
tree: CategoryNode[];
|
||||||
|
onOpenMenu: () => void;
|
||||||
|
isActive: (name: string) => boolean;
|
||||||
|
isAllActive: boolean;
|
||||||
|
}) {
|
||||||
return (
|
return (
|
||||||
<nav className="border-b-4 border-fuchsia-500 bg-slate-950 text-white">
|
<nav className="border-b-4 border-fuchsia-500 bg-slate-950 text-white">
|
||||||
<div className="mx-auto flex max-w-7xl items-center gap-1 overflow-x-auto px-4 py-2 [scrollbar-width:none]">
|
<div className="mx-auto flex max-w-7xl items-center gap-1 px-4 py-2">
|
||||||
<Button
|
<Button
|
||||||
variant="ghost"
|
variant="ghost"
|
||||||
size="icon"
|
size="icon"
|
||||||
onClick={onOpenMenu}
|
onClick={onOpenMenu}
|
||||||
aria-label="Abrir menú principal"
|
aria-label="Abrir menú principal"
|
||||||
className="mr-3 shrink-0 text-white hover:bg-white/10"
|
className="mr-2 shrink-0 text-white hover:bg-white/10"
|
||||||
>
|
>
|
||||||
<Menu />
|
<Menu />
|
||||||
</Button>
|
</Button>
|
||||||
|
|
||||||
|
<DepartmentsMegaMenu tree={tree} isActive={isActive} />
|
||||||
|
|
||||||
<Link href="/catalog" prefetch={false} aria-current={isAllActive ? "page" : undefined} className={pillClass(isAllActive)}>
|
<Link href="/catalog" prefetch={false} aria-current={isAllActive ? "page" : undefined} className={pillClass(isAllActive)}>
|
||||||
Todo
|
Todo
|
||||||
</Link>
|
</Link>
|
||||||
|
|
||||||
{tree.map((root) =>
|
|
||||||
root.children.length > 0 ? (
|
|
||||||
<div key={root.id} className="group relative shrink-0">
|
|
||||||
<Link
|
|
||||||
href={`/catalog?category=${encodeURIComponent(root.name)}`}
|
|
||||||
prefetch={false}
|
|
||||||
aria-current={isActive(root.name) ? "page" : undefined}
|
|
||||||
className={`flex items-center gap-1 ${pillClass(isActive(root.name))}`}
|
|
||||||
>
|
|
||||||
{root.name}
|
|
||||||
<ChevronDown className="size-3.5 opacity-70" />
|
|
||||||
</Link>
|
|
||||||
<div className="invisible absolute left-0 top-full z-50 min-w-56 -translate-y-1 rounded-2xl border border-slate-800 bg-slate-950 p-2 opacity-0 shadow-2xl transition group-hover:visible group-hover:translate-y-0 group-hover:opacity-100">
|
|
||||||
{root.children.map((child) => (
|
|
||||||
<Link
|
|
||||||
key={child.id}
|
|
||||||
href={`/catalog?category=${encodeURIComponent(child.name)}`}
|
|
||||||
prefetch={false}
|
|
||||||
aria-current={isActive(child.name) ? "page" : undefined}
|
|
||||||
className={`block rounded-xl px-3 py-2 text-sm font-bold transition ${
|
|
||||||
isActive(child.name) ? "bg-violet-600 text-white" : "text-white/85 hover:bg-white/10"
|
|
||||||
}`}
|
|
||||||
>
|
|
||||||
{child.name}
|
|
||||||
</Link>
|
|
||||||
))}
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
) : (
|
|
||||||
<Link
|
|
||||||
key={root.id}
|
|
||||||
href={`/catalog?category=${encodeURIComponent(root.name)}`}
|
|
||||||
prefetch={false}
|
|
||||||
aria-current={isActive(root.name) ? "page" : undefined}
|
|
||||||
className={pillClass(isActive(root.name))}
|
|
||||||
>
|
|
||||||
{root.name}
|
|
||||||
</Link>
|
|
||||||
),
|
|
||||||
)}
|
|
||||||
</div>
|
</div>
|
||||||
</nav>
|
</nav>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
function DesktopCategoryNavigationFallback({ tree, onOpenMenu }: { tree: CategoryNode[]; onOpenMenu: () => void }) {
|
function DepartmentsMegaMenu({ tree, isActive }: { tree: CategoryNode[]; isActive: (name: string) => boolean }) {
|
||||||
|
const [open, setOpen] = useState(false);
|
||||||
|
const containerRef = useRef<HTMLDivElement>(null);
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
if (!open) return;
|
||||||
|
function handlePointerDown(event: PointerEvent) {
|
||||||
|
if (containerRef.current && !containerRef.current.contains(event.target as Node)) setOpen(false);
|
||||||
|
}
|
||||||
|
function handleKeyDown(event: KeyboardEvent) {
|
||||||
|
if (event.key === "Escape") setOpen(false);
|
||||||
|
}
|
||||||
|
document.addEventListener("pointerdown", handlePointerDown);
|
||||||
|
document.addEventListener("keydown", handleKeyDown);
|
||||||
|
return () => {
|
||||||
|
document.removeEventListener("pointerdown", handlePointerDown);
|
||||||
|
document.removeEventListener("keydown", handleKeyDown);
|
||||||
|
};
|
||||||
|
}, [open]);
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<nav className="border-b-4 border-fuchsia-500 bg-slate-950 text-white">
|
<div ref={containerRef} className="relative shrink-0" onMouseEnter={() => setOpen(true)} onMouseLeave={() => setOpen(false)}>
|
||||||
<div className="mx-auto flex max-w-7xl items-center gap-1 overflow-x-auto px-4 py-2 [scrollbar-width:none]">
|
<button
|
||||||
<Button
|
type="button"
|
||||||
variant="ghost"
|
onClick={() => setOpen((value) => !value)}
|
||||||
size="icon"
|
aria-expanded={open}
|
||||||
onClick={onOpenMenu}
|
aria-haspopup="true"
|
||||||
aria-label="Abrir menú principal"
|
className={`flex items-center gap-1.5 ${pillClass(open)}`}
|
||||||
className="mr-3 shrink-0 text-white hover:bg-white/10"
|
>
|
||||||
>
|
<LayoutGrid className="size-4" />
|
||||||
<Menu />
|
Departamentos
|
||||||
</Button>
|
<ChevronDown className={`size-3.5 opacity-70 transition-transform ${open ? "rotate-180" : ""}`} />
|
||||||
|
</button>
|
||||||
|
|
||||||
<Link href="/catalog" prefetch={false} className={pillClass(false)}>
|
{open && (
|
||||||
Todo
|
<div className="absolute left-0 top-full z-50 mt-1 w-[min(92vw,64rem)] rounded-2xl border border-slate-800 bg-slate-950 p-6 shadow-2xl">
|
||||||
</Link>
|
<div className="grid grid-cols-2 gap-x-6 gap-y-5 sm:grid-cols-3 lg:grid-cols-6">
|
||||||
|
{tree.map((root) => (
|
||||||
{tree.map((root) => (
|
<div key={root.id}>
|
||||||
<Link key={root.id} href={`/catalog?category=${encodeURIComponent(root.name)}`} prefetch={false} className={pillClass(false)}>
|
<Link
|
||||||
{root.name}
|
href={`/catalog?category=${encodeURIComponent(root.name)}`}
|
||||||
</Link>
|
prefetch={false}
|
||||||
))}
|
aria-current={isActive(root.name) ? "page" : undefined}
|
||||||
</div>
|
onClick={() => setOpen(false)}
|
||||||
</nav>
|
className={`block text-sm font-black uppercase tracking-wide transition ${
|
||||||
|
isActive(root.name) ? "text-fuchsia-400" : "text-white hover:text-fuchsia-400"
|
||||||
|
}`}
|
||||||
|
>
|
||||||
|
{root.name}
|
||||||
|
</Link>
|
||||||
|
{root.children.length > 0 && (
|
||||||
|
<ul className="mt-2.5 grid gap-1.5">
|
||||||
|
{root.children.map((child) => (
|
||||||
|
<li key={child.id}>
|
||||||
|
<Link
|
||||||
|
href={`/catalog?category=${encodeURIComponent(child.name)}`}
|
||||||
|
prefetch={false}
|
||||||
|
aria-current={isActive(child.name) ? "page" : undefined}
|
||||||
|
onClick={() => setOpen(false)}
|
||||||
|
className={`block text-sm transition ${isActive(child.name) ? "font-bold text-violet-300" : "text-white/70 hover:text-white"}`}
|
||||||
|
>
|
||||||
|
{child.name}
|
||||||
|
</Link>
|
||||||
|
</li>
|
||||||
|
))}
|
||||||
|
</ul>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
))}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -2,11 +2,12 @@
|
|||||||
|
|
||||||
import Image from "next/image";
|
import Image from "next/image";
|
||||||
import Link from "next/link";
|
import Link from "next/link";
|
||||||
import { Heart, ShoppingBag, Sparkles } from "lucide-react";
|
import { Heart, ShoppingBag, Sparkles, TriangleAlert } from "lucide-react";
|
||||||
|
import { useState } from "react";
|
||||||
import { Badge } from "@/components/ui/badge";
|
import { Badge } from "@/components/ui/badge";
|
||||||
import { Button } from "@/components/ui/button";
|
import { Button } from "@/components/ui/button";
|
||||||
import type { Product } from "@/lib/headless/types";
|
import type { Product } from "@/lib/headless/types";
|
||||||
import { formatMoney } from "@/lib/utils";
|
import { formatMoney, LOW_STOCK_THRESHOLD } from "@/lib/utils";
|
||||||
import { useCartStore } from "@/store/cart-store";
|
import { useCartStore } from "@/store/cart-store";
|
||||||
import { useWishlistStore } from "@/store/wishlist-store";
|
import { useWishlistStore } from "@/store/wishlist-store";
|
||||||
|
|
||||||
@@ -16,19 +17,63 @@ export function ProductCard({ product, priority = false }: { product: Product; p
|
|||||||
const wishlistHydrated = useWishlistStore((state) => state.hasHydrated);
|
const wishlistHydrated = useWishlistStore((state) => state.hasHydrated);
|
||||||
const toggleProduct = useWishlistStore((state) => state.toggleProduct);
|
const toggleProduct = useWishlistStore((state) => state.toggleProduct);
|
||||||
const isFavorite = wishlistHydrated && wishlistProducts.some((item) => item.id === product.id);
|
const isFavorite = wishlistHydrated && wishlistProducts.some((item) => item.id === product.id);
|
||||||
|
const discountPercent =
|
||||||
|
product.compareAtPrice && product.price
|
||||||
|
? Math.round((1 - product.price / product.compareAtPrice) * 100)
|
||||||
|
: null;
|
||||||
|
|
||||||
|
const [selectedVariantId, setSelectedVariantId] = useState(product.variants[0]?.id);
|
||||||
|
const selectedVariant = product.variants.find((variant) => variant.id === selectedVariantId) ?? product.variants[0];
|
||||||
|
const lowStock =
|
||||||
|
selectedVariant?.inventoryQuantity !== null &&
|
||||||
|
selectedVariant?.inventoryQuantity !== undefined &&
|
||||||
|
selectedVariant.inventoryQuantity > 0 &&
|
||||||
|
selectedVariant.inventoryQuantity <= LOW_STOCK_THRESHOLD
|
||||||
|
? selectedVariant.inventoryQuantity
|
||||||
|
: null;
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<article className="group flex h-full flex-col overflow-hidden rounded-3xl border border-slate-100 bg-white shadow-lg shadow-slate-900/5 transition duration-300 hover:-translate-y-1.5 hover:shadow-2xl hover:shadow-violet-500/10">
|
<article className="group flex h-full flex-col overflow-hidden rounded-3xl border border-slate-100 bg-white shadow-lg shadow-slate-900/5 transition duration-300 hover:-translate-y-1.5 hover:shadow-2xl hover:shadow-violet-500/10">
|
||||||
<div className="relative aspect-square overflow-hidden bg-slate-50">
|
<div className="relative aspect-square overflow-hidden bg-slate-50">
|
||||||
<Link href={`/product/${product.slug}`} prefetch={false}><Image src={product.thumbnail} alt={product.name} fill priority={priority} sizes="(max-width: 640px) 82vw, (max-width: 1024px) 44vw, 280px" className="object-cover transition duration-500 group-hover:scale-[1.035]" /></Link>
|
<Link href={`/product/${product.slug}`} prefetch={false}><Image src={product.thumbnail} alt={product.name} fill priority={priority} sizes="(max-width: 640px) 82vw, (max-width: 1024px) 44vw, 280px" className="object-cover transition duration-500 group-hover:scale-[1.035]" /></Link>
|
||||||
<div className="absolute left-3 top-3 flex gap-2">{product.isNew && <Badge className="bg-fuchsia-500 text-white">Nuevo</Badge>}{product.featured && <Badge className="bg-yellow-300 text-slate-950"><Sparkles className="mr-1 size-3" />Top</Badge>}</div>
|
<div className="absolute left-3 top-3 flex gap-2">{discountPercent && discountPercent > 0 && <Badge className="bg-rose-600 text-white">-{discountPercent}%</Badge>}{product.isNew && <Badge className="bg-fuchsia-500 text-white">Nuevo</Badge>}{product.featured && <Badge className="bg-yellow-300 text-slate-950"><Sparkles className="mr-1 size-3" />Top</Badge>}</div>
|
||||||
<button type="button" aria-label={isFavorite ? "Quitar de favoritos" : "Agregar a favoritos"} aria-pressed={isFavorite} className={`absolute right-3 top-3 rounded-full p-2.5 shadow-lg backdrop-blur transition ${isFavorite ? "bg-fuchsia-500 text-white" : "bg-white/95 text-slate-900 hover:text-fuchsia-500"}`} onClick={() => toggleProduct(product)}><Heart className={`size-4 ${isFavorite ? "fill-current" : ""}`} /></button>
|
<button type="button" aria-label={isFavorite ? "Quitar de favoritos" : "Agregar a favoritos"} aria-pressed={isFavorite} className={`absolute right-3 top-3 rounded-full p-2.5 shadow-lg backdrop-blur transition ${isFavorite ? "bg-fuchsia-500 text-white" : "bg-white/95 text-slate-900 hover:text-fuchsia-500"}`} onClick={() => toggleProduct(product)}><Heart className={`size-4 ${isFavorite ? "fill-current" : ""}`} /></button>
|
||||||
</div>
|
</div>
|
||||||
<div className="flex flex-1 flex-col space-y-3 p-5">
|
<div className="flex flex-1 flex-col space-y-3 p-5">
|
||||||
<div className="flex items-center justify-between gap-2 text-xs font-bold text-slate-500"><span>{product.category}</span><span className="rounded-full bg-cyan-50 px-2 py-1 text-cyan-700">{product.collection}</span></div>
|
<div className="flex items-center justify-between gap-2 text-xs font-bold text-slate-500"><span>{product.category}</span><span className="rounded-full bg-cyan-50 px-2 py-1 text-cyan-700">{product.collection}</span></div>
|
||||||
<Link href={`/product/${product.slug}`} prefetch={false}><h3 className="line-clamp-2 min-h-12 text-lg font-black leading-6 text-slate-950 group-hover:text-fuchsia-600">{product.name}</h3></Link>
|
<Link href={`/product/${product.slug}`} prefetch={false}><h3 className="line-clamp-2 min-h-12 text-lg font-black leading-6 text-slate-950 group-hover:text-fuchsia-600">{product.name}</h3></Link>
|
||||||
<p className="line-clamp-2 min-h-10 text-sm leading-5 text-slate-500">{product.shortDescription}</p>
|
<p className="line-clamp-2 min-h-10 text-sm leading-5 text-slate-500">{product.shortDescription}</p>
|
||||||
<div className="mt-auto flex items-center justify-between gap-3 pt-1"><strong className="text-sm font-black">{formatMoney(product.price, product.currency)}</strong><Button variant="magenta" size="sm" onClick={() => addItem(product, product.variants[0]?.id)}><ShoppingBag className="size-4" />Agregar</Button></div>
|
{product.variants.length > 1 && (
|
||||||
|
<div className="flex flex-wrap gap-1.5">
|
||||||
|
{product.variants.map((variant) => (
|
||||||
|
<button
|
||||||
|
key={variant.id}
|
||||||
|
type="button"
|
||||||
|
disabled={!variant.available}
|
||||||
|
aria-pressed={selectedVariantId === variant.id}
|
||||||
|
aria-label={`${variant.name}: ${variant.value}`}
|
||||||
|
onClick={() => setSelectedVariantId(variant.id)}
|
||||||
|
className={`rounded-full border px-2.5 py-1 text-xs font-bold transition ${
|
||||||
|
selectedVariantId === variant.id
|
||||||
|
? "border-fuchsia-500 bg-fuchsia-50 text-fuchsia-700"
|
||||||
|
: "border-slate-200 text-slate-600 hover:border-slate-400"
|
||||||
|
} ${!variant.available ? "cursor-not-allowed opacity-40" : ""}`}
|
||||||
|
>
|
||||||
|
{variant.value}
|
||||||
|
</button>
|
||||||
|
))}
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
{lowStock !== null && (
|
||||||
|
<span className="flex items-center gap-1.5 text-xs font-bold text-amber-600"><TriangleAlert className="size-3.5" />Quedan {lowStock}</span>
|
||||||
|
)}
|
||||||
|
<div className="mt-auto flex items-center justify-between gap-3 pt-1">
|
||||||
|
<div className="flex flex-col">
|
||||||
|
{product.compareAtPrice && <span className="text-xs font-bold text-slate-400 line-through">{formatMoney(product.compareAtPrice, product.currency)}</span>}
|
||||||
|
<strong className="text-sm font-black">{formatMoney(product.price, product.currency)}</strong>
|
||||||
|
</div>
|
||||||
|
<Button variant="magenta" size="sm" onClick={() => addItem(product, selectedVariantId)}><ShoppingBag className="size-4" />Agregar</Button>
|
||||||
|
</div>
|
||||||
</div>
|
</div>
|
||||||
</article>
|
</article>
|
||||||
);
|
);
|
||||||
|
|||||||
@@ -1,14 +1,22 @@
|
|||||||
"use client";
|
"use client";
|
||||||
|
|
||||||
import { CheckCircle2, ShoppingBag, Truck } from "lucide-react";
|
import { CheckCircle2, ShoppingBag, TriangleAlert, Truck } from "lucide-react";
|
||||||
import { useState } from "react";
|
import { useState } from "react";
|
||||||
import { Button } from "@/components/ui/button";
|
import { Button } from "@/components/ui/button";
|
||||||
import type { Product } from "@/lib/headless/types";
|
import type { Product } from "@/lib/headless/types";
|
||||||
import { formatMoney } from "@/lib/utils";
|
import { formatMoney, LOW_STOCK_THRESHOLD } from "@/lib/utils";
|
||||||
import { useCartStore } from "@/store/cart-store";
|
import { useCartStore } from "@/store/cart-store";
|
||||||
|
|
||||||
export function ProductPurchase({ product }: { product: Product }) {
|
export function ProductPurchase({ product }: { product: Product }) {
|
||||||
const [variantId, setVariantId] = useState(product.variants[0]?.id);
|
const [variantId, setVariantId] = useState(product.variants[0]?.id);
|
||||||
const addItem = useCartStore((state) => state.addItem);
|
const addItem = useCartStore((state) => state.addItem);
|
||||||
return <div><div className="mb-5 flex flex-wrap gap-2">{product.variants.map((variant) => <button key={variant.id} onClick={() => setVariantId(variant.id)} className={`rounded-full border px-4 py-2 text-sm font-bold ${variantId === variant.id ? "border-fuchsia-500 bg-fuchsia-50 text-fuchsia-700" : "border-slate-200"}`}>{variant.value}</button>)}</div><div className="mb-6 flex items-end gap-3"><strong className="text-3xl font-black">{formatMoney(product.price, product.currency)}</strong>{product.compareAtPrice && <del className="text-slate-400">{formatMoney(product.compareAtPrice, product.currency)}</del>}</div><Button variant="magenta" size="lg" className="w-full" onClick={() => addItem(product, variantId)}><ShoppingBag />Añadir al carrito</Button><div className="mt-5 grid gap-3 rounded-2xl bg-slate-50 p-4 text-sm"><span className="flex items-center gap-2 font-bold"><CheckCircle2 className="size-4 text-emerald-500" />Disponibilidad por confirmar</span><span className="flex items-center gap-2 font-bold"><Truck className="size-4 text-cyan-600" />Envíos nacionales</span></div></div>;
|
const selectedVariant = product.variants.find((variant) => variant.id === variantId) ?? product.variants[0];
|
||||||
|
const lowStock =
|
||||||
|
selectedVariant?.inventoryQuantity !== null &&
|
||||||
|
selectedVariant?.inventoryQuantity !== undefined &&
|
||||||
|
selectedVariant.inventoryQuantity > 0 &&
|
||||||
|
selectedVariant.inventoryQuantity <= LOW_STOCK_THRESHOLD
|
||||||
|
? selectedVariant.inventoryQuantity
|
||||||
|
: null;
|
||||||
|
return <div><div className="mb-5 flex flex-wrap gap-2">{product.variants.map((variant) => <button key={variant.id} onClick={() => setVariantId(variant.id)} className={`rounded-full border px-4 py-2 text-sm font-bold ${variantId === variant.id ? "border-fuchsia-500 bg-fuchsia-50 text-fuchsia-700" : "border-slate-200"}`}>{variant.value}</button>)}</div><div className="mb-6 flex items-end gap-3"><strong className="text-3xl font-black">{formatMoney(product.price, product.currency)}</strong>{product.compareAtPrice && <del className="text-slate-400">{formatMoney(product.compareAtPrice, product.currency)}</del>}</div><Button variant="magenta" size="lg" className="w-full" onClick={() => addItem(product, variantId)}><ShoppingBag />Añadir al carrito</Button><div className="mt-5 grid gap-3 rounded-2xl bg-slate-50 p-4 text-sm">{lowStock !== null ? <span className="flex items-center gap-2 font-bold text-amber-600"><TriangleAlert className="size-4" />Quedan {lowStock} unidades</span> : <span className="flex items-center gap-2 font-bold"><CheckCircle2 className="size-4 text-emerald-500" />Disponibilidad por confirmar</span>}<span className="flex items-center gap-2 font-bold"><Truck className="size-4 text-cyan-600" />Envíos nacionales</span></div></div>;
|
||||||
}
|
}
|
||||||
@@ -30,7 +30,8 @@
|
|||||||
"id": "ari-001-toy-story-5-rex-default",
|
"id": "ari-001-toy-story-5-rex-default",
|
||||||
"name": "Presentación",
|
"name": "Presentación",
|
||||||
"value": "Edición original",
|
"value": "Edición original",
|
||||||
"available": true
|
"available": true,
|
||||||
|
"inventoryQuantity": null
|
||||||
}
|
}
|
||||||
],
|
],
|
||||||
"thumbnail": "/images/thumbnails/ari-001-toy-story-5-rex.webp"
|
"thumbnail": "/images/thumbnails/ari-001-toy-story-5-rex.webp"
|
||||||
@@ -66,7 +67,8 @@
|
|||||||
"id": "ari-002-toy-story-5-buzz-lightyear-default",
|
"id": "ari-002-toy-story-5-buzz-lightyear-default",
|
||||||
"name": "Presentación",
|
"name": "Presentación",
|
||||||
"value": "Edición original",
|
"value": "Edición original",
|
||||||
"available": true
|
"available": true,
|
||||||
|
"inventoryQuantity": null
|
||||||
}
|
}
|
||||||
],
|
],
|
||||||
"thumbnail": "/images/thumbnails/ari-002-toy-story-5-buzz-lightyear.webp"
|
"thumbnail": "/images/thumbnails/ari-002-toy-story-5-buzz-lightyear.webp"
|
||||||
@@ -102,7 +104,8 @@
|
|||||||
"id": "ari-003-toy-story-5-jessie-default",
|
"id": "ari-003-toy-story-5-jessie-default",
|
||||||
"name": "Presentación",
|
"name": "Presentación",
|
||||||
"value": "Edición original",
|
"value": "Edición original",
|
||||||
"available": true
|
"available": true,
|
||||||
|
"inventoryQuantity": null
|
||||||
}
|
}
|
||||||
],
|
],
|
||||||
"thumbnail": "/images/thumbnails/ari-003-toy-story-5-jessie.webp"
|
"thumbnail": "/images/thumbnails/ari-003-toy-story-5-jessie.webp"
|
||||||
@@ -138,7 +141,8 @@
|
|||||||
"id": "ari-004-toy-story-5-woody-default",
|
"id": "ari-004-toy-story-5-woody-default",
|
||||||
"name": "Presentación",
|
"name": "Presentación",
|
||||||
"value": "Edición original",
|
"value": "Edición original",
|
||||||
"available": true
|
"available": true,
|
||||||
|
"inventoryQuantity": null
|
||||||
}
|
}
|
||||||
],
|
],
|
||||||
"thumbnail": "/images/thumbnails/ari-004-toy-story-5-woody.webp"
|
"thumbnail": "/images/thumbnails/ari-004-toy-story-5-woody.webp"
|
||||||
@@ -174,7 +178,8 @@
|
|||||||
"id": "ari-005-intensamente-furia-default",
|
"id": "ari-005-intensamente-furia-default",
|
||||||
"name": "Presentación",
|
"name": "Presentación",
|
||||||
"value": "Edición original",
|
"value": "Edición original",
|
||||||
"available": true
|
"available": true,
|
||||||
|
"inventoryQuantity": null
|
||||||
}
|
}
|
||||||
],
|
],
|
||||||
"thumbnail": "/images/thumbnails/ari-005-intensamente-furia.webp"
|
"thumbnail": "/images/thumbnails/ari-005-intensamente-furia.webp"
|
||||||
@@ -210,7 +215,8 @@
|
|||||||
"id": "ari-006-intensamente-tristeza-default",
|
"id": "ari-006-intensamente-tristeza-default",
|
||||||
"name": "Presentación",
|
"name": "Presentación",
|
||||||
"value": "Edición original",
|
"value": "Edición original",
|
||||||
"available": true
|
"available": true,
|
||||||
|
"inventoryQuantity": null
|
||||||
}
|
}
|
||||||
],
|
],
|
||||||
"thumbnail": "/images/thumbnails/ari-006-intensamente-tristeza.webp"
|
"thumbnail": "/images/thumbnails/ari-006-intensamente-tristeza.webp"
|
||||||
@@ -246,7 +252,8 @@
|
|||||||
"id": "ari-007-minnie-y-mickey-mouse-default",
|
"id": "ari-007-minnie-y-mickey-mouse-default",
|
||||||
"name": "Presentación",
|
"name": "Presentación",
|
||||||
"value": "Edición original",
|
"value": "Edición original",
|
||||||
"available": true
|
"available": true,
|
||||||
|
"inventoryQuantity": null
|
||||||
}
|
}
|
||||||
],
|
],
|
||||||
"thumbnail": "/images/thumbnails/ari-007-minnie-y-mickey-mouse.webp"
|
"thumbnail": "/images/thumbnails/ari-007-minnie-y-mickey-mouse.webp"
|
||||||
@@ -282,7 +289,8 @@
|
|||||||
"id": "ari-008-angel-lilo-y-stitch-default",
|
"id": "ari-008-angel-lilo-y-stitch-default",
|
||||||
"name": "Presentación",
|
"name": "Presentación",
|
||||||
"value": "Edición original",
|
"value": "Edición original",
|
||||||
"available": true
|
"available": true,
|
||||||
|
"inventoryQuantity": null
|
||||||
}
|
}
|
||||||
],
|
],
|
||||||
"thumbnail": "/images/thumbnails/ari-008-angel-lilo-y-stitch.webp"
|
"thumbnail": "/images/thumbnails/ari-008-angel-lilo-y-stitch.webp"
|
||||||
@@ -318,7 +326,8 @@
|
|||||||
"id": "ari-009-mochilas-disney-coleccion-marvel-default",
|
"id": "ari-009-mochilas-disney-coleccion-marvel-default",
|
||||||
"name": "Presentación",
|
"name": "Presentación",
|
||||||
"value": "Rosa",
|
"value": "Rosa",
|
||||||
"available": true
|
"available": true,
|
||||||
|
"inventoryQuantity": null
|
||||||
}
|
}
|
||||||
],
|
],
|
||||||
"thumbnail": "/images/thumbnails/ari-009-mochilas-disney-coleccion-marvel.webp"
|
"thumbnail": "/images/thumbnails/ari-009-mochilas-disney-coleccion-marvel.webp"
|
||||||
@@ -354,7 +363,8 @@
|
|||||||
"id": "ari-010-mochila-ligera-y-resistente-al-agua-de-d-default",
|
"id": "ari-010-mochila-ligera-y-resistente-al-agua-de-d-default",
|
||||||
"name": "Presentación",
|
"name": "Presentación",
|
||||||
"value": "Rosa",
|
"value": "Rosa",
|
||||||
"available": true
|
"available": true,
|
||||||
|
"inventoryQuantity": null
|
||||||
}
|
}
|
||||||
],
|
],
|
||||||
"thumbnail": "/images/thumbnails/ari-010-mochila-ligera-y-resistente-al-agua-de-d.webp"
|
"thumbnail": "/images/thumbnails/ari-010-mochila-ligera-y-resistente-al-agua-de-d.webp"
|
||||||
@@ -390,7 +400,8 @@
|
|||||||
"id": "ari-011-mochila-escolar-de-spider-man-de-disney--default",
|
"id": "ari-011-mochila-escolar-de-spider-man-de-disney--default",
|
||||||
"name": "Presentación",
|
"name": "Presentación",
|
||||||
"value": "Rosa",
|
"value": "Rosa",
|
||||||
"available": true
|
"available": true,
|
||||||
|
"inventoryQuantity": null
|
||||||
}
|
}
|
||||||
],
|
],
|
||||||
"thumbnail": "/images/thumbnails/ari-011-mochila-escolar-de-spider-man-de-disney-.webp"
|
"thumbnail": "/images/thumbnails/ari-011-mochila-escolar-de-spider-man-de-disney-.webp"
|
||||||
@@ -426,7 +437,8 @@
|
|||||||
"id": "ari-012-disney-mochila-de-poliester-ultraligera--default",
|
"id": "ari-012-disney-mochila-de-poliester-ultraligera--default",
|
||||||
"name": "Presentación",
|
"name": "Presentación",
|
||||||
"value": "Rosa",
|
"value": "Rosa",
|
||||||
"available": true
|
"available": true,
|
||||||
|
"inventoryQuantity": null
|
||||||
}
|
}
|
||||||
],
|
],
|
||||||
"thumbnail": "/images/thumbnails/ari-012-disney-mochila-de-poliester-ultraligera-.webp"
|
"thumbnail": "/images/thumbnails/ari-012-disney-mochila-de-poliester-ultraligera-.webp"
|
||||||
@@ -462,7 +474,8 @@
|
|||||||
"id": "ari-013-mochila-pequena-bob-esponja-default",
|
"id": "ari-013-mochila-pequena-bob-esponja-default",
|
||||||
"name": "Presentación",
|
"name": "Presentación",
|
||||||
"value": "Rosa",
|
"value": "Rosa",
|
||||||
"available": true
|
"available": true,
|
||||||
|
"inventoryQuantity": null
|
||||||
}
|
}
|
||||||
],
|
],
|
||||||
"thumbnail": "/images/thumbnails/ari-013-mochila-pequena-bob-esponja.webp"
|
"thumbnail": "/images/thumbnails/ari-013-mochila-pequena-bob-esponja.webp"
|
||||||
@@ -498,7 +511,8 @@
|
|||||||
"id": "ari-014-mochila-casual-de-gran-capacidad-con-est-default",
|
"id": "ari-014-mochila-casual-de-gran-capacidad-con-est-default",
|
||||||
"name": "Presentación",
|
"name": "Presentación",
|
||||||
"value": "Rosa",
|
"value": "Rosa",
|
||||||
"available": true
|
"available": true,
|
||||||
|
"inventoryQuantity": null
|
||||||
}
|
}
|
||||||
],
|
],
|
||||||
"thumbnail": "/images/thumbnails/ari-014-mochila-casual-de-gran-capacidad-con-est.webp"
|
"thumbnail": "/images/thumbnails/ari-014-mochila-casual-de-gran-capacidad-con-est.webp"
|
||||||
@@ -534,7 +548,8 @@
|
|||||||
"id": "ari-015-mochila-escolar-estilo-britanico-de-disn-default",
|
"id": "ari-015-mochila-escolar-estilo-britanico-de-disn-default",
|
||||||
"name": "Presentación",
|
"name": "Presentación",
|
||||||
"value": "Rosa",
|
"value": "Rosa",
|
||||||
"available": true
|
"available": true,
|
||||||
|
"inventoryQuantity": null
|
||||||
}
|
}
|
||||||
],
|
],
|
||||||
"thumbnail": "/images/thumbnails/ari-015-mochila-escolar-estilo-britanico-de-disn.webp"
|
"thumbnail": "/images/thumbnails/ari-015-mochila-escolar-estilo-britanico-de-disn.webp"
|
||||||
@@ -570,7 +585,8 @@
|
|||||||
"id": "ari-016-disney-mochila-iron-man-de-poliester-ult-default",
|
"id": "ari-016-disney-mochila-iron-man-de-poliester-ult-default",
|
||||||
"name": "Presentación",
|
"name": "Presentación",
|
||||||
"value": "Rosa",
|
"value": "Rosa",
|
||||||
"available": true
|
"available": true,
|
||||||
|
"inventoryQuantity": null
|
||||||
}
|
}
|
||||||
],
|
],
|
||||||
"thumbnail": "/images/thumbnails/ari-016-disney-mochila-iron-man-de-poliester-ult.webp"
|
"thumbnail": "/images/thumbnails/ari-016-disney-mochila-iron-man-de-poliester-ult.webp"
|
||||||
@@ -606,7 +622,8 @@
|
|||||||
"id": "ari-017-mochila-de-disney-marvel-capitan-america-default",
|
"id": "ari-017-mochila-de-disney-marvel-capitan-america-default",
|
||||||
"name": "Presentación",
|
"name": "Presentación",
|
||||||
"value": "Rosa",
|
"value": "Rosa",
|
||||||
"available": true
|
"available": true,
|
||||||
|
"inventoryQuantity": null
|
||||||
}
|
}
|
||||||
],
|
],
|
||||||
"thumbnail": "/images/thumbnails/ari-017-mochila-de-disney-marvel-capitan-america.webp"
|
"thumbnail": "/images/thumbnails/ari-017-mochila-de-disney-marvel-capitan-america.webp"
|
||||||
|
|||||||
@@ -25,7 +25,7 @@ spec:
|
|||||||
runAsUser: 1001
|
runAsUser: 1001
|
||||||
containers:
|
containers:
|
||||||
- name: app
|
- name: app
|
||||||
image: gitea.cruzcloud.net/devops/ecommerce-frontend:v1.0.135
|
image: gitea.cruzcloud.net/devops/ecommerce-frontend:v1.0.157
|
||||||
env:
|
env:
|
||||||
- name: HEADLESS_PROVIDER
|
- name: HEADLESS_PROVIDER
|
||||||
value: medusa
|
value: medusa
|
||||||
|
|||||||
@@ -157,11 +157,19 @@ function mapVariant(variant: MedusaVariant): ProductVariant {
|
|||||||
variant.manage_inventory === false ||
|
variant.manage_inventory === false ||
|
||||||
(variant.inventory_quantity ?? 0) > 0;
|
(variant.inventory_quantity ?? 0) > 0;
|
||||||
|
|
||||||
|
// null = inventario no gestionado (backorder o manage_inventory=false),
|
||||||
|
// no hay un numero real que mostrar como "quedan N".
|
||||||
|
const inventoryQuantity =
|
||||||
|
variant.allow_backorder === true || variant.manage_inventory === false
|
||||||
|
? null
|
||||||
|
: (variant.inventory_quantity ?? 0);
|
||||||
|
|
||||||
return {
|
return {
|
||||||
id: variant.id,
|
id: variant.id,
|
||||||
name: option?.option?.title || "Presentación",
|
name: option?.option?.title || "Presentación",
|
||||||
value: option?.value || variant.title || "Estándar",
|
value: option?.value || variant.title || "Estándar",
|
||||||
available,
|
available,
|
||||||
|
inventoryQuantity,
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -3,6 +3,7 @@ export interface ProductVariant {
|
|||||||
name: string;
|
name: string;
|
||||||
value: string;
|
value: string;
|
||||||
available: boolean;
|
available: boolean;
|
||||||
|
inventoryQuantity: number | null;
|
||||||
}
|
}
|
||||||
|
|
||||||
export interface Product {
|
export interface Product {
|
||||||
|
|||||||
@@ -13,3 +13,8 @@ export function formatMoney(value: number | null, currency = "COP"): string {
|
|||||||
maximumFractionDigits: 0,
|
maximumFractionDigits: 0,
|
||||||
}).format(value);
|
}).format(value);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Umbral desde el cual mostramos "Quedan N" en vez de solo "Disponible".
|
||||||
|
// inventoryQuantity=null significa inventario no gestionado (backorder /
|
||||||
|
// manage_inventory=false en Medusa) -- ahi nunca mostramos el mensaje.
|
||||||
|
export const LOW_STOCK_THRESHOLD = 5;
|
||||||
Reference in new issue
Block a user