{
  "name": "50_543_RESEARCH_DATA",
  "nodes": [
    {
      "id": "543-trigger",
      "name": "When Called by Another Workflow",
      "type": "n8n-nodes-base.executeWorkflowTrigger",
      "typeVersion": 1,
      "position": [
        250,
        400
      ],
      "parameters": {}
    },
    {
      "id": "543-route",
      "name": "Route Research Intent",
      "type": "n8n-nodes-base.switch",
      "typeVersion": 3.2,
      "position": [
        480,
        400
      ],
      "parameters": {
        "rules": {
          "rules": [
            {
              "outputKey": "TRENDS",
              "conditions": {
                "options": {
                  "caseSensitive": true,
                  "leftValue": ""
                },
                "conditions": [
                  {
                    "leftValue": "={{ $json.intent }}",
                    "rightValue": "NOCODB_TRENDS",
                    "operator": {
                      "type": "string",
                      "operation": "equals"
                    }
                  }
                ]
              }
            },
            {
              "outputKey": "SENTIMENT",
              "conditions": {
                "options": {
                  "caseSensitive": true,
                  "leftValue": ""
                },
                "conditions": [
                  {
                    "leftValue": "={{ $json.intent }}",
                    "rightValue": "NOCODB_SENTIMENT",
                    "operator": {
                      "type": "string",
                      "operation": "equals"
                    }
                  }
                ]
              }
            },
            {
              "outputKey": "OPPORTUNITIES",
              "conditions": {
                "options": {
                  "caseSensitive": true,
                  "leftValue": ""
                },
                "conditions": [
                  {
                    "leftValue": "={{ $json.intent }}",
                    "rightValue": "NOCODB_CONTENT",
                    "operator": {
                      "type": "string",
                      "operation": "equals"
                    }
                  }
                ]
              }
            },
            {
              "outputKey": "AGENTS",
              "conditions": {
                "options": {
                  "caseSensitive": true,
                  "leftValue": ""
                },
                "conditions": [
                  {
                    "leftValue": "={{ $json.intent }}",
                    "rightValue": "AGENTS",
                    "operator": {
                      "type": "string",
                      "operation": "equals"
                    }
                  }
                ]
              }
            },
            {
              "outputKey": "CONTENT_PIECES",
              "conditions": {
                "options": {
                  "caseSensitive": true,
                  "leftValue": ""
                },
                "conditions": [
                  {
                    "leftValue": "={{ $json.intent }}",
                    "rightValue": "CONTENT_PIECES",
                    "operator": {
                      "type": "string",
                      "operation": "equals"
                    }
                  }
                ]
              }
            },
            {
              "outputKey": "PIPELINE",
              "conditions": {
                "options": {
                  "caseSensitive": true,
                  "leftValue": ""
                },
                "conditions": [
                  {
                    "leftValue": "={{ $json.intent }}",
                    "rightValue": "PIPELINE",
                    "operator": {
                      "type": "string",
                      "operation": "equals"
                    }
                  }
                ]
              }
            },
            {
              "outputKey": "AUDIT",
              "conditions": {
                "options": {
                  "caseSensitive": true,
                  "leftValue": ""
                },
                "conditions": [
                  {
                    "leftValue": "={{ $json.intent }}",
                    "rightValue": "AUDIT",
                    "operator": {
                      "type": "string",
                      "operation": "equals"
                    }
                  }
                ]
              }
            }
          ]
        },
        "options": {
          "fallbackOutput": "extra"
        }
      }
    },
    {
      "id": "543-fetch-trends",
      "name": "Fetch Trends",
      "type": "n8n-nodes-base.httpRequest",
      "typeVersion": 4.2,
      "position": [
        760,
        80
      ],
      "parameters": {
        "method": "GET",
        "url": "https://directus.automation-plus-ki.de/items/300_trends",
        "authentication": "none",
        "sendHeaders": true,
        "headerParameters": {
          "parameters": [
            {
              "name": "Authorization",
              "value": "Bearer ={{ $env.DIRECTUS_TOKEN }}"
            }
          ]
        },
        "sendQuery": true,
        "queryParameters": {
          "parameters": [
            {
              "name": "limit",
              "value": "5"
            },
            {
              "name": "sort",
              "value": "-CreatedAt"
            }
          ]
        },
        "options": {
          "timeout": 8000
        }
      },
      "onError": "continueRegularOutput"
    },
    {
      "id": "543-fetch-sentiment",
      "name": "Fetch Sentiment",
      "type": "n8n-nodes-base.httpRequest",
      "typeVersion": 4.2,
      "position": [
        760,
        200
      ],
      "parameters": {
        "method": "GET",
        "url": "https://directus.automation-plus-ki.de/items/310_sentiment",
        "authentication": "none",
        "sendHeaders": true,
        "headerParameters": {
          "parameters": [
            {
              "name": "Authorization",
              "value": "Bearer ={{ $env.DIRECTUS_TOKEN }}"
            }
          ]
        },
        "sendQuery": true,
        "queryParameters": {
          "parameters": [
            {
              "name": "limit",
              "value": "5"
            },
            {
              "name": "sort",
              "value": "-CreatedAt"
            }
          ]
        },
        "options": {
          "timeout": 8000
        }
      },
      "onError": "continueRegularOutput"
    },
    {
      "id": "543-fetch-opportunities",
      "name": "Fetch Opportunities",
      "type": "n8n-nodes-base.httpRequest",
      "typeVersion": 4.2,
      "position": [
        760,
        320
      ],
      "parameters": {
        "method": "GET",
        "url": "https://directus.automation-plus-ki.de/items/320_content_opportunities",
        "authentication": "none",
        "sendHeaders": true,
        "headerParameters": {
          "parameters": [
            {
              "name": "Authorization",
              "value": "Bearer ={{ $env.DIRECTUS_TOKEN }}"
            }
          ]
        },
        "sendQuery": true,
        "queryParameters": {
          "parameters": [
            {
              "name": "limit",
              "value": "5"
            },
            {
              "name": "sort",
              "value": "-CreatedAt"
            }
          ]
        },
        "options": {
          "timeout": 8000
        }
      },
      "onError": "continueRegularOutput"
    },
    {
      "id": "543-fetch-agents",
      "name": "Fetch Crew Agents",
      "type": "n8n-nodes-base.httpRequest",
      "typeVersion": 4.2,
      "position": [
        760,
        440
      ],
      "parameters": {
        "method": "GET",
        "url": "http://s0k444ck0w4cgc400skwkos0.<HETZNER_HOST>.sslip.io/crews/",
        "authentication": "none",
        "options": {
          "timeout": 10000
        }
      },
      "onError": "continueRegularOutput"
    },
    {
      "id": "543-fetch-pieces",
      "name": "Fetch Content Pieces",
      "type": "n8n-nodes-base.httpRequest",
      "typeVersion": 4.2,
      "position": [
        760,
        560
      ],
      "parameters": {
        "method": "GET",
        "url": "https://directus.automation-plus-ki.de/items/330_knowledge_items",
        "authentication": "none",
        "sendHeaders": true,
        "headerParameters": {
          "parameters": [
            {
              "name": "Authorization",
              "value": "Bearer ={{ $env.DIRECTUS_TOKEN }}"
            }
          ]
        },
        "sendQuery": true,
        "queryParameters": {
          "parameters": [
            {
              "name": "limit",
              "value": "10"
            },
            {
              "name": "sort",
              "value": "-created_at"
            }
          ]
        },
        "options": {
          "timeout": 8000
        }
      },
      "onError": "continueRegularOutput"
    },
    {
      "id": "543-fetch-pipeline",
      "name": "Fetch Pipeline Jobs",
      "type": "n8n-nodes-base.httpRequest",
      "typeVersion": 4.2,
      "position": [
        760,
        680
      ],
      "parameters": {
        "method": "GET",
        "url": "https://directus.automation-plus-ki.de/items/400_content_pipeline",
        "authentication": "none",
        "sendHeaders": true,
        "headerParameters": {
          "parameters": [
            {
              "name": "Authorization",
              "value": "Bearer ={{ $env.DIRECTUS_TOKEN }}"
            }
          ]
        },
        "sendQuery": true,
        "queryParameters": {
          "parameters": [
            {
              "name": "limit",
              "value": "10"
            },
            {
              "name": "sort",
              "value": "-created_at"
            }
          ]
        },
        "options": {
          "timeout": 8000
        }
      },
      "onError": "continueRegularOutput"
    },
    {
      "id": "543-fetch-audit",
      "name": "Fetch Audit Trail",
      "type": "n8n-nodes-base.httpRequest",
      "typeVersion": 4.2,
      "position": [
        760,
        800
      ],
      "parameters": {
        "method": "GET",
        "url": "https://directus.automation-plus-ki.de/items/audit_log",
        "authentication": "none",
        "sendHeaders": true,
        "headerParameters": {
          "parameters": [
            {
              "name": "Authorization",
              "value": "Bearer ={{ $env.DIRECTUS_TOKEN }}"
            }
          ]
        },
        "sendQuery": true,
        "queryParameters": {
          "parameters": [
            {
              "name": "limit",
              "value": "10"
            },
            {
              "name": "sort",
              "value": "-ts"
            }
          ]
        },
        "options": {
          "timeout": 8000
        }
      },
      "onError": "continueRegularOutput"
    },
    {
      "id": "543-fmt-trends",
      "name": "Format Trends",
      "type": "n8n-nodes-base.code",
      "typeVersion": 2,
      "position": [
        1040,
        80
      ],
      "parameters": {
        "jsCode": "const chatId = $('When Called by Another Workflow').first().json.chatId;\nconst data = $input.first().json;\nconst rows = data?.data ?? [];\n\nif (rows.length === 0) {\n  return [{ json: { chatId, response: '*Trends:* Noch keine Daten.\\n\\nWorkflow `30_310_TREND_MONITOR` l\u00e4uft t\u00e4gl. 08:00.' } }];\n}\n\nconst lines = rows.map((r, i) => {\n  const title = r.Title ?? r.title ?? r.Trend ?? r.trend ?? 'Unbekannt';\n  const score = r.Score ?? r.score ?? r.Engagement ?? '-';\n  const date = r.CreatedAt ? new Date(r.CreatedAt).toLocaleDateString('de-DE') : '';\n  return `${i + 1}. *${title}*\\nScore: ${score}  |  ${date}`;\n});\n\nreturn [{ json: { chatId, response: `*Aktuelle Trends* (letzte ${rows.length}):\\n\\n${lines.join('\\n\\n')}` } }];"
      }
    },
    {
      "id": "543-fmt-sentiment",
      "name": "Format Sentiment",
      "type": "n8n-nodes-base.code",
      "typeVersion": 2,
      "position": [
        1040,
        200
      ],
      "parameters": {
        "jsCode": "const chatId = $('When Called by Another Workflow').first().json.chatId;\nconst data = $input.first().json;\nconst rows = data?.data ?? [];\n\nif (rows.length === 0) {\n  return [{ json: { chatId, response: '*Sentiment:* Noch keine Daten.\\n\\nWorkflow `30_320_SENTIMENT_TRACKER` l\u00e4uft Mo. 08:00.' } }];\n}\n\nconst emo = { positive: '\ud83d\udfe2', neutral: '\ud83d\udfe1', negative: '\ud83d\udd34' };\nconst lines = rows.map((r, i) => {\n  const topic = r.Topic ?? r.topic ?? r.Trend ?? 'Unbekannt';\n  const s = (r.Sentiment ?? r.sentiment ?? 'neutral').toLowerCase();\n  const score = r.Score ?? r.score ?? '-';\n  const date = r.CreatedAt ? new Date(r.CreatedAt).toLocaleDateString('de-DE') : '';\n  return `${i + 1}. ${emo[s] ?? '\u26aa'} *${topic}*\\n${s}  |  Score: ${score}  |  ${date}`;\n});\n\nreturn [{ json: { chatId, response: `*Sentiment-Analyse* (letzte ${rows.length}):\\n\\n${lines.join('\\n\\n')}` } }];"
      }
    },
    {
      "id": "543-fmt-opportunities",
      "name": "Format Opportunities",
      "type": "n8n-nodes-base.code",
      "typeVersion": 2,
      "position": [
        1040,
        320
      ],
      "parameters": {
        "jsCode": "const chatId = $('When Called by Another Workflow').first().json.chatId;\nconst data = $input.first().json;\nconst rows = data?.data ?? [];\n\nif (rows.length === 0) {\n  return [{ json: { chatId, response: '*Content Opportunities:* Noch keine Daten.\\n\\nWorkflow `30_330_CONTENT_OPPORTUNITY` l\u00e4uft t\u00e4gl. 09:30.' } }];\n}\n\nconst prio = { high: '\ud83d\udd25', medium: '\ud83d\udccb', low: '\ud83d\udca1' };\nconst lines = rows.map((r, i) => {\n  const title = r.Title ?? r.title ?? r.Opportunity ?? 'Unbekannt';\n  const p = (r.Priority ?? r.priority ?? 'medium').toLowerCase();\n  const fmt = r.Format ?? r.format ?? r.Type ?? '';\n  const date = r.CreatedAt ? new Date(r.CreatedAt).toLocaleDateString('de-DE') : '';\n  return `${i + 1}. ${prio[p] ?? '\ud83d\udccb'} *${title}*\\n${p}${fmt ? '  |  ' + fmt : ''}  |  ${date}`;\n});\n\nreturn [{ json: { chatId, response: `*Content Opportunities* (letzte ${rows.length}):\\n\\n${lines.join('\\n\\n')}` } }];"
      }
    },
    {
      "id": "543-fmt-agents",
      "name": "Format Agents",
      "type": "n8n-nodes-base.code",
      "typeVersion": 2,
      "position": [
        1040,
        440
      ],
      "parameters": {
        "jsCode": "const chatId = $('When Called by Another Workflow').first().json.chatId;\nconst data = $input.first().json;\nconst crews = Array.isArray(data) ? data : [];\n\nif (crews.length === 0) {\n  return [{ json: { chatId, response: '\u274c Crew API nicht erreichbar.' } }];\n}\n\nconst totalAgents = crews.reduce((s, c) => s + (c.agents ?? 0), 0);\n\nconst lines = crews.map(c => {\n  const lastRun = c.last_run\n    ? (() => {\n        const diff = Date.now() - new Date(c.last_run).getTime();\n        const m = Math.floor(diff / 60000);\n        if (m < 1) return 'gerade eben';\n        if (m < 60) return `vor ${m}m`;\n        const h = Math.floor(m / 60);\n        if (h < 24) return `vor ${h}h`;\n        return `vor ${Math.floor(h / 24)}d`;\n      })()\n    : 'noch nie';\n  const pieces = c.recent_pieces?.length ?? 0;\n  return `\u2022 *${c.name}* \u2014 ${c.agents} Agents | ${lastRun}${pieces > 0 ? ` | ${pieces} Outputs` : ''}`;\n});\n\nreturn [{ json: { chatId, response: `*Crew AI Agent Teams* (${crews.length} Crews, ${totalAgents} Agents):\\n\\n${lines.join('\\n')}` } }];"
      }
    },
    {
      "id": "543-fmt-pieces",
      "name": "Format Content Pieces",
      "type": "n8n-nodes-base.code",
      "typeVersion": 2,
      "position": [
        1040,
        560
      ],
      "parameters": {
        "jsCode": "const chatId = $('When Called by Another Workflow').first().json.chatId;\nconst data = $input.first().json;\nconst rows = data?.data ?? [];\n\nif (rows.length === 0) {\n  return [{ json: { chatId, response: '*Content Pieces:* Noch keine Daten.\\n\\nStarte mit: `starte Content Master Flow`' } }];\n}\n\nconst statusEmo = { draft: '\u270f\ufe0f', review: '\ud83d\udd0d', approved: '\u2705', published: '\ud83d\ude80', archived: '\ud83d\udce6' };\nconst lines = rows.map((r, i) => {\n  const title = r.title ?? r.Title ?? r.piece_id ?? 'Unbekannt';\n  const status = (r.status ?? 'draft').toLowerCase();\n  const cat = r.category ?? '';\n  const date = r.created_at ?? r.CreatedAt ?? '';\n  const dateStr = date ? new Date(date).toLocaleDateString('de-DE') : '';\n  return `${i + 1}. ${statusEmo[status] ?? '\ud83d\udcc4'} *${title}*\\n${status}${cat ? '  |  ' + cat : ''}${dateStr ? '  |  ' + dateStr : ''}`;\n});\n\nconst draftN = rows.filter(r => r.status === 'draft').length;\nconst pubN = rows.filter(r => r.status === 'published').length;\n\nreturn [{ json: { chatId, response: `*Content Pieces* (${rows.length} gesamt \u2014 ${draftN} Draft, ${pubN} Published):\\n\\n${lines.join('\\n\\n')}` } }];"
      }
    },
    {
      "id": "543-fmt-pipeline",
      "name": "Format Pipeline",
      "type": "n8n-nodes-base.code",
      "typeVersion": 2,
      "position": [
        1040,
        680
      ],
      "parameters": {
        "jsCode": "const chatId = $('When Called by Another Workflow').first().json.chatId;\nconst data = $input.first().json;\nconst rows = data?.data ?? [];\n\nif (rows.length === 0) {\n  return [{ json: { chatId, response: '*Pipeline:* Keine Jobs vorhanden.\\n\\nStarte mit: `starte Content Master Flow`' } }];\n}\n\nconst stageEmo = { text: '\ud83d\udcdd', image: '\ud83d\uddbc\ufe0f', voice: '\ud83c\udf99\ufe0f', publish: '\ud83d\ude80' };\nconst statusEmo = { running: '\u26a1', done: '\u2705', failed: '\u274c', pending: '\u23f3' };\n\nconst lines = rows.map((r, i) => {\n  const jobId = r.job_id ?? r.Id ?? i + 1;\n  const topic = r.topic ?? r.Topic ?? 'Unbekannt';\n  const stage = (r.stage ?? r.Stage ?? 'text').toLowerCase();\n  const status = (r.status ?? r.Status ?? 'pending').toLowerCase();\n  const date = r.created_at ?? r.CreatedAt ?? '';\n  const dateStr = date ? new Date(date).toLocaleDateString('de-DE') : '';\n  return `${i + 1}. ${statusEmo[status] ?? '\u23f3'} *${topic}*\\n${stageEmo[stage] ?? '\ud83d\udccb'} ${stage} | ${status}${dateStr ? '  |  ' + dateStr : ''}`;\n});\n\nreturn [{ json: { chatId, response: `*Content Pipeline* (letzte ${rows.length} Jobs):\\n\\n${lines.join('\\n\\n')}` } }];"
      }
    },
    {
      "id": "543-fmt-audit",
      "name": "Format Audit",
      "type": "n8n-nodes-base.code",
      "typeVersion": 2,
      "position": [
        1040,
        800
      ],
      "parameters": {
        "jsCode": "const chatId = $('When Called by Another Workflow').first().json.chatId;\nconst data = $input.first().json;\nconst rows = data?.data ?? [];\n\nif (rows.length === 0) {\n  return [{ json: { chatId, response: '*Audit Trail:* Noch keine Eintr\u00e4ge.\\n\\nEintr\u00e4ge entstehen automatisch bei Workflow-Ausf\u00fchrungen.' } }];\n}\n\nconst resultEmo = { ok: '\u2705', error: '\u274c', blocked: '\ud83d\udeab' };\n\nconst lines = rows.map((r, i) => {\n  const actor = r.actor ?? r.Actor ?? 'system';\n  const action = r.action ?? r.Action ?? '-';\n  const resource = r.resource_type ?? r.resource_id ?? '-';\n  const result = (r.result ?? 'ok').toLowerCase();\n  const ts = r.ts ?? r.Ts ?? r.CreatedAt ?? '';\n  const tsStr = ts ? new Date(ts).toLocaleString('de-DE', { timeZone: 'Europe/Berlin', hour: '2-digit', minute: '2-digit', day: '2-digit', month: '2-digit' }) : '';\n  return `${i + 1}. ${resultEmo[result] ?? '\u2705'} *${action}*\\n${actor} \u2192 ${resource}${tsStr ? '  |  ' + tsStr : ''}`;\n});\n\nreturn [{ json: { chatId, response: `*Audit Trail* (letzte ${rows.length} Aktionen):\\n\\n${lines.join('\\n\\n')}` } }];"
      }
    },
    {
      "id": "543-fallback",
      "name": "Fallback Response",
      "type": "n8n-nodes-base.set",
      "typeVersion": 3.4,
      "position": [
        1040,
        920
      ],
      "parameters": {
        "assignments": {
          "assignments": [
            {
              "id": "f1",
              "name": "chatId",
              "value": "={{ $('When Called by Another Workflow').first().json.chatId }}",
              "type": "string"
            },
            {
              "id": "f2",
              "name": "response",
              "value": "\u2753 Unbekannte Research-Abfrage. Verf\u00fcgbar: `trends`, `sentiment`, `chancen`, `agents`, `content`, `pipeline`, `audit`",
              "type": "string"
            }
          ]
        }
      }
    }
  ],
  "connections": {
    "When Called by Another Workflow": {
      "main": [
        [
          {
            "node": "Route Research Intent",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Route Research Intent": {
      "main": [
        [
          {
            "node": "Fetch Trends",
            "type": "main",
            "index": 0
          }
        ],
        [
          {
            "node": "Fetch Sentiment",
            "type": "main",
            "index": 0
          }
        ],
        [
          {
            "node": "Fetch Opportunities",
            "type": "main",
            "index": 0
          }
        ],
        [
          {
            "node": "Fetch Crew Agents",
            "type": "main",
            "index": 0
          }
        ],
        [
          {
            "node": "Fetch Content Pieces",
            "type": "main",
            "index": 0
          }
        ],
        [
          {
            "node": "Fetch Pipeline Jobs",
            "type": "main",
            "index": 0
          }
        ],
        [
          {
            "node": "Fetch Audit Trail",
            "type": "main",
            "index": 0
          }
        ],
        [
          {
            "node": "Fallback Response",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Fetch Trends": {
      "main": [
        [
          {
            "node": "Format Trends",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Fetch Sentiment": {
      "main": [
        [
          {
            "node": "Format Sentiment",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Fetch Opportunities": {
      "main": [
        [
          {
            "node": "Format Opportunities",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Fetch Crew Agents": {
      "main": [
        [
          {
            "node": "Format Agents",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Fetch Content Pieces": {
      "main": [
        [
          {
            "node": "Format Content Pieces",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Fetch Pipeline Jobs": {
      "main": [
        [
          {
            "node": "Format Pipeline",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Fetch Audit Trail": {
      "main": [
        [
          {
            "node": "Format Audit",
            "type": "main",
            "index": 0
          }
        ]
      ]
    }
  },
  "settings": {
    "executionOrder": "v1",
    "saveDataErrorExecution": "all",
    "saveDataSuccessExecution": "none"
  },
  "staticData": null,
  "tags": [
    "telegram",
    "research"
  ],
  "meta": {
    "description": "543 \u2014 Sub-Workflow: Research & Operations Daten f\u00fcr Telegram (Trends, Sentiment, Opportunities, Agents, Content Pieces, Pipeline, Audit)"
  }
}