Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
902350b58b | ||
|
|
72ae63f2e3 | ||
|
|
4afc63bdc6 | ||
|
|
ed9891577f | ||
|
|
41c7ad25e7 | ||
|
|
2056e6c766 | ||
|
|
f2377be69c | ||
|
|
d6b84e4480 | ||
|
|
f8f540af6a | ||
|
|
51eadd98dc | ||
|
|
fbf0aec892 | ||
|
|
e3eca46e0e | ||
|
|
586313d6d7 | ||
|
|
77a15c26b1 | ||
|
|
6be8dd409c | ||
|
|
8cd43a2584 | ||
|
|
688a7d8e97 |
No files matched your search
@@ -21,7 +21,9 @@ ENV CI=true \
|
|||||||
S3_ACCESS_KEY_ID=build-access-key \
|
S3_ACCESS_KEY_ID=build-access-key \
|
||||||
S3_SECRET_ACCESS_KEY=build-secret-key \
|
S3_SECRET_ACCESS_KEY=build-secret-key \
|
||||||
S3_BUCKET=ari-shopping \
|
S3_BUCKET=ari-shopping \
|
||||||
S3_ENDPOINT=http://127.0.0.1:9000
|
S3_ENDPOINT=http://127.0.0.1:9000 \
|
||||||
|
MEILISEARCH_HOST=http://127.0.0.1:7700 \
|
||||||
|
MEILISEARCH_API_KEY=build-only-meili-key
|
||||||
|
|
||||||
COPY package.json package-lock.json .npmrc ./
|
COPY package.json package-lock.json .npmrc ./
|
||||||
|
|
||||||
|
|||||||
@@ -10,6 +10,91 @@ const required = (name: string): string => {
|
|||||||
return value
|
return value
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Mismos campos derivados de metadata/categories/collection/variants que
|
||||||
|
// mapProduct() en workloads/ecommerce/lib/headless/providers/medusa.ts --
|
||||||
|
// el documento indexado debe reflejar exactamente lo que el storefront
|
||||||
|
// ya muestra, no una vista distinta del catálogo.
|
||||||
|
function stringMetadata(
|
||||||
|
metadata: Record<string, unknown> | null | undefined,
|
||||||
|
key: string,
|
||||||
|
): string {
|
||||||
|
const value = metadata?.[key]
|
||||||
|
return typeof value === "string" ? value : ""
|
||||||
|
}
|
||||||
|
|
||||||
|
function booleanMetadata(
|
||||||
|
metadata: Record<string, unknown> | null | undefined,
|
||||||
|
key: string,
|
||||||
|
): boolean {
|
||||||
|
const value = metadata?.[key]
|
||||||
|
return value === true || value === "true"
|
||||||
|
}
|
||||||
|
|
||||||
|
async function meilisearchProductTransformer(
|
||||||
|
document: Record<string, unknown>,
|
||||||
|
) {
|
||||||
|
const metadata = (document.metadata ?? null) as Record<
|
||||||
|
string,
|
||||||
|
unknown
|
||||||
|
> | null
|
||||||
|
const categories = document.categories as
|
||||||
|
| Array<{ name?: string | null }>
|
||||||
|
| null
|
||||||
|
| undefined
|
||||||
|
const collection = document.collection as { title?: string | null } | null
|
||||||
|
const variants = document.variants as
|
||||||
|
| Array<{
|
||||||
|
inventory_quantity?: number | null
|
||||||
|
manage_inventory?: boolean | null
|
||||||
|
allow_backorder?: boolean | null
|
||||||
|
prices?: Array<{
|
||||||
|
amount?: number | null
|
||||||
|
currency_code?: string | null
|
||||||
|
}> | null
|
||||||
|
}>
|
||||||
|
| null
|
||||||
|
| undefined
|
||||||
|
const variant = variants?.[0]
|
||||||
|
const tags = document.tags as Array<{ value?: string | null }> | null
|
||||||
|
|
||||||
|
const category =
|
||||||
|
categories?.[0]?.name || stringMetadata(metadata, "category") || "Variedades"
|
||||||
|
|
||||||
|
const available =
|
||||||
|
!variant ||
|
||||||
|
variant.allow_backorder === true ||
|
||||||
|
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",
|
||||||
|
shortDescription: document.subtitle || document.title || "",
|
||||||
|
description: document.description || "",
|
||||||
|
category,
|
||||||
|
collection: collection?.title || stringMetadata(metadata, "collection") || "",
|
||||||
|
brand: stringMetadata(metadata, "brand") || "ARI Shopping",
|
||||||
|
ageRange: stringMetadata(metadata, "ageRange") || "Todas",
|
||||||
|
tags: (tags || []).map((tag) => tag.value).filter(Boolean),
|
||||||
|
price: typeof copPrice?.amount === "number" ? copPrice.amount : null,
|
||||||
|
available,
|
||||||
|
isNew: booleanMetadata(metadata, "isNew"),
|
||||||
|
featured: booleanMetadata(metadata, "featured"),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
module.exports = defineConfig({
|
module.exports = defineConfig({
|
||||||
projectConfig: {
|
projectConfig: {
|
||||||
databaseUrl: required("DATABASE_URL"),
|
databaseUrl: required("DATABASE_URL"),
|
||||||
@@ -73,4 +158,72 @@ module.exports = defineConfig({
|
|||||||
},
|
},
|
||||||
},
|
},
|
||||||
],
|
],
|
||||||
|
|
||||||
|
// ADR 0006 Etapa 2. Sin required(): a diferencia de S3/DB, Meilisearch
|
||||||
|
// es un servicio nuevo y todavia no probado en produccion en un host
|
||||||
|
// con historial de swap saturado -- si esta caido o mal configurado,
|
||||||
|
// el plugin se degrada solo (soporta enabled:false, "silently skipped"
|
||||||
|
// segun su propio README) en vez de tumbar el arranque de Medusa
|
||||||
|
// entero, que es lo que si haria required().
|
||||||
|
plugins: [
|
||||||
|
{
|
||||||
|
resolve: "@rokmohar/medusa-plugin-meilisearch",
|
||||||
|
options: {
|
||||||
|
config: {
|
||||||
|
host: process.env.MEILISEARCH_HOST ?? "",
|
||||||
|
apiKey: process.env.MEILISEARCH_API_KEY ?? "",
|
||||||
|
},
|
||||||
|
settings: {
|
||||||
|
products: {
|
||||||
|
type: "products",
|
||||||
|
enabled: Boolean(process.env.MEILISEARCH_HOST),
|
||||||
|
primaryKey: "id",
|
||||||
|
// Campos que el plugin pide via query.graph antes de pasarlos
|
||||||
|
// al transformer de arriba -- si falta alguno acá, llega
|
||||||
|
// undefined al transformer sin importar lo que este haga.
|
||||||
|
fields: [
|
||||||
|
"id",
|
||||||
|
"title",
|
||||||
|
"subtitle",
|
||||||
|
"description",
|
||||||
|
"handle",
|
||||||
|
"status",
|
||||||
|
"thumbnail",
|
||||||
|
"metadata",
|
||||||
|
"tags.value",
|
||||||
|
"categories.name",
|
||||||
|
"collection.title",
|
||||||
|
"variants.inventory_quantity",
|
||||||
|
"variants.manage_inventory",
|
||||||
|
"variants.allow_backorder",
|
||||||
|
"variants.prices.amount",
|
||||||
|
"variants.prices.currency_code",
|
||||||
|
],
|
||||||
|
indexSettings: {
|
||||||
|
// Tabla de ADR 0006 §3: Buscable / Filtrable-faceta / Ordenable.
|
||||||
|
searchableAttributes: [
|
||||||
|
"name",
|
||||||
|
"shortDescription",
|
||||||
|
"description",
|
||||||
|
"category",
|
||||||
|
"collection",
|
||||||
|
"brand",
|
||||||
|
"tags",
|
||||||
|
],
|
||||||
|
filterableAttributes: [
|
||||||
|
"category",
|
||||||
|
"collection",
|
||||||
|
"brand",
|
||||||
|
"ageRange",
|
||||||
|
"price",
|
||||||
|
"available",
|
||||||
|
],
|
||||||
|
sortableAttributes: ["price", "isNew", "featured"],
|
||||||
|
},
|
||||||
|
transformer: meilisearchProductTransformer,
|
||||||
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
],
|
||||||
})
|
})
|
||||||
+30
-1
@@ -12,7 +12,8 @@
|
|||||||
"@medusajs/admin-sdk": "2.18.0",
|
"@medusajs/admin-sdk": "2.18.0",
|
||||||
"@medusajs/cli": "2.18.0",
|
"@medusajs/cli": "2.18.0",
|
||||||
"@medusajs/framework": "2.18.0",
|
"@medusajs/framework": "2.18.0",
|
||||||
"@medusajs/medusa": "2.18.0"
|
"@medusajs/medusa": "2.18.0",
|
||||||
|
"@rokmohar/medusa-plugin-meilisearch": "^1.4.1"
|
||||||
},
|
},
|
||||||
"devDependencies": {
|
"devDependencies": {
|
||||||
"@swc/core": "^1.7.28",
|
"@swc/core": "^1.7.28",
|
||||||
@@ -6561,6 +6562,28 @@
|
|||||||
"node": ">=14.0.0"
|
"node": ">=14.0.0"
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
|
"node_modules/@rokmohar/medusa-plugin-meilisearch": {
|
||||||
|
"version": "1.4.3",
|
||||||
|
"resolved": "https://registry.npmjs.org/@rokmohar/medusa-plugin-meilisearch/-/medusa-plugin-meilisearch-1.4.3.tgz",
|
||||||
|
"integrity": "sha512-+iStv5sc2vuLk+O7OcQLlNR99fMBhGdBOJMCmDJYoTFGhzBA4ZEV18IIr2xqxUDgdQo1haF0TtYv3JmRQUuY1w==",
|
||||||
|
"license": "MIT",
|
||||||
|
"dependencies": {
|
||||||
|
"meilisearch": "^0.56.0"
|
||||||
|
},
|
||||||
|
"engines": {
|
||||||
|
"node": ">=22"
|
||||||
|
},
|
||||||
|
"peerDependencies": {
|
||||||
|
"@medusajs/admin-sdk": "^2.15.2",
|
||||||
|
"@medusajs/framework": "^2.15.2",
|
||||||
|
"@medusajs/medusa": "^2.15.2",
|
||||||
|
"@medusajs/ui": "^4.1.12",
|
||||||
|
"@tanstack/react-query": "5.64.2",
|
||||||
|
"awilix": "^8.0.1",
|
||||||
|
"react": "^18",
|
||||||
|
"react-dom": "^18"
|
||||||
|
}
|
||||||
|
},
|
||||||
"node_modules/@rolldown/pluginutils": {
|
"node_modules/@rolldown/pluginutils": {
|
||||||
"version": "1.0.0-beta.27",
|
"version": "1.0.0-beta.27",
|
||||||
"resolved": "https://registry.npmjs.org/@rolldown/pluginutils/-/pluginutils-1.0.0-beta.27.tgz",
|
"resolved": "https://registry.npmjs.org/@rolldown/pluginutils/-/pluginutils-1.0.0-beta.27.tgz",
|
||||||
@@ -11774,6 +11797,12 @@
|
|||||||
"node": ">= 0.6"
|
"node": ">= 0.6"
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
|
"node_modules/meilisearch": {
|
||||||
|
"version": "0.56.0",
|
||||||
|
"resolved": "https://registry.npmjs.org/meilisearch/-/meilisearch-0.56.0.tgz",
|
||||||
|
"integrity": "sha512-kBXba8DcSrLWHYqopCm2JL90oBy97VdIfHkP1ii7/eHufeEEEk9Zu5Vv/IFQpNzmhEpWszVFVlGvZoI6QJeGzA==",
|
||||||
|
"license": "MIT"
|
||||||
|
},
|
||||||
"node_modules/merge-descriptors": {
|
"node_modules/merge-descriptors": {
|
||||||
"version": "1.0.3",
|
"version": "1.0.3",
|
||||||
"resolved": "https://registry.npmjs.org/merge-descriptors/-/merge-descriptors-1.0.3.tgz",
|
"resolved": "https://registry.npmjs.org/merge-descriptors/-/merge-descriptors-1.0.3.tgz",
|
||||||
|
|||||||
@@ -14,7 +14,8 @@
|
|||||||
"@medusajs/admin-sdk": "2.18.0",
|
"@medusajs/admin-sdk": "2.18.0",
|
||||||
"@medusajs/cli": "2.18.0",
|
"@medusajs/cli": "2.18.0",
|
||||||
"@medusajs/framework": "2.18.0",
|
"@medusajs/framework": "2.18.0",
|
||||||
"@medusajs/medusa": "2.18.0"
|
"@medusajs/medusa": "2.18.0",
|
||||||
|
"@rokmohar/medusa-plugin-meilisearch": "^1.4.1"
|
||||||
},
|
},
|
||||||
"devDependencies": {
|
"devDependencies": {
|
||||||
"@swc/core": "^1.7.28",
|
"@swc/core": "^1.7.28",
|
||||||
|
|||||||
@@ -0,0 +1,197 @@
|
|||||||
|
import type { MedusaRequest, MedusaResponse } from "@medusajs/framework";
|
||||||
|
import {
|
||||||
|
ContainerRegistrationKeys,
|
||||||
|
QueryContext,
|
||||||
|
} from "@medusajs/framework/utils";
|
||||||
|
import {
|
||||||
|
MEILISEARCH_MODULE,
|
||||||
|
type MeiliSearchService,
|
||||||
|
} from "@rokmohar/medusa-plugin-meilisearch";
|
||||||
|
|
||||||
|
// Las rutas /store/meilisearch/* que trae el plugin (ver ADR 0006 nota de
|
||||||
|
// implementacion) no devuelven facetDistribution -- necesitamos esta
|
||||||
|
// ruta propia para pedirlo explicitamente via additionalOptions.facets,
|
||||||
|
// que el servicio del plugin reenvia tal cual al cliente Meilisearch.
|
||||||
|
const FACETS = ["category", "collection", "brand", "ageRange"];
|
||||||
|
|
||||||
|
// Mismos campos que ya usa el storefront contra /store/products
|
||||||
|
// (workloads/ecommerce/lib/headless/providers/medusa.ts) -- una vez que
|
||||||
|
// Meilisearch nos da los ids candidatos, volvemos a Medusa via
|
||||||
|
// query.graph para precio/inventario reales, nunca confiamos en el
|
||||||
|
// valor indexado (puede tener unos segundos de retraso respecto al
|
||||||
|
// evento de sincronizacion).
|
||||||
|
const PRODUCT_FIELDS = [
|
||||||
|
"id",
|
||||||
|
"handle",
|
||||||
|
"title",
|
||||||
|
"subtitle",
|
||||||
|
"description",
|
||||||
|
"thumbnail",
|
||||||
|
"external_id",
|
||||||
|
"metadata",
|
||||||
|
"images.url",
|
||||||
|
"tags.value",
|
||||||
|
"categories.name",
|
||||||
|
"collection.title",
|
||||||
|
"variants.id",
|
||||||
|
"variants.title",
|
||||||
|
"variants.sku",
|
||||||
|
"variants.manage_inventory",
|
||||||
|
"variants.allow_backorder",
|
||||||
|
"variants.inventory_quantity",
|
||||||
|
"variants.calculated_price.calculated_amount",
|
||||||
|
"variants.calculated_price.original_amount",
|
||||||
|
"variants.calculated_price.currency_code",
|
||||||
|
"variants.options.value",
|
||||||
|
"variants.options.option.title",
|
||||||
|
];
|
||||||
|
|
||||||
|
function stringParam(
|
||||||
|
query: MedusaRequest["query"],
|
||||||
|
name: string,
|
||||||
|
): string | undefined {
|
||||||
|
const value = query[name];
|
||||||
|
return typeof value === "string" && value.length > 0 ? value : undefined;
|
||||||
|
}
|
||||||
|
|
||||||
|
function numberParam(
|
||||||
|
query: MedusaRequest["query"],
|
||||||
|
name: string,
|
||||||
|
): number | undefined {
|
||||||
|
const value = stringParam(query, name);
|
||||||
|
if (!value) return undefined;
|
||||||
|
const parsed = Number(value);
|
||||||
|
return Number.isFinite(parsed) ? parsed : undefined;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Meilisearch usa comillas dobles para valores de filtro con espacios;
|
||||||
|
// escapamos las que vengan en el propio valor para no romper la sintaxis.
|
||||||
|
function escapeFilterValue(value: string): string {
|
||||||
|
return value.replace(/\\/g, "\\\\").replace(/"/g, '\\"');
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function GET(req: MedusaRequest, res: MedusaResponse) {
|
||||||
|
const meilisearchService = req.scope.resolve<MeiliSearchService>(
|
||||||
|
MEILISEARCH_MODULE,
|
||||||
|
);
|
||||||
|
const query = req.scope.resolve(ContainerRegistrationKeys.QUERY);
|
||||||
|
|
||||||
|
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"]) {
|
||||||
|
const value = stringParam(req.query, facet);
|
||||||
|
if (value) {
|
||||||
|
filterParts.push(`${facet} = "${escapeFilterValue(value)}"`);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
const minPrice = numberParam(req.query, "minPrice");
|
||||||
|
const maxPrice = numberParam(req.query, "maxPrice");
|
||||||
|
if (typeof minPrice === "number") filterParts.push(`price >= ${minPrice}`);
|
||||||
|
if (typeof maxPrice === "number") filterParts.push(`price <= ${maxPrice}`);
|
||||||
|
|
||||||
|
const indexes = await meilisearchService.getIndexesByType("products");
|
||||||
|
|
||||||
|
if (indexes.length === 0) {
|
||||||
|
// Meilisearch no configurado o el indice "products" esta
|
||||||
|
// deshabilitado -- degradar a "sin resultados" en vez de 500, el
|
||||||
|
// frontend cae de nuevo a su propio filtrado si esta ruta falla.
|
||||||
|
res.json({ products: [], facetDistribution: {}, count: 0, limit, offset });
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
const results = await Promise.all(
|
||||||
|
indexes.map((indexKey) =>
|
||||||
|
meilisearchService.search(indexKey, q, {
|
||||||
|
filter: filterParts.length ? filterParts.join(" AND ") : undefined,
|
||||||
|
paginationOptions: { limit, offset },
|
||||||
|
additionalOptions: { facets: FACETS },
|
||||||
|
}),
|
||||||
|
),
|
||||||
|
);
|
||||||
|
|
||||||
|
const hits = results.flatMap((result) => result.hits);
|
||||||
|
const totalCount = results.reduce(
|
||||||
|
(sum, result) => sum + result.estimatedTotalHits,
|
||||||
|
0,
|
||||||
|
);
|
||||||
|
|
||||||
|
const facetDistribution: Record<string, Record<string, number>> = {};
|
||||||
|
for (const result of results) {
|
||||||
|
const resultFacets = (
|
||||||
|
result as unknown as {
|
||||||
|
facetDistribution?: Record<string, Record<string, number>>;
|
||||||
|
}
|
||||||
|
).facetDistribution;
|
||||||
|
if (!resultFacets) continue;
|
||||||
|
for (const [facet, values] of Object.entries(resultFacets)) {
|
||||||
|
facetDistribution[facet] ??= {};
|
||||||
|
for (const [value, count] of Object.entries(values)) {
|
||||||
|
facetDistribution[facet][value] =
|
||||||
|
(facetDistribution[facet][value] ?? 0) + count;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const productIds = hits.map((hit) => (hit as { id: string }).id);
|
||||||
|
|
||||||
|
if (productIds.length === 0) {
|
||||||
|
res.json({ products: [], facetDistribution, count: 0, limit, offset });
|
||||||
|
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
|
||||||
|
// garantiza el mismo orden que la busqueda.
|
||||||
|
const orderedProducts = [...products].sort(
|
||||||
|
(a, b) => productIds.indexOf(a.id) - productIds.indexOf(b.id),
|
||||||
|
);
|
||||||
|
|
||||||
|
res.json({
|
||||||
|
products: orderedProducts,
|
||||||
|
facetDistribution,
|
||||||
|
count: totalCount,
|
||||||
|
limit,
|
||||||
|
offset,
|
||||||
|
});
|
||||||
|
}
|
||||||
@@ -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.
|
||||||
@@ -25,7 +25,7 @@ spec:
|
|||||||
runAsNonRoot: false
|
runAsNonRoot: false
|
||||||
containers:
|
containers:
|
||||||
- name: app
|
- name: app
|
||||||
image: gitea.cruzcloud.net/devops/docs-portal:v1.0.162
|
image: gitea.cruzcloud.net/devops/docs-portal:v1.0.164
|
||||||
# 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
|
||||||
|
|||||||
@@ -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);
|
||||||
},
|
},
|
||||||
};
|
};
|
||||||
@@ -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
|
|
||||||
Reference in new issue
Block a user