{
  "name": "Suscripciones",
  "nodes": [
    {
      "parameters": {
        "rules": {
          "values": [
            {
              "conditions": {
                "options": {
                  "caseSensitive": true,
                  "leftValue": "",
                  "typeValidation": "strict",
                  "version": 2
                },
                "conditions": [
                  {
                    "id": "58398caf-9375-4bf9-b31b-c3e59b79b0c5",
                    "leftValue": "={{ $json.accion }}",
                    "rightValue": "start",
                    "operator": {
                      "type": "string",
                      "operation": "equals",
                      "name": "filter.operator.equals"
                    }
                  }
                ],
                "combinator": "and"
              }
            },
            {
              "conditions": {
                "options": {
                  "caseSensitive": true,
                  "leftValue": "",
                  "typeValidation": "strict",
                  "version": 2
                },
                "conditions": [
                  {
                    "id": "bd9d53ee-d8c2-4657-93e1-b2ed44921a98",
                    "leftValue": "={{ $json.accion }}",
                    "rightValue": "buscar",
                    "operator": {
                      "type": "string",
                      "operation": "equals",
                      "name": "filter.operator.equals"
                    }
                  }
                ],
                "combinator": "and"
              },
              "renameOutput": true,
              "outputKey": "buscar"
            },
            {
              "conditions": {
                "options": {
                  "caseSensitive": true,
                  "leftValue": "",
                  "typeValidation": "strict",
                  "version": 2
                },
                "conditions": [
                  {
                    "id": "d5c91809-2f18-4f93-8d41-9f05eeb4c2ff",
                    "leftValue": "={{ $json.accion }}",
                    "rightValue": "seguir",
                    "operator": {
                      "type": "string",
                      "operation": "equals",
                      "name": "filter.operator.equals"
                    }
                  }
                ],
                "combinator": "and"
              },
              "renameOutput": true,
              "outputKey": "seguir"
            },
            {
              "conditions": {
                "options": {
                  "caseSensitive": true,
                  "leftValue": "",
                  "typeValidation": "strict",
                  "version": 2
                },
                "conditions": [
                  {
                    "id": "2898a0c9-9b85-4bb2-8419-ff665b509e3a",
                    "leftValue": "={{ $json.accion }}",
                    "rightValue": "cancelar",
                    "operator": {
                      "type": "string",
                      "operation": "equals",
                      "name": "filter.operator.equals"
                    }
                  }
                ],
                "combinator": "and"
              },
              "renameOutput": true,
              "outputKey": "cancelar"
            },
            {
              "conditions": {
                "options": {
                  "caseSensitive": true,
                  "leftValue": "",
                  "typeValidation": "strict",
                  "version": 2
                },
                "conditions": [
                  {
                    "id": "c77f835e-bc1e-4398-80a8-2090c5561dbf",
                    "leftValue": "={{ $json.accion }}",
                    "rightValue": "suscripciones",
                    "operator": {
                      "type": "string",
                      "operation": "equals",
                      "name": "filter.operator.equals"
                    }
                  }
                ],
                "combinator": "and"
              },
              "renameOutput": true,
              "outputKey": "suscripciones"
            },
            {
              "conditions": {
                "options": {
                  "caseSensitive": true,
                  "leftValue": "",
                  "typeValidation": "strict",
                  "version": 2
                },
                "conditions": [
                  {
                    "id": "11089e33-3a63-4512-a4c5-9eb71bc081b1",
                    "leftValue": "={{ $json.accion }}",
                    "rightValue": "error_comando",
                    "operator": {
                      "type": "string",
                      "operation": "equals",
                      "name": "filter.operator.equals"
                    }
                  }
                ],
                "combinator": "and"
              },
              "renameOutput": true,
              "outputKey": "error"
            },
            {
              "conditions": {
                "options": {
                  "caseSensitive": true,
                  "leftValue": "",
                  "typeValidation": "strict",
                  "version": 2
                },
                "conditions": [
                  {
                    "id": "87cd097f-182c-44b8-872a-472cc596c9c1",
                    "leftValue": "=",
                    "rightValue": "",
                    "operator": {
                      "type": "string",
                      "operation": "equals",
                      "name": "filter.operator.equals"
                    }
                  }
                ],
                "combinator": "and"
              },
              "renameOutput": true,
              "outputKey": "otros"
            }
          ]
        },
        "options": {}
      },
      "type": "n8n-nodes-base.switch",
      "typeVersion": 3.2,
      "position": [
        -480,
        352
      ],
      "id": "fbd0aa4a-62ac-4c09-956c-606e3f3a3c19",
      "name": "Switch",
      "alwaysOutputData": false,
      "notesInFlow": false
    },
    {
      "parameters": {
        "mode": "runOnceForEachItem",
        "jsCode": "function escapeMarkdown(text) {\n  return text\n    .replace(/([_*[\\]()~`>#+\\-=|{}.!])/g, \"\\\\$1\"); // escapa caracteres especiales\n}\n\nconst p = $json;\n\nconst descripcionSegura = escapeMarkdown(p.descripcion.slice(0, 300));\n\nreturn {\n  json: {\n    chatId: p.chatId,\n    message: `\ud83d\udcf1 *${escapeMarkdown(p.nombre)}*\\n\\n\ud83d\udcb0 *Precio:* ${escapeMarkdown(p.precio.replace(\"Incluye IVA\", \"\").trim())} ${\n      p.precio.includes(\"Incluye IVA\") ? \"_(Incluye IVA)_\" : \"\"\n    }\\n\ud83d\udcdd *Descripci\u00f3n:* ${descripcionSegura}...\\n\ud83d\udcc5 *Actualizado:* ${escapeMarkdown(new Date(p.fecha).toLocaleDateString(\"es-EC\"))}`,\n    parse_mode: \"MarkdownV2\"\n  }\n};\n\n"
      },
      "type": "n8n-nodes-base.code",
      "typeVersion": 2,
      "position": [
        224,
        -64
      ],
      "id": "b23ea85a-77ad-48a4-88f0-0474ed6e4297",
      "name": "Code1"
    },
    {
      "parameters": {
        "chatId": "={{ $('Telegram Trigger').item.json.message.chat.id }}",
        "text": "={{$json[\"message\"]}}",
        "additionalFields": {}
      },
      "type": "n8n-nodes-base.telegram",
      "typeVersion": 1.2,
      "position": [
        368,
        -64
      ],
      "id": "896330e9-a841-4a7a-9106-b1993bba9845",
      "name": "Send a text message",
      "credentials": {
        "telegramApi": {
          "name": "<your credential>"
        }
      }
    },
    {
      "parameters": {
        "chatId": "={{$json[\"chatId\"]}}",
        "text": "=\u2705 Te avisar\u00e9 cuando haya novedades sobre *{{ $('Code3').item.json.producto }}*. Puedes usar /buscar para ver si ya hay productos disponibles.",
        "additionalFields": {}
      },
      "type": "n8n-nodes-base.telegram",
      "typeVersion": 1.2,
      "position": [
        432,
        128
      ],
      "id": "f17f9d59-e3de-4656-a45d-98ffb0ac0a33",
      "name": "Send a text message1",
      "credentials": {
        "telegramApi": {
          "name": "<your credential>"
        }
      }
    },
    {
      "parameters": {
        "jsCode": "// Chat del usuario que pidi\u00f3 /suscripciones\nconst chatId = $item(0).$json.chatId;\n\n// Todas las suscripciones existentes\nconst subs = $input.all().map(i => i.json);\n\n// Filtrar solo las del usuario actual\nconst propias = subs.filter(s => String(s.chatId) === String(chatId));\n\nlet message = \"\";\n\nif (propias.length === 0) {\n  message = \"\ud83d\udced No tienes suscripciones activas.\";\n} else {\n  message = `\ud83d\udd14 *Tus suscripciones activas:*\\n\\n`;\n  propias.forEach((s, i) => {\n    const fecha = new Date(s.fecha).toLocaleDateString(\"es-EC\");\n    message += `${i + 1}. ${s.producto} _(desde ${fecha})_\\n`;\n  });\n  message += \"\\nUsa /cancelar <producto> para dejar de seguir alguno.\";\n}\n\nreturn {\n  json: { chatId, message }\n};\n"
      },
      "type": "n8n-nodes-base.code",
      "typeVersion": 2,
      "position": [
        288,
        688
      ],
      "id": "c8f27e66-7dbd-4c2a-82ae-2fb155f361d8",
      "name": "Code4"
    },
    {
      "parameters": {
        "chatId": "={{ $json.chatId }}",
        "text": "={{ $json.message }}",
        "additionalFields": {}
      },
      "type": "n8n-nodes-base.telegram",
      "typeVersion": 1.2,
      "position": [
        496,
        688
      ],
      "id": "f7b36b70-1c27-44d7-86d5-bbf3ee4f2163",
      "name": "Send a text message3",
      "credentials": {
        "telegramApi": {
          "name": "<your credential>"
        }
      }
    },
    {
      "parameters": {
        "chatId": "={{$node[\"Telegram Trigger\"].json.message.chat.id}}",
        "text": "={{ $json.message }}",
        "additionalFields": {}
      },
      "type": "n8n-nodes-base.telegram",
      "typeVersion": 1.2,
      "position": [
        1088,
        384
      ],
      "id": "cc3f8c7e-581f-4b08-946a-67ae64ab6dbf",
      "name": "Send a text message4",
      "credentials": {
        "telegramApi": {
          "name": "<your credential>"
        }
      }
    },
    {
      "parameters": {
        "operation": "append",
        "documentId": {
          "__rl": true,
          "value": "1lUw0q4H5dCIwHO4rkQVe8PCRtxGZupx1X54GAyU_e7A",
          "mode": "list",
          "cachedResultName": "suscripciones",
          "cachedResultUrl": "https://docs.google.com/spreadsheets/d/1lUw0q4H5dCIwHO4rkQVe8PCRtxGZupx1X54GAyU_e7A/edit?usp=drivesdk"
        },
        "sheetName": {
          "__rl": true,
          "value": "gid=0",
          "mode": "list",
          "cachedResultName": "chatldproductofecha_suscripcion",
          "cachedResultUrl": "https://docs.google.com/spreadsheets/d/1lUw0q4H5dCIwHO4rkQVe8PCRtxGZupx1X54GAyU_e7A/edit#gid=0"
        },
        "columns": {
          "mappingMode": "defineBelow",
          "value": {
            "chatId": "={{$node[\"Telegram Trigger\"].json.message.chat.id}} ",
            "username": "={{ $('Telegram Trigger').item.json.message.from.username }}",
            "producto": "={{ $('Code3').item.json.producto }}",
            "precioAnterior": "={{ $json.precio }}",
            "precioActual": "={{ $json.precio }}"
          },
          "matchingColumns": [],
          "schema": [
            {
              "id": "chatId",
              "displayName": "chatId",
              "required": false,
              "defaultMatch": false,
              "display": true,
              "type": "string",
              "canBeUsedToMatch": true,
              "removed": false
            },
            {
              "id": "username",
              "displayName": "username",
              "required": false,
              "defaultMatch": false,
              "display": true,
              "type": "string",
              "canBeUsedToMatch": true,
              "removed": false
            },
            {
              "id": "producto",
              "displayName": "producto",
              "required": false,
              "defaultMatch": false,
              "display": true,
              "type": "string",
              "canBeUsedToMatch": true,
              "removed": false
            },
            {
              "id": "precioAnterior",
              "displayName": "precioAnterior",
              "required": false,
              "defaultMatch": false,
              "display": true,
              "type": "string",
              "canBeUsedToMatch": true,
              "removed": false
            },
            {
              "id": "precioActual",
              "displayName": "precioActual",
              "required": false,
              "defaultMatch": false,
              "display": true,
              "type": "string",
              "canBeUsedToMatch": true,
              "removed": false
            }
          ],
          "attemptToConvertTypes": false,
          "convertFieldsToString": false
        },
        "options": {}
      },
      "type": "n8n-nodes-base.googleSheets",
      "typeVersion": 4.6,
      "position": [
        272,
        128
      ],
      "id": "0f1832bb-62da-4bcc-9c69-595745ca6f61",
      "name": "Crea una nueva suscripcion en la hoja de suscripciones1",
      "credentials": {
        "googleSheetsOAuth2Api": {
          "name": "<your credential>"
        }
      }
    },
    {
      "parameters": {
        "operation": "delete",
        "documentId": {
          "__rl": true,
          "value": "1lUw0q4H5dCIwHO4rkQVe8PCRtxGZupx1X54GAyU_e7A",
          "mode": "list",
          "cachedResultName": "suscripciones",
          "cachedResultUrl": "https://docs.google.com/spreadsheets/d/1lUw0q4H5dCIwHO4rkQVe8PCRtxGZupx1X54GAyU_e7A/edit?usp=drivesdk"
        },
        "sheetName": {
          "__rl": true,
          "value": "gid=0",
          "mode": "list",
          "cachedResultName": "chatldproductofecha_suscripcion",
          "cachedResultUrl": "https://docs.google.com/spreadsheets/d/1lUw0q4H5dCIwHO4rkQVe8PCRtxGZupx1X54GAyU_e7A/edit#gid=0"
        },
        "numberToDelete": "={{ $json.row_number }}"
      },
      "type": "n8n-nodes-base.googleSheets",
      "typeVersion": 4.6,
      "position": [
        672,
        272
      ],
      "id": "e26e4bb5-c0d6-4865-ac64-3f2be515544f",
      "name": "Elimina la suscripcion",
      "credentials": {
        "googleSheetsOAuth2Api": {
          "name": "<your credential>"
        }
      }
    },
    {
      "parameters": {
        "documentId": {
          "__rl": true,
          "value": "1lUw0q4H5dCIwHO4rkQVe8PCRtxGZupx1X54GAyU_e7A",
          "mode": "list",
          "cachedResultName": "suscripciones",
          "cachedResultUrl": "https://docs.google.com/spreadsheets/d/1lUw0q4H5dCIwHO4rkQVe8PCRtxGZupx1X54GAyU_e7A/edit?usp=drivesdk"
        },
        "sheetName": {
          "__rl": true,
          "value": "gid=0",
          "mode": "list",
          "cachedResultName": "chatldproductofecha_suscripcion",
          "cachedResultUrl": "https://docs.google.com/spreadsheets/d/1lUw0q4H5dCIwHO4rkQVe8PCRtxGZupx1X54GAyU_e7A/edit#gid=0"
        },
        "filtersUI": {
          "values": [
            {
              "lookupColumn": "chatId",
              "lookupValue": "={{$node[\"Telegram Trigger\"].json.message.chat.id}}"
            }
          ]
        },
        "options": {}
      },
      "type": "n8n-nodes-base.googleSheets",
      "typeVersion": 4.6,
      "position": [
        112,
        688
      ],
      "id": "506a22c0-5962-4480-a81f-4e50b77dfb86",
      "name": "Busca las suscripciones",
      "credentials": {
        "googleSheetsOAuth2Api": {
          "name": "<your credential>"
        }
      }
    },
    {
      "parameters": {
        "documentId": {
          "__rl": true,
          "value": "1z_JwJZtQiERl5bTEAvt6OC3KO8Uo3675-25Xl4B-XRc",
          "mode": "list",
          "cachedResultName": "Productos_GalaxyZ",
          "cachedResultUrl": "https://docs.google.com/spreadsheets/d/1z_JwJZtQiERl5bTEAvt6OC3KO8Uo3675-25Xl4B-XRc/edit?usp=drivesdk"
        },
        "sheetName": {
          "__rl": true,
          "value": 1256057081,
          "mode": "list",
          "cachedResultName": "productos_GalaxyZ",
          "cachedResultUrl": "https://docs.google.com/spreadsheets/d/1z_JwJZtQiERl5bTEAvt6OC3KO8Uo3675-25Xl4B-XRc/edit#gid=1256057081"
        },
        "filtersUI": {
          "values": [
            {
              "lookupColumn": "nombre",
              "lookupValue": "={{ $('Switch').item.json.producto }}"
            }
          ]
        },
        "options": {}
      },
      "type": "n8n-nodes-base.googleSheets",
      "typeVersion": 4.6,
      "position": [
        0,
        -64
      ],
      "id": "dcb95268-c7e5-4ff1-b9d0-36de3cf8fcbe",
      "name": "Google Sheets Productos",
      "credentials": {
        "googleSheetsOAuth2Api": {
          "name": "<your credential>"
        }
      }
    },
    {
      "parameters": {
        "updates": [
          "message"
        ],
        "additionalFields": {}
      },
      "type": "n8n-nodes-base.telegramTrigger",
      "typeVersion": 1.2,
      "position": [
        -1152,
        432
      ],
      "id": "9471215b-9eee-483b-b920-5551b62a3a73",
      "name": "Telegram Trigger",
      "credentials": {
        "telegramApi": {
          "name": "<your credential>"
        }
      }
    },
    {
      "parameters": {
        "promptType": "define",
        "text": "=Eres un asistente que analiza mensajes enviados a un bot de Telegram.\n\nTe voy a dar el mensaje: \n{{ $json.message.text }}\n\nTu tarea es identificar cu\u00e1l de los siguientes comandos est\u00e1 presente en el mensaje, y devolver una respuesta en formato JSON simple con el campo \"accion\" y, si aplica, el \"producto\".\n\nComandos v\u00e1lidos:\n- /start  \u2192 Mostrar mensaje de bienvenida\n- /buscar <t\u00e9rmino> \u2192 Buscar informaci\u00f3n sobre un producto.\n- /seguir <t\u00e9rmino> \u2192 Seguir un producto para recibir notificaciones.\n- /cancelar <t\u00e9rmino> \u2192 Dejar de seguir un producto.\n- /suscripciones \u2192 Mostrar la lista de productos seguidos.\n\nSi el mensaje no contiene ninguno de estos comandos, devuelve:\n{\"accion\": \"ninguna\", \"mensaje\": \"Comando no reconocido. Usa /buscar, /seguir, /cancelar o /suscripciones.\"}\n\nSi el mensaje parece un intento de usar un comando v\u00e1lido, pero est\u00e1 incompleto o mal escrito\n(por ejemplo: \"/busca\", \"/segui\", \"/cancel\", \"/seguir\" sin producto),\ndevuelve:\n{\"accion\": \"error_comando\", \"mensaje\": \"Comando incompleto o mal escrito. Usa /buscar, /seguir, /cancelar o /suscripciones.\"}\n\n**Ejemplos:**\n\nInput: \"/buscar Galaxy Z Flip 7\"  \nOutput: {\"accion\": \"buscar\", \"producto\": \"Galaxy Z Flip 7\"}\n\nInput: \"/seguir iPhone 16\"  \nOutput: {\"accion\": \"seguir\", \"producto\": \"iPhone 16\"}\n\nInput: \"/cancelar Galaxy Z Flip 7\"  \nOutput: {\"accion\": \"cancelar\", \"producto\": \"Galaxy Z Flip 7\"}\n\nInput: \"/suscripciones\"  \nOutput: {\"accion\": \"suscripciones\"}\n\nInput: \"Hola, c\u00f3mo est\u00e1s?\"  \nOutput: {\"accion\": \"ninguna\", \"mensaje\": \"Comando no reconocido. Usa /buscar, /seguir, /cancelar o /suscripciones.\"}\n\nInput: \"/busca\"  \nOutput: {\"accion\": \"ninguna\", \"mensaje\": \"Comando no reconocido. Usa /buscar, /seguir, /cancelar o /suscripciones.\"}\n\nInput: \"/segui iPhone\"\nOutput: {\"accion\": \"error_comando\", \"mensaje\": \"Comando incompleto o mal escrito. Usa /buscar, /seguir, /cancelar o /suscripciones.\"}\n\nInput: \"/buscar\"\nOutput: {\"accion\": \"error_comando\", \"mensaje\": \"Comando incompleto o mal escrito. Usa /buscar <producto> para buscar un producto.\"}\n\nTu salida **siempre debe ser un JSON v\u00e1lido**, sin texto adicional ni formato de c\u00f3digo.\n ",
        "options": {}
      },
      "type": "@n8n/n8n-nodes-langchain.agent",
      "typeVersion": 2.1,
      "position": [
        -976,
        432
      ],
      "id": "82beddb0-34a8-4c6d-8cda-85be474cd77e",
      "name": "AI Agent"
    },
    {
      "parameters": {
        "mode": "runOnceForEachItem",
        "jsCode": "let raw = $json.output || $json.text || \"\";\n\n// Limpia caracteres extra\u00f1os o Markdown (por si la IA devuelve ```json ... ```)\nraw = raw\n  .replace(/```json/i, \"\")\n  .replace(/```/g, \"\")\n  .trim();\n\nlet data = {};\n\ntry {\n  data = JSON.parse(raw);\n} catch (error) {\n  // Si no es JSON v\u00e1lido, lo guardamos como texto para depurar\n  data = { accion: \"error\", mensaje: \"Respuesta inv\u00e1lida del modelo\", raw };\n}\n\nreturn {\n  json: data\n};\n"
      },
      "type": "n8n-nodes-base.code",
      "typeVersion": 2,
      "position": [
        -656,
        432
      ],
      "id": "bdc35151-a86e-41a5-9977-e9452117a80a",
      "name": "Code3"
    },
    {
      "parameters": {
        "documentId": {
          "__rl": true,
          "value": "1lUw0q4H5dCIwHO4rkQVe8PCRtxGZupx1X54GAyU_e7A",
          "mode": "list",
          "cachedResultName": "suscripciones",
          "cachedResultUrl": "https://docs.google.com/spreadsheets/d/1lUw0q4H5dCIwHO4rkQVe8PCRtxGZupx1X54GAyU_e7A/edit?usp=drivesdk"
        },
        "sheetName": {
          "__rl": true,
          "value": "gid=0",
          "mode": "list",
          "cachedResultName": "chatldproductofecha_suscripcion",
          "cachedResultUrl": "https://docs.google.com/spreadsheets/d/1lUw0q4H5dCIwHO4rkQVe8PCRtxGZupx1X54GAyU_e7A/edit#gid=0"
        },
        "filtersUI": {
          "values": [
            {
              "lookupColumn": "chatId",
              "lookupValue": "={{$node[\"Telegram Trigger\"].json.message.chat.id}}"
            },
            {
              "lookupColumn": "producto",
              "lookupValue": "={{$node[\"Code3\"].json.producto}}"
            }
          ]
        },
        "options": {}
      },
      "type": "n8n-nodes-base.googleSheets",
      "typeVersion": 4.6,
      "position": [
        32,
        368
      ],
      "id": "3a252d32-0584-4dd1-9f37-50562d72e6d3",
      "name": "Google Sheets Suscripciones",
      "credentials": {
        "googleSheetsOAuth2Api": {
          "name": "<your credential>"
        }
      }
    },
    {
      "parameters": {
        "chatId": "={{$node[\"Telegram Trigger\"].json.message.chat.id}}",
        "text": "={{ $json.mensaje || \"\u274c Comando no reconocido. Usa /buscar, /seguir, /cancelar o /suscripciones.\" }}",
        "additionalFields": {}
      },
      "type": "n8n-nodes-base.telegram",
      "typeVersion": 1.2,
      "position": [
        -224,
        1104
      ],
      "id": "c95cbbb0-f84c-44f8-80a5-3a2d8135c118",
      "name": "Send a text message2",
      "credentials": {
        "telegramApi": {
          "name": "<your credential>"
        }
      }
    },
    {
      "parameters": {
        "chatId": "={{$node[\"Telegram Trigger\"].json.message.chat.id}} ",
        "text": "\ud83d\udc4b \u00a1Bienvenido! Usa /buscar para encontrar productos o /seguir para recibir alertas cuando haya novedades.",
        "additionalFields": {}
      },
      "type": "n8n-nodes-base.telegram",
      "typeVersion": 1.2,
      "position": [
        -192,
        -272
      ],
      "id": "76ff6578-dc38-494d-a1e0-dca723a49976",
      "name": "Send a text message5",
      "credentials": {
        "telegramApi": {
          "name": "<your credential>"
        }
      }
    },
    {
      "parameters": {
        "chatId": "={{$node[\"Telegram Trigger\"].json.message.chat.id}}",
        "text": "Comando incompleto o mal escrito. Usa /buscar <producto> , /seguir <producto> , /cancelar <producto> o /suscripciones.",
        "additionalFields": {}
      },
      "type": "n8n-nodes-base.telegram",
      "typeVersion": 1.2,
      "position": [
        -112,
        864
      ],
      "id": "de024a89-614d-4106-b7c0-36aaf1359bf9",
      "name": "Send a text message6",
      "credentials": {
        "telegramApi": {
          "name": "<your credential>"
        }
      }
    },
    {
      "parameters": {
        "jsCode": "// \u2705 Aseg\u00farate de estar en \"Run Once for All Items\" para usar $node\n\n// Todas las suscripciones actuales del Google Sheet\nconst subs = $input.all().map(i => i.json);\n\n// Obtenemos datos del contexto\nconst chatId = $node[\"Telegram Trigger\"].json.message.chat.id;\nconst producto = $node[\"Code3\"].json.producto?.toLowerCase().trim() || \"\";\n\n// Validaci\u00f3n r\u00e1pida\nif (!producto) {\n  return [{\n    json: {\n      chatId,\n      success: false,\n      message: \"\u274c No especificaste un producto para cancelar. Usa /cancelar <producto>.\"\n    }\n  }];\n}\n\n// Buscar coincidencia exacta entre chat y producto\nconst encontrada = subs.find(s =>\n  String(s.chatId) === String(chatId) &&\n  s.producto?.toLowerCase().trim() === producto\n);\n\n// Retornar resultado seg\u00fan se encuentre o no\nif (encontrada) {\n  return [{\n    json: {\n      chatId,\n      producto: encontrada.producto,\n      row_number: encontrada.row_number,\n      success: true\n    }\n  }];\n} else {\n  return [{\n    json: {\n      chatId,\n      producto,\n      success: false\n    }\n  }];\n}\n\n"
      },
      "type": "n8n-nodes-base.code",
      "typeVersion": 2,
      "position": [
        192,
        368
      ],
      "id": "643d03da-42d6-43b7-ac3d-6faf4aa6e418",
      "name": "Code"
    },
    {
      "parameters": {
        "conditions": {
          "options": {
            "caseSensitive": true,
            "leftValue": "",
            "typeValidation": "strict",
            "version": 2
          },
          "conditions": [
            {
              "id": "d3461d7f-c4d3-4fc6-a193-0175ff3de3c8",
              "leftValue": "={{ $json.success }}",
              "rightValue": "true",
              "operator": {
                "type": "boolean",
                "operation": "true",
                "singleValue": true
              }
            }
          ],
          "combinator": "and"
        },
        "options": {}
      },
      "type": "n8n-nodes-base.if",
      "typeVersion": 2.2,
      "position": [
        400,
        368
      ],
      "id": "88fa31fc-7fe6-4abc-9524-fb37bed87e42",
      "name": "If"
    },
    {
      "parameters": {
        "mode": "runOnceForEachItem",
        "jsCode": "const { chatId, producto, success } = $json;\n\nconst message = success\n  ? `\ud83d\uddd1\ufe0f *Suscripci\u00f3n eliminada*\\n\\nYa no recibir\u00e1s notificaciones sobre *${producto}*.`\n  : `\u274c No encontr\u00e9 una suscripci\u00f3n activa para *${producto}*.\\n\\nVerifica el nombre con /suscripciones.`;\n\nreturn { json: { chatId, message } };"
      },
      "type": "n8n-nodes-base.code",
      "typeVersion": 2,
      "position": [
        928,
        384
      ],
      "id": "9cb46c11-2ede-47cc-8888-3c9a9230e17e",
      "name": "Code8"
    },
    {
      "parameters": {
        "options": {}
      },
      "type": "@n8n/n8n-nodes-langchain.lmChatMistralCloud",
      "typeVersion": 1,
      "position": [
        -976,
        624
      ],
      "id": "779e5760-5a57-4a3b-8aa8-2527cfbf8797",
      "name": "Mistral Cloud Chat Model",
      "credentials": {
        "mistralCloudApi": {
          "name": "<your credential>"
        }
      }
    },
    {
      "parameters": {
        "documentId": {
          "__rl": true,
          "value": "1z_JwJZtQiERl5bTEAvt6OC3KO8Uo3675-25Xl4B-XRc",
          "mode": "list",
          "cachedResultName": "Productos_GalaxyZ",
          "cachedResultUrl": "https://docs.google.com/spreadsheets/d/1z_JwJZtQiERl5bTEAvt6OC3KO8Uo3675-25Xl4B-XRc/edit?usp=drivesdk"
        },
        "sheetName": {
          "__rl": true,
          "value": 1256057081,
          "mode": "list",
          "cachedResultName": "productos_GalaxyZ",
          "cachedResultUrl": "https://docs.google.com/spreadsheets/d/1z_JwJZtQiERl5bTEAvt6OC3KO8Uo3675-25Xl4B-XRc/edit#gid=1256057081"
        },
        "filtersUI": {
          "values": [
            {
              "lookupColumn": "nombre",
              "lookupValue": "={{ $json.producto }}"
            }
          ]
        },
        "options": {}
      },
      "type": "n8n-nodes-base.googleSheets",
      "typeVersion": 4.6,
      "position": [
        64,
        128
      ],
      "id": "6e29b5e1-4342-4619-b173-19a5ffacd95f",
      "name": "Get row(s) in sheet",
      "credentials": {
        "googleSheetsOAuth2Api": {
          "name": "<your credential>"
        }
      }
    }
  ],
  "connections": {
    "Switch": {
      "main": [
        [
          {
            "node": "Send a text message5",
            "type": "main",
            "index": 0
          }
        ],
        [
          {
            "node": "Google Sheets Productos",
            "type": "main",
            "index": 0
          }
        ],
        [
          {
            "node": "Get row(s) in sheet",
            "type": "main",
            "index": 0
          }
        ],
        [
          {
            "node": "Google Sheets Suscripciones",
            "type": "main",
            "index": 0
          }
        ],
        [
          {
            "node": "Busca las suscripciones",
            "type": "main",
            "index": 0
          }
        ],
        [
          {
            "node": "Send a text message6",
            "type": "main",
            "index": 0
          }
        ],
        [
          {
            "node": "Send a text message2",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Code1": {
      "main": [
        [
          {
            "node": "Send a text message",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Code4": {
      "main": [
        [
          {
            "node": "Send a text message3",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Crea una nueva suscripcion en la hoja de suscripciones1": {
      "main": [
        [
          {
            "node": "Send a text message1",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Elimina la suscripcion": {
      "main": [
        [
          {
            "node": "Code8",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Busca las suscripciones": {
      "main": [
        [
          {
            "node": "Code4",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Google Sheets Productos": {
      "main": [
        [
          {
            "node": "Code1",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Telegram Trigger": {
      "main": [
        [
          {
            "node": "AI Agent",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "AI Agent": {
      "main": [
        [
          {
            "node": "Code3",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Code3": {
      "main": [
        [
          {
            "node": "Switch",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Google Sheets Suscripciones": {
      "main": [
        [
          {
            "node": "Code",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Code": {
      "main": [
        [
          {
            "node": "If",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "If": {
      "main": [
        [
          {
            "node": "Elimina la suscripcion",
            "type": "main",
            "index": 0
          }
        ],
        [
          {
            "node": "Code8",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Code8": {
      "main": [
        [
          {
            "node": "Send a text message4",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Mistral Cloud Chat Model": {
      "ai_languageModel": [
        [
          {
            "node": "AI Agent",
            "type": "ai_languageModel",
            "index": 0
          }
        ]
      ]
    },
    "Get row(s) in sheet": {
      "main": [
        [
          {
            "node": "Crea una nueva suscripcion en la hoja de suscripciones1",
            "type": "main",
            "index": 0
          }
        ]
      ]
    }
  },
  "active": true,
  "settings": {
    "executionOrder": "v1"
  },
  "versionId": "bab23d76-014d-4822-a04a-db4426006923",
  "meta": {
    "templateCredsSetupCompleted": true
  },
  "id": "WcCkbj32zwBLpGEY",
  "tags": []
}