Compare commits

...
Author SHA1 Message Date
devops 6b5450f16f Merge fix/adr0006-etapa2-fase3b-facetas-sidebar into main
Build and Push Frontend / Escaneo de Secretos (Gitleaks) (push) Successful in 37s
Build and Push Frontend / Construir y Subir Imagen (push) Successful in 10m53s
2026-08-26 22:55:13 -05:00
devops 83d448b282 feat(ecommerce): facetas reales de Meilisearch en el sidebar del catalogo
Fase 3b (ultima) de ADR 0006 Etapa 2: los conteos de categoria/marca/edad
del sidebar de /catalog dejan de ser un snapshot client-side fijo. Ahora
se refetchean en vivo contra /api/search en cada cambio de filtro (query
debounced 300ms), tres llamadas paralelas -- una por dimension, cada una
omitiendo su propio filtro para preservar el patron Amazon de "cuantos
resultados habria si eligiera este otro valor".

- catalog-client.tsx: useMemo client-side originales pasan a ser fallback
  (mock/shopify sin searchWithFacets, o cuando la categoria activa es un
  grupo raiz sintetico que Meilisearch no puede filtrar).
- ProductFilters gana `limit` opcional; /api/search y el provider medusa
  lo reenvian -- las llamadas de solo-conteo piden limit=0 para no
  rehidratar precios de productos que no se van a mostrar.
2026-08-26 22:53:49 -05:00
devops 1ecd2015a4 chore: release v1.0.170 [skip ci] 2026-08-26 22:38:31 +00:00
devops 609fc19252 Merge fix/adr0006-etapa2-fase3a-buscador-navbar into main
Build and Push Frontend / Escaneo de Secretos (Gitleaks) (push) Successful in 22s
Build and Push Frontend / Construir y Subir Imagen (push) Successful in 7m16s
2026-08-26 17:30:54 -05:00
devops 902350b58b Fase 3a ADR 0006 Etapa 2: buscador del navbar via Meilisearch
PredictiveSearch pasa de filtrar en memoria el arreglo completo de
productos (prop products, substring match) a un fetch debounced
(250ms, con AbortController) contra la nueva ruta /api/search --
mismo componente visual, solo cambia de donde salen los datos, tal
como pide el ADR 0006 seccion 5.

/api/search (nueva, server-side) es el puente same-origin: el
componente es cliente y no puede pegarle directo al provider
server-side (MEDUSA_BACKEND_URL es DNS interno del cluster, no
resuelve desde el navegador).

CatalogProvider gana un metodo OPCIONAL searchWithFacets? (no cambia
la firma de getProducts/searchProducts) -- mock.ts y shopify.ts
compilan sin tocarlos, siguen sin implementarlo. medusa.ts lo
implementa contra /store/search (Fase 2), reutilizando mapProduct()
ya que la ruta devuelve el mismo shape de producto que /store/products.
searchProducts tambien se repunta a /store/search, dejando de usar el
?q= + re-filtro client-side de fetchProducts/matchesFilters para busqueda
(que sigue sirviendo para navegacion sin busqueda, sin cambios).

Navbar deja de pasarle products a PredictiveSearch (ya no los necesita)
pero los sigue recibiendo el mismo -- collections todavia se deriva de
ahi.

Limpieza: borrado patches/frontend-medusa-env.yaml, confirmado
huerfano (ningun kustomization lo referencia; el patch que si esta
vivo es frontend/patches/deployment.yaml).

