{
  "name": "Florycell",
  "nodes": [
    {
      "parameters": {
        "operation": "executeQuery",
        "query": "SELECT id_producto, nombre_producto, stock, precio_venta, sucursal \nFROM inventario \nWHERE nombre_producto ILIKE '%' || REPLACE($1, ' ', '%') || '%'\nLIMIT 5;",
        "options": {
          "queryReplacement": "={{ $node[\"AI Agent\"].json.output.trim() }}"
        }
      },
      "type": "n8n-nodes-base.postgres",
      "typeVersion": 2.6,
      "position": [
        416,
        240
      ],
      "id": "3484eb28-dc57-4e61-90a9-056ef77a3a7a",
      "name": "Execute a SQL query",
      "alwaysOutputData": true,
      "credentials": {
        "postgres": {
          "name": "<your credential>"
        }
      }
    },
    {
      "parameters": {
        "chatId": "={{ $item(0).$node[\"Inicio\"].json.message.chat.id }}",
        "text": "=\ud83d\udccd *Sucursal:* {{ $json.sucursal }}\n\ud83d\udcf1 *Producto:* {{ $json.nombre_producto }}\n\ud83d\udcb0 *Precio:* Q{{ $json.precio_venta }}\n\ud83d\udce6 *Disponible:* {{ $json.stock }} unidades",
        "replyMarkup": "inlineKeyboard",
        "inlineKeyboard": {
          "rows": [
            {
              "row": {
                "buttons": [
                  {
                    "text": "\ud83d\uded2 Comprar ahora.",
                    "additionalFields": {
                      "callback_data": "=id_prod:{{ $json.id_producto }}"
                    }
                  }
                ]
              }
            }
          ]
        },
        "additionalFields": {}
      },
      "type": "n8n-nodes-base.telegram",
      "typeVersion": 1.2,
      "position": [
        928,
        304
      ],
      "id": "c31990d2-4cab-4cc3-8b48-de08f1068147",
      "name": "Send a text message",
      "credentials": {
        "telegramApi": {
          "name": "<your credential>"
        }
      }
    },
    {
      "parameters": {
        "promptType": "define",
        "text": "=Analiza el siguiente mensaje: \"{{ $json.message.text }}\".\n\nEres un experto en b\u00fasqueda de inventario y validaci\u00f3n de pagos. Tu funci\u00f3n es simplificar lo que el cliente pide o identificar c\u00f3digos de transacci\u00f3n.\n\nREGLAS DE ORO:\n\nExtrae solo las palabras clave del producto y el modelo.\n\nSi el usuario dice \"hola buscando un protector para mi a24\", tu respuesta debe ser: protector a24\n\nSi el usuario dice \"vidrio templado para un samsung s24 ultra\", tu respuesta debe ser: vidrio templado s24 ultra\n\nNO uses oraciones, NO uses puntos, NO saludes. Solo las palabras clave separadas por un espacio.\n\nSi no hay un producto claro, responde: NADA.\n6. Si el mensaje es un c\u00f3digo largo con guiones (ejemplo: dc233dd2-9c04-47cf-a3b5-8b43df3cd5d6) o parece un ticket de transacci\u00f3n, responde \u00daNICAMENTE: VALIDAR_PAGO",
        "options": {}
      },
      "type": "@n8n/n8n-nodes-langchain.agent",
      "typeVersion": 3.1,
      "position": [
        -128,
        0
      ],
      "id": "50766f73-77e9-4821-ad40-f601baacf876",
      "name": "AI Agent"
    },
    {
      "parameters": {
        "model": "llama-3.3-70b-versatile",
        "options": {}
      },
      "type": "@n8n/n8n-nodes-langchain.lmChatGroq",
      "typeVersion": 1,
      "position": [
        -144,
        240
      ],
      "id": "e7361dd8-cf79-4ed6-a0e5-8840bf3fcf6b",
      "name": "Groq Chat Model",
      "credentials": {
        "groqApi": {
          "name": "<your credential>"
        }
      }
    },
    {
      "parameters": {
        "chatId": "={{ $item(0).$node[\"Inicio\"].json.message.chat.id }}",
        "text": "\u00a1Hola! \ud83d\ude05 Por el momento no cuento con ese producto en ninguna de mis sucursales.",
        "additionalFields": {}
      },
      "type": "n8n-nodes-base.telegram",
      "typeVersion": 1.2,
      "position": [
        928,
        480
      ],
      "id": "20c35a36-3ce6-487b-8ce7-be1b79cb6843",
      "name": "Send a text message1",
      "credentials": {
        "telegramApi": {
          "name": "<your credential>"
        }
      }
    },
    {
      "parameters": {
        "conditions": {
          "options": {
            "caseSensitive": true,
            "leftValue": "",
            "typeValidation": "strict",
            "version": 3
          },
          "conditions": [
            {
              "id": "68696f97-0ff9-4ccc-8dc4-6977718d2507",
              "leftValue": "={{ $node[\"Execute a SQL query\"].json.nombre_producto }}",
              "rightValue": "",
              "operator": {
                "type": "string",
                "operation": "notEmpty",
                "singleValue": true
              }
            }
          ],
          "combinator": "and"
        },
        "options": {}
      },
      "type": "n8n-nodes-base.if",
      "typeVersion": 2.3,
      "position": [
        640,
        288
      ],
      "id": "0935da3b-bfec-47c3-b093-468238497430",
      "name": "If"
    },
    {
      "parameters": {
        "content": "",
        "height": 496,
        "width": 1204,
        "color": 4
      },
      "type": "n8n-nodes-base.stickyNote",
      "position": [
        416,
        -272
      ],
      "typeVersion": 1,
      "id": "26d24222-6a3d-41a8-81b5-dc379ccaf62c",
      "name": "Sticky Note"
    },
    {
      "parameters": {
        "chatId": "={{ $item(0).$node[\"Inicio\"].json.message.chat.id }}",
        "text": "=\u26a0\ufe0f Pago no encontrado  No hemos podido validar la transacci\u00f3n {{ $node[\"Inicio\"].json.message.text }}.  Por favor, aseg\u00farate de haber completado el pago en el link y de haber copiado el c\u00f3digo correctamente. Si el problema persiste, contacta a soporte.",
        "additionalFields": {}
      },
      "type": "n8n-nodes-base.telegram",
      "typeVersion": 1.2,
      "position": [
        816,
        32
      ],
      "id": "65566165-ee0f-45fe-bb7f-0d8885a5f440",
      "name": "Send a text message3",
      "credentials": {
        "telegramApi": {
          "name": "<your credential>"
        }
      }
    },
    {
      "parameters": {
        "conditions": {
          "options": {
            "caseSensitive": true,
            "leftValue": "",
            "typeValidation": "strict",
            "version": 3
          },
          "conditions": [
            {
              "id": "edb4679a-7c02-44c0-a6cc-26085bb3bb97",
              "leftValue": "={{ $json.output }}",
              "rightValue": "VALIDAR_PAGO",
              "operator": {
                "type": "string",
                "operation": "equals"
              }
            }
          ],
          "combinator": "and"
        },
        "options": {}
      },
      "type": "n8n-nodes-base.if",
      "typeVersion": 2.3,
      "position": [
        208,
        -16
      ],
      "id": "1fb54393-4891-45f3-97c1-250d33da7af7",
      "name": "Compra o pago"
    },
    {
      "parameters": {
        "conditions": {
          "options": {
            "caseSensitive": true,
            "leftValue": "",
            "typeValidation": "strict",
            "version": 3
          },
          "conditions": [
            {
              "id": "161643b0-f08d-4351-92f7-2a7c9f30fff4",
              "leftValue": "={{ $node[\"PAgo\"].json.status }}",
              "rightValue": "={{ $json.product_id }}",
              "operator": {
                "type": "string",
                "operation": "notEmpty",
                "singleValue": true
              }
            }
          ],
          "combinator": "and"
        },
        "options": {}
      },
      "type": "n8n-nodes-base.if",
      "typeVersion": 2.3,
      "position": [
        624,
        -96
      ],
      "id": "3eda0188-e0d5-446b-bced-d7321425727a",
      "name": "Existe o no el pago"
    },
    {
      "parameters": {
        "operation": "executeQuery",
        "query": "SELECT status, cardholder_name, amount \nFROM payments \nWHERE transaction_id::text = $1;",
        "options": {
          "queryReplacement": "={{ $node[\"Inicio\"].json.message.text }}"
        }
      },
      "type": "n8n-nodes-base.postgres",
      "typeVersion": 2.6,
      "position": [
        448,
        -80
      ],
      "id": "cb74b741-3e87-4feb-bb57-72d39d20d434",
      "name": "PAgo",
      "alwaysOutputData": true,
      "credentials": {
        "postgres": {
          "name": "<your credential>"
        }
      }
    },
    {
      "parameters": {
        "updates": [
          "message"
        ],
        "additionalFields": {}
      },
      "type": "n8n-nodes-base.telegramTrigger",
      "typeVersion": 1.2,
      "position": [
        -352,
        0
      ],
      "id": "dceb2d8f-0cff-470b-ac0d-ef96e4c998c4",
      "name": "Inicio",
      "credentials": {
        "telegramApi": {
          "name": "<your credential>"
        }
      }
    },
    {
      "parameters": {
        "operation": "executeQuery",
        "query": "UPDATE inventario\nSET stock = stock - 1\nWHERE id_producto = (\n    SELECT id_producto \n    FROM pedidos_pendientes \n    WHERE telegram_id = $1\n)\nRETURNING nombre_producto, sucursal;",
        "options": {
          "queryReplacement": "{{ $node[\"Inicio\"].json.message.chat.id }}"
        }
      },
      "type": "n8n-nodes-base.postgres",
      "typeVersion": 2.6,
      "position": [
        832,
        -192
      ],
      "id": "865314c4-9919-476b-8ddc-87fe696e7b43",
      "name": "Execute a SQL query2",
      "credentials": {
        "postgres": {
          "name": "<your credential>"
        }
      }
    },
    {
      "parameters": {
        "chatId": "={{ $node[\"Inicio\"].json.message.chat.id }}",
        "text": "=\u00a1Tu pago ha sido confirmado con \u00e9xito! \ud83c\udf89  \ud83d\udce6 **Producto:** {{ $json.nombre_producto }} \ud83c\udfea **Sucursal para retirar:** Puedes pasar a recoger tu pedido a nuestra sucursal de **{{ $json.sucursal }}**.  \u00a1Muchas gracias por tu compra! Te esperamos.",
        "additionalFields": {}
      },
      "type": "n8n-nodes-base.telegram",
      "typeVersion": 1.2,
      "position": [
        992,
        -176
      ],
      "id": "0275c341-d082-4834-bc86-4a257fe38763",
      "name": "Send a text message4",
      "credentials": {
        "telegramApi": {
          "name": "<your credential>"
        }
      }
    },
    {
      "parameters": {
        "updates": [
          "callback_query"
        ],
        "additionalFields": {}
      },
      "type": "n8n-nodes-base.telegramTrigger",
      "typeVersion": 1.2,
      "position": [
        224,
        -496
      ],
      "id": "c5e77d65-b0ea-424a-bd36-714370d27e28",
      "name": "Fase2",
      "credentials": {
        "telegramApi": {
          "name": "<your credential>"
        }
      }
    },
    {
      "parameters": {
        "operation": "executeQuery",
        "query": "INSERT INTO pedidos_pendientes (telegram_id, id_producto)\nVALUES ($1, $2)\nON CONFLICT (telegram_id) \nDO UPDATE SET id_producto = $2, fecha_seleccion = NOW();",
        "options": {
          "queryReplacement": "={{ $node[\"Fase2\"].json.callback_query.from.id }}, {{ $node[\"Code in JavaScript\"].json.id_seleccionado }}"
        }
      },
      "type": "n8n-nodes-base.postgres",
      "typeVersion": 2.6,
      "position": [
        720,
        -496
      ],
      "id": "98deefac-10a5-4d52-8abc-f6317cc269fb",
      "name": "Execute a SQL query1",
      "credentials": {
        "postgres": {
          "name": "<your credential>"
        }
      }
    },
    {
      "parameters": {
        "jsCode": "// Verificamos si realmente viene un clic de Telegram\nif (items[0].json.callback_query && items[0].json.callback_query.data) {\n    const data = items[0].json.callback_query.data; // Ejemplo: \"id_prod:19\"\n    const id = data.split(':')[1];\n    \n    return {\n        id_seleccionado: parseInt(id),\n        chat_id: items[0].json.callback_query.message.chat.id,\n        callback_id: items[0].json.callback_query.id\n    };\n} else {\n    // Si lo ejecutas manualmente sin un clic, devuelve esto para no dar error\n    return { error: \"No se detect\u00f3 un clic en el bot\u00f3n todav\u00eda.\" };\n}"
      },
      "type": "n8n-nodes-base.code",
      "typeVersion": 2,
      "position": [
        464,
        -496
      ],
      "id": "658acc64-7c8c-4474-952a-c9d230365e5a",
      "name": "Code in JavaScript"
    },
    {
      "parameters": {
        "chatId": "={{ $node[\"Code in JavaScript\"].json.chat_id }}",
        "text": "=\ud83d\uded2 Orden de Compra Iniciada Has seleccionado el producto con ID: {{ $node[\"Code in JavaScript\"].json.id_seleccionado }}  Para completar tu pago, ingresa a nuestro VisaLink simulado aqu\u00ed: \ud83d\udd17 http://192.168.1.8:8000/  \u26a0\ufe0f IMPORTANTE: Al terminar el pago, la p\u00e1gina te mostrar\u00e1 un \"N\u00famero de Transacci\u00f3n\" (ejemplo: dc233dd2...).  Copia ese c\u00f3digo y p\u00e9galo aqu\u00ed abajo para confirmar tu pedido y procesar el env\u00edo.",
        "additionalFields": {}
      },
      "type": "n8n-nodes-base.telegram",
      "typeVersion": 1.2,
      "position": [
        928,
        -496
      ],
      "id": "05870a71-f7f1-4841-b938-696146eae435",
      "name": "Send a text message2",
      "credentials": {
        "telegramApi": {
          "name": "<your credential>"
        }
      }
    }
  ],
  "connections": {
    "Execute a SQL query": {
      "main": [
        [
          {
            "node": "If",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "AI Agent": {
      "main": [
        [
          {
            "node": "Compra o pago",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Groq Chat Model": {
      "ai_languageModel": [
        [
          {
            "node": "AI Agent",
            "type": "ai_languageModel",
            "index": 0
          }
        ]
      ]
    },
    "If": {
      "main": [
        [
          {
            "node": "Send a text message",
            "type": "main",
            "index": 0
          }
        ],
        [
          {
            "node": "Send a text message1",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Send a text message": {
      "main": [
        []
      ]
    },
    "Compra o pago": {
      "main": [
        [
          {
            "node": "PAgo",
            "type": "main",
            "index": 0
          }
        ],
        [
          {
            "node": "Execute a SQL query",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Existe o no el pago": {
      "main": [
        [
          {
            "node": "Execute a SQL query2",
            "type": "main",
            "index": 0
          }
        ],
        [
          {
            "node": "Send a text message3",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "PAgo": {
      "main": [
        [
          {
            "node": "Existe o no el pago",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Inicio": {
      "main": [
        [
          {
            "node": "AI Agent",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Execute a SQL query2": {
      "main": [
        [
          {
            "node": "Send a text message4",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Fase2": {
      "main": [
        [
          {
            "node": "Code in JavaScript",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Execute a SQL query1": {
      "main": [
        [
          {
            "node": "Send a text message2",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Code in JavaScript": {
      "main": [
        [
          {
            "node": "Execute a SQL query1",
            "type": "main",
            "index": 0
          }
        ]
      ]
    }
  },
  "active": false,
  "settings": {
    "executionOrder": "v1",
    "binaryMode": "separate",
    "availableInMCP": false,
    "timeSavedMode": "fixed",
    "callerPolicy": "workflowsFromSameOwner"
  },
  "versionId": "87192fc5-7f2e-4d4c-8939-f648a6b991fe",
  "meta": {
    "templateCredsSetupCompleted": true
  },
  "id": "gXcUOBNCt8QUSfOJ",
  "tags": []
}