{
  "name": "org-ai Dept Analytics",
  "nodes": [
    {
      "parameters": {
        "httpMethod": "POST",
        "path": "dept-analytics",
        "responseMode": "onReceived",
        "authentication": "headerAuth",
        "options": {}
      },
      "id": "trigger",
      "name": "Webhook",
      "type": "n8n-nodes-base.webhook",
      "typeVersion": 2,
      "position": [
        240,
        300
      ]
    },
    {
      "parameters": {
        "url": "={{ $json.body.logUrl }}",
        "sendHeaders": true,
        "headerParameters": {
          "parameters": [
            {
              "name": "Content-Type",
              "value": "application/json"
            },
            {
              "name": "x-webhook-token",
              "value": "={{ $env.N8N_WEBHOOK_AUTH_TOKEN || 'org-ai-n8n-secret-token' }}"
            }
          ]
        },
        "sendBody": true,
        "bodyParameters": {
          "parameters": [
            {
              "name": "taskId",
              "value": "={{ $json.body.taskId }}"
            },
            {
              "name": "message",
              "value": "\u5206\u6790\u90e8 (Analytics) \u30ef\u30fc\u30af\u30d5\u30ed\u30fc\u958b\u59cb"
            },
            {
              "name": "level",
              "value": "INFO"
            }
          ]
        },
        "options": {}
      },
      "id": "log-start",
      "name": "Log Start",
      "type": "n8n-nodes-base.httpRequest",
      "typeVersion": 4,
      "position": [
        460,
        300
      ]
    },
    {
      "parameters": {
        "jsCode": "const rd = $('Webhook').item.json.body;\nconst input = (rd.input ?? '').toLowerCase();\nconst hint = (rd.taskType ?? '').toLowerCase();\nconst kw = (words) => words.some(w => input.includes(w.toLowerCase()) || hint.includes(w.toLowerCase()));\n\nlet taskMode = 'market_analysis';\nif (kw(['\u30e1\u30fc\u30eb','email','mail','\u9001\u4fe1','\u914d\u4fe1'])) taskMode = 'email';\nelse if (kw(['\u30b0\u30e9\u30d5','\u30c1\u30e3\u30fc\u30c8','\u53ef\u8996\u5316','kpi','\u7d71\u8a08','\u30c8\u30ec\u30f3\u30c9'])) taskMode = 'data_visualization';\nelse if (kw(['\u5e02\u5834\u5206\u6790','\u7af6\u5408\u5206\u6790','\u30de\u30fc\u30b1\u30c3\u30c8','\u5e02\u5834\u8abf\u67fb','swot'])) taskMode = 'market_analysis';\n\nconst prompts = {\n  email: `\u3042\u306a\u305f\u306f\u5206\u6790\u90e8\u306e\u30ec\u30dd\u30fc\u30c8\u30e1\u30fc\u30ebAI\u3067\u3059\u3002\u5206\u6790\u7d50\u679c\u3092\u30d3\u30b8\u30cd\u30b9\u30e1\u30fc\u30eb\u306b\u307e\u3068\u3081\u307e\u3059\u3002\\nJSON: {\"taskType\":\"email\",\"to\":\"\",\"cc\":\"\",\"subject\":\"\",\"body\":\"\u672c\u6587\uff08\u8981\u70b9\u3092\u7b87\u6761\u66f8\u304d\u3067\uff09\"}`,\n  market_analysis: `\u3042\u306a\u305f\u306f\u30c7\u30fc\u30bf\u30b5\u30a4\u30a8\u30f3\u30c6\u30a3\u30b9\u30c8\u3067\u3059\u3002\\nJSON: {\"taskType\":\"market_analysis\",\"title\":\"\",\"summary\":\"\",\"sections\":[{\"heading\":\"\",\"content\":\"\"}],\"conclusion\":\"\",\"risks\":[]}`,\n  data_visualization: `\u3042\u306a\u305f\u306f\u30c7\u30fc\u30bf\u30b5\u30a4\u30a8\u30f3\u30c6\u30a3\u30b9\u30c8\u3067\u3059\u3002\\nJSON: {\"taskType\":\"data_visualization\",\"title\":\"\",\"chartType\":\"bar\",\"data\":[{\"label\":\"\",\"value\":0}],\"summary\":\"\"}`\n};\nconst systemPrompt = prompts[taskMode] ?? prompts.market_analysis;\nconst messages = [\n  { role: 'system', content: systemPrompt },\n  { role: 'user', content: rd.input }\n];\nreturn [{ json: { messages, taskMode, useJsonMode: true, department: 'ANALYTICS', org_id: rd.orgId, plan: rd.plan ?? 'STARTER', aiEngineUrl: rd.aiEngineUrl ?? 'http://ai-engine:8000' } }];"
      },
      "id": "build-prompt",
      "name": "Build Prompt",
      "type": "n8n-nodes-base.code",
      "typeVersion": 2,
      "position": [
        680,
        300
      ]
    },
    {
      "parameters": {
        "method": "POST",
        "url": "={{ $json.aiEngineUrl }}/llm/chat",
        "sendHeaders": true,
        "headerParameters": {
          "parameters": [
            {
              "name": "Content-Type",
              "value": "application/json"
            }
          ]
        },
        "sendBody": true,
        "contentType": "raw",
        "rawContentType": "application/json",
        "body": "={{ JSON.stringify({ messages: $json.messages, department: $json.department, org_id: $json.org_id, plan: $json.plan, json_mode: $json.useJsonMode }) }}",
        "options": {}
      },
      "id": "ai-chat",
      "name": "AI Engine Chat",
      "type": "n8n-nodes-base.httpRequest",
      "typeVersion": 4,
      "position": [
        900,
        300
      ]
    },
    {
      "parameters": {
        "rules": {
          "values": [
            {
              "conditions": {
                "options": {
                  "caseSensitive": false,
                  "leftValue": "",
                  "typeValidation": "strict"
                },
                "conditions": [
                  {
                    "leftValue": "={{ $('Build Prompt').item.json.taskMode }}",
                    "rightValue": "email",
                    "operator": {
                      "type": "string",
                      "operation": "equals"
                    }
                  }
                ],
                "combinator": "and"
              },
              "renameOutput": true,
              "outputKey": "email"
            }
          ]
        },
        "options": {
          "fallbackOutput": "extra"
        }
      },
      "id": "switch-mode",
      "name": "Switch Email vs Other",
      "type": "n8n-nodes-base.switch",
      "typeVersion": 3,
      "position": [
        1120,
        300
      ]
    },
    {
      "parameters": {
        "jsCode": "const raw = $json.content ?? '';\nlet parsed = {};\ntry { parsed = JSON.parse(raw); } catch { parsed = { to: '', subject: '(AI \u51fa\u529b\u3092JSON\u30d1\u30fc\u30b9\u5931\u6557)', body: raw }; }\nreturn [{ json: { ...parsed, _ai: $json } }];"
      },
      "id": "parse-email",
      "name": "Parse Email JSON",
      "type": "n8n-nodes-base.code",
      "typeVersion": 2,
      "position": [
        1340,
        200
      ]
    },
    {
      "parameters": {
        "sendTo": "={{ $json.to }}",
        "subject": "={{ $json.subject }}",
        "emailType": "text",
        "message": "={{ $json.body }}",
        "options": {
          "ccList": "={{ $json.cc || '' }}",
          "appendAttribution": false
        }
      },
      "id": "send-email",
      "name": "Send Email (Gmail)",
      "type": "n8n-nodes-base.gmail",
      "typeVersion": 2.1,
      "position": [
        1560,
        200
      ]
    },
    {
      "parameters": {
        "url": "={{ $('Webhook').item.json.body.callbackUrl }}",
        "sendHeaders": true,
        "headerParameters": {
          "parameters": [
            {
              "name": "Content-Type",
              "value": "application/json"
            },
            {
              "name": "x-webhook-token",
              "value": "={{ $env.N8N_WEBHOOK_AUTH_TOKEN || 'org-ai-n8n-secret-token' }}"
            }
          ]
        },
        "sendBody": true,
        "bodyParameters": {
          "parameters": [
            {
              "name": "taskId",
              "value": "={{ $('Webhook').item.json.body.taskId }}"
            },
            {
              "name": "status",
              "value": "DONE"
            },
            {
              "name": "output",
              "value": "={{ JSON.stringify({ taskType: 'email', sentTo: $('Parse Email JSON').item.json.to, subject: $('Parse Email JSON').item.json.subject }) }}"
            },
            {
              "name": "workflowId",
              "value": "={{ $workflow.id }}"
            }
          ]
        },
        "options": {}
      },
      "id": "callback-email",
      "name": "Callback (Email Done)",
      "type": "n8n-nodes-base.httpRequest",
      "typeVersion": 4,
      "position": [
        1780,
        200
      ]
    },
    {
      "parameters": {
        "url": "={{ $('Webhook').item.json.body.callbackUrl }}",
        "sendHeaders": true,
        "headerParameters": {
          "parameters": [
            {
              "name": "Content-Type",
              "value": "application/json"
            },
            {
              "name": "x-webhook-token",
              "value": "={{ $env.N8N_WEBHOOK_AUTH_TOKEN || 'org-ai-n8n-secret-token' }}"
            }
          ]
        },
        "sendBody": true,
        "bodyParameters": {
          "parameters": [
            {
              "name": "taskId",
              "value": "={{ $('Webhook').item.json.body.taskId }}"
            },
            {
              "name": "status",
              "value": "DONE"
            },
            {
              "name": "output",
              "value": "={{ $('AI Engine Chat').item.json.content }}"
            },
            {
              "name": "workflowId",
              "value": "={{ $workflow.id }}"
            }
          ]
        },
        "options": {}
      },
      "id": "callback-other",
      "name": "Callback (Other Done)",
      "type": "n8n-nodes-base.httpRequest",
      "typeVersion": 4,
      "position": [
        1340,
        400
      ]
    }
  ],
  "connections": {
    "Log Start": {
      "main": [
        [
          {
            "node": "Build Prompt",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Build Prompt": {
      "main": [
        [
          {
            "node": "AI Engine Chat",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "AI Engine Chat": {
      "main": [
        [
          {
            "node": "Switch Email vs Other",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Switch Email vs Other": {
      "main": [
        [
          {
            "node": "Parse Email JSON",
            "type": "main",
            "index": 0
          }
        ],
        [
          {
            "node": "Callback (Other Done)",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Parse Email JSON": {
      "main": [
        [
          {
            "node": "Send Email (Gmail)",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Send Email (Gmail)": {
      "main": [
        [
          {
            "node": "Callback (Email Done)",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Webhook": {
      "main": [
        [
          {
            "node": "Log Start",
            "type": "main",
            "index": 0
          }
        ]
      ]
    }
  },
  "settings": {
    "executionOrder": "v1",
    "saveManualExecutions": true
  },
  "staticData": null
}