Validado: build completo de Docker (target builder) -- npm ci,
next build con typecheck, /api/search aparece en la tabla de rutas
generada. Cero errores nuevos (los warnings de ESLint son
preexistentes en catalog-client.tsx, no tocado en esta fase).
2026-08-26 17:30:47 -05:00
gitea-actions 7d2c03f10f chore(gitops): deploy Docs Portal v1.0.169 [skip ci] 2026-08-26 22:16:37 +00:00
devops 72ae63f2e3 Merge fix/adr0006-nota-implementacion-2-gate-fase2 into main
Build and Push Docs Portal / Escaneo de Secretos (Gitleaks) (push) Successful in 20s
Build and Push Docs Portal / Construir y publicar Docs Portal (push) Successful in 4m2s
2026-08-26 17:12:13 -05:00
devops 4afc63bdc6 docs(adr): nota de implementacion 2 -- hallazgos del gate en vivo de Fase 2 2026-08-26 17:12:10 -05:00
gitea-actions ed9891577f chore(gitops): deploy Medusa v1.0.168 [skip ci] 2026-08-26 22:03:37 +00:00
devops 41c7ad25e7 Merge fix/adr0006-etapa2-fase2-currency-code-search into main
Build and Push Medusa / Escaneo de Secretos (Gitleaks) (push) Successful in 18s
Build and Push Medusa / Construir y publicar Medusa (push) Successful in 11m17s
2026-08-26 16:52:06 -05:00
devops 2056e6c766 Fase 2 fix: /store/search resuelve currency_code, no solo region_id
Confirmado en vivo: pasar solo region_id a QueryContext no alcanza --
"Method calculatePrices requires currency_code in the pricing
context" persistia. A diferencia de /store/products nativo (resuelto
por el middleware setPricingContext), esta ruta propia no pasa por esa
cadena, asi que resuelve la moneda real de la region con un
query.graph adicional antes de pedir calculated_price -- no asume COP
fijo por si el catalogo suma otra region/moneda despues.
2026-08-26 16:52:04 -05:00
gitea-actions f2377be69c chore(gitops): deploy Medusa v1.0.167 [skip ci] 2026-08-26 21:44:33 +00:00
devops d6b84e4480 Merge fix/adr0006-etapa2-fase2-region-id-search into main
Build and Push Medusa / Escaneo de Secretos (Gitleaks) (push) Successful in 24s
Build and Push Medusa / Construir y publicar Medusa (push) Successful in 12m49s
2026-08-26 16:31:24 -05:00
devops f8f540af6a Fase 2 fix: /store/search acepta region_id para calculated_price
Mismo error encontrado en el gate de verificacion, ahora en la ruta
propia en vez del job de sync: "Method calculatePrices requires
currency_code in the pricing context" -- query.graph necesita
region_id/currency_code en el contexto para resolver
variants.calculated_price. El storefront ya manda region_id contra
/store/products (medusa.ts, regionId()); esta ruta ahora acepta el
mismo query param y arma el contexto de pricing con QueryContext(),
igual que la ruta oficial /store/meilisearch/products del plugin.
2026-08-26 16:31:21 -05:00
gitea-actions 51eadd98dc chore(gitops): deploy Medusa v1.0.166 [skip ci] 2026-08-26 21:23:08 +00:00
devops fbf0aec892 Merge fix/adr0006-etapa2-fase2-precio-crudo-indexado into main
Build and Push Medusa / Escaneo de Secretos (Gitleaks) (push) Successful in 29s
Build and Push Medusa / Construir y publicar Medusa (push) Successful in 17m43s
2026-08-26 16:05:03 -05:00
devops e3eca46e0e Fase 2 fix: indexar precio crudo (variants.prices), no calculated_price
Encontrado en vivo (gate de verificacion de Fase 2): el job de sync
inicial del plugin fallaba en TODOS los productos con "Method
calculatePrices requires currency_code in the pricing context" --
variants.calculated_price necesita region_id/currency_code en el
contexto de query.graph, que el workflow interno del plugin
(sync-products.js) no provee. Las categorias si indexaron bien (21),
solo productos fallaba, por eso numberOfDocuments quedaba en 0 pese a
que el indice y sus settings se crearon correctamente.

variants.prices (lista cruda, sin resolver promociones/reglas de
precio) no requiere ese contexto y alcanza para el filtro/orden por
precio de la busqueda -- no necesitamos el precio final promocional
ahi, esa resolucion ya la hace la ruta /store/search via query.graph
con el contexto real al re-hidratar los productos.
2026-08-26 16:04:59 -05:00
gitea-actions 586313d6d7 chore(gitops): deploy Medusa v1.0.165 [skip ci] 2026-08-26 20:56:17 +00:00
devops 77a15c26b1 Merge fix/adr0006-etapa2-fase2-plugin-medusa into main
Build and Push Medusa / Escaneo de Secretos (Gitleaks) (push) Successful in 19s
Build and Push Medusa / Construir y publicar Medusa (push) Successful in 16m14s
2026-08-26 15:39:41 -05:00
gitea-actions 8cd43a2584 chore(gitops): deploy Docs Portal v1.0.164 [skip ci] 2026-08-26 20:06:30 +00:00
14 changed files with 357 additions and 48 deletions

