Guys i need help

hi guys, I need your help for a very long time I’ve been trying to create a tg bot in order to make sales reports. We have a huge database on mssql. Unfortunately, I can’t find the tools to make it work conditionally on request. If there is anyone who can help, I will be glad. I really need help.

Describe the problem/error/question

What is the error message (if any)?

Please share your workflow

(Select the nodes on your canvas and use the keyboard shortcuts CMD+C/CTRL+C and CMD+V/CTRL+V to copy and paste the workflow.)

Share the output returned by the last node

Information on your n8n setup

  • n8n version:
  • Database (default: SQLite):
  • n8n EXECUTIONS_PROCESS setting (default: own, main):
  • Running n8n via (Docker, npm, n8n cloud, desktop app):
  • Operating system:

Hi @Watcher_Official

Let´s try to help you. First let us clear some doubts:

· How do you want to trigger it? On a specific command or manually?

· Is the MySQL hosted somewhere? How are we calling it?

· The output, do you need it as a simple Telegram message or do you need it as a PDF?

· Do you need to filter something or need a AI to read and interprete?

With that info we can help with some kind of prebuild model.

I need a simple message in telegram and a plus based on the data so that I can conditionally advise the marketing and sales department, I did this: I throw off screen shots and a plus about filtering, I want the ai agent to pull out the information that I want to request and filter the data from this

Hi @Watcher_Official

Please paste your workflow instead of a screen capture.

You can select all on your workflow, copy and paste it here clicking “</>” and pasting it, so that I can actually use that code and try to help you.

