Compare commits

...
Author SHA1 Message Date
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
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
gitea-actions 586313d6d7 chore(gitops): deploy Medusa v1.0.165 [skip ci] 2026-08-26 20:56:17 +00:00
10 changed files with 231 additions and 35 deletions

No files matched your search

@@ -1,5 +1,8 @@
import type { MedusaRequest, MedusaResponse } from "@medusajs/framework"; import type { MedusaRequest, MedusaResponse } from "@medusajs/framework";
import { ContainerRegistrationKeys } from "@medusajs/framework/utils"; import {
ContainerRegistrationKeys,
QueryContext,
} from "@medusajs/framework/utils";
import { import {
MEILISEARCH_MODULE, MEILISEARCH_MODULE,
type MeiliSearchService, type MeiliSearchService,
@@ -76,6 +79,13 @@ export async function GET(req: MedusaRequest, res: MedusaResponse) {
const q = stringParam(req.query, "q") ?? ""; const q = stringParam(req.query, "q") ?? "";
const limit = numberParam(req.query, "limit") ?? 24; const limit = numberParam(req.query, "limit") ?? 24;
const offset = numberParam(req.query, "offset") ?? 0; 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[] = []; const filterParts: string[] = [];
for (const facet of ["category", "collection", "brand", "ageRange"]) { for (const facet of ["category", "collection", "brand", "ageRange"]) {
@@ -139,10 +149,36 @@ export async function GET(req: MedusaRequest, res: MedusaResponse) {
return; 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({ const { data: products = [] } = await query.graph({
entity: "product", entity: "product",
fields: PRODUCT_FIELDS, fields: PRODUCT_FIELDS,
filters: { id: productIds }, 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 // 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 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, 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). 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.
@@ -0,0 +1,43 @@
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);
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 memory: 64Mi
- name: migrations - name: migrations
image: gitea.cruzcloud.net/devops/ecommerce-medusa:v1.0.127 image: gitea.cruzcloud.net/devops/ecommerce-medusa:v1.0.168
imagePullPolicy: IfNotPresent imagePullPolicy: IfNotPresent
command: command:
- node - node
@@ -86,7 +86,7 @@ spec:
containers: containers:
- name: app - name: app
image: gitea.cruzcloud.net/devops/ecommerce-medusa:v1.0.127 image: gitea.cruzcloud.net/devops/ecommerce-medusa:v1.0.168
imagePullPolicy: IfNotPresent imagePullPolicy: IfNotPresent
envFrom: envFrom:
- configMapRef: - configMapRef:
@@ -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"> <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" /> <Image src="/images/brand/logo-ari.png" alt="ARI Shopping" fill priority sizes="80px" className="object-cover" />
</Link> </Link>
<PredictiveSearch products={products} /> <PredictiveSearch />
<div className="flex items-center gap-2"> <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="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}> <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 Link from "next/link";
import { useRouter } from "next/navigation"; import { useRouter } from "next/navigation";
import { Search, X } from "lucide-react"; 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 { Input } from "@/components/ui/input";
import type { Product } from "@/lib/headless/types"; import type { Product } from "@/lib/headless/types";
export function PredictiveSearch({ products }: { products: Product[] }) { export function PredictiveSearch() {
const router = useRouter(); const router = useRouter();
const [query, setQuery] = useState(""); const [query, setQuery] = useState("");
const normalized = query.trim().toLocaleLowerCase("es"); const [matches, setMatches] = useState<Product[]>([]);
const matches = useMemo( const [loading, setLoading] = useState(false);
() => normalized.length < 2 const normalized = query.trim();
? []
: products.filter((product) => [product.name, product.category, product.collection, product.brand].join(" ").toLocaleLowerCase("es").includes(normalized)).slice(0, 6), useEffect(() => {
[normalized, products], 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>) => { const submit = (event: FormEvent<HTMLFormElement>) => {
event.preventDefault(); 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>} {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>
</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 && ( {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"> <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) => ( {matches.map((product) => (
@@ -26,3 +26,7 @@ export async function searchProducts(query: string, limit?: number) {
export async function getCategories() { export async function getCategories() {
return provider().getCategories(); return provider().getCategories();
} }
export async function searchWithFacets(filters?: ProductFilters) {
return provider().searchWithFacets?.(filters);
}
@@ -1,6 +1,8 @@
import type { import type {
CatalogProvider, CatalogProvider,
Category, Category,
FacetDistribution,
FacetedSearchResult,
Product, Product,
ProductFilters, ProductFilters,
ProductVariant, 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 = { export const medusaCatalogProvider: CatalogProvider = {
async getProducts(filters) { async getProducts(filters) {
return fetchProducts(filters); return fetchProducts(filters);
@@ -416,6 +468,11 @@ export const medusaCatalogProvider: CatalogProvider = {
}, },
async searchProducts(query, limit = 8) { async searchProducts(query, limit = 8) {
return fetchProducts({ query }, limit); const { products } = await fetchWithFacets({ query }, limit);
return products;
},
async searchWithFacets(filters) {
return fetchWithFacets(filters);
}, },
}; };
+14
View File
@@ -47,9 +47,23 @@ export interface Category {
parentId: string | null; 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 { export interface CatalogProvider {
getProducts(filters?: ProductFilters): Promise<Product[]>; getProducts(filters?: ProductFilters): Promise<Product[]>;
getProductBySlug(slug: string): Promise<Product | null>; getProductBySlug(slug: string): Promise<Product | null>;
searchProducts(query: string, limit?: number): Promise<Product[]>; searchProducts(query: string, limit?: number): Promise<Product[]>;
getCategories(): Promise<Category[]>; 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