No files matched your search

+19 -6
View File
@@ -47,7 +47,10 @@ async function meilisearchProductTransformer(
inventory_quantity?: number | null
manage_inventory?: boolean | null
allow_backorder?: boolean | null
calculated_price?: { calculated_amount?: number | null } | null
prices?: Array<{
amount?: number | null
currency_code?: string | null
}> | null
}>
| null
| undefined
@@ -63,6 +66,18 @@ async function meilisearchProductTransformer(
variant.manage_inventory === false ||
(variant.inventory_quantity ?? 0) > 0
// variants.calculated_price requiere currency_code/region_id en el
// contexto de pricing, que el workflow de sync interno del plugin no
// provee -- hace fallar TODO el job de indexado (confirmado en vivo:
// "Method calculatePrices requires currency_code in the pricing
// context"). variants.prices es la lista cruda de precios (sin
// resolver promociones/reglas), no necesita contexto -- alcanza para
// el filtro/orden por precio en la busqueda, que no necesita el
// precio final promocional.
const copPrice = variant?.prices?.find(
(price) => price.currency_code?.toLowerCase() === "cop",
)
return {
id: document.id,
name: document.title || "Producto ARI Shopping",
@@ -73,10 +88,7 @@ async function meilisearchProductTransformer(
brand: stringMetadata(metadata, "brand") || "ARI Shopping",
ageRange: stringMetadata(metadata, "ageRange") || "Todas",
tags: (tags || []).map((tag) => tag.value).filter(Boolean),
price:
typeof variant?.calculated_price?.calculated_amount === "number"
? variant.calculated_price.calculated_amount
: null,
price: typeof copPrice?.amount === "number" ? copPrice.amount : null,
available,
isNew: booleanMetadata(metadata, "isNew"),
featured: booleanMetadata(metadata, "featured"),
@@ -184,7 +196,8 @@ module.exports = defineConfig({
"variants.inventory_quantity",
"variants.manage_inventory",
"variants.allow_backorder",
"variants.calculated_price.calculated_amount",
"variants.prices.amount",
"variants.prices.currency_code",
],
indexSettings: {
// Tabla de ADR 0006 §3: Buscable / Filtrable-faceta / Ordenable.
@@ -1,5 +1,8 @@
import type { MedusaRequest, MedusaResponse } from "@medusajs/framework";
import { ContainerRegistrationKeys } from "@medusajs/framework/utils";
import {
ContainerRegistrationKeys,
QueryContext,
} from "@medusajs/framework/utils";
import {
MEILISEARCH_MODULE,
type MeiliSearchService,
@@ -76,6 +79,13 @@ export async function GET(req: MedusaRequest, res: MedusaResponse) {
const q = stringParam(req.query, "q") ?? "";
const limit = numberParam(req.query, "limit") ?? 24;
const offset = numberParam(req.query, "offset") ?? 0;
// calculated_price exige region_id/currency_code en el contexto de
// pricing o query.graph tira "Method calculatePrices requires
// currency_code in the pricing context" (mismo error que ya rompio el
// job de sync -- ver medusa-config.ts). El storefront ya manda
// region_id contra /store/products (medusa.ts, regionId()); esta ruta
// espera el mismo query param.
const regionId = stringParam(req.query, "region_id");
const filterParts: string[] = [];
for (const facet of ["category", "collection", "brand", "ageRange"]) {
@@ -139,10 +149,36 @@ export async function GET(req: MedusaRequest, res: MedusaResponse) {
return;
}
// calculatePrices exige currency_code en el contexto -- no alcanza con
// region_id solo (a diferencia de /store/products nativo, que lo
// resuelve el middleware setPricingContext; esta ruta no pasa por esa
// cadena). Resolvemos la moneda real de la region en vez de asumir COP
// fijo, por si el catalogo suma otra region/moneda mas adelante.
let currencyCode: string | undefined;
if (regionId) {
const { data: regions = [] } = await query.graph({
entity: "region",
fields: ["id", "currency_code"],
filters: { id: regionId },
});
currencyCode = regions[0]?.currency_code;
}
const { data: products = [] } = await query.graph({
entity: "product",
fields: PRODUCT_FIELDS,
filters: { id: productIds },
context:
regionId && currencyCode
? {
variants: {
calculated_price: QueryContext({
region_id: regionId,
currency_code: currencyCode,
}),
},
}
: {},
});
// Preserva el ranking de relevancia de Meilisearch -- query.graph no
@@ -295,3 +295,36 @@ desviaciones reales respecto al diseño de §4/§5 de este ADR:
Ninguna de las tres cambia la decisión ni sus consecuencias — cambian
el cómo, no el qué. Plan de implementación completo, fase por fase,
en la sesión que aprobó esta Etapa 2 (2026-08-26).
## Nota de implementación 2 (2026-08-26, gate en vivo de Fase 2)
Dos bugs reales encontrados y corregidos durante el gate de
verificación en vivo (crear/editar productos, categoría y colección
reales y confirmar que llegan a Meilisearch), ambos con la misma causa
raíz: `variants.calculated_price` de Medusa exige `region_id` **y**
`currency_code` resueltos en el contexto de pricing de la consulta, y
ninguno de los dos caminos nuevos de este ADR pasa por el middleware
nativo (`setPricingContext`) que se lo da gratis a `/store/products`:
1. El job de sync inicial del plugin (`sync-products.js`, corre una
vez al boot) hacía fallar el indexado de **todos** los productos
con `Method calculatePrices requires currency_code in the pricing
context` — las categorías sí indexaban bien (no llevan precio).
Arreglado indexando el precio crudo (`variants.prices`, sin
resolver promociones/reglas) en vez de `calculated_price` — alcanza
para el filtro/orden por precio de la búsqueda.
2. La ruta propia `/store/search` pegaba el mismo error al re-hidratar
productos vía `query.graph`. Pasar `region_id` solo no alcanzó;
hubo que resolver el `currency_code` real de la región con una
consulta adicional antes de armar el `QueryContext`.
Confirmado en vivo, con el fix aplicado: búsqueda por texto, facetas
sobre las 27 unidades del catálogo real, y precio calculado correcto
(`calculated_amount`/`currency_code`) en la respuesta de
`/store/search`. También confirmado en vivo que los tres eventos que
el ADR original marcaba como "verificar, no asumir" — `product.*`,
`product-category.*` y **`product-collection.updated`** (el que tenía
un reporte público de no disparar siempre) — sí sincronizan de forma
confiable en esta combinación exacta (Medusa 2.18.0 + plugin 1.4.1),
propagando un rename de categoría/colección al documento indexado en
menos de 10 segundos.
@@ -25,7 +25,7 @@ spec:
runAsNonRoot: false
containers:
- name: app
image: gitea.cruzcloud.net/devops/docs-portal:v1.0.162
image: gitea.cruzcloud.net/devops/docs-portal:v1.0.169
# El base saca TODAS las capabilities. Probado en vivo y
# revertido: con drop: ALL (aunque se agregue NET_BIND_SERVICE
# de vuelta) el propio entrypoint de nginx:1.27-alpine falla al
@@ -0,0 +1,45 @@
import { searchWithFacets } from "@/lib/headless/client";
import type { ProductFilters } from "@/lib/headless/types";
// PredictiveSearch es un componente cliente y no puede pegarle directo
// al provider server-side (MEDUSA_BACKEND_URL es un nombre DNS interno
// del cluster, no resuelve desde el navegador) -- esta ruta es el
// puente same-origin.
export async function GET(request: Request) {
const { searchParams } = new URL(request.url);
const filters: ProductFilters = {
query: searchParams.get("q") ?? undefined,
category: searchParams.get("category") ?? undefined,
collection: searchParams.get("collection") ?? undefined,
brand: searchParams.get("brand") ?? undefined,
ageRange: searchParams.get("ageRange") ?? undefined,
};
const minPrice = searchParams.get("minPrice");
if (minPrice) filters.minPrice = Number(minPrice);
const maxPrice = searchParams.get("maxPrice");
if (maxPrice) filters.maxPrice = Number(maxPrice);
const limit = searchParams.get("limit");
if (limit) filters.limit = Number(limit);
try {
const result = await searchWithFacets(filters);
// provider actual no implementa searchWithFacets (mock/shopify) --
// degradar a vacío, no a 500; el componente cliente cae de nuevo a
// su propio filtrado si esta ruta no trae nada útil.
return Response.json(
result ?? { products: [], facetDistribution: {}, count: 0 },
);
} catch (error) {
return Response.json(
{
products: [],
facetDistribution: {},
count: 0,
error: (error as Error).message,
},
{ status: 502 },
);
}
}
@@ -65,7 +65,7 @@ spec:
memory: 64Mi
- name: migrations
image: gitea.cruzcloud.net/devops/ecommerce-medusa:v1.0.127
image: gitea.cruzcloud.net/devops/ecommerce-medusa:v1.0.168
imagePullPolicy: IfNotPresent
command:
- node
@@ -86,7 +86,7 @@ spec:
containers:
- name: app
image: gitea.cruzcloud.net/devops/ecommerce-medusa:v1.0.127
image: gitea.cruzcloud.net/devops/ecommerce-medusa:v1.0.168
imagePullPolicy: IfNotPresent
envFrom:
- configMapRef:
@@ -7,7 +7,7 @@ import { PromoTile } from "@/components/home/category-tiles";
import { ProductCard } from "@/components/product/product-card";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import type { Category, Product } from "@/lib/headless/types";
import type { Category, FacetDistribution, 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
@@ -156,8 +156,10 @@ export function CatalogClient({
// 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(() => {
// resultados habria si se eligiera ese valor. Sirven de fallback cuando
// el provider activo no soporta facetas reales (mock/shopify) o cuando
// la busqueda en vivo todavia no respondio.
const fallbackCategoryCounts = useMemo(() => {
const base = products.filter(
(product) => matchesQuery(product, query) && matchesCollection(product, collection) && matchesBrand(product, brand) && matchesAge(product, age) && matchesPrice(product, maxPrice),
);
@@ -170,7 +172,7 @@ export function CatalogClient({
return counts;
}, [age, brand, categories, categoryGroups, collection, maxPrice, products, query]);
const brandCounts = useMemo(() => {
const fallbackBrandCounts = useMemo(() => {
const base = products.filter(
(product) =>
matchesQuery(product, query) &&
@@ -187,7 +189,7 @@ export function CatalogClient({
return counts;
}, [age, allowedCategories, brands, category, collection, maxPrice, products, query]);
const ageCounts = useMemo(() => {
const fallbackAgeCounts = useMemo(() => {
const base = products.filter(
(product) =>
matchesQuery(product, query) &&
@@ -204,6 +206,98 @@ export function CatalogClient({
return counts;
}, [ages, allowedCategories, brand, category, collection, maxPrice, products, query]);
// "Mochilas y morrales" etc.: nombre sintetico de grupo que no existe
// como valor indexado en Meilisearch (ningun producto lo tiene como
// category real, solo sus hijos -- ver categoryGroups arriba). Mientras
// esa sea la categoria activa, las facetas en vivo de marca/edad no
// pueden filtrar por ella y se degrada al conteo client-side, que si
// sabe expandir el grupo via matchesCategory/allowedCategories.
const categoryIsLeafOrNone = category === "Todos" || !categoryGroups[category];
// Conteos reales via Meilisearch (ADR 0006 Etapa 2 Fase 3b): un fetch
// por dimension contra /api/search, cada uno omitiendo su propio filtro
// (mismo criterio de auto-exclusion que el fallback de arriba) para que
// los conteos reflejen el subconjunto ya filtrado por las OTRAS
// dimensiones y se puedan seguir eligiendo otros valores. `limit=0` evita
// rehidratar precios de productos que no vamos a mostrar -- solo importan
// `facetDistribution` y `count`.
const [liveFacets, setLiveFacets] = useState<{
category: Record<string, number> | null;
categoryTotal: number | null;
brand: Record<string, number> | null;
brandTotal: number | null;
ageRange: Record<string, number> | null;
ageTotal: number | null;
}>({ category: null, categoryTotal: null, brand: null, brandTotal: null, ageRange: null, ageTotal: null });
useEffect(() => {
const controller = new AbortController();
function buildParams(omit: "category" | "brand" | "ageRange"): URLSearchParams {
const params = new URLSearchParams({ limit: "0" });
if (query) params.set("q", query);
if (collection) params.set("collection", collection);
if (omit !== "category" && category !== "Todos" && categoryIsLeafOrNone) {
params.set("category", category);
}
if (omit !== "brand" && brand !== "Todas") params.set("brand", brand);
if (omit !== "ageRange" && age !== "Todas") params.set("ageRange", age);
if (maxPrice > 0) params.set("maxPrice", String(maxPrice));
return params;
}
async function fetchFacet(omit: "category" | "brand" | "ageRange") {
const response = await fetch(`/api/search?${buildParams(omit).toString()}`, {
signal: controller.signal,
});
return (await response.json()) as { facetDistribution?: FacetDistribution; count?: number };
}
const timer = setTimeout(() => {
Promise.all([fetchFacet("category"), fetchFacet("brand"), fetchFacet("ageRange")])
.then(([categoryRes, brandRes, ageRes]) => {
// Un facetDistribution vacio ({}) es la senal de degrade explicita
// de /api/search (provider sin searchWithFacets, o Meilisearch
// sin indices todavia) -- distinto de una faceta real con 0
// resultados, que igual trae la clave presente.
const categoryFacet = categoryRes.facetDistribution && "category" in categoryRes.facetDistribution ? categoryRes.facetDistribution.category : null;
const brandFacet = brandRes.facetDistribution && "brand" in brandRes.facetDistribution ? brandRes.facetDistribution.brand : null;
const ageFacet = ageRes.facetDistribution && "ageRange" in ageRes.facetDistribution ? ageRes.facetDistribution.ageRange : null;
setLiveFacets({
category: categoryFacet,
categoryTotal: categoryFacet ? (categoryRes.count ?? 0) : null,
brand: categoryIsLeafOrNone ? brandFacet : null,
brandTotal: categoryIsLeafOrNone && brandFacet ? (brandRes.count ?? 0) : null,
ageRange: categoryIsLeafOrNone ? ageFacet : null,
ageTotal: categoryIsLeafOrNone && ageFacet ? (ageRes.count ?? 0) : null,
});
})
.catch((error) => {
if ((error as Error).name !== "AbortError") {
setLiveFacets({ category: null, categoryTotal: null, brand: null, brandTotal: null, ageRange: null, ageTotal: null });
}
});
}, 300);
return () => {
clearTimeout(timer);
controller.abort();
};
}, [age, brand, category, categoryIsLeafOrNone, collection, maxPrice, query]);
const categoryCounts = useMemo(
() => (liveFacets.category ? { Todos: liveFacets.categoryTotal ?? 0, ...liveFacets.category } : fallbackCategoryCounts),
[fallbackCategoryCounts, liveFacets.category, liveFacets.categoryTotal],
);
const brandCounts = useMemo(
() => (liveFacets.brand ? { Todas: liveFacets.brandTotal ?? 0, ...liveFacets.brand } : fallbackBrandCounts),
[fallbackBrandCounts, liveFacets.brand, liveFacets.brandTotal],
);
const ageCounts = useMemo(
() => (liveFacets.ageRange ? { Todas: liveFacets.ageTotal ?? 0, ...liveFacets.ageRange } : fallbackAgeCounts),
[fallbackAgeCounts, liveFacets.ageRange, liveFacets.ageTotal],
);
const reset = () => {
setQuery("");
setCategory("Todos");
@@ -56,7 +56,7 @@ export function Navbar({ products, categories }: { products: Product[]; categori
<Link href="/" className="relative size-16 overflow-hidden rounded-full border-2 border-slate-900 bg-black shadow-lg lg:size-20">
<Image src="/images/brand/logo-ari.png" alt="ARI Shopping" fill priority sizes="80px" className="object-cover" />
</Link>
<PredictiveSearch products={products} />
<PredictiveSearch />
<div className="flex items-center gap-2">
<Button variant="outline" size="icon" aria-label="Mi cuenta" className="hidden border-slate-300 bg-white text-slate-900 hover:border-violet-400 hover:bg-violet-50 sm:inline-flex" onClick={() => setAccountOpen(true)}><UserRound /></Button>
<Button variant="outline" size="icon" aria-label={`Favoritos: ${wishlistCount}`} className="relative hidden border-slate-300 bg-white text-slate-900 hover:border-fuchsia-400 hover:bg-fuchsia-50 sm:inline-flex" onClick={openWishlist}>
@@ -4,20 +4,45 @@ import Image from "next/image";
import Link from "next/link";
import { useRouter } from "next/navigation";
import { Search, X } from "lucide-react";
import { FormEvent, useMemo, useState } from "react";
import { FormEvent, useEffect, useState } from "react";
import { Input } from "@/components/ui/input";
import type { Product } from "@/lib/headless/types";
export function PredictiveSearch({ products }: { products: Product[] }) {
export function PredictiveSearch() {
const router = useRouter();
const [query, setQuery] = useState("");
const normalized = query.trim().toLocaleLowerCase("es");
const matches = useMemo(
() => normalized.length < 2
? []
: products.filter((product) => [product.name, product.category, product.collection, product.brand].join(" ").toLocaleLowerCase("es").includes(normalized)).slice(0, 6),
[normalized, products],
);
const [matches, setMatches] = useState<Product[]>([]);
const [loading, setLoading] = useState(false);
const normalized = query.trim();
useEffect(() => {
if (normalized.length < 2) {
setMatches([]);
setLoading(false);
return;
}
const controller = new AbortController();
setLoading(true);
const timer = setTimeout(() => {
fetch(`/api/search?q=${encodeURIComponent(normalized)}`, {
signal: controller.signal,
})
.then((response) => response.json())
.then((data: { products?: Product[] }) => {
setMatches((data.products ?? []).slice(0, 6));
})
.catch((error) => {
if ((error as Error).name !== "AbortError") setMatches([]);
})
.finally(() => setLoading(false));
}, 250);
return () => {
clearTimeout(timer);
controller.abort();
};
}, [normalized]);
const submit = (event: FormEvent<HTMLFormElement>) => {
event.preventDefault();
@@ -36,6 +61,11 @@ export function PredictiveSearch({ products }: { products: Product[] }) {
{query && <button type="button" aria-label="Limpiar búsqueda" className="absolute right-4 top-1/2 -translate-y-1/2 rounded-full p-1 text-slate-400 hover:bg-slate-100" onClick={() => setQuery("")}><X className="size-4" /></button>}
</div>
</div>
{loading && normalized.length >= 2 && matches.length === 0 && (
<div className="absolute left-0 right-0 top-[calc(100%+10px)] z-50 rounded-2xl border border-slate-200 bg-white p-4 text-center text-sm text-slate-500 shadow-2xl">
Buscando…
</div>
)}
{matches.length > 0 && (
<div className="absolute left-0 right-0 top-[calc(100%+10px)] z-50 overflow-hidden rounded-2xl border border-slate-200 bg-white p-2 shadow-2xl">
{matches.map((product) => (
@@ -25,7 +25,7 @@ spec:
runAsUser: 1001
containers:
- name: app
image: gitea.cruzcloud.net/devops/ecommerce-frontend:v1.0.157
image: gitea.cruzcloud.net/devops/ecommerce-frontend:v1.0.170
env:
- name: HEADLESS_PROVIDER
value: medusa
@@ -26,3 +26,7 @@ export async function searchProducts(query: string, limit?: number) {
export async function getCategories() {
return provider().getCategories();
}
export async function searchWithFacets(filters?: ProductFilters) {
return provider().searchWithFacets?.(filters);
}
@@ -1,6 +1,8 @@
import type {
CatalogProvider,
Category,
FacetDistribution,
FacetedSearchResult,
Product,
ProductFilters,
ProductVariant,
@@ -385,6 +387,56 @@ async function fetchCategories(): Promise<Category[]> {
}));
}
type MedusaSearchResponse = {
products: MedusaProduct[];
facetDistribution?: FacetDistribution;
count?: number;
};
// Pega contra /store/search (ADR 0006 Etapa 2) en vez de /store/products
// -- Meilisearch resuelve texto tolerante a errores de tipeo y facetas
// reales, la ruta del backend re-hidrata precio/inventario vía
// query.graph antes de responder, así que el shape de MedusaProduct es
// exactamente el mismo que ya mapea mapProduct().
async function fetchWithFacets(
filters?: ProductFilters,
limit = 24,
): Promise<FacetedSearchResult> {
const params = new URLSearchParams({
limit: String(limit),
region_id: regionId(),
});
if (filters?.query) params.set("q", filters.query);
if (filters?.category && filters.category !== "Todos") {
params.set("category", filters.category);
}
if (filters?.collection) params.set("collection", filters.collection);
if (filters?.brand && filters.brand !== "Todas") {
params.set("brand", filters.brand);
}
if (filters?.ageRange && filters.ageRange !== "Todas") {
params.set("ageRange", filters.ageRange);
}
if (typeof filters?.minPrice === "number") {
params.set("minPrice", String(filters.minPrice));
}
if (typeof filters?.maxPrice === "number") {
params.set("maxPrice", String(filters.maxPrice));
}
const response = await medusaFetch<MedusaSearchResponse>(
"/store/search",
params,
);
return {
products: response.products.map(mapProduct),
facetDistribution: response.facetDistribution ?? {},
count: response.count ?? response.products.length,
};
}
export const medusaCatalogProvider: CatalogProvider = {
async getProducts(filters) {
return fetchProducts(filters);
@@ -416,6 +468,11 @@ export const medusaCatalogProvider: CatalogProvider = {
},
async searchProducts(query, limit = 8) {
return fetchProducts({ query }, limit);
const { products } = await fetchWithFacets({ query }, limit);
return products;
},
async searchWithFacets(filters) {
return fetchWithFacets(filters, filters?.limit ?? 24);
},
};
+18
View File
@@ -38,6 +38,10 @@ export interface ProductFilters {
ageRange?: string;
minPrice?: number;
maxPrice?: number;
// Solo lo usa searchWithFacets -- limit=0 pide facetDistribution/count
// sin rehidratar precios de productos que no se van a mostrar (ver
// sidebar de facetas en catalog-client.tsx).
limit?: number;
}
export interface Category {
@@ -47,9 +51,23 @@ export interface Category {
parentId: string | null;
}
// facet -> valor -> cuantos productos del resultado filtrado tienen ese
// valor (ej. { brand: { Marvel: 5, Disney: 10 } }).
export type FacetDistribution = Record<string, Record<string, number>>;
export interface FacetedSearchResult {
products: Product[];
facetDistribution: FacetDistribution;
count: number;
}
export interface CatalogProvider {
getProducts(filters?: ProductFilters): Promise<Product[]>;
getProductBySlug(slug: string): Promise<Product | null>;
searchProducts(query: string, limit?: number): Promise<Product[]>;
getCategories(): Promise<Category[]>;
// Opcional a propósito: mock.ts y shopify.ts no lo implementan y
// siguen compilando igual -- los llamadores caen de nuevo al
// filtrado/conteo 100% client-side que ya existe cuando no está.
searchWithFacets?(filters?: ProductFilters): Promise<FacetedSearchResult>;
}
@@ -1,21 +0,0 @@
apiVersion: apps/v1
kind: Deployment
metadata:
name: frontend-deploy
spec:
template:
spec:
containers:
- name: web
env:
- name: HEADLESS_PROVIDER
value: medusa
- name: MEDUSA_BACKEND_URL
value: http://medusa-svc:9000
- name: MEDUSA_PUBLISHABLE_KEY
valueFrom:
secretKeyRef:
name: commerce-storefront
key: MEDUSA_PUBLISHABLE_KEY