{
“nodes”: [
{
“parameters”: {
“updates”: [
“message”
],
“additionalFields”: {}
},
“type”: “n8n-nodes-base.telegramTrigger”,
“typeVersion”: 1.2,
“position”: [
12656,
8400
],
“id”: “4a139bdd-2844-47e7-8821-b620256ee8a7”,
“name”: “Telegram Trigger”,
“webhookId”: “0fb68d3e-c18f-41a6-b81a-d62f52fd221e”,
“credentials”: {
“telegramApi”: {
“id”: “8Sa5zFznuUljXiBz”,
“name”: “Telegram account”
}
}
},
{
“parameters”: {
“rules”: {
“values”: [
{
“conditions”: {
“options”: {
“caseSensitive”: true,
“leftValue”: “”,
“typeValidation”: “strict”,
“version”: 2
},
“conditions”: [
{
“leftValue”: “={{ $json.message.text }}”,
“rightValue”: “”,
“operator”: {
“type”: “string”,
“operation”: “exists”,
“singleValue”: true
},
“id”: “text-exists”
}
],
“combinator”: “and”
},
“renameOutput”: true,
“outputKey”: “текст”
},
{
“conditions”: {
“options”: {
“caseSensitive”: true,
“leftValue”: “”,
“typeValidation”: “strict”,
“version”: 2
},
“conditions”: [
{
“id”: “voice-exists”,
“leftValue”: “={{ $json.message.voice.mime_type }}”,
“rightValue”: “”,
“operator”: {
“type”: “string”,
“operation”: “exists”,
“singleValue”: true
}
}
],
“combinator”: “and”
},
“renameOutput”: true,
“outputKey”: “голосовое”
}
]
},
“options”: {}
},
“type”: “n8n-nodes-base.switch”,
“typeVersion”: 3.2,
“position”: [
12880,
8400
],
“id”: “59a43b75-7d97-46ce-922a-7dec7f12f99a”,
“name”: “Switch1”
},
{
“parameters”: {
“resource”: “audio”,
“operation”: “transcribe”,
“options”: {
“language”: “RU”
}
},
“type”: “@n8n/n8n-nodes-langchain.openAi”,
“typeVersion”: 1.8,
“position”: [
13328,
8560
],
“id”: “cfd67d73-4a5a-44e1-a2bf-204f3de4e23b”,
“name”: “Transcribe a recording”,
“credentials”: {
“openAiApi”: {
“id”: “KFA5u9VO47RTp6HI”,
“name”: “n8n free OpenAI API credits”
}
}
},
{
“parameters”: {
“assignments”: {
“assignments”: [
{
“id”: “text-field”,
“name”: “text”,
“value”: “={{ $(‘Switch1’).item.json.message.text || $(‘Transcribe a recording’).item.json.text }}”,
“type”: “string”
},
{
“id”: “voice-field”,
“name”: “voice”,
“value”: “={{ $(‘Switch1’).item.json.message.voice?.mime_type || ‘’ }}”,
“type”: “string”
}
]
},
“options”: {}
},
“type”: “n8n-nodes-base.set”,
“typeVersion”: 3.4,
“position”: [
13440,
8400
],
“id”: “47d6fd83-b03c-499d-bc8d-214168d62ef1”,
“name”: “Edit Fields”
},
{
“parameters”: {
“resource”: “file”,
“fileId”: “={{ $(‘Switch1’).item.json.message.voice?.file_id }}”,
“additionalFields”: {}
},
“type”: “n8n-nodes-base.telegram”,
“typeVersion”: 1.2,
“position”: [
13120,
8560
],
“id”: “c8de0d07-5131-4fcf-a670-f41c3c247628”,
“name”: “Get a file”,
“webhookId”: “get-file-webhook”,
“credentials”: {
“telegramApi”: {
“id”: “8Sa5zFznuUljXiBz”,
“name”: “Telegram account”
}
}
},
{
“parameters”: {
“chatId”: “={{ $(‘Switch1’).item.json.message.from.id }}”,
“text”: “={{ $(‘AI Agent’).item.json.output }}”,
“additionalFields”: {}
},
“type”: “n8n-nodes-base.telegram”,
“typeVersion”: 1.2,
“position”: [
14976,
8400
],
“id”: “8f150572-8f27-4553-8952-015add8f3215”,
“name”: “Send a text message”,
“webhookId”: “send-message-webhook”,
“credentials”: {
“telegramApi”: {
“id”: “8Sa5zFznuUljXiBz”,
“name”: “Telegram account”
}
}
},
{
“parameters”: {
“model”: {
“__rl”: true,
“value”: “gpt-5-mini”,
“mode”: “list”,
“cachedResultName”: “gpt-5-mini”
},
“options”: {}
},
“type”: “@n8n/n8n-nodes-langchain.lmChatOpenAi”,
“typeVersion”: 1.2,
“position”: [
13632,
8656
],
“id”: “d7cef362-ca6a-4961-a8b5-b1a5dfc0aa8a”,
“name”: “OpenAI Chat Model”,
“credentials”: {
“openAiApi”: {
“id”: “KFA5u9VO47RTp6HI”,
“name”: “n8n free OpenAI API credits”
}
}
},
{
“parameters”: {
“promptType”: “define”,
“text”: “={{ $(‘Edit Fields’).item.json.text }}”,
“options”: {
“systemMessage”: “You are a helpful assistant that coordinates multiple specialized tools to answer user questions about restaurant operations.\n\nYour available tools:\n1. sales_food - Use when users ask about dish sales, revenue, or quantities sold for specific menu items\n2. sales_concept - Use when users ask about sales concepts or need to generate sales-related data\n3. dish prices - Use when users ask about menu item prices\n4. movement - Use when users ask about warehouse data, product movement, or inventory stock\n5. kasavana - Use for Kasavana-Smith analysis queries\n\nInstructions:\n- Analyze the user’s question carefully to determine which tool(s) to call\n- Extract relevant parameters from the user’s message (dates, dish names, venues, etc.)\n- Call the appropriate tool(s) with the correct parameters\n- Present the results in a clear, user-friendly format\n- If dates are not specified, use reasonable defaults (current month or today)\n- Always respond in the same language as the user’s question”
}
},
“type”: “@n8n/n8n-nodes-langchain.agent”,
“typeVersion”: 3,
“position”: [
13856,
8400
],
“id”: “ca70bc98-c0dd-4649-912d-aace4a7ca816”,
“name”: “AI Agent”
},
{
“parameters”: {
“sessionIdType”: “customKey”,
“sessionKey”: “={{ $(‘Switch1’).item.json.message.from.id }}”,
“contextWindowLength”: 10
},
“type”: “@n8n/n8n-nodes-langchain.memoryBufferWindow”,
“typeVersion”: 1.3,
“position”: [
13872,
8688
],
“id”: “daea0d64-336f-4db1-9d8a-687e8a414dfe”,
“name”: “Simple Memory”,
“notesInFlow”: false
},
{
“parameters”: {
“workflowId”: {
“__rl”: true,
“value”: “F6l3q0Xsqq1dkFzfRd9_7”,
“mode”: “list”,
“cachedResultUrl”: “/workflow/F6l3q0Xsqq1dkFzfRd9_7”,
“cachedResultName”: “SQL 1 Движение Товаров (Авто 3 месяца)”
},
“workflowInputs”: {
“mappingMode”: “defineBelow”,
“value”: {},
“matchingColumns”: ,
“schema”: ,
“attemptToConvertTypes”: false,
“convertFieldsToString”: false
}
},
“type”: “@n8n/n8n-nodes-langchain.toolWorkflow”,
“typeVersion”: 2.2,
“position”: [
14160,
8672
],
“id”: “98ae86c3-e3b3-48bc-9ffe-abcfe616692b”,
“name”: “Call ‘SQL 1 Движение Товаров (Авто 3 месяца)’”
},
{
“parameters”: {
“workflowId”: {
“__rl”: true,
“value”: “02gYw03iXc_qE4xEjosYU”,
“mode”: “list”,
“cachedResultUrl”: “/workflow/02gYw03iXc_qE4xEjosYU”,
“cachedResultName”: “KASAVANA_simple”
},
“workflowInputs”: {
“mappingMode”: “defineBelow”,
“value”: {},
“matchingColumns”: ,
“schema”: ,
“attemptToConvertTypes”: false,
“convertFieldsToString”: false
}
},
“type”: “@n8n/n8n-nodes-langchain.toolWorkflow”,
“typeVersion”: 2.2,
“position”: [
14384,
8656
],
“id”: “a569f7e3-94cc-4974-890c-8d67ca6638d6”,
“name”: “Call ‘KASAVANA_simple’”
}
],
“connections”: {
“Telegram Trigger”: {
“main”: [
[
{
“node”: “Switch1”,
“type”: “main”,
“index”: 0
}
]
]
},
“Switch1”: {
“main”: [
[
{
“node”: “Edit Fields”,
“type”: “main”,
“index”: 0
}
],
[
{
“node”: “Get a file”,
“type”: “main”,
“index”: 0
}
]
]
},
“Transcribe a recording”: {
“main”: [
[
{
“node”: “Edit Fields”,
“type”: “main”,
“index”: 0
}
]
]
},
“Edit Fields”: {
“main”: [
[
{
“node”: “AI Agent”,
“type”: “main”,
“index”: 0
}
]
]
},
“Get a file”: {
“main”: [
[
{
“node”: “Transcribe a recording”,
“type”: “main”,
“index”: 0
}
]
]
},
“OpenAI Chat Model”: {
“ai_languageModel”: [
[
{
“node”: “AI Agent”,
“type”: “ai_languageModel”,
“index”: 0
}
]
]
},
“AI Agent”: {
“main”: [
[
{
“node”: “Send a text message”,
“type”: “main”,
“index”: 0
}
]
]
},
“Simple Memory”: {
“ai_memory”: [
[
{
“node”: “AI Agent”,
“type”: “ai_memory”,
“index”: 0
}
]
]
},
“Call ‘SQL 1 Движение Товаров (Авто 3 месяца)’”: {
“ai_tool”: [
[
{
“node”: “AI Agent”,
“type”: “ai_tool”,
“index”: 0
}
]
]
},
“Call ‘KASAVANA_simple’”: {
“ai_tool”: [
[
{
“node”: “AI Agent”,
“type”: “ai_tool”,
“index”: 0
}
]
]
}
},
“pinData”: {},
“meta”: {
“templateCredsSetupCompleted”: true,
“instanceId”: “ca0f17bdb55b5898eb621563fd688a731524a4de6fcf1adfa7ee37974f563147”
}
}

