{
  "name": "KALELE_PRODUCTOS_SIMILARES",
  "nodes": [
    {
      "parameters": {
        "inputSource": "passthrough"
      },
      "type": "n8n-nodes-base.executeWorkflowTrigger",
      "typeVersion": 1.1,
      "position": [
        0,
        0
      ],
      "id": "trg-sim-001",
      "name": "When Executed by Another Workflow"
    },
    {
      "parameters": {
        "jsCode": "// Recibe { query } y parsea categor\u00eda / talla / color del texto.\nconst trg = $input.first().json || {};\nconst raw = (trg.query || '').toString().trim();\nconst lower = raw.toLowerCase();\n\n// Mapeo de palabras \u2192 nombre exacto de categor\u00eda en kaleleboutique.com\nconst mapaCategorias = {\n  'vestido gala': 'Vestidos Gala', 'vestidos gala': 'Vestidos Gala', 'gala': 'Vestidos Gala',\n  'vestido': 'Vestidos', 'vestidos': 'Vestidos',\n  'top': 'Tops', 'tops': 'Tops',\n  'blusa': 'Blusas', 'blusas': 'Blusas',\n  'pantalon': 'Pantalones', 'pantalones': 'Pantalones', 'pantal\u00f3n': 'Pantalones',\n  'falda short': 'Faldas Shorts', 'faldas shorts': 'Faldas Shorts',\n  'falda': 'Faldas', 'faldas': 'Faldas',\n  'short': 'Shorts', 'shorts': 'Shorts',\n  'enterizo': 'Enterizos', 'enterizos': 'Enterizos', 'mono': 'Enterizos',\n  'abrigo': 'Abrigos', 'abrigos': 'Abrigos', 'chaqueta': 'Abrigos', 'jacket': 'Abrigos',\n  'blazer': 'Blazers', 'blazers': 'Blazers',\n  'set': 'Sets', 'sets': 'Sets', 'conjunto': 'Sets',\n  'zapato': 'Zapatos', 'zapatos': 'Zapatos',\n  'bota': 'Botas', 'botas': 'Botas',\n  'bailarina': 'Bailarinas', 'bailarinas': 'Bailarinas',\n  'plataforma': 'Plataformas', 'plataformas': 'Plataformas', 'tacon': 'Plataformas', 'tac\u00f3n': 'Plataformas',\n  'accesorio': 'Accesorios', 'accesorios': 'Accesorios',\n  'chaleco': 'Chaleco',\n  'sale': 'SALE', 'oferta': 'SALE', 'descuento': 'SALE'\n};\nlet categoriaNombre = '';\nfor (const k of Object.keys(mapaCategorias).sort((a,b)=>b.length-a.length)) {\n  if (lower.includes(k)) { categoriaNombre = mapaCategorias[k]; break; }\n}\n\nconst tallaMatch = lower.match(/\\b(xxl|xl|xs|[sml])\\b/i);\nconst talla = tallaMatch ? tallaMatch[1].toLowerCase() : '';\n\nconst coloresConocidos = ['negro','blanco','rojo','azul','verde','amarillo','rosa','rosado','morado','lila','beige','crema','cafe','caf\u00e9','marron','marr\u00f3n','gris','dorado','plateado','naranja','celeste','turquesa','vino','nude','floral','multi'];\nlet color = '';\nfor (const c of coloresConocidos) { if (lower.includes(c)) { color = c; break; } }\n\nreturn [{ json: { query_original: raw, categoria: categoriaNombre, color, talla } }];"
      },
      "type": "n8n-nodes-base.code",
      "typeVersion": 2,
      "position": [
        240,
        0
      ],
      "id": "code-parse-001",
      "name": "Parsear query"
    },
    {
      "parameters": {
        "url": "https://kaleleboutique.com/wp-json/wc/store/v1/products/categories",
        "options": {
          "timeout": 15000
        }
      },
      "type": "n8n-nodes-base.httpRequest",
      "typeVersion": 4.2,
      "position": [
        480,
        0
      ],
      "id": "http-cats-001",
      "name": "Listar categor\u00edas"
    },
    {
      "parameters": {
        "jsCode": "// Resuelve el ID de la categor\u00eda a partir del nombre parseado.\nconst parsed = $('Parsear query').first().json;\nconst nombreCat = (parsed.categoria || '').toLowerCase();\nconst cats = $input.first().json;\n\nlet categoryId = '';\nif (nombreCat && Array.isArray(cats)) {\n  const match = cats.find(c => (c.name || '').toLowerCase() === nombreCat)\n             || cats.find(c => (c.name || '').toLowerCase().includes(nombreCat));\n  if (match) categoryId = match.id;\n}\n\nreturn [{\n  json: {\n    category: categoryId,\n    search: (parsed.color || ''),\n    talla: (parsed.talla || '').toLowerCase(),\n    query_original: parsed.query_original\n  }\n}];"
      },
      "type": "n8n-nodes-base.code",
      "typeVersion": 2,
      "position": [
        720,
        0
      ],
      "id": "code-resolve-001",
      "name": "Resolver categor\u00eda"
    },
    {
      "parameters": {
        "url": "https://kaleleboutique.com/wp-json/wc/store/v1/products",
        "sendQuery": true,
        "queryParameters": {
          "parameters": [
            {
              "name": "category",
              "value": "={{ $json.category }}"
            },
            {
              "name": "search",
              "value": "={{ $json.search }}"
            },
            {
              "name": "stock_status",
              "value": "instock"
            },
            {
              "name": "per_page",
              "value": "15"
            },
            {
              "name": "orderby",
              "value": "popularity"
            }
          ]
        },
        "options": {
          "response": {
            "response": {
              "neverError": true
            }
          },
          "timeout": 15000
        }
      },
      "type": "n8n-nodes-base.httpRequest",
      "typeVersion": 4.2,
      "position": [
        960,
        0
      ],
      "id": "http-sim-001",
      "name": "WooCommerce Similares"
    },
    {
      "parameters": {
        "jsCode": "const parsed = $('Parsear query').first().json;\nconst tallaPedida = (parsed.talla || '').toLowerCase();\n\nfunction extraerTallas(attrs) {\n  const a = (attrs || []).find(x => (x.name || '').toLowerCase() === 'talla');\n  return a ? a.terms.map(t => t.name.toLowerCase()) : [];\n}\nfunction extraerColores(attrs) {\n  const a = (attrs || []).find(x => (x.name || '').toLowerCase() === 'color');\n  return a ? a.terms.map(t => t.name.toLowerCase()) : [];\n}\nfunction limpiarPrecio(p) {\n  if (!p || !p.price) return '';\n  const symbol = p.currency_prefix || '\u20a1';\n  const n = parseInt(p.price, 10);\n  if (isNaN(n)) return p.price;\n  return symbol + n.toLocaleString('es-CR');\n}\n\nconst raw = $input.first().json;\nconst productos = Array.isArray(raw) ? raw : (raw.data || []);\n\nconst candidatos = productos\n  .filter(p => p.is_in_stock && p.is_purchasable)\n  .map(p => ({\n    id: p.id,\n    nombre: p.name,\n    precio: limpiarPrecio(p.prices),\n    categoria: (p.categories || []).map(c => c.name).join(', '),\n    tallas: extraerTallas(p.attributes),\n    colores: extraerColores(p.attributes),\n    foto: (p.images && p.images[0]) ? p.images[0].src : '',\n    link: p.permalink\n  }))\n  .filter(p => !tallaPedida || p.tallas.length === 0 || p.tallas.includes(tallaPedida))\n  .slice(0, 5);\n\nreturn [{\n  json: {\n    status: candidatos.length > 0 ? 'ok' : 'sin_similares',\n    query: parsed.query_original,\n    total: candidatos.length,\n    similares: candidatos\n  }\n}];"
      },
      "type": "n8n-nodes-base.code",
      "typeVersion": 2,
      "position": [
        1200,
        0
      ],
      "id": "code-sim-001",
      "name": "Formatear similares"
    },
    {
      "parameters": {
        "assignments": {
          "assignments": [
            {
              "id": "out-sim-1",
              "name": "respuesta",
              "value": "={{ JSON.stringify($json) }}",
              "type": "string"
            }
          ]
        },
        "options": {}
      },
      "type": "n8n-nodes-base.set",
      "typeVersion": 3.4,
      "position": [
        1440,
        0
      ],
      "id": "set-sim-001",
      "name": "Edit Fields"
    }
  ],
  "connections": {
    "When Executed by Another Workflow": {
      "main": [
        [
          {
            "node": "Parsear query",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Parsear query": {
      "main": [
        [
          {
            "node": "Listar categor\u00edas",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Listar categor\u00edas": {
      "main": [
        [
          {
            "node": "Resolver categor\u00eda",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Resolver categor\u00eda": {
      "main": [
        [
          {
            "node": "WooCommerce Similares",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "WooCommerce Similares": {
      "main": [
        [
          {
            "node": "Formatear similares",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Formatear similares": {
      "main": [
        [
          {
            "node": "Edit Fields",
            "type": "main",
            "index": 0
          }
        ]
      ]
    }
  },
  "active": true,
  "settings": {
    "executionOrder": "v1"
  },
  "tags": []
}