{
“nodes”: [
{
“parameters”: {
“jsCode”: “// Форматируем ответ\nconst results = $input.all();\nconst params = $node[“Парсер и SQL”].json;\n\nconsole.log(‘Получено записей:’, results.length);\n\nlet answer = ‘’;\n\nif (results.length === 0) {\n answer = ‘Не найдено данных’;\n if (params.searchItem) {\n answer += ’ по товару: ’ + params.searchItem;\n }\n if (params.searchStore) {\n answer += ’ на складе: ’ + params.searchStore;\n }\n if (params.searchCategory) {\n answer += ’ в категории: ’ + params.searchCategory;\n }\n answer += ’ за период: ’ + params.periodStart + ’ - ’ + params.periodEnd + ‘.’;\n} else {\n // Заголовок\n answer = ‘:bar_chart: ДВИЖЕНИЕ ТОВАРОВ\n’;\n answer += ‘===================\n\n’;\n \n answer += ‘:date: Фиксированный период: ’ + params.periodStart + ’ - ’ + params.periodEnd + ‘\n’;\n answer += ’ (Ноябрь 2025 - Февраль 2026)\n\n’;\n \n if (params.searchItem) {\n answer += ':magnifying_glass_tilted_left: Товар: ’ + params.searchItem + ‘\n’;\n }\n if (params.searchStore) {\n answer += ':convenience_store: Склад: ’ + params.searchStore + ‘\n’;\n }\n if (params.searchCategory) {\n answer += ':file_folder: Категория: ’ + params.searchCategory + ‘\n’;\n }\n answer += ‘:bar_chart: Найдено записей: ’ + results.length.toLocaleString() + ‘\n\n’;\n \n // Суммируем показатели\n let totalStart = 0;\n let totalIncome = 0;\n let totalSales = 0;\n let totalTransfers = 0;\n let totalWriteOff = 0;\n let totalSurplus = 0;\n let totalShortage = 0;\n let totalEnd = 0;\n \n // Группируем по месяцам\n const months = {};\n const products = {};\n const stores = {};\n \n results.forEach(item => {\n const data = item.json;\n const period = data.Код_периода;\n \n // Суммируем общие показатели\n totalStart += data.Остатки_на_начало || 0;\n totalIncome += data.Приход || 0;\n totalSales += data.Продажи || 0;\n totalTransfers += data.Внутренние_перемещения || 0;\n totalWriteOff += data.Списания || 0;\n totalSurplus += data.Излишки_инвентаризации || 0;\n totalShortage += data.Недостача_инвентаризации || 0;\n totalEnd += data.Остатки_на_конец || 0;\n \n // Группируем по месяцам\n if (!months[period]) {\n months[period] = {\n продажи: 0,\n приход: 0,\n остатокКонец: 0,\n товаров: new Set()\n };\n }\n months[period].продажи += data.Продажи || 0;\n months[period].приход += data.Приход || 0;\n months[period].остатокКонец += data.Остатки_на_конец || 0;\n months[period].товаров.add(data.Код_товара);\n \n // Группируем по товарам\n const productKey = data.Код_товара + ‘|’ + data.Наименование_товара;\n if (!products[productKey]) {\n products[productKey] = {\n код: data.Код_товара,\n название: data.Наименование_товара,\n категория: data.Категория_блюда,\n единица: data.Единица_измерения,\n продажи: 0,\n приход: 0\n };\n }\n products[productKey].продажи += data.Продажи || 0;\n products[productKey].приход += data.Приход || 0;\n \n // Группируем по складам\n const store = data.Склад || ‘Не указан’;\n if (!stores[store]) {\n stores[store] = {\n продажи: 0,\n приход: 0,\n товаров: new Set()\n };\n }\n stores[store].продажи += data.Продажи || 0;\n stores[store].приход += data.Приход || 0;\n stores[store].товаров.add(data.Код_товара);\n });\n \n // 1. Общая сводка\n answer += ‘:chart_increasing: ОБЩАЯ СВОДКА за период:\n’;\n answer += ’ Остатки на начало: ’ + totalStart.toFixed(2) + ‘\n’;\n answer += ’ Приход: ’ + totalIncome.toFixed(2) + ‘\n’;\n answer += ’ Продажи: ’ + totalSales.toFixed(2) + ‘\n’;\n answer += ’ Внутренние перемещения: ’ + totalTransfers.toFixed(2) + ‘\n’;\n answer += ’ Списания: ’ + totalWriteOff.toFixed(2) + ‘\n’;\n answer += ’ Излишки: ’ + totalSurplus.toFixed(2) + ‘\n’;\n answer += ’ Недостачи: ’ + totalShortage.toFixed(2) + ‘\n’;\n answer += ’ Остатки на конец: ’ + totalEnd.toFixed(2) + ‘\n\n’;\n \n // 2. По месяцам\n answer += ‘:spiral_calendar: РАСПРЕДЕЛЕНИЕ ПО МЕСЯЦАМ:\n’;\n \n // Сортируем месяцы в правильном порядке: 2025-11, 2025-12, 2026-01, 2026-02\n const monthOrder = [‘2025-11’, ‘2025-12’, ‘2026-01’, ‘2026-02’];\n const sortedMonths = monthOrder.filter(month => months[month]);\n \n sortedMonths.forEach(month => {\n const data = months[month];\n const monthNames = {\n ‘2025-11’: ‘Ноябрь 2025’,\n ‘2025-12’: ‘Декабрь 2025’,\n ‘2026-01’: ‘Январь 2026’,\n ‘2026-02’: ‘Февраль 2026’\n };\n \n answer += ’ ’ + monthNames[month] + ’ (’ + month + ‘):\n’;\n answer += ’ Продажи: ’ + data.продажи.toFixed(2) + ‘\n’;\n answer += ’ Приход: ’ + data.приход.toFixed(2) + ‘\n’;\n answer += ’ Остаток на конец: ’ + data.остатокКонец.toFixed(2) + ‘\n’;\n answer += ’ Уникальных товаров: ’ + data.товаров.size + ‘\n’;\n });\n \n // 3. Топ товаров по продажам\n answer += ‘\n​:trophy: ТОП-10 ТОВАРОВ ПО ПРОДАЖАМ:\n’;\n \n const sortedProducts = Object.values(products)\n .sort((a, b) => b.продажи - a.продажи)\n .slice(0, 10);\n \n if (sortedProducts.length > 0) {\n sortedProducts.forEach((product, index) => {\n answer += ’ ’ + (index + 1) + ‘. ’ + product.название + ‘\n’;\n answer += ’ Код: ’ + product.код + ’ | Категория: ’ + product.категория + ‘\n’;\n answer += ’ Продажи: ’ + product.продажи.toFixed(2) + ’ ’ + product.единица + ‘\n’;\n answer += ’ Приход: ’ + product.приход.toFixed(2) + ’ ’ + product.единица + ‘\n’;\n });\n } else {\n answer += ’ Нет данных о продажах\n’;\n }\n \n // 4. По складам\n answer += ‘\n​:package: РАСПРЕДЕЛЕНИЕ ПО СКЛАДАМ:\n’;\n \n const sortedStores = Object.entries(stores)\n .sort((a, b) => b[1].продажи - a[1].продажи);\n \n sortedStores.forEach(([store, data], index) => {\n answer += ’ ’ + (index + 1) + '. ’ + store + ‘\n’;\n answer += ’ Продажи: ’ + data.продажи.toFixed(2) + ‘\n’;\n answer += ’ Приход: ’ + data.приход.toFixed(2) + ‘\n’;\n answer += ’ Уникальных товаров: ’ + data.товаров.size + ‘\n’;\n });\n \n // 5. Примеры данных\n answer += ‘\n​:clipboard: ПРИМЕРЫ ДАННЫХ (первые 3 записи):\n’;\n \n if (results.length >= 3) {\n results.slice(0, 3).forEach((item, index) => {\n const data = item.json;\n answer += ‘\n Запись ’ + (index + 1) + ‘:\n’;\n answer += ’ Период: ’ + data.Код_периода + ‘\n’;\n answer += ’ Склад: ’ + data.Склад + ‘\n’;\n answer += ’ Товар: ’ + data.Наименование_товара + ’ (’ + data.Код_товара + ‘)\n’;\n answer += ’ Категория: ’ + data.Категория_блюда + ‘\n’;\n answer += ’ Продажи: ’ + data.Продажи + ’ ’ + data.Единица_измерения + ‘\n’;\n answer += ’ Приход: ’ + data.Приход + ‘, Остаток: ’ + data.Остатки_на_конец + ‘\n’;\n });\n } else {\n answer += ’ Недостаточно данных для примера\n’;\n }\n}\n\nreturn [{\n json: {\n готовый_ответ: answer,\n есть_данные: results.length > 0,\n количество_записей: results.length,\n параметры_поиска: {\n товар: params.searchItem,\n склад: params.searchStore,\n категория: params.searchCategory,\n период_начала: params.periodStart,\n период_окончания: params.periodEnd\n }\n }\n}];”
},
“type”: “n8n-nodes-base.code”,
“typeVersion”: 2,
“position”: [
-1200,
-512
],
“id”: “e561c2b1-d6e0-44c4-af73-7c3a7d65f742”,
“name”: “Форматирование”
},
{
“parameters”: {
“operation”: “executeQuery”,
“query”: “={{ $node[“Парсер и SQL”].json[“query”] }}”
},
“type”: “n8n-nodes-base.microsoftSql”,
“typeVersion”: 1.1,
“position”: [
-1408,
-512
],
“id”: “81272fcc-43ea-4f83-9b1b-d078e43bad81”,
“name”: “Microsoft SQL”,
“credentials”: {
“microsoftSql”: {
“id”: “cA559H038U3Klz4d”,
“name”: “Microsoft SQL account”
}
}
},
{
“parameters”: {
“jsCode”: “// Получаем запрос\nconst input = $input.first().json;\nconst query = (input.query || input.message || input.text || ‘’).toLowerCase();\n\nconsole.log(‘Получен запрос:’, query);\n\n// Определяем параметры поиска\nlet searchItem = ‘’;\nlet searchStore = ‘’;\nlet searchCategory = ‘’;\n\n// Поиск товара\nif (query.includes(‘бургер’)) searchItem = ‘бургер’;\nelse if (query.includes(‘пицц’)) searchItem = ‘пицца’;\nelse if (query.includes(‘суп’)) searchItem = ‘суп’;\nelse if (query.includes(‘салат’)) searchItem = ‘салат’;\nelse if (query.includes(‘кофе’)) searchItem = ‘кофе’;\nelse if (query.includes(‘чай’)) searchItem = ‘чай’;\nelse if (query.includes(‘десерт’)) searchItem = ‘десерт’;\nelse if (query.includes(‘напиток’)) searchItem = ‘напиток’;\nelse if (query.includes(‘пиво’)) searchItem = ‘пиво’;\nelse if (query.includes(‘водк’)) searchItem = ‘водка’;\nelse if (query.includes(‘вино’)) searchItem = ‘вино’;\n\n// Поиск склада\nif (query.includes(‘шпатен’)) searchStore = ‘Шпатен’;\nelse if (query.includes(‘центр’)) searchStore = ‘Центр’;\nelse if (query.includes(‘аэропорт’)) searchStore = ‘Аэропорт’;\nelse if (query.includes(‘склад’)) searchStore = query.match(/склад[\s\w]*/)?.[0] || ‘’;\n\n// Поиск категории\nif (query.includes(‘горяч’)) searchCategory = ‘Горячее’;\nelse if (query.includes(‘холод’)) searchCategory = ‘Холодное’;\nelse if (query.includes(‘напит’)) searchCategory = ‘Напитки’;\nelse if (query.includes(‘закуск’)) searchCategory = ‘Закуски’;\nelse if (query.includes(‘алкоголь’)) searchCategory = ‘Алкоголь’;\nelse if (query.includes(‘безалкоголь’)) searchCategory = ‘Безалкогольные’;\n\n// Фиксированный период: Ноябрь 2025 - Февраль 2026\nconst periodStart = ‘2025-11’;\nconst periodEnd = ‘2026-02’;\n\nconsole.log(‘Фиксированный период:’, periodStart, ‘-’, periodEnd);\n\n// Формируем SQL запрос\nlet sqlQuery = ‘’;\n\n// Базовый запрос\nsqlQuery += 'SELECT ';\nsqlQuery += '[Код_периода], ';\nsqlQuery += '[Склад], ';\nsqlQuery += '[Код_товара], ';\nsqlQuery += '[Наименование_товара], ';\nsqlQuery += '[Категория_блюда], ';\nsqlQuery += '[Единица_измерения], ';\nsqlQuery += '[Остатки_на_начало], ';\nsqlQuery += '[Приход], ';\nsqlQuery += '[Продажи], ';\nsqlQuery += '[Внутренние_перемещения], ';\nsqlQuery += '[Списания], ';\nsqlQuery += '[Излишки_инвентаризации], ';\nsqlQuery += '[Недостача_инвентаризации], ';\nsqlQuery += '[Остатки_на_конец] ';\nsqlQuery += 'FROM [UT].[Движение_товара] ‘;\n\n// Фильтр по фиксированному периоду\nsqlQuery += ‘WHERE [Код_периода] >= \’’ + periodStart + ‘\’ ‘;\nsqlQuery += ‘AND [Код_периода] <= \’’ + periodEnd + ‘\’ ‘;\n\n// Фильтр по товару\nif (searchItem) {\n sqlQuery += ‘AND [Наименование_товара] LIKE \’%’ + searchItem + ‘%\’ ‘;\n}\n\n// Фильтр по складу\nif (searchStore) {\n sqlQuery += ‘AND [Склад] LIKE \’%’ + searchStore + ‘%\’ ‘;\n}\n\n// Фильтр по категории\nif (searchCategory) {\n sqlQuery += ‘AND [Категория_блюда] LIKE \’%’ + searchCategory + ‘%\’ ';\n}\n\n// Сортировка\nsqlQuery += ‘ORDER BY [Код_периода] DESC, [Продажи] DESC’;\n\nconsole.log(‘Сформирован SQL:’, sqlQuery);\n\nreturn [{\n json: {\n query: sqlQuery,\n searchItem: searchItem,\n searchStore: searchStore,\n searchCategory: searchCategory,\n periodStart: periodStart,\n periodEnd: periodEnd,\n originalQuery: query\n }\n}];”
},
“type”: “n8n-nodes-base.code”,
“typeVersion”: 2,
“position”: [
-1600,
-512
],
“id”: “ac2bcb10-4533-4837-b555-376f545d7f98”,
“name”: “Парсер и SQL”
},
{
“parameters”: {
“inputSource”: “jsonExample”
},
“type”: “n8n-nodes-base.executeWorkflowTrigger”,
“typeVersion”: 1.1,
“position”: [
-1824,
-512
],
“id”: “7608a202-4931-4324-95f9-e8bdb8b53b24”,
“name”: “When Executed by Another Workflow”
}
],
“connections”: {
“Microsoft SQL”: {
“main”: [
[
{
“node”: “Форматирование”,
“type”: “main”,
“index”: 0
}
]
]
},
“Парсер и SQL”: {
“main”: [
[
{
“node”: “Microsoft SQL”,
“type”: “main”,
“index”: 0
}
]
]
},
“When Executed by Another Workflow”: {
“main”: [
[
{
“node”: “Парсер и SQL”,
“type”: “main”,
“index”: 0
}
]
]
}
},
“pinData”: {},
“meta”: {
“templateCredsSetupCompleted”: true,
“instanceId”: “ca0f17bdb55b5898eb621563fd688a731524a4de6fcf1adfa7ee37974f563147”
}
}

Hi @Watcher_Official
Sorry, I´ve been trying to get it working for you. Here´s the setup I would go with. Your two flows in a stable way

· First flow - SQL

Second Flow -

So, here we have first flow using the database with users question, turns in to SQL. You will have to add the workflow ID that you will use from your URL.

Second Flow lists from Telegram and if you ask, grabs info from the first flow. You will need to change the “Reemplaza” ID,

Let me know if this works or we can do it other way!

I tried, thank you very much, but we have a lot of volume there, namely records in the table, and our entire table is in mssql. if, for example, records exceed 100,000 thousand there, it starts to lag because the AI agent pulls everything and not what is required, maybe there is another filtering option, that is, I ask via telegram for an example, do me the report of one of the restaurants for 2025-12 so that he could give me a database like you had such a lifetime and, accordingly, so that the AI agent would make a recommendation after that

Here’s how you can set this up:

Basic Flow:

  1. Telegram Trigger - Listens for commands from users

  2. Conditional Logic - Routes different report requests to appropriate queries

  3. MSSQL Node - Queries your database based on the request

  4. Format Results - Prepares the data in a readable format

  5. Telegram Response - Sends the report back to the user

What you need to know to build your workflow:

  1. What types of reports do you need? For example:

    • Daily sales summary

    • Sales by product

    • Sales by region/salesperson

    • Custom date range reports

  2. How should users request reports? For example:

    • /daily - today’s sales

    • /weekly - this week’s sales

    • /product ProductName - sales for specific product

  3. What information should each report include? (total sales, number of orders, top products, etc.)

  4. Do you already have a Telegram bot token? (If not, I can guide you through creating one)

Once you share these details, we can start building a complete workflow that handles multiple report types with conditional routing based on the user’s commands.

2 Likes

I need to build a monthly report and a weekly report, yes, I have everything ready, everything is connected, we have a lot of products.